2 * Xing VBR tagging for LAME.
4 * Copyright (c) 1999 A.L. Faber
5 * Copyright (c) 2001 Jonathan Dee
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.
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.
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.
23 /* $Id: VbrTag.c,v 1.103.2.1 2011/11/18 09:18:28 robert Exp $ */
33 #include "bitstream.h"
35 #include "lame_global_flags.h"
39 /* woraround for SunOS 4.x, it has SEEK_* defined here */
45 /* #define DEBUG_VBRTAG */
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)"
59 #define VBRHEADERSIZE (NUMTOCENTRIES+4+4+4+4+4)
61 #define LAMEHEADERSIZE (VBRHEADERSIZE + 9 + 1 + 1 + 8 + 1 + 1 + 3 + 1 + 1 + 2 + 4 + 2 + 2)
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
68 extern const char* get_lame_tag_encoder_short_version(void);
70 static const char VBRTag0[] = { "Xing" };
71 static const char VBRTag1[] = { "Info" };
76 /* Lookup table for fast CRC computation
77 * See 'CRC_update_lookup'
78 * Uses the polynomial x^16+x^15+x^2+1 */
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
119 /***********************************************************************
120 * Robert Hegemann 2001-01-17
121 ***********************************************************************/
124 addVbr(VBR_seek_info_t * v, int bitrate)
132 if (v->seen < v->want) {
136 if (v->pos < v->size) {
137 v->bag[v->pos] = v->sum;
141 if (v->pos == v->size) {
142 for (i = 1; i < v->size; i += 2) {
143 v->bag[i / 2] = v->bag[i];
151 Xing_seek_table(VBR_seek_info_t const* v, unsigned char *t)
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)
166 seek_point = (int) (256. * act / sum);
167 if (seek_point > 255)
173 #ifdef DEBUG_VBR_SEEKING_TABLE
175 print_seeking(unsigned char *t)
179 printf("seeking table ");
180 for (i = 0; i < NUMTOCENTRIES; ++i) {
181 printf(" %d ", t[i]);
188 /****************************************************************************
189 * AddVbrFrame: Add VBR entry, used to fill the VBR the TOC entries
191 * nStreamPos: how many bytes did we write to the bitstream so far
192 * (in Bytes NOT Bits)
193 ****************************************************************************
196 AddVbrFrame(lame_internal_flags * gfc)
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);
204 /*-------------------------------------------------------------*/
206 ExtractI4(const unsigned char *buf)
209 /* big endian extract */
221 CreateI4(unsigned char *buf, uint32_t nValue)
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;
233 CreateI2(unsigned char *buf, int nValue)
235 /* big endian create */
236 buf[0] = (nValue >> 8) & 0xff;
237 buf[1] = (nValue) & 0xff;
240 /* check for magic strings*/
242 IsVbrTag(const unsigned char *buf)
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]));
251 return (isTag0 || isTag1);
254 #define SHIFT_IN_BITS_VALUE(x,n,v) ( x = (x << (n)) | ( (v) & ~(-1 << (n)) ) )
257 setLameTagFrameHeader(lame_internal_flags const *gfc, unsigned char *buffer)
259 SessionConfig_t const *const cfg = &gfc->cfg;
260 EncResult_t const *const eov = &gfc->ov_enc;
263 SHIFT_IN_BITS_VALUE(buffer[0], 8u, 0xffu);
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);
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);
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);
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);
289 if (1 == cfg->version) {
290 bitrate = XING_BITRATE1;
293 if (cfg->samplerate_out < 16000)
294 bitrate = XING_BITRATE25;
296 bitrate = XING_BITRATE2;
299 if (cfg->vbr == vbr_off)
300 bitrate = cfg->avg_bitrate;
302 if (cfg->free_format)
305 bbyte = 16 * BitrateIndex(bitrate, cfg->version, cfg->samplerate_out);
308 /* Use as much of the info from the real frames in the
309 * Xing header: samplerate, channels, crc, etc...
311 if (cfg->version == 1) {
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 */
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 */
326 static int CheckVbrTag(unsigned char *buf);
328 /*-------------------------------------------------------------*/
329 /* Same as GetVbrTag below, but only checks for the Xing tag.
330 requires buf to contain only 40 bytes */
331 /*-------------------------------------------------------------*/
333 CheckVbrTag(unsigned char *buf)
337 /* get selected MPEG header data */
338 h_id = (buf[1] >> 3) & 1;
339 h_mode = (buf[3] >> 6) & 3;
341 /* determine offset of header */
357 return IsVbrTag(buf);
362 GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf)
365 int h_bitrate, h_id, h_mode, h_sr_index, h_layer;
366 int enc_delay, enc_padding;
368 /* get Vbr header data */
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 */
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];
383 /* check for FFE syncword */
384 if ((buf[1] >> 4) == 0xE)
385 pTagData->samprate = samplerate_table[2][h_sr_index];
387 pTagData->samprate = samplerate_table[h_id][h_sr_index];
388 /* if( h_id == 0 ) */
389 /* pTagData->samprate >>= 1; */
393 /* determine offset of header */
414 pTagData->h_id = h_id;
416 head_flags = pTagData->flags = ExtractI4(buf);
417 buf += 4; /* get flags */
419 if (head_flags & FRAMES_FLAG) {
420 pTagData->frames = ExtractI4(buf);
424 if (head_flags & BYTES_FLAG) {
425 pTagData->bytes = ExtractI4(buf);
429 if (head_flags & TOC_FLAG) {
430 if (pTagData->toc != NULL) {
431 for (i = 0; i < NUMTOCENTRIES; i++)
432 pTagData->toc[i] = buf[i];
434 buf += NUMTOCENTRIES;
437 pTagData->vbr_scale = -1;
439 if (head_flags & VBR_SCALE_FLAG) {
440 pTagData->vbr_scale = ExtractI4(buf);
444 pTagData->headersize = ((h_id + 1) * 72000 * h_bitrate) / pTagData->samprate;
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)
455 if (enc_padding < 0 || enc_padding > 3000)
458 pTagData->enc_delay = enc_delay;
459 pTagData->enc_padding = enc_padding;
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++) {
474 fprintf(stderr, "\n");
475 fprintf(stderr, " %3d", (int) (pTagData->toc[i]));
478 fprintf(stderr, "\n***************** END OF VBR TAG INFO ***************\n");
480 return 1; /* success */
484 /****************************************************************************
485 * InitVbrTag: Initializes the header, and write empty frame to stream
487 * fpStream: pointer to output file stream
488 * nMode : Channel Mode: 0=STEREO 1=JS 2=DS 3=MONO
489 ****************************************************************************
492 InitVbrTag(lame_global_flags * gfp)
494 lame_internal_flags *gfc = gfp->internal_flags;
495 SessionConfig_t const *const cfg = &gfc->cfg;
498 #define MAXFRAMESIZE 2880 /* or 0xB40, the max freeformat 640 32kHz framesize */
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
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
511 * MPEG 2 values are the same since the framesize and samplerate
512 * are each reduced by a factor of 2.
516 if (1 == cfg->version) {
517 kbps_header = XING_BITRATE1;
520 if (cfg->samplerate_out < 16000)
521 kbps_header = XING_BITRATE25;
523 kbps_header = XING_BITRATE2;
526 if (cfg->vbr == vbr_off)
527 kbps_header = cfg->avg_bitrate;
529 /** make sure LAME Header fits into Frame
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;
542 gfc->VBR_seek_table.nVbrNumFrames = 0;
543 gfc->VBR_seek_table.nBytesWritten = 0;
544 gfc->VBR_seek_table.sum = 0;
546 gfc->VBR_seek_table.seen = 0;
547 gfc->VBR_seek_table.want = 1;
548 gfc->VBR_seek_table.pos = 0;
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;
556 gfc->VBR_seek_table.size = 0;
557 ERRORF(gfc, "Error: can't allocate VbrFrames buffer\n");
558 gfc->cfg.write_lame_tag = 0;
563 /* write dummy VBR tag of all 0's into bitstream */
565 uint8_t buffer[MAXFRAMESIZE];
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);
581 /* fast CRC-16 computation - uses table crc16_lookup 8*/
583 CRC_update_lookup(uint16_t value, uint16_t crc)
587 crc = (crc >> 8) ^ crc16_lookup[tmp & 0xff];
592 UpdateMusicCRC(uint16_t * crc, unsigned char const *buffer, int size)
595 for (i = 0; i < size; ++i)
596 *crc = CRC_update_lookup(buffer[i], *crc);
603 /****************************************************************************
604 * Jonathan Dee 2001/08/31
606 * PutLameVBR: Write LAME info: mini version + info on various switches used
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)
612 ****************************************************************************
615 PutLameVBR(lame_global_flags const *gfp, size_t nMusicLength, uint8_t * pbtStreamBuffer, uint16_t crc)
617 lame_internal_flags const *gfc = gfp->internal_flags;
618 SessionConfig_t const *const cfg = &gfc->cfg;
620 int nBytesWritten = 0;
623 int enc_delay = gfc->ov_enc.encoder_delay; /* encoder delay */
624 int enc_padding = gfc->ov_enc.encoder_padding; /* encoder padding */
626 /*recall: cfg->vbr_q is for example set by the switch -V */
627 /* gfp->quality by -q, -h, -f, etc */
629 int nQuality = (100 - 10 * gfp->VBR_q - gfp->quality);
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.
642 const char *szVersion = get_lame_tag_encoder_short_version();
644 uint8_t nRevision = 0x00;
646 uint8_t vbr_type_translator[] = { 1, 5, 3, 2, 4, 0, 3 }; /*numbering different in vbr_mode vs. Lame tag */
649 (((cfg->lowpassfreq / 100.0) + .5) > 255 ? 255 : (cfg->lowpassfreq / 100.0) + .5);
651 uint32_t nPeakSignalAmplitude = 0;
653 uint16_t nRadioReplayGain = 0;
654 uint16_t nAudiophileReplayGain = 0;
656 uint8_t nNoiseShaping = cfg->noise_shaping;
657 uint8_t nStereoMode = 0;
659 uint8_t nSourceFreq = 0;
661 uint16_t nMusicCRC = 0;
663 /*psy model type: Gpsycho or NsPsytune */
664 unsigned char bExpNPsyTune = 1; /* only NsPsytune */
665 unsigned char bSafeJoint = (cfg->use_safe_joint_stereo) != 0;
667 unsigned char bNoGapMore = 0;
668 unsigned char bNoGapPrevious = 0;
670 int nNoGapCount = gfp->nogap_total;
671 int nNoGapCurr = gfp->nogap_current;
674 uint8_t nAthType = cfg->ATHtype; /*4 bits. */
678 /* if ABR, {store bitrate <=255} else { store "-b"} */
682 nABRBitrate = cfg->vbr_avg_bitrate_kbps;
686 nABRBitrate = cfg->avg_bitrate;
689 default:{ /*vbr modes */
690 nABRBitrate = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];;
695 /*revision and vbr method */
696 if (cfg->vbr < sizeof(vbr_type_translator))
697 nVBR = vbr_type_translator[cfg->vbr];
699 nVBR = 0x00; /*unknown. */
701 nRevMethod = 0x10 * nRevision + nVBR;
705 if (cfg->findReplayGain) {
706 int RadioGain = gfc->ov_rpg.RadioGain;
707 if (RadioGain > 0x1FE)
709 if (RadioGain < -0x1FE)
712 nRadioReplayGain = 0x2000; /* set name code */
713 nRadioReplayGain |= 0xC00; /* set originator code to `determined automatically' */
716 nRadioReplayGain |= RadioGain; /* set gain adjustment */
718 nRadioReplayGain |= 0x200; /* set the sign bit */
719 nRadioReplayGain |= -RadioGain; /* set gain adjustment */
724 if (cfg->findPeakSample)
725 nPeakSignalAmplitude =
726 abs((int) ((((FLOAT) gfc->ov_rpg.PeakSample) / 32767.0) * pow(2, 23) + .5));
729 if (nNoGapCount != -1) {
733 if (nNoGapCurr < nNoGapCount - 1)
739 nFlags = nAthType + (bExpNPsyTune << 4)
742 + (bNoGapPrevious << 7);
748 /*stereo mode field... a bit ugly. */
773 /*Intensity stereo : nStereoMode = 6. IS is not implemented */
775 if (cfg->samplerate_in <= 32000)
777 else if (cfg->samplerate_in == 48000)
779 else if (cfg->samplerate_in > 48000)
782 nSourceFreq = 0x01; /*default is 44100Hz. */
785 /*Check if the user overrided the default LAME behaviour with some nasty options */
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)
792 nMisc = nNoiseShaping + (nStereoMode << 2)
794 + (nSourceFreq << 6);
797 nMusicCRC = gfc->nMusicCRC;
800 /*Write all this information into the stream */
801 CreateI4(&pbtStreamBuffer[nBytesWritten], nQuality);
804 strncpy((char *) &pbtStreamBuffer[nBytesWritten], szVersion, 9);
807 pbtStreamBuffer[nBytesWritten] = nRevMethod;
810 pbtStreamBuffer[nBytesWritten] = nLowpass;
813 CreateI4(&pbtStreamBuffer[nBytesWritten], nPeakSignalAmplitude);
816 CreateI2(&pbtStreamBuffer[nBytesWritten], nRadioReplayGain);
819 CreateI2(&pbtStreamBuffer[nBytesWritten], nAudiophileReplayGain);
822 pbtStreamBuffer[nBytesWritten] = nFlags;
825 if (nABRBitrate >= 255)
826 pbtStreamBuffer[nBytesWritten] = 0xFF;
828 pbtStreamBuffer[nBytesWritten] = nABRBitrate;
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;
837 pbtStreamBuffer[nBytesWritten] = nMisc;
841 pbtStreamBuffer[nBytesWritten++] = 0; /*unused in rev0 */
843 CreateI2(&pbtStreamBuffer[nBytesWritten], cfg->preset);
846 CreateI4(&pbtStreamBuffer[nBytesWritten], (int) nMusicLength);
849 CreateI2(&pbtStreamBuffer[nBytesWritten], nMusicCRC);
852 /*Calculate tag CRC.... must be done here, since it includes
853 *previous information*/
855 for (i = 0; i < nBytesWritten; i++)
856 crc = CRC_update_lookup(pbtStreamBuffer[i], crc);
858 CreateI2(&pbtStreamBuffer[nBytesWritten], crc);
861 return nBytesWritten;
865 skipId3v2(FILE * fpStream)
869 unsigned char id3v2Header[10];
871 /* seek to the beginning of the stream */
872 if (fseek(fpStream, 0, SEEK_SET) != 0) {
873 return -2; /* not seekable, abort */
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 */
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;
891 /* no ID3 version 2 tag in this stream */
900 lame_get_lametag_frame(lame_global_flags const *gfp, unsigned char *buffer, size_t size)
902 lame_internal_flags *gfc;
903 SessionConfig_t const *cfg;
904 unsigned long stream_size;
905 unsigned int nStreamIndex;
906 uint8_t btToc[NUMTOCENTRIES];
911 gfc = gfp->internal_flags;
915 if (gfc->class_id != LAME_ID) {
919 if (cfg->write_lame_tag == 0) {
922 if (gfc->VBR_seek_table.pos <= 0) {
925 if (size < gfc->VBR_seek_table.TotalFrameSize) {
926 return gfc->VBR_seek_table.TotalFrameSize;
932 memset(buffer, 0, gfc->VBR_seek_table.TotalFrameSize);
934 /* 4 bytes frame header */
936 setLameTagFrameHeader(gfc, buffer);
938 /* Clear all TOC entries */
939 memset(btToc, 0, sizeof(btToc));
941 if (cfg->free_format) {
943 for (i = 1; i < NUMTOCENTRIES; ++i)
944 btToc[i] = 255 * i / 100;
947 Xing_seek_table(&gfc->VBR_seek_table, btToc);
949 #ifdef DEBUG_VBR_SEEKING_TABLE
950 print_seeking(btToc);
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)
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];
972 buffer[nStreamIndex++] = VBRTag0[0];
973 buffer[nStreamIndex++] = VBRTag0[1];
974 buffer[nStreamIndex++] = VBRTag0[2];
975 buffer[nStreamIndex++] = VBRTag0[3];
978 /* Put header flags */
979 CreateI4(&buffer[nStreamIndex], FRAMES_FLAG + BYTES_FLAG + TOC_FLAG + VBR_SCALE_FLAG);
982 /* Put Total Number of frames */
983 CreateI4(&buffer[nStreamIndex], gfc->VBR_seek_table.nVbrNumFrames);
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);
992 memcpy(&buffer[nStreamIndex], btToc, sizeof(btToc));
993 nStreamIndex += sizeof(btToc);
996 if (cfg->error_protection) {
997 /* (jo) error_protection: add crc16 information to header */
998 CRC_writeheader(gfc, (char *) buffer);
1001 /*work out CRC so far: initially crc = 0 */
1002 uint16_t crc = 0x00;
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);
1012 VBRTAGDATA TestHeader;
1013 GetVbrTag(&TestHeader, buffer);
1017 return gfc->VBR_seek_table.TotalFrameSize;
1020 /***********************************************************************
1022 * PutVbrTag: Write final VBR tag to the file
1024 * lpszFileName: filename of MP3 bit stream
1025 * nVbrScale : encoder quality indicator (0..100)
1026 ****************************************************************************
1030 PutVbrTag(lame_global_flags const *gfp, FILE * fpStream)
1032 lame_internal_flags *gfc = gfp->internal_flags;
1037 uint8_t buffer[MAXFRAMESIZE];
1039 if (gfc->VBR_seek_table.pos <= 0)
1042 /* Seek to end of file */
1043 fseek(fpStream, 0, SEEK_END);
1046 lFileSize = ftell(fpStream);
1048 /* Abort if file has zero length. Yes, it can happen :) */
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
1058 id3v2TagSize = skipId3v2(fpStream);
1060 if (id3v2TagSize < 0) {
1061 return id3v2TagSize;
1064 /*Seek to the beginning of the stream */
1065 fseek(fpStream, id3v2TagSize, SEEK_SET);
1067 nbytes = lame_get_lametag_frame(gfp, buffer, sizeof(buffer));
1068 if (nbytes > sizeof(buffer)) {
1076 /* Put it all to disk again */
1077 if (fwrite(buffer, nbytes, 1, fpStream) != 1) {
1081 return 0; /* success */