1 /*
2 * Xing VBR tagging for LAME.
3 *
4 * Copyright (c) 1999 A.L. Faber
5 * Copyright (c) 2001 Jonathan Dee
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
16 *
17 * You should have received a copy of the GNU Library General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
21 */
22
23 /* $Id: VbrTag.c,v 1.103.2.1 2011/11/18 09:18:28 robert Exp $ */
24
25 #ifdef HAVE_CONFIG_H
26 # include <config.h>
27 #endif
28
29 #include "lame.h"
30 #include "lame-machine.h"
31 #include "encoder.h"
32 #include "util.h"
33 #include "bitstream.h"
34 #include "VbrTag.h"
35 #include "lame_global_flags.h"
36 #include "tables.h"
37
38 #ifdef __sun__
39 /* woraround for SunOS 4.x, it has SEEK_* defined here */
40 #include <unistd.h>
41 #endif
42
43
44 #ifdef _DEBUG
45 /* #define DEBUG_VBRTAG */
46 #endif
47
48 /*
49 * 4 bytes for Header Tag
50 * 4 bytes for Header Flags
51 * 100 bytes for entry (NUMTOCENTRIES)
52 * 4 bytes for FRAME SIZE
53 * 4 bytes for STREAM_SIZE
54 * 4 bytes for VBR SCALE. a VBR quality indicator: 0=best 100=worst
55 * 20 bytes for LAME tag. for example, "LAME3.12 (beta 6)"
56 * ___________
57 * 140 bytes
58 */
59 #define VBRHEADERSIZE (NUMTOCENTRIES+4+4+4+4+4)
60
61 #define LAMEHEADERSIZE (VBRHEADERSIZE + 9 + 1 + 1 + 8 + 1 + 1 + 3 + 1 + 1 + 2 + 4 + 2 + 2)
62
63 /* the size of the Xing header (MPEG1 and MPEG2) in kbps */
64 #define XING_BITRATE1 128
65 #define XING_BITRATE2 64
66 #define XING_BITRATE25 32
67
68 extern const char* get_lame_tag_encoder_short_version(void);
69
70 static const char VBRTag0[] = { "Xing" };
71 static const char VBRTag1[] = { "Info" };
72
73
74
75
76 /* Lookup table for fast CRC computation
77 * See 'CRC_update_lookup'
78 * Uses the polynomial x^16+x^15+x^2+1 */
79
80 static const unsigned int crc16_lookup[256] = {
81 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
82 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
83 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
84 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
85 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
86 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
87 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
88 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
89 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
90 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
91 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
92 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
93 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
94 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
95 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
96 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
97 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
98 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
99 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
100 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
101 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
102 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
103 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
104 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
105 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
106 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
107 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
108 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
109 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
110 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
111 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
112 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
113 };
114
115
116
117
118
119 /***********************************************************************
120 * Robert Hegemann 2001-01-17
121 ***********************************************************************/
122
123 static void
addVbr(VBR_seek_info_t * v,int bitrate)124 addVbr(VBR_seek_info_t * v, int bitrate)
125 {
126 int i;
127
128 v->nVbrNumFrames++;
129 v->sum += bitrate;
130 v->seen++;
131
132 if (v->seen < v->want) {
133 return;
134 }
135
136 if (v->pos < v->size) {
137 v->bag[v->pos] = v->sum;
138 v->pos++;
139 v->seen = 0;
140 }
141 if (v->pos == v->size) {
142 for (i = 1; i < v->size; i += 2) {
143 v->bag[i / 2] = v->bag[i];
144 }
145 v->want *= 2;
146 v->pos /= 2;
147 }
148 }
149
150 static void
Xing_seek_table(VBR_seek_info_t const * v,unsigned char * t)151 Xing_seek_table(VBR_seek_info_t const* v, unsigned char *t)
152 {
153 int i, indx;
154 int seek_point;
155
156 if (v->pos <= 0)
157 return;
158
159 for (i = 1; i < NUMTOCENTRIES; ++i) {
160 float j = i / (float) NUMTOCENTRIES, act, sum;
161 indx = (int) (floor(j * v->pos));
162 if (indx > v->pos - 1)
163 indx = v->pos - 1;
164 act = v->bag[indx];
165 sum = v->sum;
166 seek_point = (int) (256. * act / sum);
167 if (seek_point > 255)
168 seek_point = 255;
169 t[i] = seek_point;
170 }
171 }
172
173 #ifdef DEBUG_VBR_SEEKING_TABLE
174 static void
print_seeking(unsigned char * t)175 print_seeking(unsigned char *t)
176 {
177 int i;
178
179 printf("seeking table ");
180 for (i = 0; i < NUMTOCENTRIES; ++i) {
181 printf(" %d ", t[i]);
182 }
183 printf("\n");
184 }
185 #endif
186
187
188 /****************************************************************************
189 * AddVbrFrame: Add VBR entry, used to fill the VBR the TOC entries
190 * Paramters:
191 * nStreamPos: how many bytes did we write to the bitstream so far
192 * (in Bytes NOT Bits)
193 ****************************************************************************
194 */
195 void
AddVbrFrame(lame_internal_flags * gfc)196 AddVbrFrame(lame_internal_flags * gfc)
197 {
198 int kbps = bitrate_table[gfc->cfg.version][gfc->ov_enc.bitrate_index];
199 assert(gfc->VBR_seek_table.bag);
200 addVbr(&gfc->VBR_seek_table, kbps);
201 }
202
203
204 /*-------------------------------------------------------------*/
205 static int
ExtractI4(const unsigned char * buf)206 ExtractI4(const unsigned char *buf)
207 {
208 int x;
209 /* big endian extract */
210 x = buf[0];
211 x <<= 8;
212 x |= buf[1];
213 x <<= 8;
214 x |= buf[2];
215 x <<= 8;
216 x |= buf[3];
217 return x;
218 }
219
220 static void
CreateI4(unsigned char * buf,uint32_t nValue)221 CreateI4(unsigned char *buf, uint32_t nValue)
222 {
223 /* big endian create */
224 buf[0] = (nValue >> 24) & 0xff;
225 buf[1] = (nValue >> 16) & 0xff;
226 buf[2] = (nValue >> 8) & 0xff;
227 buf[3] = (nValue) & 0xff;
228 }
229
230
231
232 static void
CreateI2(unsigned char * buf,int nValue)233 CreateI2(unsigned char *buf, int nValue)
234 {
235 /* big endian create */
236 buf[0] = (nValue >> 8) & 0xff;
237 buf[1] = (nValue) & 0xff;
238 }
239
240 /* check for magic strings*/
241 static int
IsVbrTag(const unsigned char * buf)242 IsVbrTag(const unsigned char *buf)
243 {
244 int isTag0, isTag1;
245
246 isTag0 = ((buf[0] == VBRTag0[0]) && (buf[1] == VBRTag0[1]) && (buf[2] == VBRTag0[2])
247 && (buf[3] == VBRTag0[3]));
248 isTag1 = ((buf[0] == VBRTag1[0]) && (buf[1] == VBRTag1[1]) && (buf[2] == VBRTag1[2])
249 && (buf[3] == VBRTag1[3]));
250
251 return (isTag0 || isTag1);
252 }
253
254 #define SHIFT_IN_BITS_VALUE(x,n,v) ( x = (x << (n)) | ( (v) & ~(-1 << (n)) ) )
255
256 static void
setLameTagFrameHeader(lame_internal_flags const * gfc,unsigned char * buffer)257 setLameTagFrameHeader(lame_internal_flags const *gfc, unsigned char *buffer)
258 {
259 SessionConfig_t const *const cfg = &gfc->cfg;
260 EncResult_t const *const eov = &gfc->ov_enc;
261 char abyte, bbyte;
262
263 SHIFT_IN_BITS_VALUE(buffer[0], 8u, 0xffu);
264
265 SHIFT_IN_BITS_VALUE(buffer[1], 3u, 7);
266 SHIFT_IN_BITS_VALUE(buffer[1], 1u, (cfg->samplerate_out < 16000) ? 0 : 1);
267 SHIFT_IN_BITS_VALUE(buffer[1], 1u, cfg->version);
268 SHIFT_IN_BITS_VALUE(buffer[1], 2u, 4 - 3);
269 SHIFT_IN_BITS_VALUE(buffer[1], 1u, (!cfg->error_protection) ? 1 : 0);
270
271 SHIFT_IN_BITS_VALUE(buffer[2], 4u, eov->bitrate_index);
272 SHIFT_IN_BITS_VALUE(buffer[2], 2u, cfg->samplerate_index);
273 SHIFT_IN_BITS_VALUE(buffer[2], 1u, 0);
274 SHIFT_IN_BITS_VALUE(buffer[2], 1u, cfg->extension);
275
276 SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->mode);
277 SHIFT_IN_BITS_VALUE(buffer[3], 2u, eov->mode_ext);
278 SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->copyright);
279 SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->original);
280 SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->emphasis);
281
282 /* the default VBR header. 48 kbps layer III, no padding, no crc */
283 /* but sampling freq, mode andy copyright/copy protection taken */
284 /* from first valid frame */
285 buffer[0] = (uint8_t) 0xff;
286 abyte = (buffer[1] & (unsigned char) 0xf1);
287 {
288 int bitrate;
289 if (1 == cfg->version) {
290 bitrate = XING_BITRATE1;
291 }
292 else {
293 if (cfg->samplerate_out < 16000)
294 bitrate = XING_BITRATE25;
295 else
296 bitrate = XING_BITRATE2;
297 }
298
299 if (cfg->vbr == vbr_off)
300 bitrate = cfg->avg_bitrate;
301
302 if (cfg->free_format)
303 bbyte = 0x00;
304 else
305 bbyte = 16 * BitrateIndex(bitrate, cfg->version, cfg->samplerate_out);
306 }
307
308 /* Use as much of the info from the real frames in the
309 * Xing header: samplerate, channels, crc, etc...
310 */
311 if (cfg->version == 1) {
312 /* MPEG1 */
313 buffer[1] = abyte | (char) 0x0a; /* was 0x0b; */
314 abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
315 buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG1 frame */
316 }
317 else {
318 /* MPEG2 */
319 buffer[1] = abyte | (char) 0x02; /* was 0x03; */
320 abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
321 buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG2 frame */
322 }
323 }
324
325 #if 0
326 static int CheckVbrTag(unsigned char *buf);
327
328 /*-------------------------------------------------------------*/
329 /* Same as GetVbrTag below, but only checks for the Xing tag.
330 requires buf to contain only 40 bytes */
331 /*-------------------------------------------------------------*/
332 int
333 CheckVbrTag(unsigned char *buf)
334 {
335 int h_id, h_mode;
336
337 /* get selected MPEG header data */
338 h_id = (buf[1] >> 3) & 1;
339 h_mode = (buf[3] >> 6) & 3;
340
341 /* determine offset of header */
342 if (h_id) {
343 /* mpeg1 */
344 if (h_mode != 3)
345 buf += (32 + 4);
346 else
347 buf += (17 + 4);
348 }
349 else {
350 /* mpeg2 */
351 if (h_mode != 3)
352 buf += (17 + 4);
353 else
354 buf += (9 + 4);
355 }
356
357 return IsVbrTag(buf);
358 }
359 #endif
360
361 int
GetVbrTag(VBRTAGDATA * pTagData,const unsigned char * buf)362 GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf)
363 {
364 int i, head_flags;
365 int h_bitrate, h_id, h_mode, h_sr_index, h_layer;
366 int enc_delay, enc_padding;
367
368 /* get Vbr header data */
369 pTagData->flags = 0;
370
371 /* get selected MPEG header data */
372 h_layer = (buf[1] >> 1) & 3;
373 if ( h_layer != 0x01 ) {
374 /* the following code assumes Layer-3, so give up here */
375 return 0;
376 }
377 h_id = (buf[1] >> 3) & 1;
378 h_sr_index = (buf[2] >> 2) & 3;
379 h_mode = (buf[3] >> 6) & 3;
380 h_bitrate = ((buf[2] >> 4) & 0xf);
381 h_bitrate = bitrate_table[h_id][h_bitrate];
382
383 /* check for FFE syncword */
384 if ((buf[1] >> 4) == 0xE)
385 pTagData->samprate = samplerate_table[2][h_sr_index];
386 else
387 pTagData->samprate = samplerate_table[h_id][h_sr_index];
388 /* if( h_id == 0 ) */
389 /* pTagData->samprate >>= 1; */
390
391
392
393 /* determine offset of header */
394 if (h_id) {
395 /* mpeg1 */
396 if (h_mode != 3)
397 buf += (32 + 4);
398 else
399 buf += (17 + 4);
400 }
401 else {
402 /* mpeg2 */
403 if (h_mode != 3)
404 buf += (17 + 4);
405 else
406 buf += (9 + 4);
407 }
408
409 if (!IsVbrTag(buf))
410 return 0;
411
412 buf += 4;
413
414 pTagData->h_id = h_id;
415
416 head_flags = pTagData->flags = ExtractI4(buf);
417 buf += 4; /* get flags */
418
419 if (head_flags & FRAMES_FLAG) {
420 pTagData->frames = ExtractI4(buf);
421 buf += 4;
422 }
423
424 if (head_flags & BYTES_FLAG) {
425 pTagData->bytes = ExtractI4(buf);
426 buf += 4;
427 }
428
429 if (head_flags & TOC_FLAG) {
430 if (pTagData->toc != NULL) {
431 for (i = 0; i < NUMTOCENTRIES; i++)
432 pTagData->toc[i] = buf[i];
433 }
434 buf += NUMTOCENTRIES;
435 }
436
437 pTagData->vbr_scale = -1;
438
439 if (head_flags & VBR_SCALE_FLAG) {
440 pTagData->vbr_scale = ExtractI4(buf);
441 buf += 4;
442 }
443
444 pTagData->headersize = ((h_id + 1) * 72000 * h_bitrate) / pTagData->samprate;
445
446 buf += 21;
447 enc_delay = buf[0] << 4;
448 enc_delay += buf[1] >> 4;
449 enc_padding = (buf[1] & 0x0F) << 8;
450 enc_padding += buf[2];
451 /* check for reasonable values (this may be an old Xing header, */
452 /* not a INFO tag) */
453 if (enc_delay < 0 || enc_delay > 3000)
454 enc_delay = -1;
455 if (enc_padding < 0 || enc_padding > 3000)
456 enc_padding = -1;
457
458 pTagData->enc_delay = enc_delay;
459 pTagData->enc_padding = enc_padding;
460
461 #ifdef DEBUG_VBRTAG
462 fprintf(stderr, "\n\n********************* VBR TAG INFO *****************\n");
463 fprintf(stderr, "tag :%s\n", VBRTag);
464 fprintf(stderr, "head_flags :%d\n", head_flags);
465 fprintf(stderr, "bytes :%d\n", pTagData->bytes);
466 fprintf(stderr, "frames :%d\n", pTagData->frames);
467 fprintf(stderr, "VBR Scale :%d\n", pTagData->vbr_scale);
468 fprintf(stderr, "enc_delay = %i \n", enc_delay);
469 fprintf(stderr, "enc_padding= %i \n", enc_padding);
470 fprintf(stderr, "toc:\n");
471 if (pTagData->toc != NULL) {
472 for (i = 0; i < NUMTOCENTRIES; i++) {
473 if ((i % 10) == 0)
474 fprintf(stderr, "\n");
475 fprintf(stderr, " %3d", (int) (pTagData->toc[i]));
476 }
477 }
478 fprintf(stderr, "\n***************** END OF VBR TAG INFO ***************\n");
479 #endif
480 return 1; /* success */
481 }
482
483
484 /****************************************************************************
485 * InitVbrTag: Initializes the header, and write empty frame to stream
486 * Paramters:
487 * fpStream: pointer to output file stream
488 * nMode : Channel Mode: 0=STEREO 1=JS 2=DS 3=MONO
489 ****************************************************************************
490 */
491 int
InitVbrTag(lame_global_flags * gfp)492 InitVbrTag(lame_global_flags * gfp)
493 {
494 lame_internal_flags *gfc = gfp->internal_flags;
495 SessionConfig_t const *const cfg = &gfc->cfg;
496 int kbps_header;
497
498 #define MAXFRAMESIZE 2880 /* or 0xB40, the max freeformat 640 32kHz framesize */
499
500 /*
501 * Xing VBR pretends to be a 48kbs layer III frame. (at 44.1kHz).
502 * (at 48kHz they use 56kbs since 48kbs frame not big enough for
503 * table of contents)
504 * let's always embed Xing header inside a 64kbs layer III frame.
505 * this gives us enough room for a LAME version string too.
506 * size determined by sampling frequency (MPEG1)
507 * 32kHz: 216 bytes@48kbs 288bytes@ 64kbs
508 * 44.1kHz: 156 bytes 208bytes@64kbs (+1 if padding = 1)
509 * 48kHz: 144 bytes 192
510 *
511 * MPEG 2 values are the same since the framesize and samplerate
512 * are each reduced by a factor of 2.
513 */
514
515
516 if (1 == cfg->version) {
517 kbps_header = XING_BITRATE1;
518 }
519 else {
520 if (cfg->samplerate_out < 16000)
521 kbps_header = XING_BITRATE25;
522 else
523 kbps_header = XING_BITRATE2;
524 }
525
526 if (cfg->vbr == vbr_off)
527 kbps_header = cfg->avg_bitrate;
528
529 /** make sure LAME Header fits into Frame
530 */
531 {
532 int total_frame_size = ((cfg->version + 1) * 72000 * kbps_header) / cfg->samplerate_out;
533 int header_size = (cfg->sideinfo_len + LAMEHEADERSIZE);
534 gfc->VBR_seek_table.TotalFrameSize = total_frame_size;
535 if (total_frame_size < header_size || total_frame_size > MAXFRAMESIZE) {
536 /* disable tag, it wont fit */
537 gfc->cfg.write_lame_tag = 0;
538 return 0;
539 }
540 }
541
542 gfc->VBR_seek_table.nVbrNumFrames = 0;
543 gfc->VBR_seek_table.nBytesWritten = 0;
544 gfc->VBR_seek_table.sum = 0;
545
546 gfc->VBR_seek_table.seen = 0;
547 gfc->VBR_seek_table.want = 1;
548 gfc->VBR_seek_table.pos = 0;
549
550 if (gfc->VBR_seek_table.bag == NULL) {
551 gfc->VBR_seek_table.bag = malloc(400 * sizeof(int));
552 if (gfc->VBR_seek_table.bag != NULL) {
553 gfc->VBR_seek_table.size = 400;
554 }
555 else {
556 gfc->VBR_seek_table.size = 0;
557 ERRORF(gfc, "Error: can't allocate VbrFrames buffer\n");
558 gfc->cfg.write_lame_tag = 0;
559 return -1;
560 }
561 }
562
563 /* write dummy VBR tag of all 0's into bitstream */
564 {
565 uint8_t buffer[MAXFRAMESIZE];
566 size_t i, n;
567
568 memset(buffer, 0, sizeof(buffer));
569 setLameTagFrameHeader(gfc, buffer);
570 n = gfc->VBR_seek_table.TotalFrameSize;
571 for (i = 0; i < n; ++i) {
572 add_dummy_byte(gfc, buffer[i], 1);
573 }
574 }
575 /* Success */
576 return 0;
577 }
578
579
580
581 /* fast CRC-16 computation - uses table crc16_lookup 8*/
582 static uint16_t
CRC_update_lookup(uint16_t value,uint16_t crc)583 CRC_update_lookup(uint16_t value, uint16_t crc)
584 {
585 uint16_t tmp;
586 tmp = crc ^ value;
587 crc = (crc >> 8) ^ crc16_lookup[tmp & 0xff];
588 return crc;
589 }
590
591 void
UpdateMusicCRC(uint16_t * crc,unsigned char const * buffer,int size)592 UpdateMusicCRC(uint16_t * crc, unsigned char const *buffer, int size)
593 {
594 int i;
595 for (i = 0; i < size; ++i)
596 *crc = CRC_update_lookup(buffer[i], *crc);
597 }
598
599
600
601
602
603 /****************************************************************************
604 * Jonathan Dee 2001/08/31
605 *
606 * PutLameVBR: Write LAME info: mini version + info on various switches used
607 * Paramters:
608 * pbtStreamBuffer : pointer to output buffer
609 * id3v2size : size of id3v2 tag in bytes
610 * crc : computation of crc-16 of Lame Tag so far (starting at frame sync)
611 *
612 ****************************************************************************
613 */
614 static int
PutLameVBR(lame_global_flags const * gfp,size_t nMusicLength,uint8_t * pbtStreamBuffer,uint16_t crc)615 PutLameVBR(lame_global_flags const *gfp, size_t nMusicLength, uint8_t * pbtStreamBuffer, uint16_t crc)
616 {
617 lame_internal_flags const *gfc = gfp->internal_flags;
618 SessionConfig_t const *const cfg = &gfc->cfg;
619
620 int nBytesWritten = 0;
621 int i;
622
623 int enc_delay = gfc->ov_enc.encoder_delay; /* encoder delay */
624 int enc_padding = gfc->ov_enc.encoder_padding; /* encoder padding */
625
626 /*recall: cfg->vbr_q is for example set by the switch -V */
627 /* gfp->quality by -q, -h, -f, etc */
628
629 int nQuality = (100 - 10 * gfp->VBR_q - gfp->quality);
630
631
632 /*
633 NOTE:
634 Even though the specification for the LAME VBR tag
635 did explicitly mention other encoders than LAME,
636 many SW/HW decoder seem to be able to make use of
637 this tag only, if the encoder version starts with LAME.
638 To be compatible with such decoders, ANY encoder will
639 be forced to write a fake LAME version string!
640 As a result, the encoder version info becomes worthless.
641 */
642 const char *szVersion = get_lame_tag_encoder_short_version();
643 uint8_t nVBR;
644 uint8_t nRevision = 0x00;
645 uint8_t nRevMethod;
646 uint8_t vbr_type_translator[] = { 1, 5, 3, 2, 4, 0, 3 }; /*numbering different in vbr_mode vs. Lame tag */
647
648 uint8_t nLowpass =
649 (((cfg->lowpassfreq / 100.0) + .5) > 255 ? 255 : (cfg->lowpassfreq / 100.0) + .5);
650
651 uint32_t nPeakSignalAmplitude = 0;
652
653 uint16_t nRadioReplayGain = 0;
654 uint16_t nAudiophileReplayGain = 0;
655
656 uint8_t nNoiseShaping = cfg->noise_shaping;
657 uint8_t nStereoMode = 0;
658 int bNonOptimal = 0;
659 uint8_t nSourceFreq = 0;
660 uint8_t nMisc = 0;
661 uint16_t nMusicCRC = 0;
662
663 /*psy model type: Gpsycho or NsPsytune */
664 unsigned char bExpNPsyTune = 1; /* only NsPsytune */
665 unsigned char bSafeJoint = (cfg->use_safe_joint_stereo) != 0;
666
667 unsigned char bNoGapMore = 0;
668 unsigned char bNoGapPrevious = 0;
669
670 int nNoGapCount = gfp->nogap_total;
671 int nNoGapCurr = gfp->nogap_current;
672
673
674 uint8_t nAthType = cfg->ATHtype; /*4 bits. */
675
676 uint8_t nFlags = 0;
677
678 /* if ABR, {store bitrate <=255} else { store "-b"} */
679 int nABRBitrate;
680 switch (cfg->vbr) {
681 case vbr_abr:{
682 nABRBitrate = cfg->vbr_avg_bitrate_kbps;
683 break;
684 }
685 case vbr_off:{
686 nABRBitrate = cfg->avg_bitrate;
687 break;
688 }
689 default:{ /*vbr modes */
690 nABRBitrate = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];;
691 }
692 }
693
694
695 /*revision and vbr method */
696 if (cfg->vbr < sizeof(vbr_type_translator))
697 nVBR = vbr_type_translator[cfg->vbr];
698 else
699 nVBR = 0x00; /*unknown. */
700
701 nRevMethod = 0x10 * nRevision + nVBR;
702
703
704 /* ReplayGain */
705 if (cfg->findReplayGain) {
706 int RadioGain = gfc->ov_rpg.RadioGain;
707 if (RadioGain > 0x1FE)
708 RadioGain = 0x1FE;
709 if (RadioGain < -0x1FE)
710 RadioGain = -0x1FE;
711
712 nRadioReplayGain = 0x2000; /* set name code */
713 nRadioReplayGain |= 0xC00; /* set originator code to `determined automatically' */
714
715 if (RadioGain >= 0)
716 nRadioReplayGain |= RadioGain; /* set gain adjustment */
717 else {
718 nRadioReplayGain |= 0x200; /* set the sign bit */
719 nRadioReplayGain |= -RadioGain; /* set gain adjustment */
720 }
721 }
722
723 /* peak sample */
724 if (cfg->findPeakSample)
725 nPeakSignalAmplitude =
726 abs((int) ((((FLOAT) gfc->ov_rpg.PeakSample) / 32767.0) * pow(2, 23) + .5));
727
728 /*nogap */
729 if (nNoGapCount != -1) {
730 if (nNoGapCurr > 0)
731 bNoGapPrevious = 1;
732
733 if (nNoGapCurr < nNoGapCount - 1)
734 bNoGapMore = 1;
735 }
736
737 /*flags */
738
739 nFlags = nAthType + (bExpNPsyTune << 4)
740 + (bSafeJoint << 5)
741 + (bNoGapMore << 6)
742 + (bNoGapPrevious << 7);
743
744
745 if (nQuality < 0)
746 nQuality = 0;
747
748 /*stereo mode field... a bit ugly. */
749
750 switch (cfg->mode) {
751 case MONO:
752 nStereoMode = 0;
753 break;
754 case STEREO:
755 nStereoMode = 1;
756 break;
757 case DUAL_CHANNEL:
758 nStereoMode = 2;
759 break;
760 case JOINT_STEREO:
761 if (cfg->force_ms)
762 nStereoMode = 4;
763 else
764 nStereoMode = 3;
765 break;
766 case NOT_SET:
767 /* FALLTHROUGH */
768 default:
769 nStereoMode = 7;
770 break;
771 }
772
773 /*Intensity stereo : nStereoMode = 6. IS is not implemented */
774
775 if (cfg->samplerate_in <= 32000)
776 nSourceFreq = 0x00;
777 else if (cfg->samplerate_in == 48000)
778 nSourceFreq = 0x02;
779 else if (cfg->samplerate_in > 48000)
780 nSourceFreq = 0x03;
781 else
782 nSourceFreq = 0x01; /*default is 44100Hz. */
783
784
785 /*Check if the user overrided the default LAME behaviour with some nasty options */
786
787 if (cfg->short_blocks == short_block_forced || cfg->short_blocks == short_block_dispensed || ((cfg->lowpassfreq == -1) && (cfg->highpassfreq == -1)) || /* "-k" */
788 (cfg->disable_reservoir && cfg->avg_bitrate < 320) ||
789 cfg->noATH || cfg->ATHonly || (nAthType == 0) || cfg->samplerate_in <= 32000)
790 bNonOptimal = 1;
791
792 nMisc = nNoiseShaping + (nStereoMode << 2)
793 + (bNonOptimal << 5)
794 + (nSourceFreq << 6);
795
796
797 nMusicCRC = gfc->nMusicCRC;
798
799
800 /*Write all this information into the stream */
801 CreateI4(&pbtStreamBuffer[nBytesWritten], nQuality);
802 nBytesWritten += 4;
803
804 strncpy((char *) &pbtStreamBuffer[nBytesWritten], szVersion, 9);
805 nBytesWritten += 9;
806
807 pbtStreamBuffer[nBytesWritten] = nRevMethod;
808 nBytesWritten++;
809
810 pbtStreamBuffer[nBytesWritten] = nLowpass;
811 nBytesWritten++;
812
813 CreateI4(&pbtStreamBuffer[nBytesWritten], nPeakSignalAmplitude);
814 nBytesWritten += 4;
815
816 CreateI2(&pbtStreamBuffer[nBytesWritten], nRadioReplayGain);
817 nBytesWritten += 2;
818
819 CreateI2(&pbtStreamBuffer[nBytesWritten], nAudiophileReplayGain);
820 nBytesWritten += 2;
821
822 pbtStreamBuffer[nBytesWritten] = nFlags;
823 nBytesWritten++;
824
825 if (nABRBitrate >= 255)
826 pbtStreamBuffer[nBytesWritten] = 0xFF;
827 else
828 pbtStreamBuffer[nBytesWritten] = nABRBitrate;
829 nBytesWritten++;
830
831 pbtStreamBuffer[nBytesWritten] = enc_delay >> 4; /* works for win32, does it for unix? */
832 pbtStreamBuffer[nBytesWritten + 1] = (enc_delay << 4) + (enc_padding >> 8);
833 pbtStreamBuffer[nBytesWritten + 2] = enc_padding;
834
835 nBytesWritten += 3;
836
837 pbtStreamBuffer[nBytesWritten] = nMisc;
838 nBytesWritten++;
839
840
841 pbtStreamBuffer[nBytesWritten++] = 0; /*unused in rev0 */
842
843 CreateI2(&pbtStreamBuffer[nBytesWritten], cfg->preset);
844 nBytesWritten += 2;
845
846 CreateI4(&pbtStreamBuffer[nBytesWritten], (int) nMusicLength);
847 nBytesWritten += 4;
848
849 CreateI2(&pbtStreamBuffer[nBytesWritten], nMusicCRC);
850 nBytesWritten += 2;
851
852 /*Calculate tag CRC.... must be done here, since it includes
853 *previous information*/
854
855 for (i = 0; i < nBytesWritten; i++)
856 crc = CRC_update_lookup(pbtStreamBuffer[i], crc);
857
858 CreateI2(&pbtStreamBuffer[nBytesWritten], crc);
859 nBytesWritten += 2;
860
861 return nBytesWritten;
862 }
863
864 static long
skipId3v2(FILE * fpStream)865 skipId3v2(FILE * fpStream)
866 {
867 size_t nbytes;
868 long id3v2TagSize;
869 unsigned char id3v2Header[10];
870
871 /* seek to the beginning of the stream */
872 if (fseek(fpStream, 0, SEEK_SET) != 0) {
873 return -2; /* not seekable, abort */
874 }
875 /* read 10 bytes in case there's an ID3 version 2 header here */
876 nbytes = fread(id3v2Header, 1, sizeof(id3v2Header), fpStream);
877 if (nbytes != sizeof(id3v2Header)) {
878 return -3; /* not readable, maybe opened Write-Only */
879 }
880 /* does the stream begin with the ID3 version 2 file identifier? */
881 if (!strncmp((char *) id3v2Header, "ID3", 3)) {
882 /* the tag size (minus the 10-byte header) is encoded into four
883 * bytes where the most significant bit is clear in each byte */
884 id3v2TagSize = (((id3v2Header[6] & 0x7f) << 21)
885 | ((id3v2Header[7] & 0x7f) << 14)
886 | ((id3v2Header[8] & 0x7f) << 7)
887 | (id3v2Header[9] & 0x7f))
888 + sizeof id3v2Header;
889 }
890 else {
891 /* no ID3 version 2 tag in this stream */
892 id3v2TagSize = 0;
893 }
894 return id3v2TagSize;
895 }
896
897
898
899 size_t
lame_get_lametag_frame(lame_global_flags const * gfp,unsigned char * buffer,size_t size)900 lame_get_lametag_frame(lame_global_flags const *gfp, unsigned char *buffer, size_t size)
901 {
902 lame_internal_flags *gfc;
903 SessionConfig_t const *cfg;
904 unsigned long stream_size;
905 unsigned int nStreamIndex;
906 uint8_t btToc[NUMTOCENTRIES];
907
908 if (gfp == 0) {
909 return 0;
910 }
911 gfc = gfp->internal_flags;
912 if (gfc == 0) {
913 return 0;
914 }
915 if (gfc->class_id != LAME_ID) {
916 return 0;
917 }
918 cfg = &gfc->cfg;
919 if (cfg->write_lame_tag == 0) {
920 return 0;
921 }
922 if (gfc->VBR_seek_table.pos <= 0) {
923 return 0;
924 }
925 if (size < gfc->VBR_seek_table.TotalFrameSize) {
926 return gfc->VBR_seek_table.TotalFrameSize;
927 }
928 if (buffer == 0) {
929 return 0;
930 }
931
932 memset(buffer, 0, gfc->VBR_seek_table.TotalFrameSize);
933
934 /* 4 bytes frame header */
935
936 setLameTagFrameHeader(gfc, buffer);
937
938 /* Clear all TOC entries */
939 memset(btToc, 0, sizeof(btToc));
940
941 if (cfg->free_format) {
942 int i;
943 for (i = 1; i < NUMTOCENTRIES; ++i)
944 btToc[i] = 255 * i / 100;
945 }
946 else {
947 Xing_seek_table(&gfc->VBR_seek_table, btToc);
948 }
949 #ifdef DEBUG_VBR_SEEKING_TABLE
950 print_seeking(btToc);
951 #endif
952
953 /* Start writing the tag after the zero frame */
954 nStreamIndex = cfg->sideinfo_len;
955 /* note! Xing header specifies that Xing data goes in the
956 * ancillary data with NO ERROR PROTECTION. If error protecton
957 * in enabled, the Xing data still starts at the same offset,
958 * and now it is in sideinfo data block, and thus will not
959 * decode correctly by non-Xing tag aware players */
960 if (cfg->error_protection)
961 nStreamIndex -= 2;
962
963 /* Put Vbr tag */
964 if (cfg->vbr == vbr_off) {
965 buffer[nStreamIndex++] = VBRTag1[0];
966 buffer[nStreamIndex++] = VBRTag1[1];
967 buffer[nStreamIndex++] = VBRTag1[2];
968 buffer[nStreamIndex++] = VBRTag1[3];
969
970 }
971 else {
972 buffer[nStreamIndex++] = VBRTag0[0];
973 buffer[nStreamIndex++] = VBRTag0[1];
974 buffer[nStreamIndex++] = VBRTag0[2];
975 buffer[nStreamIndex++] = VBRTag0[3];
976 }
977
978 /* Put header flags */
979 CreateI4(&buffer[nStreamIndex], FRAMES_FLAG + BYTES_FLAG + TOC_FLAG + VBR_SCALE_FLAG);
980 nStreamIndex += 4;
981
982 /* Put Total Number of frames */
983 CreateI4(&buffer[nStreamIndex], gfc->VBR_seek_table.nVbrNumFrames);
984 nStreamIndex += 4;
985
986 /* Put total audio stream size, including Xing/LAME Header */
987 stream_size = gfc->VBR_seek_table.nBytesWritten + gfc->VBR_seek_table.TotalFrameSize;
988 CreateI4(&buffer[nStreamIndex], stream_size);
989 nStreamIndex += 4;
990
991 /* Put TOC */
992 memcpy(&buffer[nStreamIndex], btToc, sizeof(btToc));
993 nStreamIndex += sizeof(btToc);
994
995
996 if (cfg->error_protection) {
997 /* (jo) error_protection: add crc16 information to header */
998 CRC_writeheader(gfc, (char *) buffer);
999 }
1000 {
1001 /*work out CRC so far: initially crc = 0 */
1002 uint16_t crc = 0x00;
1003 unsigned int i;
1004 for (i = 0; i < nStreamIndex; i++)
1005 crc = CRC_update_lookup(buffer[i], crc);
1006 /*Put LAME VBR info */
1007 nStreamIndex += PutLameVBR(gfp, stream_size, buffer + nStreamIndex, crc);
1008 }
1009
1010 #ifdef DEBUG_VBRTAG
1011 {
1012 VBRTAGDATA TestHeader;
1013 GetVbrTag(&TestHeader, buffer);
1014 }
1015 #endif
1016
1017 return gfc->VBR_seek_table.TotalFrameSize;
1018 }
1019
1020 /***********************************************************************
1021 *
1022 * PutVbrTag: Write final VBR tag to the file
1023 * Paramters:
1024 * lpszFileName: filename of MP3 bit stream
1025 * nVbrScale : encoder quality indicator (0..100)
1026 ****************************************************************************
1027 */
1028
1029 int
PutVbrTag(lame_global_flags const * gfp,FILE * fpStream)1030 PutVbrTag(lame_global_flags const *gfp, FILE * fpStream)
1031 {
1032 lame_internal_flags *gfc = gfp->internal_flags;
1033
1034 long lFileSize;
1035 long id3v2TagSize;
1036 size_t nbytes;
1037 uint8_t buffer[MAXFRAMESIZE];
1038
1039 if (gfc->VBR_seek_table.pos <= 0)
1040 return -1;
1041
1042 /* Seek to end of file */
1043 fseek(fpStream, 0, SEEK_END);
1044
1045 /* Get file size */
1046 lFileSize = ftell(fpStream);
1047
1048 /* Abort if file has zero length. Yes, it can happen :) */
1049 if (lFileSize == 0)
1050 return -1;
1051
1052 /*
1053 * The VBR tag may NOT be located at the beginning of the stream.
1054 * If an ID3 version 2 tag was added, then it must be skipped to write
1055 * the VBR tag data.
1056 */
1057
1058 id3v2TagSize = skipId3v2(fpStream);
1059
1060 if (id3v2TagSize < 0) {
1061 return id3v2TagSize;
1062 }
1063
1064 /*Seek to the beginning of the stream */
1065 fseek(fpStream, id3v2TagSize, SEEK_SET);
1066
1067 nbytes = lame_get_lametag_frame(gfp, buffer, sizeof(buffer));
1068 if (nbytes > sizeof(buffer)) {
1069 return -1;
1070 }
1071
1072 if (nbytes < 1) {
1073 return 0;
1074 }
1075
1076 /* Put it all to disk again */
1077 if (fwrite(buffer, nbytes, 1, fpStream) != 1) {
1078 return -1;
1079 }
1080
1081 return 0; /* success */
1082 }
1083