fixed graphics bug
[swftools.git] / lib / lame / lame.c
1 /* -*- mode: C; mode: fold -*- */
2 /*
3  *      LAME MP3 encoding engine
4  *
5  *      Copyright (c) 1999 Mark Taylor
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: lame.c,v 1.1 2002/04/28 17:30:20 kramm Exp $ */
24
25 #include "config_static.h"
26
27
28 #include <assert.h>
29 #include "lame-analysis.h"
30 #include "lame.h"
31 #include "util.h"
32 #include "bitstream.h"
33 #include "version.h"
34 #include "tables.h"
35 #include "quantize_pvt.h"
36 #include "VbrTag.h"
37
38 #if defined(__FreeBSD__) && !defined(__alpha__)
39 #include <floatingpoint.h>
40 #endif
41 #ifdef __riscos__
42 #include "asmstuff.h"
43 #endif
44
45 #ifdef WITH_DMALLOC
46 #include <dmalloc.h>
47 #endif
48
49
50 static void
51 lame_init_params_ppflt_lowpass(FLOAT8 amp_lowpass[32], FLOAT lowpass1,
52                                FLOAT lowpass2, int *lowpass_band,
53                                int *minband, int *maxband)
54 {
55     int     band;
56     FLOAT8  freq;
57
58     for (band = 0; band <= 31; band++) {
59         freq = band / 31.0;
60         amp_lowpass[band] = 1;
61         /* this band and above will be zeroed: */
62         if (freq >= lowpass2) {
63             *lowpass_band = Min(*lowpass_band, band);
64             amp_lowpass[band] = 0;
65         }
66         if (lowpass1 < freq && freq < lowpass2) {
67             *minband = Min(*minband, band);
68             *maxband = Max(*maxband, band);
69             amp_lowpass[band] = cos((PI / 2) *
70                                     (lowpass1 - freq) / (lowpass2 - lowpass1));
71         }
72         /*
73          * DEBUGF("lowpass band=%i  amp=%f \n",
74          *      band, gfc->amp_lowpass[band]);
75          */
76     }
77 }
78
79 /* lame_init_params_ppflt */
80
81 /*}}}*/
82 /* static void   lame_init_params_ppflt         (lame_internal_flags *gfc)                                                                                        *//*{{{ */
83
84 static void
85 lame_init_params_ppflt(lame_global_flags * gfp)
86 {
87     lame_internal_flags *gfc = gfp->internal_flags;
88   /***************************************************************/
89     /* compute info needed for polyphase filter (filter type==0, default) */
90   /***************************************************************/
91
92     int     band, maxband, minband;
93     FLOAT8  freq;
94
95     if (gfc->lowpass1 > 0) {
96         minband = 999;
97         maxband = -1;
98         lame_init_params_ppflt_lowpass(gfc->amp_lowpass,
99                                        gfc->lowpass1, gfc->lowpass2,
100                                        &gfc->lowpass_band, &minband, &maxband);
101         /* compute the *actual* transition band implemented by
102          * the polyphase filter */
103         if (minband == 999) {
104             gfc->lowpass1 = (gfc->lowpass_band - .75) / 31.0;
105         }
106         else {
107             gfc->lowpass1 = (minband - .75) / 31.0;
108         }
109         gfc->lowpass2 = gfc->lowpass_band / 31.0;
110
111         gfc->lowpass_start_band = minband;
112         gfc->lowpass_end_band = maxband;
113
114         /* as the lowpass may have changed above
115          * calculate the amplification here again
116          */
117         for (band = minband; band <= maxband; band++) {
118             freq = band / 31.0;
119             gfc->amp_lowpass[band] =
120                 cos((PI / 2) * (gfc->lowpass1 - freq) /
121                     (gfc->lowpass2 - gfc->lowpass1));
122         }
123     }
124     else {
125         gfc->lowpass_start_band = 0;
126         gfc->lowpass_end_band = -1; /* do not to run into for-loops */
127     }
128
129     /* make sure highpass filter is within 90% of what the effective
130      * highpass frequency will be */
131     if (gfc->highpass2 > 0) {
132         if (gfc->highpass2 < .9 * (.75 / 31.0)) {
133             gfc->highpass1 = 0;
134             gfc->highpass2 = 0;
135             MSGF(gfc, "Warning: highpass filter disabled.  "
136                  "highpass frequency too small\n");
137         }
138     }
139
140     if (gfc->highpass2 > 0) {
141         minband = 999;
142         maxband = -1;
143         for (band = 0; band <= 31; band++) {
144             freq = band / 31.0;
145             gfc->amp_highpass[band] = 1;
146             /* this band and below will be zereod */
147             if (freq <= gfc->highpass1) {
148                 gfc->highpass_band = Max(gfc->highpass_band, band);
149                 gfc->amp_highpass[band] = 0;
150             }
151             if (gfc->highpass1 < freq && freq < gfc->highpass2) {
152                 minband = Min(minband, band);
153                 maxband = Max(maxband, band);
154                 gfc->amp_highpass[band] =
155                     cos((PI / 2) *
156                         (gfc->highpass2 - freq) /
157                         (gfc->highpass2 - gfc->highpass1));
158             }
159             /*
160                DEBUGF("highpass band=%i  amp=%f \n",
161                band, gfc->amp_highpass[band]);
162              */
163         }
164         /* compute the *actual* transition band implemented by
165          * the polyphase filter */
166         gfc->highpass1 = gfc->highpass_band / 31.0;
167         if (maxband == -1) {
168             gfc->highpass2 = (gfc->highpass_band + .75) / 31.0;
169         }
170         else {
171             gfc->highpass2 = (maxband + .75) / 31.0;
172         }
173
174         gfc->highpass_start_band = minband;
175         gfc->highpass_end_band = maxband;
176
177         /* as the highpass may have changed above
178          * calculate the amplification here again
179          */
180         for (band = minband; band <= maxband; band++) {
181             freq = band / 31.0;
182             gfc->amp_highpass[band] =
183                 cos((PI / 2) * (gfc->highpass2 - freq) /
184                     (gfc->highpass2 - gfc->highpass1));
185         }
186     }
187     else {
188         gfc->highpass_start_band = 0;
189         gfc->highpass_end_band = -1; /* do not to run into for-loops */
190     }
191     /*
192        DEBUGF("lowpass band with amp=0:  %i \n",gfc->lowpass_band);
193        DEBUGF("highpass band with amp=0:  %i \n",gfc->highpass_band);
194        DEBUGF("lowpass band start:  %i \n",gfc->lowpass_start_band);
195        DEBUGF("lowpass band end:    %i \n",gfc->lowpass_end_band);
196        DEBUGF("highpass band start:  %i \n",gfc->highpass_start_band);
197        DEBUGF("highpass band end:    %i \n",gfc->highpass_end_band);
198      */
199 }
200
201 /*}}}*/
202
203
204 static void
205 optimum_bandwidth(double *const lowerlimit,
206                   double *const upperlimit,
207                   const unsigned bitrate,
208                   const int samplefreq,
209                   const double channels)
210 {
211 /* 
212  *  Input:
213  *      bitrate     total bitrate in bps
214  *      samplefreq  output sampling frequency in Hz
215  *      channels    1 for mono, 2+epsilon for MS stereo, 3 for LR stereo
216  *                  epsilon is the percentage of LR frames for typical audio
217  *                  (I use 'Fade to Gray' by Metallica)
218  *
219  *   Output:
220  *      lowerlimit: best lowpass frequency limit for input filter in Hz
221  *      upperlimit: best highpass frequency limit for input filter in Hz
222  */
223     double  f_low;
224     double  f_high;
225     double  br;
226
227     assert(bitrate >= 8000 && bitrate <= 320000);
228     assert(samplefreq >= 8000 && samplefreq <= 48000);
229     assert(channels == 1 || (channels >= 2 && channels <= 3));
230
231     if (samplefreq >= 32000)
232         br =
233             bitrate - (channels ==
234                        1 ? (17 + 4) * 8 : (32 + 4) * 8) * samplefreq / 1152;
235     else
236         br =
237             bitrate - (channels ==
238                        1 ? (9 + 4) * 8 : (17 + 4) * 8) * samplefreq / 576;
239
240     if (channels >= 2.)
241         br /= 1.75 + 0.25 * (channels - 2.); // MS needs 1.75x mono, LR needs 2.00x mono (experimental data of a lot of albums)
242
243     br *= 0.5;          // the sine and cosine term must share the bitrate
244
245 /* 
246  *  So, now we have the bitrate for every spectral line.
247  *  Let's look at the current settings:
248  *
249  *    Bitrate   limit    bits/line
250  *     8 kbps   0.34 kHz  4.76
251  *    16 kbps   1.9 kHz   2.06
252  *    24 kbps   2.8 kHz   2.21
253  *    32 kbps   3.85 kHz  2.14
254  *    40 kbps   5.1 kHz   2.06
255  *    48 kbps   5.6 kHz   2.21
256  *    56 kbps   7.0 kHz   2.10
257  *    64 kbps   7.7 kHz   2.14
258  *    80 kbps  10.1 kHz   2.08
259  *    96 kbps  11.2 kHz   2.24
260  *   112 kbps  14.0 kHz   2.12
261  *   128 kbps  15.4 kHz   2.17
262  *   160 kbps  18.2 kHz   2.05
263  *   192 kbps  21.1 kHz   2.14
264  *   224 kbps  22.0 kHz   2.41
265  *   256 kbps  22.0 kHz   2.78
266  *
267  *   What can we see?
268  *       Value for 8 kbps is nonsense (although 8 kbps and stereo is nonsense)
269  *       Values are between 2.05 and 2.24 for 16...192 kbps
270  *       Some bitrate lack the following bitrates have: 16, 40, 80, 160 kbps
271  *       A lot of bits per spectral line have: 24, 48, 96 kbps
272  *
273  *   What I propose?
274  *       A slightly with the bitrate increasing bits/line function. It is
275  *       better to decrease NMR for low bitrates to get a little bit more
276  *       bandwidth. So we have a better trade off between twickling and
277  *       muffled sound.
278  */
279
280     f_low = br / log10(br * 4.425e-3); // Tests with 8, 16, 32, 64, 112 and 160 kbps
281  
282 /*
283 GB 04/04/01
284 sfb21 is a huge bitrate consumer in vbr with the new ath.
285 Need to reduce the lowpass to more reasonable values. This extra lowpass
286 won't reduce quality over 3.87 as the previous ath was doing this lowpass
287 */
288 /*GB 22/05/01
289 I'm also extending this to CBR as tests showed that a
290 limited bandwidth is increasing quality
291 */
292     if (f_low>18400)
293             f_low = 18400+(f_low-18400)/4;
294
295 /*
296  *  What we get now?
297  *
298  *    Bitrate       limit  bits/line    difference
299  *     8 kbps (8)  1.89 kHz  0.86          +1.6 kHz
300  *    16 kbps (8)  3.16 kHz  1.24          +1.2 kHz
301  *    32 kbps(16)  5.08 kHz  1.54          +1.2 kHz
302  *    56 kbps(22)  7.88 kHz  1.80          +0.9 kHz
303  *    64 kbps(22)  8.83 kHz  1.86          +1.1 kHz
304  *   112 kbps(32) 14.02 kHz  2.12           0.0 kHz
305  *   112 kbps(44) 13.70 kHz  2.11          -0.3 kHz
306  *   128 kbps     15.40 kHz  2.17           0.0 kHz
307  *   160 kbps     16.80 kHz  2.22          -1.4 kHz 
308  *   192 kbps     19.66 kHz  2.30          -1.4 kHz
309  *   256 kbps     22.05 kHz  2.78           0.0 kHz
310  */
311
312
313 /*
314  *  Now we try to choose a good high pass filtering frequency.
315  *  This value is currently not used.
316  *    For fu < 16 kHz:  sqrt(fu*fl) = 560 Hz
317  *    For fu = 18 kHz:  no high pass filtering
318  *  This gives:
319  *
320  *   2 kHz => 160 Hz
321  *   3 kHz => 107 Hz
322  *   4 kHz =>  80 Hz
323  *   8 kHz =>  40 Hz
324  *  16 kHz =>  20 Hz
325  *  17 kHz =>  10 Hz
326  *  18 kHz =>   0 Hz
327  *
328  *  These are ad hoc values and these can be optimized if a high pass is available.
329  */
330     if (f_low <= 16000)
331         f_high = 16000. * 20. / f_low;
332     else if (f_low <= 18000)
333         f_high = 180. - 0.01 * f_low;
334     else
335         f_high = 0.;
336
337     /*  
338      *  When we sometimes have a good highpass filter, we can add the highpass
339      *  frequency to the lowpass frequency
340      */
341
342     if (lowerlimit != NULL)
343         *lowerlimit = (f_low>0.5 * samplefreq ? 0.5 * samplefreq : f_low); // roel - fixes mono "-b320 -a"
344     if (upperlimit != NULL)
345         *upperlimit = f_high;
346 /*
347  * Now the weak points:
348  *
349  *   - the formula f_low=br/log10(br*4.425e-3) is an ad hoc formula
350  *     (but has a physical background and is easy to tune)
351  *   - the switch to the ATH based bandwidth selecting is the ad hoc
352  *     value of 128 kbps
353  */
354 }
355
356 static int
357 optimum_samplefreq(int lowpassfreq, int input_samplefreq)
358 {
359 /*
360  * Rules:
361  *
362  *  - output sample frequency should NOT be decreased by more than 3% if lowpass allows this
363  *  - if possible, sfb21 should NOT be used
364  *
365  *  Problem: Switches to 32 kHz at 112 kbps
366  */
367     if (input_samplefreq <= 8000 * 1.03 || lowpassfreq <= 3622)
368         return 8000;
369     if (input_samplefreq <= 11025 * 1.03 || lowpassfreq <= 4991)
370         return 11025;
371     if (input_samplefreq <= 12000 * 1.03 || lowpassfreq <= 5620)
372         return 12000;
373     if (input_samplefreq <= 16000 * 1.03 || lowpassfreq <= 7244)
374         return 16000;
375     if (input_samplefreq <= 22050 * 1.03 || lowpassfreq <= 9982)
376         return 22050;
377     if (input_samplefreq <= 24000 * 1.03 || lowpassfreq <= 11240)
378         return 24000;
379     if (input_samplefreq <= 32000 * 1.03 || lowpassfreq <= 15264)
380         return 32000;
381     if (input_samplefreq <= 44100 * 1.03)
382         return 44100;
383     return 48000;
384 }
385
386
387 /* set internal feature flags.  USER should not access these since
388  * some combinations will produce strange results */
389 void
390 lame_init_qval(lame_global_flags * gfp)
391 {
392     lame_internal_flags *gfc = gfp->internal_flags;
393
394     switch (gfp->quality) {
395     case 9:            /* no psymodel, no noise shaping */
396         gfc->filter_type = 0;
397         gfc->psymodel = 0;
398         gfc->quantization = 0;
399         gfc->noise_shaping = 0;
400         gfc->noise_shaping_amp = 0;
401         gfc->noise_shaping_stop = 0;
402         gfc->use_best_huffman = 0;
403         break;
404
405     case 8:
406         gfp->quality = 7;
407     case 7:            /* use psymodel (for short block and m/s switching), but no noise shapping */
408         gfc->filter_type = 0;
409         gfc->psymodel = 1;
410         gfc->quantization = 0;
411         gfc->noise_shaping = 0;
412         gfc->noise_shaping_amp = 0;
413         gfc->noise_shaping_stop = 0;
414         gfc->use_best_huffman = 0;
415         break;
416
417     case 6:
418         gfp->quality = 5;
419     case 5:            /* the default */
420         gfc->filter_type = 0;
421         gfc->psymodel = 1;
422         gfc->quantization = 0;
423         gfc->noise_shaping = 1;
424          /**/ gfc->noise_shaping_amp = 0;
425         gfc->noise_shaping_stop = 0;
426         gfc->use_best_huffman = 0;
427         break;
428
429     case 4:
430         gfp->quality = 3;
431     case 3:
432         gfc->filter_type = 0;
433         gfc->psymodel = 1;
434         gfc->quantization = 1;
435         gfc->noise_shaping = 1;
436         gfc->noise_shaping_amp = 0;
437         gfc->noise_shaping_stop = 0;
438         gfc->use_best_huffman = 1;
439         break;
440
441     case 2:
442         gfc->filter_type = 0;
443         gfc->psymodel = 1;
444         gfc->quantization = 1;
445         gfc->noise_shaping = 1;
446         gfc->noise_shaping_amp = 1;
447         gfc->noise_shaping_stop = 1;
448         gfc->use_best_huffman = 1;
449         break;
450
451     case 1:
452         gfc->filter_type = 0;
453         gfc->psymodel = 1;
454         gfc->quantization = 1;
455         gfc->noise_shaping = 1;
456         gfc->noise_shaping_amp = 2;
457         gfc->noise_shaping_stop = 1;
458         gfc->use_best_huffman = 1;
459         break;
460
461     case 0:            /* 0..1 quality */
462         gfc->filter_type = 0; /* 1 not yet coded */
463         gfc->psymodel = 1;
464         gfc->quantization = 1;
465         gfc->noise_shaping = 1; /* 2=usually lowers quality */
466         gfc->noise_shaping_amp = 3;
467         gfc->noise_shaping_stop = 1;
468         gfc->use_best_huffman = 1; /* 2 not yet coded */
469     }
470
471     /* modifications to the above rules: */
472
473     /* -Z option toggles scalefactor_scale: */
474     if ( (gfp->experimentalZ & 1) > 0) {
475         gfc->noise_shaping = 2;
476     }
477 }
478
479
480
481
482
483
484
485 /* int           lame_init_params               (lame_global_flags *gfp)                                                                                          *//*{{{ */
486
487 /********************************************************************
488  *   initialize internal params based on data in gf
489  *   (globalflags struct filled in by calling program)
490  *
491  *  OUTLINE:
492  *
493  * We first have some complex code to determine bitrate, 
494  * output samplerate and mode.  It is complicated by the fact
495  * that we allow the user to set some or all of these parameters,
496  * and need to determine best possible values for the rest of them:
497  *
498  *  1. set some CPU related flags
499  *  2. check if we are mono->mono, stereo->mono or stereo->stereo
500  *  3.  compute bitrate and output samplerate:
501  *          user may have set compression ratio
502  *          user may have set a bitrate  
503  *          user may have set a output samplerate
504  *  4. set some options which depend on output samplerate
505  *  5. compute the actual compression ratio
506  *  6. set mode based on compression ratio
507  *
508  *  The remaining code is much simpler - it just sets options
509  *  based on the mode & compression ratio: 
510  *   
511  *   set allow_diff_short based on mode
512  *   select lowpass filter based on compression ratio & mode
513  *   set the bitrate index, and min/max bitrates for VBR modes
514  *   disable VBR tag if it is not appropriate
515  *   initialize the bitstream
516  *   initialize scalefac_band data
517  *   set sideinfo_len (based on channels, CRC, out_samplerate)
518  *   write an id3v2 tag into the bitstream
519  *   write VBR tag into the bitstream
520  *   set mpeg1/2 flag
521  *   estimate the number of frames (based on a lot of data)
522  *         
523  *   now we set more flags:
524  *   nspsytune:
525  *      see code
526  *   VBR modes
527  *      see code      
528  *   CBR/ABR
529  *      see code   
530  *
531  *  Finally, we set the algorithm flags based on the gfp->quality value
532  *  lame_init_qval(gfp);
533  *
534  ********************************************************************/
535 int
536 lame_init_params(lame_global_flags * const gfp)
537 {
538
539     int     i;
540     int     j;
541     lame_internal_flags *gfc = gfp->internal_flags;
542
543     gfc->gfp = gfp;
544
545     gfc->Class_ID = 0;
546
547     /* report functions */
548     gfc->report.msgf   = gfp->report.msgf;
549     gfc->report.debugf = gfp->report.debugf;
550     gfc->report.errorf = gfp->report.errorf;
551
552     gfc->CPU_features.i387 = has_i387();
553     gfc->CPU_features.AMD_3DNow = has_3DNow();
554     gfc->CPU_features.MMX = has_MMX();
555     gfc->CPU_features.SIMD = has_SIMD();
556     gfc->CPU_features.SIMD2 = has_SIMD2();
557
558
559     if (NULL == gfc->ATH)
560         gfc->ATH = calloc(1, sizeof(ATH_t));
561
562     if (NULL == gfc->ATH)
563         return -2;  // maybe error codes should be enumerated in lame.h ??
564
565     if (NULL == gfc->VBR)
566         gfc->VBR = calloc(1, sizeof(VBR_t));
567     if (NULL == gfc->VBR)
568         return -2;
569         
570     if (NULL == gfc->PSY)
571         gfc->PSY = calloc(1, sizeof(PSY_t));
572     if (NULL == gfc->PSY)
573         return -2;
574         
575 #ifdef KLEMM_44
576     /* Select the fastest functions for this CPU */
577     init_scalar_functions(gfc);
578 #endif
579
580     gfc->channels_in = gfp->num_channels;
581     if (gfc->channels_in == 1)
582         gfp->mode = MONO;
583     gfc->channels_out = (gfp->mode == MONO) ? 1 : 2;
584     gfc->mode_ext = MPG_MD_LR_LR;
585     if (gfp->mode == MONO)
586         gfp->force_ms = 0; // don't allow forced mid/side stereo for mono output
587
588
589     if (gfp->VBR != vbr_off) {
590         gfp->free_format = 0; /* VBR can't be mixed with free format */
591     }
592
593     if (gfp->VBR == vbr_off && gfp->brate == 0) {
594         /* no bitrate or compression ratio specified, use a compression ratio of 11.025 */
595         if (gfp->compression_ratio == 0)
596             gfp->compression_ratio = 11.025; /* rate to compress a CD down to exactly 128000 bps */
597     }
598
599
600     if (gfp->VBR == vbr_off && gfp->brate == 0) {
601         /* no bitrate or compression ratio specified, use 11.025 */
602         if (gfp->compression_ratio == 0)
603             gfp->compression_ratio = 11.025; /* rate to compress a CD down to exactly 128000 bps */
604     }
605
606     /* find bitrate if user specify a compression ratio */
607     if (gfp->VBR == vbr_off && gfp->compression_ratio > 0) {
608
609         if (gfp->out_samplerate == 0)
610             gfp->out_samplerate = map2MP3Frequency( (int)( 0.97 * gfp->in_samplerate ) ); /* round up with a margin of 3% */
611
612         /* choose a bitrate for the output samplerate which achieves
613          * specified compression ratio 
614          */
615         gfp->brate =
616             gfp->out_samplerate * 16 * gfc->channels_out / (1.e3 *
617                                                             gfp->
618                                                             compression_ratio);
619
620         /* we need the version for the bitrate table look up */
621         gfc->samplerate_index = SmpFrqIndex(gfp->out_samplerate, &gfp->version);
622
623         if (!gfp->free_format) /* for non Free Format find the nearest allowed bitrate */
624             gfp->brate =
625                 FindNearestBitrate(gfp->brate, gfp->version,
626                                    gfp->out_samplerate);
627     }
628
629     if (gfp->VBR != vbr_off && gfp->brate >= 320)
630         gfp->VBR = vbr_off; /* at 160 kbps (MPEG-2/2.5)/ 320 kbps (MPEG-1) only Free format or CBR are possible, no VBR */
631
632
633     if (gfp->out_samplerate == 0) { /* if output sample frequency is not given, find an useful value */
634         gfp->out_samplerate = map2MP3Frequency( (int)( 0.97 * gfp->in_samplerate ) );
635
636
637         /* check if user specified bitrate requires downsampling, if compression    */
638         /* ratio is > 13, choose a new samplerate to get the ratio down to about 10 */
639
640         if (gfp->VBR == vbr_off && gfp->brate > 0) {
641             gfp->compression_ratio =
642                 gfp->out_samplerate * 16 * gfc->channels_out / (1.e3 *
643                                                                 gfp->brate);
644             if (gfp->compression_ratio > 13.)
645                 gfp->out_samplerate =
646                     map2MP3Frequency( (int)( (10. * 1.e3 * gfp->brate) /
647                                      (16 * gfc->channels_out)));
648         }
649         if (gfp->VBR == vbr_abr) {
650             gfp->compression_ratio =
651                 gfp->out_samplerate * 16 * gfc->channels_out / (1.e3 *
652                                                                 gfp->
653                                                                 VBR_mean_bitrate_kbps);
654             if (gfp->compression_ratio > 13.)
655                 gfp->out_samplerate =
656                     map2MP3Frequency((int)((10. * 1.e3 * gfp->VBR_mean_bitrate_kbps) /
657                                      (16 * gfc->channels_out)));
658         }
659     }
660
661     if (gfp->ogg) {
662         gfp->framesize = 1024;
663         gfp->encoder_delay = ENCDELAY;
664         gfc->coding = coding_Ogg_Vorbis;
665     }
666     else {
667         gfc->mode_gr = gfp->out_samplerate <= 24000 ? 1 : 2; // Number of granules per frame
668         gfp->framesize = 576 * gfc->mode_gr;
669         gfp->encoder_delay = ENCDELAY;
670         gfc->coding = coding_MPEG_Layer_3;
671     }
672
673     gfc->frame_size = gfp->framesize;
674
675     gfc->resample_ratio = (double) gfp->in_samplerate / gfp->out_samplerate;
676
677     /* 
678      *  sample freq       bitrate     compression ratio
679      *     [kHz]      [kbps/channel]   for 16 bit input
680      *     44.1            56               12.6
681      *     44.1            64               11.025
682      *     44.1            80                8.82
683      *     22.05           24               14.7
684      *     22.05           32               11.025
685      *     22.05           40                8.82
686      *     16              16               16.0
687      *     16              24               10.667
688      *
689      */
690     /* 
691      *  For VBR, take a guess at the compression_ratio. 
692      *  For example:
693      *
694      *    VBR_q    compression     like
695      *     -        4.4         320 kbps/44 kHz
696      *   0...1      5.5         256 kbps/44 kHz
697      *     2        7.3         192 kbps/44 kHz
698      *     4        8.8         160 kbps/44 kHz
699      *     6       11           128 kbps/44 kHz
700      *     9       14.7          96 kbps
701      *
702      *  for lower bitrates, downsample with --resample
703      */
704
705     switch (gfp->VBR) {
706     case vbr_mt:
707     case vbr_rh:
708     case vbr_mtrh:
709         {
710             FLOAT8  cmp[] = { 5.7, 6.5, 7.3, 8.2, 9.1, 10, 11, 12, 13, 14 };
711             gfp->compression_ratio = cmp[gfp->VBR_q];
712         }
713         break;
714     case vbr_abr:
715         gfp->compression_ratio =
716             gfp->out_samplerate * 16 * gfc->channels_out / (1.e3 *
717                                                             gfp->
718                                                             VBR_mean_bitrate_kbps);
719         break;
720     default:
721         gfp->compression_ratio =
722             gfp->out_samplerate * 16 * gfc->channels_out / (1.e3 * gfp->brate);
723         break;
724     }
725
726
727     /* mode = -1 (not set by user) or 
728      * mode = MONO (because of only 1 input channel).  
729      * If mode has been set, then select between STEREO or J-STEREO
730      * At higher quality (lower compression) use STEREO instead of J-STEREO.
731      * (unless the user explicitly specified a mode)
732      *
733      * The threshold to switch to STEREO is:
734      *    48 kHz:   171 kbps (used at 192+)
735      *    44.1 kHz: 160 kbps (used at 160+)
736      *    32 kHz:   119 kbps (used at 128+)
737      *
738      *   Note, that for 32 kHz/128 kbps J-STEREO FM recordings sound much
739      *   better than STEREO, so I'm not so very happy with that. 
740      *   fs < 32 kHz I have not tested.
741      */
742     if (gfp->mode == NOT_SET) {
743         if (gfp->compression_ratio < 8)
744             gfp->mode = STEREO;
745         else
746             gfp->mode = JOINT_STEREO;
747     }
748
749     /* KLEMM's jstereo with ms threshold adjusted via compression ratio */
750     if (gfp->mode_automs) {
751         if (gfp->mode != MONO && gfp->compression_ratio < 6.6)
752             gfp->mode = STEREO;
753     }
754
755
756
757
758
759
760   /****************************************************************/
761   /* if a filter has not been enabled, see if we should add one: */
762   /****************************************************************/
763     if (gfp->lowpassfreq == 0) {
764         double  lowpass;
765         double  highpass;
766         double  channels;
767
768         switch (gfp->mode) {
769         case MONO:
770             channels = 1.;
771             break;
772         case JOINT_STEREO:
773             channels = 2. + 0.00;
774             break;
775         case DUAL_CHANNEL:
776         case STEREO:
777             channels = 3.;
778             break;
779         default:    
780             channels = 1.;  // just to make data flow analysis happy :-)
781             assert(0);
782             break;
783         }
784
785         optimum_bandwidth(&lowpass,
786                           &highpass,
787                           gfp->out_samplerate * 16 * gfc->channels_out /
788                           gfp->compression_ratio, gfp->out_samplerate, channels);
789                         
790 /*  roel - is this still needed?
791                 if (lowpass > 0.5 * gfp->out_samplerate) {
792             //MSGF(gfc,"Lowpass @ %7.1f Hz\n", lowpass);
793             gfc->lowpass1 = gfc->lowpass2 =
794                 lowpass / (0.5 * gfp->out_samplerate);
795         }
796 */
797         gfp->lowpassfreq = lowpass;
798
799 #if 0
800         if (gfp->out_samplerate !=
801             optimum_samplefreq(lowpass, gfp->in_samplerate)) {
802             MSGF(gfc,
803                  "I would suggest to use %u Hz instead of %u Hz sample frequency\n",
804                  optimum_samplefreq(lowpass, gfp->in_samplerate),
805                  gfp->out_samplerate);
806         }
807         fflush(stderr);
808 #endif
809     }
810
811     /* apply user driven high pass filter */
812     if (gfp->highpassfreq > 0) {
813         gfc->highpass1 = 2. * gfp->highpassfreq / gfp->out_samplerate; /* will always be >=0 */
814         if (gfp->highpasswidth >= 0)
815             gfc->highpass2 =
816                 2. * (gfp->highpassfreq +
817                       gfp->highpasswidth) / gfp->out_samplerate;
818         else            /* 0% above on default */
819             gfc->highpass2 =
820                 (1 + 0.00) * 2. * gfp->highpassfreq / gfp->out_samplerate;
821     }
822
823     /* apply user driven low pass filter */
824     if (gfp->lowpassfreq > 0) {
825         gfc->lowpass2 = 2. * gfp->lowpassfreq / gfp->out_samplerate; /* will always be >=0 */
826         if (gfp->lowpasswidth >= 0) {
827             gfc->lowpass1 =
828                 2. * (gfp->lowpassfreq -
829                       gfp->lowpasswidth) / gfp->out_samplerate;
830             if (gfc->lowpass1 < 0) /* has to be >= 0 */
831                 gfc->lowpass1 = 0;
832         }
833         else {          /* 0% below on default */
834             gfc->lowpass1 =
835                 (1 - 0.00) * 2. * gfp->lowpassfreq / gfp->out_samplerate;
836         }
837     }
838
839
840
841
842   /**********************************************************************/
843   /* compute info needed for polyphase filter (filter type==0, default) */
844   /**********************************************************************/
845     lame_init_params_ppflt(gfp);
846
847
848   /*******************************************************/
849   /* compute info needed for FIR filter (filter_type==1) */
850   /*******************************************************/
851    /* not yet coded */
852
853
854
855   /*******************************************************
856    * samplerate and bitrate index
857    *******************************************************/
858     gfc->samplerate_index = SmpFrqIndex(gfp->out_samplerate, &gfp->version);
859     if (gfc->samplerate_index < 0)
860         return -1;
861
862     if (gfp->VBR == vbr_off) {
863         if (gfp->free_format) {
864             gfc->bitrate_index = 0;
865         }
866         else {
867             gfc->bitrate_index = BitrateIndex(gfp->brate, gfp->version,
868                                               gfp->out_samplerate);
869             if (gfc->bitrate_index < 0)
870                 return -1;
871         }
872     }
873     else {              /* choose a min/max bitrate for VBR */
874         /* if the user didn't specify VBR_max_bitrate: */
875         gfc->VBR_min_bitrate = 1; /* default: allow   8 kbps (MPEG-2) or  32 kbps (MPEG-1) */
876         gfc->VBR_max_bitrate = 14; /* default: allow 160 kbps (MPEG-2) or 320 kbps (MPEG-1) */
877
878         if (gfp->VBR_min_bitrate_kbps)
879             if (
880                 (gfc->VBR_min_bitrate =
881                  BitrateIndex(gfp->VBR_min_bitrate_kbps, gfp->version,
882                               gfp->out_samplerate)) < 0) return -1;
883         if (gfp->VBR_max_bitrate_kbps)
884             if (
885                 (gfc->VBR_max_bitrate =
886                  BitrateIndex(gfp->VBR_max_bitrate_kbps, gfp->version,
887                               gfp->out_samplerate)) < 0) return -1;
888
889         gfp->VBR_min_bitrate_kbps =
890             bitrate_table[gfp->version][gfc->VBR_min_bitrate];
891         gfp->VBR_max_bitrate_kbps =
892             bitrate_table[gfp->version][gfc->VBR_max_bitrate];
893
894         gfp->VBR_mean_bitrate_kbps =
895             Min(bitrate_table[gfp->version][gfc->VBR_max_bitrate],
896                 gfp->VBR_mean_bitrate_kbps);
897         gfp->VBR_mean_bitrate_kbps =
898             Max(bitrate_table[gfp->version][gfc->VBR_min_bitrate],
899                 gfp->VBR_mean_bitrate_kbps);
900
901
902     }
903
904     /* for CBR, we will write an "info" tag. */
905     //    if ((gfp->VBR == vbr_off)) 
906     //  gfp->bWriteVbrTag = 0;
907
908     if (gfp->ogg)
909         gfp->bWriteVbrTag = 0;
910 #if defined(HAVE_GTK)
911     if (gfp->analysis)
912         gfp->bWriteVbrTag = 0;
913 #endif
914
915     /* some file options not allowed if output is: not specified or stdout */
916     if (gfc->pinfo != NULL)
917         gfp->bWriteVbrTag = 0; /* disable Xing VBR tag */
918
919     init_bit_stream_w(gfc);
920
921     j =
922         gfc->samplerate_index + (3 * gfp->version) + 6 * (gfp->out_samplerate <
923                                                           16000);
924     for (i = 0; i < SBMAX_l + 1; i++)
925         gfc->scalefac_band.l[i] = sfBandIndex[j].l[i];
926     for (i = 0; i < SBMAX_s + 1; i++)
927         gfc->scalefac_band.s[i] = sfBandIndex[j].s[i];
928
929     /* determine the mean bitrate for main data */
930     if (gfp->version == 1) /* MPEG 1 */
931         gfc->sideinfo_len = (gfc->channels_out == 1) ? 4 + 17 : 4 + 32;
932     else                /* MPEG 2 */
933         gfc->sideinfo_len = (gfc->channels_out == 1) ? 4 + 9 : 4 + 17;
934
935     if (gfp->error_protection)
936         gfc->sideinfo_len += 2;
937
938     lame_init_bitstream(gfp);
939
940
941     if (gfp->version == 1) /* 0 indicates use lower sample freqs algorithm */
942         gfc->is_mpeg1 = 1; /* yes */
943     else
944         gfc->is_mpeg1 = 0; /* no */
945
946     gfc->Class_ID = LAME_ID;
947
948
949     if (gfp->exp_nspsytune & 1) {
950         int     i,j;
951
952         gfc->nsPsy.use = 1;
953         gfc->nsPsy.safejoint = (gfp->exp_nspsytune & 2) != 0;
954         for (i = 0; i < 19; i++)
955             gfc->nsPsy.pefirbuf[i] = 700;
956
957         if (gfp->ATHtype == -1)
958             gfp->ATHtype = 4;
959
960         gfc->nsPsy.bass = gfc->nsPsy.alto = gfc->nsPsy.treble = 0;
961
962         i = (gfp->exp_nspsytune >> 2) & 63;
963         if (i >= 32)
964             i -= 64;
965         gfc->nsPsy.bass = pow(10, i / 4.0 / 10.0);
966         i = (gfp->exp_nspsytune >> 8) & 63;
967         if (i >= 32)
968             i -= 64;
969         gfc->nsPsy.alto = pow(10, i / 4.0 / 10.0);
970         i = (gfp->exp_nspsytune >> 14) & 63;
971         if (i >= 32)
972             i -= 64;
973         gfc->nsPsy.treble = pow(10, i / 4.0 / 10.0);
974         /*  to be compatible with Naoki's original code, the next 6 bits
975          *  define only the amount of changing treble for sfb21 */
976         j = (gfp->exp_nspsytune >> 20) & 63;
977         if (j >= 32)
978             j -= 64;
979         gfc->nsPsy.sfb21 = pow(10, (i+j) / 4.0 / 10.0);
980     }
981
982     assert( gfp->VBR_q <= 9 );
983     assert( gfp->VBR_q >= 0 );
984     
985     gfc->PSY->tonalityPatch = 0;
986   
987     switch (gfp->VBR) {
988
989     case vbr_mt:
990         gfp->VBR = vbr_mtrh;
991         
992     case vbr_mtrh:
993
994         if (gfp->ATHtype < 0) gfp->ATHtype = 4;
995         if (gfp->quality < 0) gfp->quality = 2;
996         if (gfp->quality > 7) {
997             gfp->quality = 7;     // needs psymodel
998             ERRORF( gfc, "VBR needs a psymodel, switching to quality level 7\n");
999         }
1000
1001         /*  tonality
1002          */
1003         if (gfp->cwlimit <= 0) gfp->cwlimit = 0.42 * gfp->out_samplerate;
1004         gfc->PSY->tonalityPatch = 1;
1005
1006         if ( gfp->experimentalX <= 4 && gfp->experimentalX >= 0 )
1007         {   /* map experimentalX settings to internal secltions */
1008             static char const map[] = {2,1,0,3,6};
1009             gfc->VBR->quality = map[gfp->experimentalX];
1010         }
1011         else    /* defaulting to */
1012         {
1013             gfc->VBR->quality = 2;
1014         }   
1015         if ( gfc->VBR->quality > 5 ) {
1016             static float const dbQ[10] = { -6,-4.75,-3.5,-2.25,-1,.25,1.5,2.75,4,5.25 };
1017             gfc->VBR->mask_adjust = dbQ[gfp->VBR_q];
1018             gfc->VBR->smooth = 1;   // not finally
1019         }
1020         else {
1021             static const float dbQ[10]={-2.,-1.0,-.66,-.33,0.,0.33,.66,1.0,1.33,1.66};
1022             gfc->VBR->mask_adjust = dbQ[gfp->VBR_q];
1023             gfc->VBR->smooth = 1;
1024         }
1025         if ( gfc->VBR->quality == 1 ) {
1026             static float const dbQ[10] = { -2., -1.4, -.7, 0, .7, 1.5, 2.3, 3.1, 4., 5 };
1027             gfc->VBR->mask_adjust = dbQ[gfp->VBR_q];
1028             gfc->VBR->smooth = 0;    
1029         }
1030         if ( gfc->VBR->quality == 0 ) {
1031             static float const dbQ[10] = { -1., -.6, -.3, 0, 1, 2, 3, 4, 5, 6};
1032             gfc->VBR->mask_adjust = dbQ[gfp->VBR_q];
1033             gfc->VBR->smooth = 0;    
1034             gfc->PSY->tonalityPatch = 0;
1035         }
1036         
1037         gfc->VBR->bitpressure = 1;
1038         
1039         if (gfp->experimentalY)
1040             gfc->sfb21_extra = 0;
1041         else
1042             gfc->sfb21_extra = (gfp->out_samplerate > 44000);
1043         
1044         if ( gfp->athaa_type < 0 )
1045             gfc->ATH->use_adjust = 3;
1046         else
1047             gfc->ATH->use_adjust = gfp->athaa_type;
1048         
1049         break;
1050         
1051
1052     case vbr_rh:
1053
1054         if (gfp->VBR == vbr_rh) /* because of above fall thru */
1055         {   static const FLOAT8 dbQ[10]={-2.,-1.0,-.66,-.33,0.,0.33,.66,1.0,1.33,1.66};
1056             static const FLOAT8 dbQns[10]={- 4,- 3,-2,-1,0,0.7,1.4,2.1,2.8,3.5};
1057             /*static const FLOAT8 atQns[10]={-16,-12,-8,-4,0,  1,  2,  3,  4,  5};*/
1058             if ( gfc->nsPsy.use )
1059                 gfc->VBR->mask_adjust = dbQns[gfp->VBR_q];
1060             else {
1061                 gfc->PSY->tonalityPatch = 1;
1062                 gfc->VBR->mask_adjust = dbQ[gfp->VBR_q]; 
1063             }
1064         }
1065         gfc->VBR->bitpressure = 1;
1066         
1067         /*  use Gabriel's adaptative ATH shape for VBR by default
1068          */
1069         if (gfp->ATHtype == -1)
1070             gfp->ATHtype = 4;
1071
1072         /*  automatic ATH adjustment on, VBR modes need it
1073          */
1074         if ( gfp->athaa_type < 0 )
1075             gfc->ATH->use_adjust = 3;
1076         else
1077             gfc->ATH->use_adjust = gfp->athaa_type;
1078
1079         /*  sfb21 extra only with MPEG-1 at higher sampling rates
1080          */
1081         if ( gfp->experimentalY )
1082             gfc->sfb21_extra = 0;
1083         else 
1084             gfc->sfb21_extra = (gfp->out_samplerate > 44000);
1085
1086         /*  VBR needs at least the output of GPSYCHO,
1087          *  so we have to garantee that by setting a minimum 
1088          *  quality level, actually level 5 does it.
1089          *  the -v and -V x settings switch the quality to level 2
1090          *  you would have to add a -q 5 to reduce the quality
1091          *  down to level 5
1092          */
1093         if (gfp->quality > 5)
1094             gfp->quality = 5;
1095
1096
1097         /*  default quality setting is 2
1098          */
1099         if (gfp->quality < 0)
1100             gfp->quality = 2;
1101
1102         break;
1103
1104     default:
1105
1106         if (gfp->ATHtype == -1)
1107             gfp->ATHtype = 2;
1108
1109         /*  automatic ATH adjustment off by default
1110          *  not so important for CBR code?
1111          */
1112         if ( gfp->athaa_type < 0 )
1113             gfc->ATH->use_adjust = 0;
1114         else
1115             gfc->ATH->use_adjust = gfp->athaa_type;
1116
1117
1118         /*  no sfb21 extra with CBR code
1119          */
1120         gfc->sfb21_extra = 0;
1121
1122         /*  default quality setting for CBR/ABR is 5
1123          */
1124         if (gfp->quality < 0)
1125             gfp->quality = 5;
1126
1127         break;
1128     }
1129     /*  just another daily changing developer switch  */
1130     if ( gfp->tune ) gfc->VBR->mask_adjust = gfp->tune_value_a;
1131
1132     /* initialize internal qval settings */
1133     lame_init_qval(gfp);
1134
1135 #ifdef KLEMM_44
1136     gfc->mfbuf[0] = (sample_t *) calloc(sizeof(sample_t), MFSIZE);
1137     gfc->mfbuf[1] = (sample_t *) calloc(sizeof(sample_t), MFSIZE);
1138     gfc->sampfreq_in = unround_samplefrequency(gfp->in_samplerate);
1139     gfc->sampfreq_out = gfp->out_samplerate;
1140     gfc->resample_in = resample_open(gfc->sampfreq_in,
1141                                      gfc->sampfreq_out, -1.0 /* Auto */, 32);
1142 #endif
1143
1144     /* initialize internal adaptive ATH settings  -jd */
1145     gfc->athaa_sensitivity_p = pow( 10.0, gfp->athaa_sensitivity / -10.0 );
1146
1147
1148     gfc->PSY->cwlimit = gfp->cwlimit <= 0 ? 8871.7f : gfp->cwlimit;
1149     
1150     if (gfp->short_blocks == short_block_not_set) {
1151         gfp->short_blocks =  short_block_allowed;
1152     }
1153     if (gfp->short_blocks == short_block_allowed && gfp->mode == JOINT_STEREO) {
1154         gfp->short_blocks =  short_block_coupled;
1155     }    
1156     
1157     if ( gfp->athaa_loudapprox < 0 ) gfp->athaa_loudapprox = 2;
1158     
1159     if (gfp->useTemporal < 0 ) gfp->useTemporal = 1;  // on by default
1160
1161
1162     if ( gfp->experimentalY )
1163         MSGF(gfc,"\n *** WARNING *** the meaning of the experimental -Y has changed!\n"
1164                    "                 now it tells LAME to ignore sfb21 noise shaping (VBR)\n\n");
1165
1166     if ( gfp->preset_expopts && gfc->presetTune.use < 1 )
1167         MSGF(gfc,"\n*** WARNING ***\n\n"
1168                          "Specialized tunings for the preset you are using have been deactivated.\n"
1169                  "This is *NOT* recommended and will lead to a decrease in quality!\n"
1170                      "\n*** WARNING ***\n\n");
1171
1172     return 0;
1173 }
1174
1175 /*}}}*/
1176 /* void          lame_print_config              (lame_global_flags *gfp)                                                                                          *//*{{{ */
1177
1178 /*
1179  *  print_config
1180  *
1181  *  Prints some selected information about the coding parameters via 
1182  *  the macro command MSGF(), which is currently mapped to lame_errorf 
1183  *  (reports via a error function?), which is a printf-like function 
1184  *  for <stderr>.
1185  */
1186
1187 void
1188 lame_print_config(const lame_global_flags * gfp)
1189 {
1190     lame_internal_flags *gfc = gfp->internal_flags;
1191     double  out_samplerate = gfp->out_samplerate;
1192     double  in_samplerate = gfp->out_samplerate * gfc->resample_ratio;
1193
1194     MSGF(gfc, "LAME version %s (%s)\n", get_lame_version(), get_lame_url());
1195
1196     if (gfc->CPU_features.MMX
1197         || gfc->CPU_features.AMD_3DNow
1198         || gfc->CPU_features.SIMD || gfc->CPU_features.SIMD2) {
1199         MSGF(gfc, "CPU features:");
1200
1201         if (gfc->CPU_features.i387)
1202             MSGF(gfc, " i387");
1203         if (gfc->CPU_features.MMX)
1204 #ifdef MMX_choose_table
1205             MSGF(gfc, ", MMX (ASM used)");
1206 #else
1207             MSGF(gfc, ", MMX");
1208 #endif
1209         if (gfc->CPU_features.AMD_3DNow)
1210             MSGF(gfc, ", 3DNow!");
1211         if (gfc->CPU_features.SIMD)
1212             MSGF(gfc, ", SIMD");
1213         if (gfc->CPU_features.SIMD2)
1214             MSGF(gfc, ", SIMD2");
1215         MSGF(gfc, "\n");
1216     }
1217
1218     if (gfp->num_channels == 2 && gfc->channels_out == 1 /* mono */ ) {
1219         MSGF
1220             (gfc,
1221              "Autoconverting from stereo to mono. Setting encoding to mono mode.\n");
1222     }
1223
1224     if (gfc->resample_ratio != 1.) {
1225         MSGF(gfc, "Resampling:  input %g kHz  output %g kHz\n",
1226              1.e-3 * in_samplerate, 1.e-3 * out_samplerate);
1227     }
1228
1229     if (gfc->filter_type == 0) {
1230         if (gfc->highpass2 > 0.)
1231             MSGF
1232                 (gfc,
1233                  "Using polyphase highpass filter, transition band: %5.0f Hz - %5.0f Hz\n",
1234                  0.5 * gfc->highpass1 * out_samplerate,
1235                  0.5 * gfc->highpass2 * out_samplerate);
1236         if (gfc->lowpass1 > 0.) {
1237             MSGF
1238                 (gfc,
1239                  "Using polyphase lowpass  filter, transition band: %5.0f Hz - %5.0f Hz\n",
1240                  0.5 * gfc->lowpass1 * out_samplerate,
1241                  0.5 * gfc->lowpass2 * out_samplerate);
1242         }
1243         else {
1244             MSGF(gfc, "polyphase lowpass filter disabled\n");
1245         }
1246     }
1247     else {
1248         MSGF(gfc, "polyphase filters disabled\n");
1249     }
1250
1251     if (gfp->free_format) {
1252         MSGF(gfc,
1253              "Warning: many decoders cannot handle free format bitstreams\n");
1254         if (gfp->brate > 320) {
1255             MSGF
1256                 (gfc,
1257                  "Warning: many decoders cannot handle free format bitrates >320 kbps (see documentation)\n");
1258         }
1259     }
1260 }
1261
1262
1263 /**     rh:
1264  *      some pretty printing is very welcome at this point!
1265  *      so, if someone is willing to do so, please do it!
1266  *      add more, if you see more...
1267  */
1268 void 
1269 lame_print_internals( const lame_global_flags * gfp )
1270 {
1271     lame_internal_flags *gfc = gfp->internal_flags;
1272     const char * pc = "";
1273
1274     /*  compiler/processor optimizations, operational, etc.
1275      */
1276     MSGF( gfc, "\nmisc:\n\n" );
1277     
1278     MSGF( gfc, "\tscaling: %f\n", gfp->scale );
1279     MSGF( gfc, "\tch0 (left) scaling: %f\n", gfp->scale_left );
1280     MSGF( gfc, "\tch1 (right) scaling: %f\n", gfp->scale_right );
1281     MSGF( gfc, "\tfilter type: %d\n", gfc->filter_type );
1282     pc = gfc->quantization ? "xr^3/4" : "ISO";
1283     MSGF( gfc, "\tquantization: %s\n", pc );
1284     switch( gfc->use_best_huffman ) {
1285     default: pc = "normal"; break;
1286     case  1: pc = "best (outside loop)"; break;
1287     case  2: pc = "best (inside loop, slow)"; break;
1288     } 
1289     MSGF( gfc, "\thuffman search: %s\n", pc ); 
1290     MSGF( gfc, "\texperimental X=%d Y=%d Z=%d\n", gfp->experimentalX, gfp->experimentalY, gfp->experimentalZ );
1291     MSGF( gfc, "\t...\n" );
1292
1293     /*  everything controlling the stream format 
1294      */
1295     MSGF( gfc, "\nstream format:\n\n" );
1296     switch ( gfp->version ) {
1297     case 0:  pc = "2.5"; break;
1298     case 1:  pc = "1";   break;
1299     case 2:  pc = "2";   break;
1300     default: pc = "?";   break;
1301     }
1302     MSGF( gfc, "\tMPEG-%s Layer 3\n", pc );
1303     switch ( gfp->mode ) {
1304     case JOINT_STEREO: pc = "joint stereo";   break;
1305     case STEREO      : pc = "stereo";         break;
1306     case DUAL_CHANNEL: pc = "dual channel";   break;
1307     case MONO        : pc = "mono";           break;
1308     case NOT_SET     : pc = "not set (error)"; break;
1309     default          : pc = "unknown (error)"; break;
1310     }
1311     MSGF( gfc, "\t%d channel - %s\n", gfc->channels_out, pc );
1312     switch ( gfp->padding_type ) {
1313     case PAD_NO    : pc = "off";    break;
1314     case PAD_ALL   : pc = "all";    break;
1315     case PAD_ADJUST: pc = "auto";   break;
1316     default        : pc = "(error)"; break;
1317     }
1318     MSGF( gfc, "\tpadding: %s\n", pc );
1319     
1320     if ( vbr_default == gfp->VBR )  pc = "(default)";
1321     else if ( gfp->free_format )    pc = "(free format)";
1322     else pc = "";
1323     switch ( gfp->VBR ) {
1324     case vbr_off : MSGF( gfc, "\tconstant bitrate - CBR %s\n",      pc ); break;
1325     case vbr_abr : MSGF( gfc, "\tvariable bitrate - ABR %s\n",      pc ); break;
1326     case vbr_rh  : MSGF( gfc, "\tvariable bitrate - VBR rh %s\n",   pc ); break;
1327     case vbr_mt  : MSGF( gfc, "\tvariable bitrate - VBR mt %s\n",   pc ); break;
1328     case vbr_mtrh: MSGF( gfc, "\tvariable bitrate - VBR mtrh %s\n", pc ); break; 
1329     default      : MSGF( gfc, "\t ?? oops, some new one ?? \n" );         break;
1330     }
1331     if (gfp->bWriteVbrTag) 
1332     MSGF( gfc, "\tusing LAME Tag\n" );
1333     MSGF( gfc, "\t...\n" );
1334     
1335     /*  everything controlling psychoacoustic settings, like ATH, etc.
1336      */
1337     MSGF( gfc, "\npsychoacoustic:\n\n" );
1338     
1339     MSGF( gfc, "\ttonality estimation limit: %f Hz\n", gfc->PSY->cwlimit );
1340     switch ( gfp->short_blocks ) {
1341     default:
1342     case short_block_not_set:   pc = "?";               break;
1343     case short_block_allowed:   pc = "allowed";         break;
1344     case short_block_coupled:   pc = "channel coupled"; break;
1345     case short_block_dispensed: pc = "dispensed";       break;
1346     case short_block_forced:    pc = "forced";          break;
1347     }
1348     MSGF( gfc, "\tusing short blocks: %s\n", pc );    
1349     MSGF( gfc, "\tadjust masking: %f dB\n", gfc->VBR->mask_adjust );
1350     MSGF( gfc, "\tpsymodel: %d\n", gfc->psymodel );
1351     MSGF( gfc, "\tnoise shaping: %d\n", gfc->noise_shaping );
1352     MSGF( gfc, "\t ^ amplification: %d\n", gfc->noise_shaping_amp );
1353     MSGF( gfc, "\t ^ stopping: %d\n", gfc->noise_shaping_stop );
1354     
1355     pc = "using";
1356     if ( gfp->ATHshort ) pc = "the only masking for short blocks";
1357     if ( gfp->ATHonly  ) pc = "the only masking";
1358     if ( gfp->noATH    ) pc = "not used";
1359     MSGF( gfc, "\tATH: %s\n", pc );
1360     MSGF( gfc, "\t ^ type: %d\n", gfp->ATHtype );
1361     MSGF( gfc, "\t ^ adjust type: %d\n", gfc->ATH->use_adjust );
1362     MSGF( gfc, "\t ^ adapt threshold type: %d\n", gfp->athaa_loudapprox );
1363     
1364     if ( gfc->nsPsy.use ) {
1365     MSGF( gfc, "\texperimental psy tunings by Naoki Shibata\n" ); 
1366     MSGF( gfc, "\t   adjust masking bass=%g dB, alto=%g dB, treble=%g dB, sfb21=%g dB\n", 
1367         10*log10(gfc->nsPsy.bass),   10*log10(gfc->nsPsy.alto), 
1368         10*log10(gfc->nsPsy.treble), 10*log10(gfc->nsPsy.sfb21) );
1369     }
1370     pc = gfp->useTemporal ? "yes" : "no";
1371     MSGF( gfc, "\tusing temporal masking effect: %s\n", pc );
1372     MSGF( gfc, "\t...\n" );
1373     
1374     /*  that's all ?
1375      */
1376     MSGF( gfc, "\n" );
1377     return;
1378 }
1379
1380
1381
1382 /* int           lame_encode_frame              (lame_global_flags *gfp, sample_t inbuf_l[],sample_t inbuf_r[], char *mp3buf, int mp3buf_size)                    *//*{{{ */
1383
1384 /* routine to feed exactly one frame (gfp->framesize) worth of data to the 
1385 encoding engine.  All buffering, resampling, etc, handled by calling
1386 program.  
1387 */
1388 int
1389 lame_encode_frame(lame_global_flags * gfp,
1390                   sample_t inbuf_l[], sample_t inbuf_r[],
1391                   unsigned char *mp3buf, int mp3buf_size)
1392 {
1393     int     ret;
1394     if (gfp->ogg) {
1395 #ifdef HAVE_VORBIS_ENCODER
1396         ret = lame_encode_ogg_frame(gfp, inbuf_l, inbuf_r, mp3buf, mp3buf_size);
1397 #else
1398         return -5;      /* wanna encode ogg without vorbis */
1399 #endif
1400     }
1401     else {
1402         ret = lame_encode_mp3_frame(gfp, inbuf_l, inbuf_r, mp3buf, mp3buf_size);
1403     }
1404
1405
1406
1407     gfp->frameNum++;
1408     return ret;
1409 }
1410
1411 /*}}}*/
1412 /* int           lame_encode_buffer             (lame_global_flags* gfp, short int buffer_l[], short int buffer_r[], int nsamples, char* mp3buf, int mp3buf_size )*//*{{{ */
1413
1414
1415
1416 /*
1417  * THE MAIN LAME ENCODING INTERFACE
1418  * mt 3/00
1419  *
1420  * input pcm data, output (maybe) mp3 frames.
1421  * This routine handles all buffering, resampling and filtering for you.
1422  * The required mp3buffer_size can be computed from num_samples,
1423  * samplerate and encoding rate, but here is a worst case estimate:
1424  *
1425  * mp3buffer_size in bytes = 1.25*num_samples + 7200
1426  *
1427  * return code = number of bytes output in mp3buffer.  can be 0
1428 */
1429 int
1430 lame_encode_buffer_sample_t(lame_global_flags * gfp,
1431                    sample_t buffer_l[],
1432                    sample_t buffer_r[],
1433                    int nsamples, unsigned char *mp3buf, const int mp3buf_size)
1434 {
1435     lame_internal_flags *gfc = gfp->internal_flags;
1436     int     mp3size = 0, ret, i, ch, mf_needed;
1437     int mp3out;
1438     sample_t *mfbuf[2];
1439     sample_t *in_buffer[2];
1440
1441     if (gfc->Class_ID != LAME_ID)
1442         return -3;
1443
1444     if (nsamples == 0)
1445         return 0;
1446
1447     /* copy out any tags that may have been written into bitstream */
1448     mp3out = copy_buffer(gfc,mp3buf,mp3buf_size,0);
1449     if (mp3out<0) return mp3out;  // not enough buffer space
1450     mp3buf += mp3out;
1451     mp3size += mp3out;
1452
1453
1454     in_buffer[0]=buffer_l;
1455     in_buffer[1]=buffer_r;  
1456
1457
1458     /* some sanity checks */
1459 #if ENCDELAY < MDCTDELAY
1460 # error ENCDELAY is less than MDCTDELAY, see encoder.h
1461 #endif
1462 #if FFTOFFSET > BLKSIZE
1463 # error FFTOFFSET is greater than BLKSIZE, see encoder.h
1464 #endif
1465
1466     mf_needed = BLKSIZE + gfp->framesize - FFTOFFSET; /* amount needed for FFT */
1467     mf_needed = Max(mf_needed, 286 + 576 * (1 + gfc->mode_gr)); /* amount needed for MDCT/filterbank */
1468     assert(MFSIZE >= mf_needed);
1469
1470     mfbuf[0] = gfc->mfbuf[0];
1471     mfbuf[1] = gfc->mfbuf[1];
1472
1473     if (gfp->num_channels == 2 && gfc->channels_out == 1) {
1474         /* downsample to mono */
1475         for (i = 0; i < nsamples; ++i) {
1476             in_buffer[0][i] =
1477                 0.5 * ((FLOAT8) in_buffer[0][i] + in_buffer[1][i]);
1478             in_buffer[1][i] = 0.0;
1479         }
1480     }
1481
1482
1483     while (nsamples > 0) {
1484         int     n_in = 0;    /* number of input samples processed with fill_buffer */
1485         int     n_out = 0;   /* number of samples output with fill_buffer */
1486         /* n_in <> n_out if we are resampling */
1487
1488         /* copy in new samples into mfbuf, with resampling & scaling if necessary */
1489         fill_buffer(gfp, mfbuf, in_buffer, nsamples, &n_in, &n_out);
1490
1491         /* update in_buffer counters */
1492         nsamples -= n_in;
1493         in_buffer[0] += n_in;
1494         if (gfc->channels_out == 2)
1495             in_buffer[1] += n_in;
1496
1497         /* update mfbuf[] counters */
1498         gfc->mf_size += n_out;
1499         assert(gfc->mf_size <= MFSIZE);
1500         gfc->mf_samples_to_encode += n_out;
1501
1502
1503         if (gfc->mf_size >= mf_needed) {
1504             /* encode the frame.  */
1505             // mp3buf              = pointer to current location in buffer
1506             // mp3buf_size         = size of original mp3 output buffer
1507             //                     = 0 if we should not worry about the
1508             //                       buffer size because calling program is 
1509             //                       to lazy to compute it
1510             // mp3size             = size of data written to buffer so far
1511             // mp3buf_size-mp3size = amount of space avalable 
1512
1513             int buf_size=mp3buf_size - mp3size;
1514             if (mp3buf_size==0) buf_size=0;
1515
1516             ret =
1517                 lame_encode_frame(gfp, mfbuf[0], mfbuf[1], mp3buf,buf_size);
1518
1519             if (ret < 0) goto retr;
1520             mp3buf += ret;
1521             mp3size += ret;
1522
1523             /* shift out old samples */
1524             gfc->mf_size -= gfp->framesize;
1525             gfc->mf_samples_to_encode -= gfp->framesize;
1526             for (ch = 0; ch < gfc->channels_out; ch++)
1527                 for (i = 0; i < gfc->mf_size; i++)
1528                     mfbuf[ch][i] = mfbuf[ch][i + gfp->framesize];
1529         }
1530     }
1531     assert(nsamples == 0);
1532     ret = mp3size;
1533
1534   retr:
1535     return ret;
1536 }
1537
1538
1539 int
1540 lame_encode_buffer(lame_global_flags * gfp,
1541                    const short int buffer_l[],
1542                    const short int buffer_r[],
1543                    const int nsamples, unsigned char *mp3buf, const int mp3buf_size)
1544 {
1545     lame_internal_flags *gfc = gfp->internal_flags;
1546     int     ret, i;
1547     sample_t *in_buffer[2];
1548
1549     if (gfc->Class_ID != LAME_ID)
1550         return -7; //-3
1551
1552     if (nsamples == 0)
1553         return 0;
1554
1555     in_buffer[0] = calloc(sizeof(sample_t), nsamples);
1556     in_buffer[1] = calloc(sizeof(sample_t), nsamples);
1557
1558     if (in_buffer[0] == NULL || in_buffer[1] == NULL) {
1559         ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
1560         return -2;
1561     }
1562
1563     /* make a copy of input buffer, changing type to sample_t */
1564     for (i = 0; i < nsamples; i++) {
1565         in_buffer[0][i] = buffer_l[i];
1566         in_buffer[1][i] = buffer_r[i];
1567     }
1568
1569     ret = lame_encode_buffer_sample_t(gfp,in_buffer[0],in_buffer[1],
1570                                       nsamples, mp3buf, mp3buf_size);
1571     
1572     free(in_buffer[0]);
1573     free(in_buffer[1]);
1574     return ret;
1575 }
1576
1577
1578 int
1579 lame_encode_buffer_float(lame_global_flags * gfp,
1580                    const float buffer_l[],
1581                    const float buffer_r[],
1582                    const int nsamples, unsigned char *mp3buf, const int mp3buf_size)
1583 {
1584     lame_internal_flags *gfc = gfp->internal_flags;
1585     int     ret, i;
1586     sample_t *in_buffer[2];
1587
1588     if (gfc->Class_ID != LAME_ID)
1589         return -3;
1590
1591     if (nsamples == 0)
1592         return 0;
1593
1594     in_buffer[0] = calloc(sizeof(sample_t), nsamples);
1595     in_buffer[1] = calloc(sizeof(sample_t), nsamples);
1596
1597     if (in_buffer[0] == NULL || in_buffer[1] == NULL) {
1598         ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
1599         return -2;
1600     }
1601
1602     /* make a copy of input buffer, changing type to sample_t */
1603     for (i = 0; i < nsamples; i++) {
1604         in_buffer[0][i] = buffer_l[i];
1605         in_buffer[1][i] = buffer_r[i];
1606     }
1607
1608     ret = lame_encode_buffer_sample_t(gfp,in_buffer[0],in_buffer[1],
1609                                       nsamples, mp3buf, mp3buf_size);
1610     
1611     free(in_buffer[0]);
1612     free(in_buffer[1]);
1613     return ret;
1614 }
1615
1616
1617
1618 int
1619 lame_encode_buffer_int(lame_global_flags * gfp,
1620                    const int buffer_l[],
1621                    const int buffer_r[],
1622                    const int nsamples, unsigned char *mp3buf, const int mp3buf_size)
1623 {
1624     lame_internal_flags *gfc = gfp->internal_flags;
1625     int     ret, i;
1626     sample_t *in_buffer[2];
1627
1628     if (gfc->Class_ID != LAME_ID)
1629         return -3;
1630
1631     if (nsamples == 0)
1632         return 0;
1633
1634     in_buffer[0] = calloc(sizeof(sample_t), nsamples);
1635     in_buffer[1] = calloc(sizeof(sample_t), nsamples);
1636
1637     if (in_buffer[0] == NULL || in_buffer[1] == NULL) {
1638         ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
1639         return -2;
1640     }
1641
1642     /* make a copy of input buffer, changing type to sample_t */
1643     for (i = 0; i < nsamples; i++) {
1644                                 /* internal code expects +/- 32768.0 */
1645       in_buffer[0][i] = buffer_l[i] * (1.0 / ( 1 << (8 * sizeof(int) - 16)));
1646       in_buffer[1][i] = buffer_r[i] * (1.0 / ( 1 << (8 * sizeof(int) - 16)));
1647     }
1648
1649     ret = lame_encode_buffer_sample_t(gfp,in_buffer[0],in_buffer[1],
1650                                       nsamples, mp3buf, mp3buf_size);
1651     
1652     free(in_buffer[0]);
1653     free(in_buffer[1]);
1654     return ret;
1655
1656 }
1657
1658
1659
1660
1661 int
1662 lame_encode_buffer_long2(lame_global_flags * gfp,
1663                    const long buffer_l[],
1664                    const long buffer_r[],
1665                    const int nsamples, unsigned char *mp3buf, const int mp3buf_size)
1666 {
1667     lame_internal_flags *gfc = gfp->internal_flags;
1668     int     ret, i;
1669     sample_t *in_buffer[2];
1670
1671     if (gfc->Class_ID != LAME_ID)
1672         return -3;
1673
1674     if (nsamples == 0)
1675         return 0;
1676
1677     in_buffer[0] = calloc(sizeof(sample_t), nsamples);
1678     in_buffer[1] = calloc(sizeof(sample_t), nsamples);
1679
1680     if (in_buffer[0] == NULL || in_buffer[1] == NULL) {
1681         ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
1682         return -2;
1683     }
1684
1685     /* make a copy of input buffer, changing type to sample_t */
1686     for (i = 0; i < nsamples; i++) {
1687                                 /* internal code expects +/- 32768.0 */
1688       in_buffer[0][i] = buffer_l[i] * (1.0 / ( 1 << (8 * sizeof(long) - 16)));
1689       in_buffer[1][i] = buffer_r[i] * (1.0 / ( 1 << (8 * sizeof(long) - 16)));
1690     }
1691
1692     ret = lame_encode_buffer_sample_t(gfp,in_buffer[0],in_buffer[1],
1693                                       nsamples, mp3buf, mp3buf_size);
1694     
1695     free(in_buffer[0]);
1696     free(in_buffer[1]);
1697     return ret;
1698
1699 }
1700
1701
1702
1703 int
1704 lame_encode_buffer_long(lame_global_flags * gfp,
1705                    const long buffer_l[],
1706                    const long buffer_r[],
1707                    const int nsamples, unsigned char *mp3buf, const int mp3buf_size)
1708 {
1709     lame_internal_flags *gfc = gfp->internal_flags;
1710     int     ret, i;
1711     sample_t *in_buffer[2];
1712
1713     if (gfc->Class_ID != LAME_ID)
1714         return -3;
1715
1716     if (nsamples == 0)
1717         return 0;
1718
1719     in_buffer[0] = calloc(sizeof(sample_t), nsamples);
1720     in_buffer[1] = calloc(sizeof(sample_t), nsamples);
1721
1722     if (in_buffer[0] == NULL || in_buffer[1] == NULL) {
1723         ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
1724         return -2;
1725     }
1726
1727     /* make a copy of input buffer, changing type to sample_t */
1728     for (i = 0; i < nsamples; i++) {
1729         in_buffer[0][i] = buffer_l[i];
1730         in_buffer[1][i] = buffer_r[i];
1731     }
1732
1733     ret = lame_encode_buffer_sample_t(gfp,in_buffer[0],in_buffer[1],
1734                                       nsamples, mp3buf, mp3buf_size);
1735     
1736     free(in_buffer[0]);
1737     free(in_buffer[1]);
1738     return ret;
1739 }
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751 int
1752 lame_encode_buffer_interleaved(lame_global_flags * gfp,
1753                                short int buffer[],
1754                                int nsamples,
1755                                unsigned char *mp3buf, int mp3buf_size)
1756 {
1757     int     ret, i;
1758     short int *buffer_l;
1759     short int *buffer_r;
1760
1761     buffer_l = malloc(sizeof(short int) * nsamples);
1762     buffer_r = malloc(sizeof(short int) * nsamples);
1763     if (buffer_l == NULL || buffer_r == NULL) {
1764         return -2;
1765     }
1766     for (i = 0; i < nsamples; i++) {
1767         buffer_l[i] = buffer[2 * i];
1768         buffer_r[i] = buffer[2 * i + 1];
1769     }
1770     ret =
1771         lame_encode_buffer(gfp, buffer_l, buffer_r, nsamples, mp3buf,
1772                            mp3buf_size);
1773     free(buffer_l);
1774     free(buffer_r);
1775     return ret;
1776
1777 }
1778
1779
1780 /*}}}*/
1781 /* int           lame_encode                    (lame_global_flags* gfp, short int in_buffer[2][1152], char* mp3buf, int size )                                   *//*{{{ */
1782
1783
1784 /* old LAME interface.  use lame_encode_buffer instead */
1785
1786 int
1787 lame_encode(lame_global_flags * const gfp,
1788             const short int in_buffer[2][1152],
1789             unsigned char *const mp3buf, const int size)
1790 {
1791     lame_internal_flags *gfc = gfp->internal_flags;
1792
1793     if (gfc->Class_ID != LAME_ID)
1794         return -3;
1795
1796     return lame_encode_buffer(gfp, in_buffer[0], in_buffer[1], gfp->framesize,
1797                               mp3buf, size);
1798 }
1799
1800 /*}}}*/
1801 /* int           lame_encode_flush              (lame_global_flags* gfp, char* mp3buffer, int mp3buffer_size )                                                    *//*{{{ */
1802
1803
1804
1805 /*****************************************************************
1806  Flush mp3 buffer, pad with ancillary data so last frame is complete.
1807  Reset reservoir size to 0                  
1808  but keep all PCM samples and MDCT data in memory             
1809  This option is used to break a large file into several mp3 files 
1810  that when concatenated together will decode with no gaps         
1811  Because we set the reservoir=0, they will also decode seperately 
1812  with no errors. 
1813 *********************************************************************/
1814 int
1815 lame_encode_flush_nogap(lame_global_flags * gfp,
1816                   unsigned char *mp3buffer, int mp3buffer_size)
1817 {
1818     lame_internal_flags *gfc = gfp->internal_flags;
1819     flush_bitstream(gfp);
1820     return copy_buffer(gfc,mp3buffer, mp3buffer_size,1);
1821 }
1822
1823
1824 /* called by lame_init_params.  You can also call this after flush_nogap 
1825    if you want to write new id3v2 and Xing VBR tags into the bitstream */
1826 int
1827 lame_init_bitstream(lame_global_flags * gfp)
1828 {
1829     lame_internal_flags *gfc = gfp->internal_flags;
1830     int i;
1831     gfp->frameNum=0;
1832
1833     if (!gfp->ogg)
1834         id3tag_write_v2(gfp);
1835
1836     /* initialize histogram data optionally used by frontend */
1837     for ( i = 0; i < 16; i++ ) 
1838         gfc->bitrate_stereoMode_Hist [i] [0] =
1839             gfc->bitrate_stereoMode_Hist [i] [1] =
1840             gfc->bitrate_stereoMode_Hist [i] [2] =
1841             gfc->bitrate_stereoMode_Hist [i] [3] =
1842             gfc->bitrate_stereoMode_Hist [i] [4] = 0;
1843
1844     /* Write initial VBR Header to bitstream and init VBR data */
1845     if (gfp->bWriteVbrTag)
1846         InitVbrTag(gfp);
1847
1848     
1849     return 0;
1850 }
1851
1852
1853 /*****************************************************************/
1854 /* flush internal PCM sample buffers, then mp3 buffers           */
1855 /* then write id3 v1 tags into bitstream.                        */
1856 /*****************************************************************/
1857
1858 int
1859 lame_encode_flush(lame_global_flags * gfp,
1860                   unsigned char *mp3buffer, int mp3buffer_size)
1861 {
1862     lame_internal_flags *gfc = gfp->internal_flags;
1863     short int buffer[2][1152];
1864     int     imp3 = 0, mp3count, mp3buffer_size_remaining;
1865
1866     /* we always add POSTDELAY=288 padding to make sure granule with real
1867      * data can be complety decoded (because of 50% overlap with next granule */
1868     int end_padding=POSTDELAY;  
1869
1870     memset(buffer, 0, sizeof(buffer));
1871     mp3count = 0;
1872
1873
1874     while (gfc->mf_samples_to_encode > 0) {
1875
1876         mp3buffer_size_remaining = mp3buffer_size - mp3count;
1877
1878         /* if user specifed buffer size = 0, dont check size */
1879         if (mp3buffer_size == 0)
1880             mp3buffer_size_remaining = 0;
1881
1882         /* send in a frame of 0 padding until all internal sample buffers
1883          * are flushed 
1884          */
1885         imp3 = lame_encode_buffer(gfp, buffer[0], buffer[1], gfp->framesize,
1886                                   mp3buffer, mp3buffer_size_remaining);
1887
1888         /* don't count the above padding: */
1889         gfc->mf_samples_to_encode -= gfp->framesize;
1890         if (gfc->mf_samples_to_encode < 0) {
1891             /* we added extra padding to the end */
1892             end_padding += -gfc->mf_samples_to_encode;  
1893         }
1894
1895
1896         if (imp3 < 0) {
1897             /* some type of fatal error */
1898             return imp3;
1899         }
1900         mp3buffer += imp3;
1901         mp3count += imp3;
1902     }
1903
1904     mp3buffer_size_remaining = mp3buffer_size - mp3count;
1905     /* if user specifed buffer size = 0, dont check size */
1906     if (mp3buffer_size == 0)
1907         mp3buffer_size_remaining = 0;
1908
1909     if (gfp->ogg) {
1910 #ifdef HAVE_VORBIS_ENCODER
1911         /* ogg related stuff */
1912         imp3 = lame_encode_ogg_finish(gfp, mp3buffer, mp3buffer_size_remaining);
1913 #endif
1914     }
1915     else {
1916         /* mp3 related stuff.  bit buffer might still contain some mp3 data */
1917         flush_bitstream(gfp);
1918         imp3 = copy_buffer(gfc,mp3buffer, mp3buffer_size_remaining, 1);
1919         if (imp3 < 0) {
1920             /* some type of fatal error */
1921             return imp3;
1922         }
1923         mp3buffer += imp3;
1924         mp3count += imp3;
1925         mp3buffer_size_remaining = mp3buffer_size - mp3count;
1926         /* if user specifed buffer size = 0, dont check size */
1927         if (mp3buffer_size == 0)
1928             mp3buffer_size_remaining = 0;
1929
1930
1931         /* write a id3 tag to the bitstream */
1932         id3tag_write_v1(gfp);
1933         imp3 = copy_buffer(gfc,mp3buffer, mp3buffer_size_remaining, 0);
1934     }
1935
1936     if (imp3 < 0) {
1937         return imp3;
1938     }
1939     mp3count += imp3;
1940     gfp->encoder_padding=end_padding;
1941     return mp3count;
1942 }
1943
1944 /*}}}*/
1945 /* void          lame_close                     (lame_global_flags *gfp)                                                                                          *//*{{{ */
1946
1947 /***********************************************************************
1948  *
1949  *      lame_close ()
1950  *
1951  *  frees internal buffers
1952  *
1953  ***********************************************************************/
1954
1955 int
1956 lame_close(lame_global_flags * gfp)
1957 {
1958     lame_internal_flags *gfc = gfp->internal_flags;
1959
1960     if (gfc->Class_ID != LAME_ID)
1961         return -3;
1962
1963     gfc->Class_ID = 0;
1964
1965     // this routien will free all malloc'd data in gfc, and then free gfc:
1966     freegfc(gfc);
1967
1968     gfp->internal_flags = NULL;
1969
1970     if (gfp->lame_allocated_gfp)
1971         free(gfp);
1972
1973     return 0;
1974 }
1975
1976
1977 /*}}}*/
1978 /* int           lame_encode_finish             (lame_global_flags* gfp, char* mp3buffer, int mp3buffer_size )                                                    *//*{{{ */
1979
1980
1981 /*****************************************************************/
1982 /* flush internal mp3 buffers, and free internal buffers         */
1983 /*****************************************************************/
1984
1985 int
1986 lame_encode_finish(lame_global_flags * gfp,
1987                    unsigned char *mp3buffer, int mp3buffer_size)
1988 {
1989     int     ret = lame_encode_flush(gfp, mp3buffer, mp3buffer_size);
1990
1991     lame_close(gfp);
1992
1993     return ret;
1994 }
1995
1996 /*}}}*/
1997 /* void          lame_mp3_tags_fid              (lame_global_flags *gfp,FILE *fpStream)                                                                           *//*{{{ */
1998
1999 /*****************************************************************/
2000 /* write VBR Xing header, and ID3 version 1 tag, if asked for    */
2001 /*****************************************************************/
2002 void
2003 lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream)
2004 {
2005     if (gfp->bWriteVbrTag) {
2006         /* Map VBR_q to Xing quality value: 0=worst, 100=best */
2007         int     nQuality = ((9-gfp->VBR_q) * 100) / 9;
2008
2009         /* Write Xing header again */
2010         if (fpStream && !fseek(fpStream, 0, SEEK_SET))
2011             PutVbrTag(gfp, fpStream, nQuality);
2012     }
2013
2014
2015 }
2016 /*}}}*/
2017 /* lame_global_flags *lame_init                 (void)                                                                                                            *//*{{{ */
2018
2019 lame_global_flags *
2020 lame_init(void)
2021 {
2022     lame_global_flags *gfp;
2023     int     ret;
2024
2025     gfp = calloc(1, sizeof(lame_global_flags));
2026     if (gfp == NULL)
2027         return NULL;
2028
2029     ret = lame_init_old(gfp);
2030     if (ret != 0) {
2031         free(gfp);
2032         return NULL;
2033     }
2034
2035     gfp->lame_allocated_gfp = 1;
2036     return gfp;
2037 }
2038
2039 /*}}}*/
2040 /* int           lame_init_old                  (lame_global_flags *gfp)                                                                                          *//*{{{ */
2041
2042 /* initialize mp3 encoder */
2043 int
2044 lame_init_old(lame_global_flags * gfp)
2045 {
2046     lame_internal_flags *gfc;
2047
2048     disable_FPE();      // disable floating point exceptions
2049
2050     memset(gfp, 0, sizeof(lame_global_flags));
2051
2052     if (NULL ==
2053         (gfc = gfp->internal_flags =
2054          calloc(1, sizeof(lame_internal_flags)))) return -1;
2055
2056     /* Global flags.  set defaults here for non-zero values */
2057     /* see lame.h for description */
2058     /* set integer values to -1 to mean that LAME will compute the
2059      * best value, UNLESS the calling program as set it
2060      * (and the value is no longer -1)
2061      */
2062
2063
2064     gfp->mode = NOT_SET;
2065     gfp->original = 1;
2066     gfp->in_samplerate = 1000 * 44.1;
2067     gfp->num_channels = 2;
2068     gfp->num_samples = MAX_U_32_NUM;
2069
2070     gfp->bWriteVbrTag = 1;
2071     gfp->quality = -1;
2072     gfp->short_blocks = short_block_not_set;
2073
2074     gfp->lowpassfreq = 0;
2075     gfp->highpassfreq = 0;
2076     gfp->lowpasswidth = -1;
2077     gfp->highpasswidth = -1;
2078
2079     gfp->padding_type = PAD_ADJUST;
2080     gfp->VBR = vbr_off;
2081     gfp->VBR_q = 4;
2082     gfp->VBR_mean_bitrate_kbps = 128;
2083     gfp->VBR_min_bitrate_kbps = 0;
2084     gfp->VBR_max_bitrate_kbps = 0;
2085     gfp->VBR_hard_min = 0;
2086
2087
2088     gfc->resample_ratio = 1;
2089     gfc->lowpass_band = 32;
2090     gfc->highpass_band = -1;
2091     gfc->VBR_min_bitrate = 1; /* not  0 ????? */
2092     gfc->VBR_max_bitrate = 13; /* not 14 ????? */
2093
2094     gfc->OldValue[0] = 180;
2095     gfc->OldValue[1] = 180;
2096     gfc->CurrentStep = 4;
2097     gfc->masking_lower = 1;
2098
2099     gfp->athaa_type = -1;
2100     gfp->ATHtype = -1;  /* default = -1 = set in lame_init_params */
2101     gfp->athaa_loudapprox = -1; /* 1 = flat loudness approx. (total energy) */
2102                                 /* 2 = equal loudness curve */
2103     gfp->athaa_sensitivity = 0.0; /* no offset */
2104     gfp->useTemporal = -1;
2105
2106     /* The reason for
2107      *       int mf_samples_to_encode = ENCDELAY + POSTDELAY;
2108      * ENCDELAY = internal encoder delay.  And then we have to add POSTDELAY=288
2109      * because of the 50% MDCT overlap.  A 576 MDCT granule decodes to
2110      * 1152 samples.  To synthesize the 576 samples centered under this granule
2111      * we need the previous granule for the first 288 samples (no problem), and
2112      * the next granule for the next 288 samples (not possible if this is last
2113      * granule).  So we need to pad with 288 samples to make sure we can
2114      * encode the 576 samples we are interested in.
2115      */
2116     gfc->mf_samples_to_encode = ENCDELAY + POSTDELAY;
2117     gfp->encoder_padding = 0;
2118     gfc->mf_size = ENCDELAY - MDCTDELAY; /* we pad input with this many 0's */
2119
2120 #ifdef KLEMM_44
2121     /* XXX: this wasn't protectes by KLEMM_44 initially! */
2122     gfc->last_ampl = gfc->ampl = +1.0;
2123 #endif
2124     return 0;
2125 }
2126
2127 /*}}}*/
2128
2129 /***********************************************************************
2130  *
2131  *  some simple statistics
2132  *
2133  *  Robert Hegemann 2000-10-11
2134  *
2135  ***********************************************************************/
2136
2137 /*  histogram of used bitrate indexes:
2138  *  One has to weight them to calculate the average bitrate in kbps
2139  *
2140  *  bitrate indices:
2141  *  there are 14 possible bitrate indices, 0 has the special meaning 
2142  *  "free format" which is not possible to mix with VBR and 15 is forbidden
2143  *  anyway.
2144  *
2145  *  stereo modes:
2146  *  0: LR   number of left-right encoded frames
2147  *  1: LR-I number of left-right and intensity encoded frames
2148  *  2: MS   number of mid-side encoded frames
2149  *  3: MS-I number of mid-side and intensity encoded frames
2150  *
2151  *  4: number of encoded frames
2152  *
2153  */
2154
2155 void
2156 lame_bitrate_hist(const lame_global_flags * const gfp, int bitrate_count[14])
2157 {
2158     const lame_internal_flags *gfc;
2159     int     i;
2160
2161     if (NULL == bitrate_count)
2162         return;
2163     if (NULL == gfp)
2164         return;
2165     gfc = gfp->internal_flags;
2166     if (NULL == gfc)
2167         return;
2168
2169     for (i = 0; i < 14; i++)
2170         bitrate_count[i] = gfc->bitrate_stereoMode_Hist[i + 1][4];
2171 }
2172
2173
2174 void
2175 lame_bitrate_kbps(const lame_global_flags * const gfp, int bitrate_kbps[14])
2176 {
2177     const lame_internal_flags *gfc;
2178     int     i;
2179
2180     if (NULL == bitrate_kbps)
2181         return;
2182     if (NULL == gfp)
2183         return;
2184     gfc = gfp->internal_flags;
2185     if (NULL == gfc)
2186         return;
2187
2188     for (i = 0; i < 14; i++)
2189         bitrate_kbps[i] = bitrate_table[gfp->version][i + 1];
2190 }
2191
2192
2193
2194 void
2195 lame_stereo_mode_hist(const lame_global_flags * const gfp, int stmode_count[4])
2196 {
2197     const lame_internal_flags *gfc;
2198     int     i;
2199
2200     if (NULL == stmode_count)
2201         return;
2202     if (NULL == gfp)
2203         return;
2204     gfc = gfp->internal_flags;
2205     if (NULL == gfc)
2206         return;
2207
2208     for (i = 0; i < 4; i++) {
2209         int     j, sum = 0;
2210         for (j = 0; j < 14; j++)
2211             sum += gfc->bitrate_stereoMode_Hist[j + 1][i];
2212         stmode_count[i] = sum;
2213     }
2214 }
2215
2216
2217
2218 void
2219 lame_bitrate_stereo_mode_hist(const lame_global_flags * const gfp,
2220                               int bitrate_stmode_count[14][4])
2221 {
2222     const lame_internal_flags *gfc;
2223     int     i;
2224     int     j;
2225
2226     if (NULL == bitrate_stmode_count)
2227         return;
2228     if (NULL == gfp)
2229         return;
2230     gfc = gfp->internal_flags;
2231     if (NULL == gfc)
2232         return;
2233
2234     for (j = 0; j < 14; j++)
2235         for (i = 0; i < 4; i++)
2236             bitrate_stmode_count[j][i] = gfc->bitrate_stereoMode_Hist[j + 1][i];
2237 }
2238
2239 /* end of lame.c */