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