• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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$ */
24 
25 #ifdef HAVE_CONFIG_H
26 # include <config.h>
27 #endif
28 
29 #include "lame.h"
30 #include "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 #include "VbrTagCrc.h"
81 
82 
83 
84 
85 
86 /***********************************************************************
87  *  Robert Hegemann 2001-01-17
88  ***********************************************************************/
89 
90 static void
addVbr(VBR_seek_info_t * v,int bitrate)91 addVbr(VBR_seek_info_t * v, int bitrate)
92 {
93     int     i;
94 
95     v->nVbrNumFrames++;
96     v->sum += bitrate;
97     v->seen++;
98 
99     if (v->seen < v->want) {
100         return;
101     }
102 
103     if (v->pos < v->size) {
104         v->bag[v->pos] = v->sum;
105         v->pos++;
106         v->seen = 0;
107     }
108     if (v->pos == v->size) {
109         for (i = 1; i < v->size; i += 2) {
110             v->bag[i / 2] = v->bag[i];
111         }
112         v->want *= 2;
113         v->pos /= 2;
114     }
115 }
116 
117 static void
Xing_seek_table(VBR_seek_info_t const * v,unsigned char * t)118 Xing_seek_table(VBR_seek_info_t const* v, unsigned char *t)
119 {
120     int     i, indx;
121     int     seek_point;
122 
123     if (v->pos <= 0)
124         return;
125 
126     for (i = 1; i < NUMTOCENTRIES; ++i) {
127         float   j = i / (float) NUMTOCENTRIES, act, sum;
128         indx = (int) (floor(j * v->pos));
129         if (indx > v->pos - 1)
130             indx = v->pos - 1;
131         act = v->bag[indx];
132         sum = v->sum;
133         seek_point = (int) (256. * act / sum);
134         if (seek_point > 255)
135             seek_point = 255;
136         t[i] = seek_point;
137     }
138 }
139 
140 #ifdef DEBUG_VBR_SEEKING_TABLE
141 static void
print_seeking(unsigned char * t)142 print_seeking(unsigned char *t)
143 {
144     int     i;
145 
146     printf("seeking table ");
147     for (i = 0; i < NUMTOCENTRIES; ++i) {
148         printf(" %d ", t[i]);
149     }
150     printf("\n");
151 }
152 #endif
153 
154 
155 /****************************************************************************
156  * AddVbrFrame: Add VBR entry, used to fill the VBR the TOC entries
157  * Paramters:
158  *      nStreamPos: how many bytes did we write to the bitstream so far
159  *                              (in Bytes NOT Bits)
160  ****************************************************************************
161 */
162 void
AddVbrFrame(lame_internal_flags * gfc)163 AddVbrFrame(lame_internal_flags * gfc)
164 {
165     int     kbps = bitrate_table[gfc->cfg.version][gfc->ov_enc.bitrate_index];
166     assert(gfc->VBR_seek_table.bag);
167     addVbr(&gfc->VBR_seek_table, kbps);
168 }
169 
170 
171 /*-------------------------------------------------------------*/
172 static int
ExtractI4(const unsigned char * buf)173 ExtractI4(const unsigned char *buf)
174 {
175     int     x;
176     /* big endian extract */
177     x = buf[0];
178     x <<= 8;
179     x |= buf[1];
180     x <<= 8;
181     x |= buf[2];
182     x <<= 8;
183     x |= buf[3];
184     return x;
185 }
186 
187 static void
CreateI4(unsigned char * buf,uint32_t nValue)188 CreateI4(unsigned char *buf, uint32_t nValue)
189 {
190     /* big endian create */
191     buf[0] = (nValue >> 24) & 0xff;
192     buf[1] = (nValue >> 16) & 0xff;
193     buf[2] = (nValue >> 8) & 0xff;
194     buf[3] = (nValue) & 0xff;
195 }
196 
197 
198 
199 static void
CreateI2(unsigned char * buf,int nValue)200 CreateI2(unsigned char *buf, int nValue)
201 {
202     /* big endian create */
203     buf[0] = (nValue >> 8) & 0xff;
204     buf[1] = (nValue) & 0xff;
205 }
206 
207 /* check for magic strings*/
208 static int
IsVbrTag(const unsigned char * buf)209 IsVbrTag(const unsigned char *buf)
210 {
211     int     isTag0, isTag1;
212 
213     isTag0 = ((buf[0] == VBRTag0[0]) && (buf[1] == VBRTag0[1]) && (buf[2] == VBRTag0[2])
214               && (buf[3] == VBRTag0[3]));
215     isTag1 = ((buf[0] == VBRTag1[0]) && (buf[1] == VBRTag1[1]) && (buf[2] == VBRTag1[2])
216               && (buf[3] == VBRTag1[3]));
217 
218     return (isTag0 || isTag1);
219 }
220 
221 #define SHIFT_IN_BITS_VALUE(x,n,v) ( x = (x << (n)) | ( (v) & ~(-1 << (n)) ) )
222 
223 static void
setLameTagFrameHeader(lame_internal_flags const * gfc,unsigned char * buffer)224 setLameTagFrameHeader(lame_internal_flags const *gfc, unsigned char *buffer)
225 {
226     SessionConfig_t const *const cfg = &gfc->cfg;
227     EncResult_t const *const eov = &gfc->ov_enc;
228     char    abyte, bbyte;
229 
230     SHIFT_IN_BITS_VALUE(buffer[0], 8u, 0xffu);
231 
232     SHIFT_IN_BITS_VALUE(buffer[1], 3u, 7);
233     SHIFT_IN_BITS_VALUE(buffer[1], 1u, (cfg->samplerate_out < 16000) ? 0 : 1);
234     SHIFT_IN_BITS_VALUE(buffer[1], 1u, cfg->version);
235     SHIFT_IN_BITS_VALUE(buffer[1], 2u, 4 - 3);
236     SHIFT_IN_BITS_VALUE(buffer[1], 1u, (!cfg->error_protection) ? 1 : 0);
237 
238     SHIFT_IN_BITS_VALUE(buffer[2], 4u, eov->bitrate_index);
239     SHIFT_IN_BITS_VALUE(buffer[2], 2u, cfg->samplerate_index);
240     SHIFT_IN_BITS_VALUE(buffer[2], 1u, 0);
241     SHIFT_IN_BITS_VALUE(buffer[2], 1u, cfg->extension);
242 
243     SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->mode);
244     SHIFT_IN_BITS_VALUE(buffer[3], 2u, eov->mode_ext);
245     SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->copyright);
246     SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->original);
247     SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->emphasis);
248 
249     /* the default VBR header. 48 kbps layer III, no padding, no crc */
250     /* but sampling freq, mode andy copyright/copy protection taken */
251     /* from first valid frame */
252     buffer[0] = (uint8_t) 0xff;
253     abyte = (buffer[1] & (unsigned char) 0xf1);
254     {
255         int     bitrate;
256         if (1 == cfg->version) {
257             bitrate = XING_BITRATE1;
258         }
259         else {
260             if (cfg->samplerate_out < 16000)
261                 bitrate = XING_BITRATE25;
262             else
263                 bitrate = XING_BITRATE2;
264         }
265 
266         if (cfg->vbr == vbr_off)
267             bitrate = cfg->avg_bitrate;
268 
269         if (cfg->free_format)
270             bbyte = 0x00;
271         else
272             bbyte = 16 * BitrateIndex(bitrate, cfg->version, cfg->samplerate_out);
273     }
274 
275     /* Use as much of the info from the real frames in the
276      * Xing header:  samplerate, channels, crc, etc...
277      */
278     if (cfg->version == 1) {
279         /* MPEG1 */
280         buffer[1] = abyte | (char) 0x0a; /* was 0x0b; */
281         abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
282         buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG1 frame */
283     }
284     else {
285         /* MPEG2 */
286         buffer[1] = abyte | (char) 0x02; /* was 0x03; */
287         abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
288         buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG2 frame */
289     }
290 }
291 
292 #if 0
293 static int CheckVbrTag(unsigned char *buf);
294 
295 /*-------------------------------------------------------------*/
296 /* Same as GetVbrTag below, but only checks for the Xing tag.
297    requires buf to contain only 40 bytes */
298 /*-------------------------------------------------------------*/
299 int
300 CheckVbrTag(unsigned char *buf)
301 {
302     int     h_id, h_mode;
303 
304     /* get selected MPEG header data */
305     h_id = (buf[1] >> 3) & 1;
306     h_mode = (buf[3] >> 6) & 3;
307 
308     /*  determine offset of header */
309     if (h_id) {
310         /* mpeg1 */
311         if (h_mode != 3)
312             buf += (32 + 4);
313         else
314             buf += (17 + 4);
315     }
316     else {
317         /* mpeg2 */
318         if (h_mode != 3)
319             buf += (17 + 4);
320         else
321             buf += (9 + 4);
322     }
323 
324     return IsVbrTag(buf);
325 }
326 #endif
327 
328 int
GetVbrTag(VBRTAGDATA * pTagData,const unsigned char * buf)329 GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf)
330 {
331     int     i, head_flags;
332     int     h_bitrate, h_id, h_mode, h_sr_index, h_layer;
333     int     enc_delay, enc_padding;
334 
335     /* get Vbr header data */
336     pTagData->flags = 0;
337 
338     /* get selected MPEG header data */
339     h_layer = (buf[1] >> 1) & 3;
340     if ( h_layer != 0x01 ) {
341         /* the following code assumes Layer-3, so give up here */
342         return 0;
343     }
344     h_id = (buf[1] >> 3) & 1;
345     h_sr_index = (buf[2] >> 2) & 3;
346     h_mode = (buf[3] >> 6) & 3;
347     h_bitrate = ((buf[2] >> 4) & 0xf);
348     h_bitrate = bitrate_table[h_id][h_bitrate];
349 
350     /* check for FFE syncword */
351     if ((buf[1] >> 4) == 0xE)
352         pTagData->samprate = samplerate_table[2][h_sr_index];
353     else
354         pTagData->samprate = samplerate_table[h_id][h_sr_index];
355     /* if( h_id == 0 ) */
356     /*  pTagData->samprate >>= 1; */
357 
358 
359 
360     /*  determine offset of header */
361     if (h_id) {
362         /* mpeg1 */
363         if (h_mode != 3)
364             buf += (32 + 4);
365         else
366             buf += (17 + 4);
367     }
368     else {
369         /* mpeg2 */
370         if (h_mode != 3)
371             buf += (17 + 4);
372         else
373             buf += (9 + 4);
374     }
375 
376     if (!IsVbrTag(buf))
377         return 0;
378 
379     buf += 4;
380 
381     pTagData->h_id = h_id;
382 
383     head_flags = pTagData->flags = ExtractI4(buf);
384     buf += 4;           /* get flags */
385 
386     if (head_flags & FRAMES_FLAG) {
387         pTagData->frames = ExtractI4(buf);
388         buf += 4;
389     }
390 
391     if (head_flags & BYTES_FLAG) {
392         pTagData->bytes = ExtractI4(buf);
393         buf += 4;
394     }
395 
396     if (head_flags & TOC_FLAG) {
397         if (pTagData->toc != NULL) {
398             for (i = 0; i < NUMTOCENTRIES; i++)
399                 pTagData->toc[i] = buf[i];
400         }
401         buf += NUMTOCENTRIES;
402     }
403 
404     pTagData->vbr_scale = -1;
405 
406     if (head_flags & VBR_SCALE_FLAG) {
407         pTagData->vbr_scale = ExtractI4(buf);
408         buf += 4;
409     }
410 
411     pTagData->headersize = ((h_id + 1) * 72000 * h_bitrate) / pTagData->samprate;
412 
413     buf += 21;
414     enc_delay = buf[0] << 4;
415     enc_delay += buf[1] >> 4;
416     enc_padding = (buf[1] & 0x0F) << 8;
417     enc_padding += buf[2];
418     /* check for reasonable values (this may be an old Xing header, */
419     /* not a INFO tag) */
420     if (enc_delay < 0 || enc_delay > 3000)
421         enc_delay = -1;
422     if (enc_padding < 0 || enc_padding > 3000)
423         enc_padding = -1;
424 
425     pTagData->enc_delay = enc_delay;
426     pTagData->enc_padding = enc_padding;
427 
428 #ifdef DEBUG_VBRTAG
429     fprintf(stderr, "\n\n********************* VBR TAG INFO *****************\n");
430     fprintf(stderr, "tag         :%s\n", VBRTag);
431     fprintf(stderr, "head_flags  :%d\n", head_flags);
432     fprintf(stderr, "bytes       :%d\n", pTagData->bytes);
433     fprintf(stderr, "frames      :%d\n", pTagData->frames);
434     fprintf(stderr, "VBR Scale   :%d\n", pTagData->vbr_scale);
435     fprintf(stderr, "enc_delay  = %i \n", enc_delay);
436     fprintf(stderr, "enc_padding= %i \n", enc_padding);
437     fprintf(stderr, "toc:\n");
438     if (pTagData->toc != NULL) {
439         for (i = 0; i < NUMTOCENTRIES; i++) {
440             if ((i % 10) == 0)
441                 fprintf(stderr, "\n");
442             fprintf(stderr, " %3d", (int) (pTagData->toc[i]));
443         }
444     }
445     fprintf(stderr, "\n***************** END OF VBR TAG INFO ***************\n");
446 #endif
447     return 1;           /* success */
448 }
449 
450 
451 /****************************************************************************
452  * InitVbrTag: Initializes the header, and write empty frame to stream
453  * Paramters:
454  *                              fpStream: pointer to output file stream
455  *                              nMode   : Channel Mode: 0=STEREO 1=JS 2=DS 3=MONO
456  ****************************************************************************
457 */
458 int
InitVbrTag(lame_global_flags * gfp)459 InitVbrTag(lame_global_flags * gfp)
460 {
461     lame_internal_flags *gfc = gfp->internal_flags;
462     SessionConfig_t const *const cfg = &gfc->cfg;
463     int     kbps_header;
464 
465 #define MAXFRAMESIZE 2880 /* or 0xB40, the max freeformat 640 32kHz framesize */
466 
467     /*
468      * Xing VBR pretends to be a 48kbs layer III frame.  (at 44.1kHz).
469      * (at 48kHz they use 56kbs since 48kbs frame not big enough for
470      * table of contents)
471      * let's always embed Xing header inside a 64kbs layer III frame.
472      * this gives us enough room for a LAME version string too.
473      * size determined by sampling frequency (MPEG1)
474      * 32kHz:    216 bytes@48kbs    288bytes@ 64kbs
475      * 44.1kHz:  156 bytes          208bytes@64kbs     (+1 if padding = 1)
476      * 48kHz:    144 bytes          192
477      *
478      * MPEG 2 values are the same since the framesize and samplerate
479      * are each reduced by a factor of 2.
480      */
481 
482 
483     if (1 == cfg->version) {
484         kbps_header = XING_BITRATE1;
485     }
486     else {
487         if (cfg->samplerate_out < 16000)
488             kbps_header = XING_BITRATE25;
489         else
490             kbps_header = XING_BITRATE2;
491     }
492 
493     if (cfg->vbr == vbr_off)
494         kbps_header = cfg->avg_bitrate;
495 
496     /** make sure LAME Header fits into Frame
497      */
498     {
499         int     total_frame_size = ((cfg->version + 1) * 72000 * kbps_header) / cfg->samplerate_out;
500         int     header_size = (cfg->sideinfo_len + LAMEHEADERSIZE);
501         gfc->VBR_seek_table.TotalFrameSize = total_frame_size;
502         if (total_frame_size < header_size || total_frame_size > MAXFRAMESIZE) {
503             /* disable tag, it wont fit */
504             gfc->cfg.write_lame_tag = 0;
505             return 0;
506         }
507     }
508 
509     gfc->VBR_seek_table.nVbrNumFrames = 0;
510     gfc->VBR_seek_table.nBytesWritten = 0;
511     gfc->VBR_seek_table.sum = 0;
512 
513     gfc->VBR_seek_table.seen = 0;
514     gfc->VBR_seek_table.want = 1;
515     gfc->VBR_seek_table.pos = 0;
516 
517     if (gfc->VBR_seek_table.bag == NULL) {
518         gfc->VBR_seek_table.bag = lame_calloc(int, 400);
519         if (gfc->VBR_seek_table.bag != NULL) {
520             gfc->VBR_seek_table.size = 400;
521         }
522         else {
523             gfc->VBR_seek_table.size = 0;
524             ERRORF(gfc, "Error: can't allocate VbrFrames buffer\n");
525             gfc->cfg.write_lame_tag = 0;
526             return -1;
527         }
528     }
529 
530     /* write dummy VBR tag of all 0's into bitstream */
531     {
532         uint8_t buffer[MAXFRAMESIZE];
533         size_t  i, n;
534 
535         memset(buffer, 0, sizeof(buffer));
536         setLameTagFrameHeader(gfc, buffer);
537         n = gfc->VBR_seek_table.TotalFrameSize;
538         for (i = 0; i < n; ++i) {
539             add_dummy_byte(gfc, buffer[i], 1);
540         }
541     }
542     /* Success */
543     return 0;
544 }
545 
546 
547 
548 /* fast CRC-16 computation - uses table crc16_lookup 8*/
549 static uint16_t
CRC_update_lookup(uint16_t crc,unsigned char const * buffer,int size)550 CRC_update_lookup(uint16_t crc, unsigned char const *buffer, int size)
551 {
552     while (size >= 8) {
553         crc ^= buffer[1] << 8 | buffer[0];
554 
555         crc = crc16_lookup[7][crc & 0xFF] ^ crc16_lookup[6][crc >> 8 ] ^
556               crc16_lookup[5][buffer[2] ] ^ crc16_lookup[4][buffer[3]] ^
557               crc16_lookup[3][buffer[4] ] ^ crc16_lookup[2][buffer[5]] ^
558               crc16_lookup[1][buffer[6] ] ^ crc16_lookup[0][buffer[7]];
559 
560         buffer += 8;
561         size -= 8;
562     }
563 
564     while (size--) crc = (crc >> 8) ^ crc16_lookup[0][(crc & 0xff) ^ *buffer++];
565     return crc;
566 }
567 
568 void
UpdateMusicCRC(uint16_t * crc,unsigned char const * buffer,int size)569 UpdateMusicCRC(uint16_t * crc, unsigned char const *buffer, int size)
570 {
571     *crc = CRC_update_lookup(*crc, buffer, size);
572 }
573 
574 
575 
576 
577 
578 /****************************************************************************
579  * Jonathan Dee 2001/08/31
580  *
581  * PutLameVBR: Write LAME info: mini version + info on various switches used
582  * Paramters:
583  *                              pbtStreamBuffer : pointer to output buffer
584  *                              id3v2size               : size of id3v2 tag in bytes
585  *                              crc                             : computation of crc-16 of Lame Tag so far (starting at frame sync)
586  *
587  ****************************************************************************
588 */
589 static int
PutLameVBR(lame_global_flags const * gfp,size_t nMusicLength,uint8_t * pbtStreamBuffer,uint16_t crc)590 PutLameVBR(lame_global_flags const *gfp, size_t nMusicLength, uint8_t * pbtStreamBuffer, uint16_t crc)
591 {
592     lame_internal_flags const *gfc = gfp->internal_flags;
593     SessionConfig_t const *const cfg = &gfc->cfg;
594 
595     int     nBytesWritten = 0;
596     int     i;
597 
598     int     enc_delay = gfc->ov_enc.encoder_delay; /* encoder delay */
599     int     enc_padding = gfc->ov_enc.encoder_padding; /* encoder padding  */
600 
601     /*recall: cfg->vbr_q is for example set by the switch -V  */
602     /*   gfp->quality by -q, -h, -f, etc */
603 
604     int     nQuality = (100 - 10 * gfp->VBR_q - gfp->quality);
605 
606 
607     /*
608     NOTE:
609             Even though the specification for the LAME VBR tag
610             did explicitly mention other encoders than LAME,
611             many SW/HW decoder seem to be able to make use of
612             this tag only, if the encoder version starts with LAME.
613             To be compatible with such decoders, ANY encoder will
614             be forced to write a fake LAME version string!
615             As a result, the encoder version info becomes worthless.
616     */
617     const char *szVersion = get_lame_tag_encoder_short_version();
618     uint8_t nVBR;
619     uint8_t nRevision = 0x00;
620     uint8_t nRevMethod;
621     uint8_t vbr_type_translator[] = { 1, 5, 3, 2, 4, 0, 3 }; /*numbering different in vbr_mode vs. Lame tag */
622 
623     uint8_t nLowpass =
624         (((cfg->lowpassfreq / 100.0) + .5) > 255 ? 255 : (cfg->lowpassfreq / 100.0) + .5);
625 
626     uint32_t nPeakSignalAmplitude = 0;
627 
628     uint16_t nRadioReplayGain = 0;
629     uint16_t nAudiophileReplayGain = 0;
630 
631     uint8_t nNoiseShaping = cfg->noise_shaping;
632     uint8_t nStereoMode = 0;
633     int     bNonOptimal = 0;
634     uint8_t nSourceFreq = 0;
635     uint8_t nMisc = 0;
636     uint16_t nMusicCRC = 0;
637 
638     /*psy model type: Gpsycho or NsPsytune */
639     unsigned char bExpNPsyTune = 1; /* only NsPsytune */
640     unsigned char bSafeJoint = (cfg->use_safe_joint_stereo) != 0;
641 
642     unsigned char bNoGapMore = 0;
643     unsigned char bNoGapPrevious = 0;
644 
645     int     nNoGapCount = gfp->nogap_total;
646     int     nNoGapCurr = gfp->nogap_current;
647 
648 
649     uint8_t nAthType = cfg->ATHtype; /*4 bits. */
650 
651     uint8_t nFlags = 0;
652 
653     /* if ABR, {store bitrate <=255} else { store "-b"} */
654     int     nABRBitrate;
655     switch (cfg->vbr) {
656     case vbr_abr:{
657             nABRBitrate = cfg->vbr_avg_bitrate_kbps;
658             break;
659         }
660     case vbr_off:{
661             nABRBitrate = cfg->avg_bitrate;
662             break;
663         }
664     default:{          /*vbr modes */
665             nABRBitrate = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];;
666         }
667     }
668 
669 
670     /*revision and vbr method */
671     if (cfg->vbr < sizeof(vbr_type_translator))
672         nVBR = vbr_type_translator[cfg->vbr];
673     else
674         nVBR = 0x00;    /*unknown. */
675 
676     nRevMethod = 0x10 * nRevision + nVBR;
677 
678 
679     /* ReplayGain */
680     if (cfg->findReplayGain) {
681         int     RadioGain = gfc->ov_rpg.RadioGain;
682         if (RadioGain > 0x1FE)
683             RadioGain = 0x1FE;
684         if (RadioGain < -0x1FE)
685             RadioGain = -0x1FE;
686 
687         nRadioReplayGain = 0x2000; /* set name code */
688         nRadioReplayGain |= 0xC00; /* set originator code to `determined automatically' */
689 
690         if (RadioGain >= 0)
691             nRadioReplayGain |= RadioGain; /* set gain adjustment */
692         else {
693             nRadioReplayGain |= 0x200; /* set the sign bit */
694             nRadioReplayGain |= -RadioGain; /* set gain adjustment */
695         }
696     }
697 
698     /* peak sample */
699     if (cfg->findPeakSample)
700         nPeakSignalAmplitude =
701             abs((int) ((((FLOAT) gfc->ov_rpg.PeakSample) / 32767.0) * pow(2, 23) + .5));
702 
703     /*nogap */
704     if (nNoGapCount != -1) {
705         if (nNoGapCurr > 0)
706             bNoGapPrevious = 1;
707 
708         if (nNoGapCurr < nNoGapCount - 1)
709             bNoGapMore = 1;
710     }
711 
712     /*flags */
713 
714     nFlags = nAthType + (bExpNPsyTune << 4)
715         + (bSafeJoint << 5)
716         + (bNoGapMore << 6)
717         + (bNoGapPrevious << 7);
718 
719 
720     if (nQuality < 0)
721         nQuality = 0;
722 
723     /*stereo mode field... a bit ugly. */
724 
725     switch (cfg->mode) {
726     case MONO:
727         nStereoMode = 0;
728         break;
729     case STEREO:
730         nStereoMode = 1;
731         break;
732     case DUAL_CHANNEL:
733         nStereoMode = 2;
734         break;
735     case JOINT_STEREO:
736         if (cfg->force_ms)
737             nStereoMode = 4;
738         else
739             nStereoMode = 3;
740         break;
741     case NOT_SET:
742         /* FALLTHROUGH */
743     default:
744         nStereoMode = 7;
745         break;
746     }
747 
748     /*Intensity stereo : nStereoMode = 6. IS is not implemented */
749 
750     if (cfg->samplerate_in <= 32000)
751         nSourceFreq = 0x00;
752     else if (cfg->samplerate_in == 48000)
753         nSourceFreq = 0x02;
754     else if (cfg->samplerate_in > 48000)
755         nSourceFreq = 0x03;
756     else
757         nSourceFreq = 0x01; /*default is 44100Hz. */
758 
759 
760     /*Check if the user overrided the default LAME behaviour with some nasty options */
761 
762     if (cfg->short_blocks == short_block_forced || cfg->short_blocks == short_block_dispensed || ((cfg->lowpassfreq == -1) && (cfg->highpassfreq == -1)) || /* "-k" */
763         (cfg->disable_reservoir && cfg->avg_bitrate < 320) ||
764         cfg->noATH || cfg->ATHonly || (nAthType == 0) || cfg->samplerate_in <= 32000)
765         bNonOptimal = 1;
766 
767     nMisc = nNoiseShaping + (nStereoMode << 2)
768         + (bNonOptimal << 5)
769         + (nSourceFreq << 6);
770 
771 
772     nMusicCRC = gfc->nMusicCRC;
773 
774 
775     /*Write all this information into the stream */
776     CreateI4(&pbtStreamBuffer[nBytesWritten], nQuality);
777     nBytesWritten += 4;
778 
779     strncpy((char *) &pbtStreamBuffer[nBytesWritten], szVersion, 9);
780     nBytesWritten += 9;
781 
782     pbtStreamBuffer[nBytesWritten] = nRevMethod;
783     nBytesWritten++;
784 
785     pbtStreamBuffer[nBytesWritten] = nLowpass;
786     nBytesWritten++;
787 
788     CreateI4(&pbtStreamBuffer[nBytesWritten], nPeakSignalAmplitude);
789     nBytesWritten += 4;
790 
791     CreateI2(&pbtStreamBuffer[nBytesWritten], nRadioReplayGain);
792     nBytesWritten += 2;
793 
794     CreateI2(&pbtStreamBuffer[nBytesWritten], nAudiophileReplayGain);
795     nBytesWritten += 2;
796 
797     pbtStreamBuffer[nBytesWritten] = nFlags;
798     nBytesWritten++;
799 
800     if (nABRBitrate >= 255)
801         pbtStreamBuffer[nBytesWritten] = 0xFF;
802     else
803         pbtStreamBuffer[nBytesWritten] = nABRBitrate;
804     nBytesWritten++;
805 
806     pbtStreamBuffer[nBytesWritten] = enc_delay >> 4; /* works for win32, does it for unix? */
807     pbtStreamBuffer[nBytesWritten + 1] = (enc_delay << 4) + (enc_padding >> 8);
808     pbtStreamBuffer[nBytesWritten + 2] = enc_padding;
809 
810     nBytesWritten += 3;
811 
812     pbtStreamBuffer[nBytesWritten] = nMisc;
813     nBytesWritten++;
814 
815 
816     pbtStreamBuffer[nBytesWritten++] = 0; /*unused in rev0 */
817 
818     CreateI2(&pbtStreamBuffer[nBytesWritten], cfg->preset);
819     nBytesWritten += 2;
820 
821     CreateI4(&pbtStreamBuffer[nBytesWritten], (int) nMusicLength);
822     nBytesWritten += 4;
823 
824     CreateI2(&pbtStreamBuffer[nBytesWritten], nMusicCRC);
825     nBytesWritten += 2;
826 
827     /*Calculate tag CRC.... must be done here, since it includes
828      *previous information*/
829 
830     crc = CRC_update_lookup(crc, pbtStreamBuffer, nBytesWritten);
831 
832     CreateI2(&pbtStreamBuffer[nBytesWritten], crc);
833     nBytesWritten += 2;
834 
835     return nBytesWritten;
836 }
837 
838 static long
skipId3v2(FILE * fpStream)839 skipId3v2(FILE * fpStream)
840 {
841     size_t  nbytes;
842     long    id3v2TagSize;
843     unsigned char id3v2Header[10];
844 
845     /* seek to the beginning of the stream */
846     if (fseek(fpStream, 0, SEEK_SET) != 0) {
847         return -2;      /* not seekable, abort */
848     }
849     /* read 10 bytes in case there's an ID3 version 2 header here */
850     nbytes = fread(id3v2Header, 1, sizeof(id3v2Header), fpStream);
851     if (nbytes != sizeof(id3v2Header)) {
852         return -3;      /* not readable, maybe opened Write-Only */
853     }
854     /* does the stream begin with the ID3 version 2 file identifier? */
855     if (!strncmp((char *) id3v2Header, "ID3", 3)) {
856         /* the tag size (minus the 10-byte header) is encoded into four
857          * bytes where the most significant bit is clear in each byte */
858         id3v2TagSize = (((id3v2Header[6] & 0x7f) << 21)
859                         | ((id3v2Header[7] & 0x7f) << 14)
860                         | ((id3v2Header[8] & 0x7f) << 7)
861                         | (id3v2Header[9] & 0x7f))
862             + sizeof id3v2Header;
863     }
864     else {
865         /* no ID3 version 2 tag in this stream */
866         id3v2TagSize = 0;
867     }
868     return id3v2TagSize;
869 }
870 
871 
872 
873 size_t
lame_get_lametag_frame(lame_global_flags const * gfp,unsigned char * buffer,size_t size)874 lame_get_lametag_frame(lame_global_flags const *gfp, unsigned char *buffer, size_t size)
875 {
876     lame_internal_flags *gfc;
877     SessionConfig_t const *cfg;
878     unsigned long stream_size;
879     unsigned int  nStreamIndex;
880     uint8_t btToc[NUMTOCENTRIES];
881 
882     if (gfp == 0) {
883         return 0;
884     }
885     gfc = gfp->internal_flags;
886     if (gfc == 0) {
887         return 0;
888     }
889     if (!is_lame_internal_flags_valid(gfc)) {
890         return 0;
891     }
892     cfg = &gfc->cfg;
893     if (cfg->write_lame_tag == 0) {
894         return 0;
895     }
896     if (gfc->VBR_seek_table.pos <= 0) {
897         return 0;
898     }
899     if (size < gfc->VBR_seek_table.TotalFrameSize) {
900         return gfc->VBR_seek_table.TotalFrameSize;
901     }
902     if (buffer == 0) {
903         return 0;
904     }
905 
906     memset(buffer, 0, gfc->VBR_seek_table.TotalFrameSize);
907 
908     /* 4 bytes frame header */
909 
910     setLameTagFrameHeader(gfc, buffer);
911 
912     /* Clear all TOC entries */
913     memset(btToc, 0, sizeof(btToc));
914 
915     if (cfg->free_format) {
916         int     i;
917         for (i = 1; i < NUMTOCENTRIES; ++i)
918             btToc[i] = 255 * i / 100;
919     }
920     else {
921         Xing_seek_table(&gfc->VBR_seek_table, btToc);
922     }
923 #ifdef DEBUG_VBR_SEEKING_TABLE
924     print_seeking(btToc);
925 #endif
926 
927     /* Start writing the tag after the zero frame */
928     nStreamIndex = cfg->sideinfo_len;
929     /* note! Xing header specifies that Xing data goes in the
930      * ancillary data with NO ERROR PROTECTION.  If error protecton
931      * in enabled, the Xing data still starts at the same offset,
932      * and now it is in sideinfo data block, and thus will not
933      * decode correctly by non-Xing tag aware players */
934     if (cfg->error_protection)
935         nStreamIndex -= 2;
936 
937     /* Put Vbr tag */
938     if (cfg->vbr == vbr_off) {
939         buffer[nStreamIndex++] = VBRTag1[0];
940         buffer[nStreamIndex++] = VBRTag1[1];
941         buffer[nStreamIndex++] = VBRTag1[2];
942         buffer[nStreamIndex++] = VBRTag1[3];
943 
944     }
945     else {
946         buffer[nStreamIndex++] = VBRTag0[0];
947         buffer[nStreamIndex++] = VBRTag0[1];
948         buffer[nStreamIndex++] = VBRTag0[2];
949         buffer[nStreamIndex++] = VBRTag0[3];
950     }
951 
952     /* Put header flags */
953     CreateI4(&buffer[nStreamIndex], FRAMES_FLAG + BYTES_FLAG + TOC_FLAG + VBR_SCALE_FLAG);
954     nStreamIndex += 4;
955 
956     /* Put Total Number of frames */
957     CreateI4(&buffer[nStreamIndex], gfc->VBR_seek_table.nVbrNumFrames);
958     nStreamIndex += 4;
959 
960     /* Put total audio stream size, including Xing/LAME Header */
961     stream_size = gfc->VBR_seek_table.nBytesWritten + gfc->VBR_seek_table.TotalFrameSize;
962     CreateI4(&buffer[nStreamIndex], stream_size);
963     nStreamIndex += 4;
964 
965     /* Put TOC */
966     memcpy(&buffer[nStreamIndex], btToc, sizeof(btToc));
967     nStreamIndex += sizeof(btToc);
968 
969 
970     if (cfg->error_protection) {
971         /* (jo) error_protection: add crc16 information to header */
972         CRC_writeheader(gfc, (char *) buffer);
973     }
974     {
975         /*work out CRC so far: initially crc = 0 */
976         uint16_t crc = 0x00;
977         crc = CRC_update_lookup(crc, buffer, nStreamIndex);
978         /*Put LAME VBR info */
979         nStreamIndex += PutLameVBR(gfp, stream_size, buffer + nStreamIndex, crc);
980     }
981 
982 #ifdef DEBUG_VBRTAG
983     {
984         VBRTAGDATA TestHeader;
985         GetVbrTag(&TestHeader, buffer);
986     }
987 #endif
988 
989     return gfc->VBR_seek_table.TotalFrameSize;
990 }
991 
992 /***********************************************************************
993  *
994  * PutVbrTag: Write final VBR tag to the file
995  * Paramters:
996  *                              lpszFileName: filename of MP3 bit stream
997  *                              nVbrScale       : encoder quality indicator (0..100)
998  ****************************************************************************
999  */
1000 
1001 int
PutVbrTag(lame_global_flags const * gfp,FILE * fpStream)1002 PutVbrTag(lame_global_flags const *gfp, FILE * fpStream)
1003 {
1004     lame_internal_flags *gfc = gfp->internal_flags;
1005 
1006     long    lFileSize;
1007     long    id3v2TagSize;
1008     size_t  nbytes;
1009     uint8_t buffer[MAXFRAMESIZE];
1010 
1011     if (gfc->VBR_seek_table.pos <= 0)
1012         return -1;
1013 
1014     /* Seek to end of file */
1015     fseek(fpStream, 0, SEEK_END);
1016 
1017     /* Get file size */
1018     lFileSize = ftell(fpStream);
1019 
1020     /* Abort if file has zero length. Yes, it can happen :) */
1021     if (lFileSize == 0)
1022         return -1;
1023 
1024     /*
1025      * The VBR tag may NOT be located at the beginning of the stream.
1026      * If an ID3 version 2 tag was added, then it must be skipped to write
1027      * the VBR tag data.
1028      */
1029 
1030     id3v2TagSize = skipId3v2(fpStream);
1031 
1032     if (id3v2TagSize < 0) {
1033         return id3v2TagSize;
1034     }
1035 
1036     /*Seek to the beginning of the stream */
1037     fseek(fpStream, id3v2TagSize, SEEK_SET);
1038 
1039     nbytes = lame_get_lametag_frame(gfp, buffer, sizeof(buffer));
1040     if (nbytes > sizeof(buffer)) {
1041         return -1;
1042     }
1043 
1044     if (nbytes < 1) {
1045         return 0;
1046     }
1047 
1048     /* Put it all to disk again */
1049     if (fwrite(buffer, nbytes, 1, fpStream) != 1) {
1050         return -1;
1051     }
1052 
1053     return 0;           /* success */
1054 }
1055