]> 4ch.mooo.com Git - 16.git/blob - src/lib/dl/ext/lame/lame.c
refresh wwww
[16.git] / src / lib / dl / ext / lame / lame.c
1 /* -*- mode: C; mode: fold -*- */
2 /*
3  *      LAME MP3 encoding engine
4  *
5  *      Copyright (c) 1999-2000 Mark Taylor
6  *      Copyright (c) 2000-2005 Takehiro Tominaga
7  *      Copyright (c) 2000-2011 Robert Hegemann
8  *      Copyright (c) 2000-2005 Gabriel Bouvigne
9  *      Copyright (c) 2000-2004 Alexander Leidinger
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public
22  * License along with this library; if not, write to the
23  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24  * Boston, MA 02111-1307, USA.
25  */
26
27 /* $Id: lame.c,v 1.365 2011/10/18 21:51:20 robert Exp $ */
28
29 #ifdef HAVE_CONFIG_H
30 # include <config.h>
31 #endif
32
33
34 #include "lame.h"
35 #include "machine.h"
36
37 #include "encoder.h"
38 #include "util.h"
39 #include "lame_global_flags.h"
40 #include "gain_analysis.h"
41 #include "bitstream.h"
42 #include "quantize_pvt.h"
43 #include "set_get.h"
44 #include "quantize.h"
45 #include "psymodel.h"
46 #include "version.h"
47 #include "vbrtag.h"
48 #include "tables.h"
49
50
51 #if defined(__FreeBSD__) && !defined(__alpha__)
52 #include <floatingpoint.h>
53 #endif
54 #ifdef __riscos__
55 #include "asmstuff.h"
56 #endif
57
58 #ifdef __sun__
59 /* woraround for SunOS 4.x, it has SEEK_* defined here */
60 #include <unistd.h>
61 #endif
62
63
64 #define LAME_DEFAULT_QUALITY 3
65
66
67
68 int
69 is_lame_global_flags_valid(const lame_global_flags * gfp)
70 {
71     if (gfp == NULL)
72         return 0;
73     if (gfp->class_id != LAME_ID)
74         return 0;
75     return 1;
76 }
77
78
79 int
80 is_lame_internal_flags_valid(const lame_internal_flags * gfc)
81 {
82     if (gfc == NULL)
83         return 0;
84     if (gfc->class_id != LAME_ID)
85         return 0;
86     return 1;
87 }
88
89
90
91 static  FLOAT
92 filter_coef(FLOAT x)
93 {
94     if (x > 1.0)
95         return 0.0;
96     if (x <= 0.0)
97         return 1.0;
98
99     return cos(PI / 2 * x);
100 }
101
102 static void
103 lame_init_params_ppflt(lame_internal_flags * gfc)
104 {
105     SessionConfig_t *const cfg = &gfc->cfg;
106     
107     /***************************************************************/
108     /* compute info needed for polyphase filter (filter type==0, default) */
109     /***************************************************************/
110
111     int     band, maxband, minband;
112     FLOAT   freq;
113     int     lowpass_band = 32;
114     int     highpass_band = -1;
115
116     if (cfg->lowpass1 > 0) {
117         minband = 999;
118         for (band = 0; band <= 31; band++) {
119             freq = band / 31.0;
120             /* this band and above will be zeroed: */
121             if (freq >= cfg->lowpass2) {
122                 lowpass_band = Min(lowpass_band, band);
123             }
124             if (cfg->lowpass1 < freq && freq < cfg->lowpass2) {
125                 minband = Min(minband, band);
126             }
127         }
128
129         /* compute the *actual* transition band implemented by
130          * the polyphase filter */
131         if (minband == 999) {
132             cfg->lowpass1 = (lowpass_band - .75) / 31.0;
133         }
134         else {
135             cfg->lowpass1 = (minband - .75) / 31.0;
136         }
137         cfg->lowpass2 = lowpass_band / 31.0;
138     }
139
140     /* make sure highpass filter is within 90% of what the effective
141      * highpass frequency will be */
142     if (cfg->highpass2 > 0) {
143         if (cfg->highpass2 < .9 * (.75 / 31.0)) {
144             cfg->highpass1 = 0;
145             cfg->highpass2 = 0;
146             MSGF(gfc, "Warning: highpass filter disabled.  " "highpass frequency too small\n");
147         }
148     }
149
150     if (cfg->highpass2 > 0) {
151         maxband = -1;
152         for (band = 0; band <= 31; band++) {
153             freq = band / 31.0;
154             /* this band and below will be zereod */
155             if (freq <= cfg->highpass1) {
156                 highpass_band = Max(highpass_band, band);
157             }
158             if (cfg->highpass1 < freq && freq < cfg->highpass2) {
159                 maxband = Max(maxband, band);
160             }
161         }
162         /* compute the *actual* transition band implemented by
163          * the polyphase filter */
164         cfg->highpass1 = highpass_band / 31.0;
165         if (maxband == -1) {
166             cfg->highpass2 = (highpass_band + .75) / 31.0;
167         }
168         else {
169             cfg->highpass2 = (maxband + .75) / 31.0;
170         }
171     }
172
173     for (band = 0; band < 32; band++) {
174         FLOAT fc1, fc2;
175         freq = band / 31.0f;
176         if (cfg->highpass2 > cfg->highpass1) {
177             fc1 = filter_coef((cfg->highpass2 - freq) / (cfg->highpass2 - cfg->highpass1 + 1e-20));
178         }
179         else {
180             fc1 = 1.0f;
181         }
182         if (cfg->lowpass2 > cfg->lowpass1) {
183             fc2 = filter_coef((freq - cfg->lowpass1)  / (cfg->lowpass2 - cfg->lowpass1 + 1e-20));
184         }
185         else {
186             fc2 = 1.0f;
187         }
188         gfc->sv_enc.amp_filter[band] = fc1 * fc2;
189     }
190 }
191
192
193 static void
194 optimum_bandwidth(double *const lowerlimit, double *const upperlimit, const unsigned bitrate)
195 {
196 /*
197  *  Input:
198  *      bitrate     total bitrate in kbps
199  *
200  *   Output:
201  *      lowerlimit: best lowpass frequency limit for input filter in Hz
202  *      upperlimit: best highpass frequency limit for input filter in Hz
203  */
204     int     table_index;
205
206     typedef struct {
207         int     bitrate;     /* only indicative value */
208         int     lowpass;
209     } band_pass_t;
210
211     static const band_pass_t freq_map[] = {
212         {8, 2000},
213         {16, 3700},
214         {24, 3900},
215         {32, 5500},
216         {40, 7000},
217         {48, 7500},
218         {56, 10000},
219         {64, 11000},
220         {80, 13500},
221         {96, 15100},
222         {112, 15600},
223         {128, 17000},
224         {160, 17500},
225         {192, 18600},
226         {224, 19400},
227         {256, 19700},
228         {320, 20500}
229     };
230
231
232     table_index = nearestBitrateFullIndex(bitrate);
233
234     (void) freq_map[table_index].bitrate;
235     *lowerlimit = freq_map[table_index].lowpass;
236
237
238 /*
239  *  Now we try to choose a good high pass filtering frequency.
240  *  This value is currently not used.
241  *    For fu < 16 kHz:  sqrt(fu*fl) = 560 Hz
242  *    For fu = 18 kHz:  no high pass filtering
243  *  This gives:
244  *
245  *   2 kHz => 160 Hz
246  *   3 kHz => 107 Hz
247  *   4 kHz =>  80 Hz
248  *   8 kHz =>  40 Hz
249  *  16 kHz =>  20 Hz
250  *  17 kHz =>  10 Hz
251  *  18 kHz =>   0 Hz
252  *
253  *  These are ad hoc values and these can be optimized if a high pass is available.
254  */
255 /*    if (f_low <= 16000)
256         f_high = 16000. * 20. / f_low;
257     else if (f_low <= 18000)
258         f_high = 180. - 0.01 * f_low;
259     else
260         f_high = 0.;*/
261
262     /*
263      *  When we sometimes have a good highpass filter, we can add the highpass
264      *  frequency to the lowpass frequency
265      */
266
267     /*if (upperlimit != NULL)
268      *upperlimit = f_high;*/
269     (void) upperlimit;
270 }
271
272
273 static int
274 optimum_samplefreq(int lowpassfreq, int input_samplefreq)
275 {
276 /*
277  * Rules:
278  *  - if possible, sfb21 should NOT be used
279  *
280  */
281     int     suggested_samplefreq = 44100;
282
283     if (input_samplefreq >= 48000)
284         suggested_samplefreq = 48000;
285     else if (input_samplefreq >= 44100)
286         suggested_samplefreq = 44100;
287     else if (input_samplefreq >= 32000)
288         suggested_samplefreq = 32000;
289     else if (input_samplefreq >= 24000)
290         suggested_samplefreq = 24000;
291     else if (input_samplefreq >= 22050)
292         suggested_samplefreq = 22050;
293     else if (input_samplefreq >= 16000)
294         suggested_samplefreq = 16000;
295     else if (input_samplefreq >= 12000)
296         suggested_samplefreq = 12000;
297     else if (input_samplefreq >= 11025)
298         suggested_samplefreq = 11025;
299     else if (input_samplefreq >= 8000)
300         suggested_samplefreq = 8000;
301
302     if (lowpassfreq == -1)
303         return suggested_samplefreq;
304
305     if (lowpassfreq <= 15960)
306         suggested_samplefreq = 44100;
307     if (lowpassfreq <= 15250)
308         suggested_samplefreq = 32000;
309     if (lowpassfreq <= 11220)
310         suggested_samplefreq = 24000;
311     if (lowpassfreq <= 9970)
312         suggested_samplefreq = 22050;
313     if (lowpassfreq <= 7230)
314         suggested_samplefreq = 16000;
315     if (lowpassfreq <= 5420)
316         suggested_samplefreq = 12000;
317     if (lowpassfreq <= 4510)
318         suggested_samplefreq = 11025;
319     if (lowpassfreq <= 3970)
320         suggested_samplefreq = 8000;
321
322     if (input_samplefreq < suggested_samplefreq) {
323         /* choose a valid MPEG sample frequency above the input sample frequency
324            to avoid SFB21/12 bitrate bloat
325            rh 061115
326          */
327         if (input_samplefreq > 44100) {
328             return 48000;
329         }
330         if (input_samplefreq > 32000) {
331             return 44100;
332         }
333         if (input_samplefreq > 24000) {
334             return 32000;
335         }
336         if (input_samplefreq > 22050) {
337             return 24000;
338         }
339         if (input_samplefreq > 16000) {
340             return 22050;
341         }
342         if (input_samplefreq > 12000) {
343             return 16000;
344         }
345         if (input_samplefreq > 11025) {
346             return 12000;
347         }
348         if (input_samplefreq > 8000) {
349             return 11025;
350         }
351         return 8000;
352     }
353     return suggested_samplefreq;
354 }
355
356
357
358
359
360 /* set internal feature flags.  USER should not access these since
361  * some combinations will produce strange results */
362 static void
363 lame_init_qval(lame_global_flags * gfp)
364 {
365     lame_internal_flags *const gfc = gfp->internal_flags;
366     SessionConfig_t *const cfg = &gfc->cfg;
367
368     switch (gfp->quality) {
369     default:
370     case 9:            /* no psymodel, no noise shaping */
371         cfg->noise_shaping = 0;
372         cfg->noise_shaping_amp = 0;
373         cfg->noise_shaping_stop = 0;
374         cfg->use_best_huffman = 0;
375         cfg->full_outer_loop = 0;
376         break;
377
378     case 8:
379         gfp->quality = 7;
380         /*lint --fallthrough */
381     case 7:            /* use psymodel (for short block and m/s switching), but no noise shapping */
382         cfg->noise_shaping = 0;
383         cfg->noise_shaping_amp = 0;
384         cfg->noise_shaping_stop = 0;
385         cfg->use_best_huffman = 0;
386         cfg->full_outer_loop = 0;
387         if (gfp->VBR == vbr_mt || gfp->VBR == vbr_mtrh) {
388             cfg->full_outer_loop  = -1;
389         }
390         break;
391
392     case 6:
393         if (cfg->noise_shaping == 0)
394             cfg->noise_shaping = 1;
395         cfg->noise_shaping_amp = 0;
396         cfg->noise_shaping_stop = 0;
397         if (cfg->subblock_gain == -1)
398             cfg->subblock_gain = 1;
399         cfg->use_best_huffman = 0;
400         cfg->full_outer_loop = 0;
401         break;
402
403     case 5:
404         if (cfg->noise_shaping == 0)
405             cfg->noise_shaping = 1;
406         cfg->noise_shaping_amp = 0;
407         cfg->noise_shaping_stop = 0;
408         if (cfg->subblock_gain == -1)
409             cfg->subblock_gain = 1;
410         cfg->use_best_huffman = 0;
411         cfg->full_outer_loop = 0;
412         break;
413
414     case 4:
415         if (cfg->noise_shaping == 0)
416             cfg->noise_shaping = 1;
417         cfg->noise_shaping_amp = 0;
418         cfg->noise_shaping_stop = 0;
419         if (cfg->subblock_gain == -1)
420             cfg->subblock_gain = 1;
421         cfg->use_best_huffman = 1;
422         cfg->full_outer_loop = 0;
423         break;
424
425     case 3:
426         if (cfg->noise_shaping == 0)
427             cfg->noise_shaping = 1;
428         cfg->noise_shaping_amp = 1;
429         cfg->noise_shaping_stop = 1;
430         if (cfg->subblock_gain == -1)
431             cfg->subblock_gain = 1;
432         cfg->use_best_huffman = 1;
433         cfg->full_outer_loop = 0;
434         break;
435
436     case 2:
437         if (cfg->noise_shaping == 0)
438             cfg->noise_shaping = 1;
439         if (gfc->sv_qnt.substep_shaping == 0)
440             gfc->sv_qnt.substep_shaping = 2;
441         cfg->noise_shaping_amp = 1;
442         cfg->noise_shaping_stop = 1;
443         if (cfg->subblock_gain == -1)
444             cfg->subblock_gain = 1;
445         cfg->use_best_huffman = 1; /* inner loop */
446         cfg->full_outer_loop = 0;
447         break;
448
449     case 1:
450         if (cfg->noise_shaping == 0)
451             cfg->noise_shaping = 1;
452         if (gfc->sv_qnt.substep_shaping == 0)
453             gfc->sv_qnt.substep_shaping = 2;
454         cfg->noise_shaping_amp = 2;
455         cfg->noise_shaping_stop = 1;
456         if (cfg->subblock_gain == -1)
457             cfg->subblock_gain = 1;
458         cfg->use_best_huffman = 1;
459         cfg->full_outer_loop = 0;
460         break;
461
462     case 0:
463         if (cfg->noise_shaping == 0)
464             cfg->noise_shaping = 1;
465         if (gfc->sv_qnt.substep_shaping == 0)
466             gfc->sv_qnt.substep_shaping = 2;
467         cfg->noise_shaping_amp = 2;
468         cfg->noise_shaping_stop = 1;
469         if (cfg->subblock_gain == -1)
470             cfg->subblock_gain = 1;
471         cfg->use_best_huffman = 1; /*type 2 disabled because of it slowness,
472                                       in favor of full outer loop search */
473         cfg->full_outer_loop = 1;
474         break;
475     }
476
477 }
478
479
480
481 static double
482 linear_int(double a, double b, double m)
483 {
484     return a + m * (b - a);
485 }
486
487
488
489 /********************************************************************
490  *   initialize internal params based on data in gf
491  *   (globalflags struct filled in by calling program)
492  *
493  *  OUTLINE:
494  *
495  * We first have some complex code to determine bitrate,
496  * output samplerate and mode.  It is complicated by the fact
497  * that we allow the user to set some or all of these parameters,
498  * and need to determine best possible values for the rest of them:
499  *
500  *  1. set some CPU related flags
501  *  2. check if we are mono->mono, stereo->mono or stereo->stereo
502  *  3.  compute bitrate and output samplerate:
503  *          user may have set compression ratio
504  *          user may have set a bitrate
505  *          user may have set a output samplerate
506  *  4. set some options which depend on output samplerate
507  *  5. compute the actual compression ratio
508  *  6. set mode based on compression ratio
509  *
510  *  The remaining code is much simpler - it just sets options
511  *  based on the mode & compression ratio:
512  *
513  *   set allow_diff_short based on mode
514  *   select lowpass filter based on compression ratio & mode
515  *   set the bitrate index, and min/max bitrates for VBR modes
516  *   disable VBR tag if it is not appropriate
517  *   initialize the bitstream
518  *   initialize scalefac_band data
519  *   set sideinfo_len (based on channels, CRC, out_samplerate)
520  *   write an id3v2 tag into the bitstream
521  *   write VBR tag into the bitstream
522  *   set mpeg1/2 flag
523  *   estimate the number of frames (based on a lot of data)
524  *
525  *   now we set more flags:
526  *   nspsytune:
527  *      see code
528  *   VBR modes
529  *      see code
530  *   CBR/ABR
531  *      see code
532  *
533  *  Finally, we set the algorithm flags based on the gfp->quality value
534  *  lame_init_qval(gfp);
535  *
536  ********************************************************************/
537 int
538 lame_init_params(lame_global_flags * gfp)
539 {
540
541     int     i;
542     int     j;
543     lame_internal_flags *const gfc = gfp->internal_flags;
544     SessionConfig_t *const cfg = &gfc->cfg;
545
546     gfc->class_id = 0;
547
548     cfg->enforce_min_bitrate = gfp->VBR_hard_min;
549     cfg->analysis = gfp->analysis;
550     if (cfg->analysis)
551         gfp->write_lame_tag = 0;
552
553     /* some file options not allowed if output is: not specified or stdout */
554     if (gfc->pinfo != NULL)
555         gfp->write_lame_tag = 0; /* disable Xing VBR tag */
556
557     /* report functions */
558     gfc->report_msg = gfp->report.msgf;
559     gfc->report_dbg = gfp->report.debugf;
560     gfc->report_err = gfp->report.errorf;
561
562     if (gfp->asm_optimizations.amd3dnow)
563         gfc->CPU_features.AMD_3DNow = has_3DNow();
564     else
565         gfc->CPU_features.AMD_3DNow = 0;
566
567     if (gfp->asm_optimizations.mmx)
568         gfc->CPU_features.MMX = has_MMX();
569     else
570         gfc->CPU_features.MMX = 0;
571
572     if (gfp->asm_optimizations.sse) {
573         gfc->CPU_features.SSE = has_SSE();
574         gfc->CPU_features.SSE2 = has_SSE2();
575     }
576     else {
577         gfc->CPU_features.SSE = 0;
578         gfc->CPU_features.SSE2 = 0;
579     }
580
581
582     if (NULL == gfc->ATH)
583         gfc->ATH = calloc(1, sizeof(ATH_t));
584
585     if (NULL == gfc->ATH)
586         return -2;      /* maybe error codes should be enumerated in lame.h ?? */
587
588     if (NULL == gfc->sv_rpg.rgdata)
589         gfc->sv_rpg.rgdata = calloc(1, sizeof(replaygain_t));
590     if (NULL == gfc->sv_rpg.rgdata) {
591         freegfc(gfc);
592         gfp->internal_flags = NULL;
593         return -2;
594     }
595
596     cfg->error_protection = gfp->error_protection;
597     cfg->copyright = gfp->copyright;
598     cfg->original = gfp->original;
599     cfg->extension = gfp->extension;
600     cfg->emphasis = gfp->emphasis;
601
602     cfg->channels_in = gfp->num_channels;
603     if (cfg->channels_in == 1)
604         gfp->mode = MONO;
605     cfg->channels_out = (gfp->mode == MONO) ? 1 : 2;
606     if (gfp->mode == MONO)
607         gfp->force_ms = 0; /* don't allow forced mid/side stereo for mono output */
608     cfg->force_ms = gfp->force_ms;
609
610     if (gfp->VBR == vbr_off && gfp->VBR_mean_bitrate_kbps != 128 && gfp->brate == 0)
611         gfp->brate = gfp->VBR_mean_bitrate_kbps;
612
613     switch (gfp->VBR) {
614     case vbr_off:
615     case vbr_mtrh:
616     case vbr_mt:
617         /* these modes can handle free format condition */
618         break;
619     default:
620         gfp->free_format = 0; /* mode can't be mixed with free format */
621         break;
622     }
623
624     cfg->free_format = gfp->free_format;
625
626     if (gfp->VBR == vbr_off && gfp->brate == 0) {
627         /* no bitrate or compression ratio specified, use 11.025 */
628         if (EQ(gfp->compression_ratio, 0))
629             gfp->compression_ratio = 11.025; /* rate to compress a CD down to exactly 128000 bps */
630     }
631
632     /* find bitrate if user specify a compression ratio */
633     if (gfp->VBR == vbr_off && gfp->compression_ratio > 0) {
634
635         if (gfp->samplerate_out == 0)
636             gfp->samplerate_out = map2MP3Frequency((int) (0.97 * gfp->samplerate_in)); /* round up with a margin of 3% */
637
638         /* choose a bitrate for the output samplerate which achieves
639          * specified compression ratio
640          */
641         gfp->brate = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->compression_ratio);
642
643         /* we need the version for the bitrate table look up */
644         cfg->samplerate_index = SmpFrqIndex(gfp->samplerate_out, &cfg->version);
645
646         if (!cfg->free_format) /* for non Free Format find the nearest allowed bitrate */
647             gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, gfp->samplerate_out);
648     }
649     if (gfp->samplerate_out) {
650         if (gfp->samplerate_out < 16000) {
651             gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);
652             gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 64);
653         }
654         else if (gfp->samplerate_out < 32000) {
655             gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);
656             gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 160);
657         }
658         else {
659             gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 32);
660             gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 320);
661         }
662     }
663     /* WORK IN PROGRESS */
664     /* mapping VBR scale to internal VBR quality settings */
665     if (gfp->samplerate_out == 0 && (gfp->VBR == vbr_mt || gfp->VBR == vbr_mtrh)) {
666         float const qval = gfp->VBR_q + gfp->VBR_q_frac;
667         struct q_map { int sr_a; float qa, qb, ta, tb; int lp; };
668         static struct q_map const m[9]
669         = { {48000, 0.0,6.5,  0.0,6.5, 23700}
670           , {44100, 0.0,6.5,  0.0,6.5, 21780}
671           , {32000, 6.5,8.0,  5.2,6.5, 15800}
672           , {24000, 8.0,8.5,  5.2,6.0, 11850}
673           , {22050, 8.5,9.01, 5.2,6.5, 10892}
674           , {16000, 9.01,9.4, 4.9,6.5,  7903}
675           , {12000, 9.4,9.6,  4.5,6.0,  5928}
676           , {11025, 9.6,9.9,  5.1,6.5,  5446}
677           , { 8000, 9.9,10.,  4.9,6.5,  3952}
678         };
679         for (i = 2; i < 9; ++i) {
680             if (gfp->samplerate_in == m[i].sr_a) {
681                 if (qval < m[i].qa) {
682                     double d = qval / m[i].qa;
683                     d = d * m[i].ta;
684                     gfp->VBR_q = (int)d;
685                     gfp->VBR_q_frac = d - gfp->VBR_q;
686                 }
687             }
688             if (gfp->samplerate_in >= m[i].sr_a) {
689                 if (m[i].qa <= qval && qval < m[i].qb) {
690                     float const q_ = m[i].qb-m[i].qa;
691                     float const t_ = m[i].tb-m[i].ta;
692                     double d = m[i].ta + t_ * (qval-m[i].qa) / q_;
693                     gfp->VBR_q = (int)d;
694                     gfp->VBR_q_frac = d - gfp->VBR_q;
695                     gfp->samplerate_out = m[i].sr_a;
696                     if (gfp->lowpassfreq == 0) {
697                         gfp->lowpassfreq = -1;
698                     }
699                     break;
700                 }
701             }
702         }
703     }
704
705     /****************************************************************/
706     /* if a filter has not been enabled, see if we should add one: */
707     /****************************************************************/
708     if (gfp->lowpassfreq == 0) {
709         double  lowpass = 16000;
710         double  highpass;
711
712         switch (gfp->VBR) {
713         case vbr_off:{
714                 optimum_bandwidth(&lowpass, &highpass, gfp->brate);
715                 break;
716             }
717         case vbr_abr:{
718                 optimum_bandwidth(&lowpass, &highpass, gfp->VBR_mean_bitrate_kbps);
719                 break;
720             }
721         case vbr_rh:{
722                 int const x[11] = {
723                     19500, 19000, 18600, 18000, 17500, 16000, 15600, 14900, 12500, 10000, 3950
724                 };
725                 if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
726                     double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
727                     lowpass = linear_int(a, b, m);
728                 }
729                 else {
730                     lowpass = 19500;
731                 }
732                 break;
733             }
734         case vbr_mtrh:
735         case vbr_mt:{
736                 int const x[11] = {
737                     24000, 19500, 18500, 18000, 17500, 17000, 16500, 15600, 15200, 7230, 3950
738                 };
739                 if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
740                     double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
741                     lowpass = linear_int(a, b, m);
742                 }
743                 else {
744                     lowpass = 21500;
745                 }
746                 break;
747             }
748         default:{
749                 int const x[11] = {
750                     19500, 19000, 18500, 18000, 17500, 16500, 15500, 14500, 12500, 9500, 3950
751                 };
752                 if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
753                     double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
754                     lowpass = linear_int(a, b, m);
755                 }
756                 else {
757                     lowpass = 19500;
758                 }
759             }
760         }
761
762         if (gfp->mode == MONO && (gfp->VBR == vbr_off || gfp->VBR == vbr_abr))
763             lowpass *= 1.5;
764
765         gfp->lowpassfreq = lowpass;
766     }
767
768     if (gfp->samplerate_out == 0) {
769         if (2 * gfp->lowpassfreq > gfp->samplerate_in) {
770             gfp->lowpassfreq = gfp->samplerate_in / 2;
771         }
772         gfp->samplerate_out = optimum_samplefreq((int) gfp->lowpassfreq, gfp->samplerate_in);
773     }
774     if (gfp->VBR == vbr_mt || gfp->VBR == vbr_mtrh) {
775         gfp->lowpassfreq = Min(24000, gfp->lowpassfreq);
776     }
777     else {
778         gfp->lowpassfreq = Min(20500, gfp->lowpassfreq);
779     }
780     gfp->lowpassfreq = Min(gfp->samplerate_out / 2, gfp->lowpassfreq);
781
782     if (gfp->VBR == vbr_off) {
783         gfp->compression_ratio = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
784     }
785     if (gfp->VBR == vbr_abr) {
786         gfp->compression_ratio =
787             gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);
788     }
789
790     /* do not compute ReplayGain values and do not find the peak sample
791        if we can't store them */
792     if (!gfp->write_lame_tag) {
793         gfp->findReplayGain = 0;
794         gfp->decode_on_the_fly = 0;
795         cfg->findPeakSample = 0;
796     }
797
798     cfg->findReplayGain = gfp->findReplayGain;
799     cfg->decode_on_the_fly = gfp->decode_on_the_fly;
800
801     if (cfg->decode_on_the_fly)
802         cfg->findPeakSample = 1;
803
804     if (cfg->findReplayGain) {
805         if (InitGainAnalysis(gfc->sv_rpg.rgdata, gfp->samplerate_out) == INIT_GAIN_ANALYSIS_ERROR) {
806             freegfc(gfc);
807             gfp->internal_flags = NULL;
808             return -6;
809         }
810     }
811
812 #ifdef DECODE_ON_THE_FLY
813     if (cfg->decode_on_the_fly && !gfp->decode_only) {
814         if (gfc->hip) {
815             hip_decode_exit(gfc->hip);
816         }
817         gfc->hip = hip_decode_init();
818         /* report functions */
819         hip_set_errorf(gfc->hip, gfp->report.errorf);
820         hip_set_debugf(gfc->hip, gfp->report.debugf);
821         hip_set_msgf(gfc->hip, gfp->report.msgf);
822     }
823 #endif
824
825     cfg->disable_reservoir = gfp->disable_reservoir;
826     cfg->lowpassfreq = gfp->lowpassfreq;
827     cfg->highpassfreq = gfp->highpassfreq;
828     cfg->samplerate_in = gfp->samplerate_in;
829     cfg->samplerate_out = gfp->samplerate_out;
830     cfg->mode_gr = cfg->samplerate_out <= 24000 ? 1 : 2; /* Number of granules per frame */
831     gfc->ov_enc.encoder_delay = ENCDELAY;
832
833
834     /*
835      *  sample freq       bitrate     compression ratio
836      *     [kHz]      [kbps/channel]   for 16 bit input
837      *     44.1            56               12.6
838      *     44.1            64               11.025
839      *     44.1            80                8.82
840      *     22.05           24               14.7
841      *     22.05           32               11.025
842      *     22.05           40                8.82
843      *     16              16               16.0
844      *     16              24               10.667
845      *
846      */
847     /*
848      *  For VBR, take a guess at the compression_ratio.
849      *  For example:
850      *
851      *    VBR_q    compression     like
852      *     -        4.4         320 kbps/44 kHz
853      *   0...1      5.5         256 kbps/44 kHz
854      *     2        7.3         192 kbps/44 kHz
855      *     4        8.8         160 kbps/44 kHz
856      *     6       11           128 kbps/44 kHz
857      *     9       14.7          96 kbps
858      *
859      *  for lower bitrates, downsample with --resample
860      */
861
862     switch (gfp->VBR) {
863     case vbr_mt:
864     case vbr_rh:
865     case vbr_mtrh:
866         {
867             /*numbers are a bit strange, but they determine the lowpass value */
868             FLOAT const cmp[] = { 5.7, 6.5, 7.3, 8.2, 10, 11.9, 13, 14, 15, 16.5 };
869             gfp->compression_ratio = cmp[gfp->VBR_q];
870         }
871         break;
872     case vbr_abr:
873         gfp->compression_ratio =
874             cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);
875         break;
876     default:
877         gfp->compression_ratio = cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
878         break;
879     }
880
881
882     /* mode = -1 (not set by user) or
883      * mode = MONO (because of only 1 input channel).
884      * If mode has not been set, then select J-STEREO
885      */
886     if (gfp->mode == NOT_SET) {
887         gfp->mode = JOINT_STEREO;
888     }
889
890     cfg->mode = gfp->mode;
891
892
893     /* apply user driven high pass filter */
894     if (cfg->highpassfreq > 0) {
895         cfg->highpass1 = 2. * cfg->highpassfreq;
896
897         if (gfp->highpasswidth >= 0)
898             cfg->highpass2 = 2. * (cfg->highpassfreq + gfp->highpasswidth);
899         else            /* 0% above on default */
900             cfg->highpass2 = (1 + 0.00) * 2. * cfg->highpassfreq;
901
902         cfg->highpass1 /= cfg->samplerate_out;
903         cfg->highpass2 /= cfg->samplerate_out;
904     }
905     else {
906         cfg->highpass1 = 0;
907         cfg->highpass2 = 0;
908     }
909     /* apply user driven low pass filter */
910     cfg->lowpass1 = 0;
911     cfg->lowpass2 = 0;
912     if (cfg->lowpassfreq > 0 && cfg->lowpassfreq < (cfg->samplerate_out / 2) ) {
913         cfg->lowpass2 = 2. * cfg->lowpassfreq;
914         if (gfp->lowpasswidth >= 0) {
915             cfg->lowpass1 = 2. * (cfg->lowpassfreq - gfp->lowpasswidth);
916             if (cfg->lowpass1 < 0) /* has to be >= 0 */
917                 cfg->lowpass1 = 0;
918         }
919         else {          /* 0% below on default */
920             cfg->lowpass1 = (1 - 0.00) * 2. * cfg->lowpassfreq;
921         }
922         cfg->lowpass1 /= cfg->samplerate_out;
923         cfg->lowpass2 /= cfg->samplerate_out;
924     }
925
926
927
928
929   /**********************************************************************/
930     /* compute info needed for polyphase filter (filter type==0, default) */
931   /**********************************************************************/
932     lame_init_params_ppflt(gfc);
933
934
935   /*******************************************************
936    * samplerate and bitrate index
937    *******************************************************/
938     cfg->samplerate_index = SmpFrqIndex(cfg->samplerate_out, &cfg->version);
939     if (cfg->samplerate_index < 0) {
940         freegfc(gfc);
941         gfp->internal_flags = NULL;
942         return -1;
943     }
944
945     if (gfp->VBR == vbr_off) {
946         if (cfg->free_format) {
947             gfc->ov_enc.bitrate_index = 0;
948         }
949         else {
950             gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, cfg->samplerate_out);
951             gfc->ov_enc.bitrate_index = BitrateIndex(gfp->brate, cfg->version, cfg->samplerate_out);
952             if (gfc->ov_enc.bitrate_index <= 0) {
953                 freegfc(gfc);
954                 gfp->internal_flags = NULL;
955                 return -1;
956             }
957         }
958     }
959     else {
960         gfc->ov_enc.bitrate_index = 1;
961     }
962
963     init_bit_stream_w(gfc);
964
965     j = cfg->samplerate_index + (3 * cfg->version) + 6 * (cfg->samplerate_out < 16000);
966     for (i = 0; i < SBMAX_l + 1; i++)
967         gfc->scalefac_band.l[i] = sfBandIndex[j].l[i];
968
969     for (i = 0; i < PSFB21 + 1; i++) {
970         int const size = (gfc->scalefac_band.l[22] - gfc->scalefac_band.l[21]) / PSFB21;
971         int const start = gfc->scalefac_band.l[21] + i * size;
972         gfc->scalefac_band.psfb21[i] = start;
973     }
974     gfc->scalefac_band.psfb21[PSFB21] = 576;
975
976     for (i = 0; i < SBMAX_s + 1; i++)
977         gfc->scalefac_band.s[i] = sfBandIndex[j].s[i];
978
979     for (i = 0; i < PSFB12 + 1; i++) {
980         int const size = (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) / PSFB12;
981         int const start = gfc->scalefac_band.s[12] + i * size;
982         gfc->scalefac_band.psfb12[i] = start;
983     }
984     gfc->scalefac_band.psfb12[PSFB12] = 192;
985
986     /* determine the mean bitrate for main data */
987     if (cfg->mode_gr == 2) /* MPEG 1 */
988         cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 17 : 4 + 32;
989     else                /* MPEG 2 */
990         cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 9 : 4 + 17;
991
992     if (cfg->error_protection)
993         cfg->sideinfo_len += 2;
994
995     gfc->class_id = LAME_ID;
996
997     {
998         int     k;
999
1000         for (k = 0; k < 19; k++)
1001             gfc->sv_enc.pefirbuf[k] = 700 * cfg->mode_gr * cfg->channels_out;
1002
1003         if (gfp->ATHtype == -1)
1004             gfp->ATHtype = 4;
1005     }
1006
1007     assert(gfp->VBR_q <= 9);
1008     assert(gfp->VBR_q >= 0);
1009
1010     switch (gfp->VBR) {
1011
1012     case vbr_mt:
1013     case vbr_mtrh:{
1014             if (gfp->strict_ISO < 0) {
1015                 gfp->strict_ISO = MDB_MAXIMUM;
1016             }
1017             if (gfp->useTemporal < 0) {
1018                 gfp->useTemporal = 0; /* off by default for this VBR mode */
1019             }
1020
1021             (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);
1022             /*  The newer VBR code supports only a limited
1023                subset of quality levels:
1024                9-5=5 are the same, uses x^3/4 quantization
1025                4-0=0 are the same  5 plus best huffman divide code
1026              */
1027             if (gfp->quality < 0)
1028                 gfp->quality = LAME_DEFAULT_QUALITY;
1029             if (gfp->quality < 5)
1030                 gfp->quality = 0;
1031             if (gfp->quality > 7)
1032                 gfp->quality = 7;
1033
1034             /*  sfb21 extra only with MPEG-1 at higher sampling rates
1035              */
1036             if (gfp->experimentalY)
1037                 gfc->sv_qnt.sfb21_extra = 0;
1038             else
1039                 gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
1040
1041             gfc->iteration_loop = VBR_new_iteration_loop;
1042             break;
1043
1044         }
1045     case vbr_rh:{
1046
1047             (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);
1048
1049             /*  sfb21 extra only with MPEG-1 at higher sampling rates
1050              */
1051             if (gfp->experimentalY)
1052                 gfc->sv_qnt.sfb21_extra = 0;
1053             else
1054                 gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
1055
1056             /*  VBR needs at least the output of GPSYCHO,
1057              *  so we have to garantee that by setting a minimum
1058              *  quality level, actually level 6 does it.
1059              *  down to level 6
1060              */
1061             if (gfp->quality > 6)
1062                 gfp->quality = 6;
1063
1064
1065             if (gfp->quality < 0)
1066                 gfp->quality = LAME_DEFAULT_QUALITY;
1067
1068             gfc->iteration_loop = VBR_old_iteration_loop;
1069             break;
1070         }
1071
1072     default:           /* cbr/abr */  {
1073             vbr_mode vbrmode;
1074
1075             /*  no sfb21 extra with CBR code
1076              */
1077             gfc->sv_qnt.sfb21_extra = 0;
1078
1079             if (gfp->quality < 0)
1080                 gfp->quality = LAME_DEFAULT_QUALITY;
1081
1082
1083             vbrmode = gfp->VBR;
1084             if (vbrmode == vbr_off)
1085                 (void) lame_set_VBR_mean_bitrate_kbps(gfp, gfp->brate);
1086             /* second, set parameters depending on bitrate */
1087             (void) apply_preset(gfp, gfp->VBR_mean_bitrate_kbps, 0);
1088             gfp->VBR = vbrmode;
1089
1090             if (vbrmode == vbr_off) {
1091                 gfc->iteration_loop = CBR_iteration_loop;
1092             }
1093             else {
1094                 gfc->iteration_loop = ABR_iteration_loop;
1095             }
1096             break;
1097         }
1098     }
1099
1100     /*initialize default values common for all modes */
1101
1102     gfc->sv_qnt.mask_adjust = gfp->maskingadjust;
1103     gfc->sv_qnt.mask_adjust_short = gfp->maskingadjust_short;
1104
1105     /*  just another daily changing developer switch  */
1106     if (gfp->tune) {
1107         gfc->sv_qnt.mask_adjust += gfp->tune_value_a;
1108         gfc->sv_qnt.mask_adjust_short += gfp->tune_value_a;
1109     }
1110
1111
1112     if (gfp->VBR != vbr_off) { /* choose a min/max bitrate for VBR */
1113         /* if the user didn't specify VBR_max_bitrate: */
1114         cfg->vbr_min_bitrate_index = 1; /* default: allow   8 kbps (MPEG-2) or  32 kbps (MPEG-1) */
1115         cfg->vbr_max_bitrate_index = 14; /* default: allow 160 kbps (MPEG-2) or 320 kbps (MPEG-1) */
1116         if (cfg->samplerate_out < 16000)
1117             cfg->vbr_max_bitrate_index = 8; /* default: allow 64 kbps (MPEG-2.5) */
1118         if (gfp->VBR_min_bitrate_kbps) {
1119             gfp->VBR_min_bitrate_kbps =
1120                 FindNearestBitrate(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);
1121             cfg->vbr_min_bitrate_index =
1122                 BitrateIndex(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);
1123             if (cfg->vbr_min_bitrate_index < 0)
1124                 return -1;
1125         }
1126         if (gfp->VBR_max_bitrate_kbps) {
1127             gfp->VBR_max_bitrate_kbps =
1128                 FindNearestBitrate(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);
1129             cfg->vbr_max_bitrate_index =
1130                 BitrateIndex(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);
1131             if (cfg->vbr_max_bitrate_index < 0)
1132                 return -1;
1133         }
1134         gfp->VBR_min_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];
1135         gfp->VBR_max_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_max_bitrate_index];
1136         gfp->VBR_mean_bitrate_kbps =
1137             Min(bitrate_table[cfg->version][cfg->vbr_max_bitrate_index],
1138                 gfp->VBR_mean_bitrate_kbps);
1139         gfp->VBR_mean_bitrate_kbps =
1140             Max(bitrate_table[cfg->version][cfg->vbr_min_bitrate_index],
1141                 gfp->VBR_mean_bitrate_kbps);
1142     }
1143
1144     cfg->preset = gfp->preset;
1145     cfg->write_lame_tag = gfp->write_lame_tag;
1146     cfg->vbr = gfp->VBR;
1147     gfc->sv_qnt.substep_shaping = gfp->substep_shaping;
1148     cfg->noise_shaping = gfp->noise_shaping;
1149     cfg->subblock_gain = gfp->subblock_gain;
1150     cfg->use_best_huffman = gfp->use_best_huffman;
1151     cfg->avg_bitrate = gfp->brate;
1152     cfg->vbr_avg_bitrate_kbps = gfp->VBR_mean_bitrate_kbps;
1153     cfg->compression_ratio = gfp->compression_ratio;
1154
1155     /* initialize internal qval settings */
1156     lame_init_qval(gfp);
1157
1158
1159     /*  automatic ATH adjustment on
1160      */
1161     if (gfp->athaa_type < 0)
1162         gfc->ATH->use_adjust = 3;
1163     else
1164         gfc->ATH->use_adjust = gfp->athaa_type;
1165
1166
1167     /* initialize internal adaptive ATH settings  -jd */
1168     gfc->ATH->aa_sensitivity_p = pow(10.0, gfp->athaa_sensitivity / -10.0);
1169
1170
1171     if (gfp->short_blocks == short_block_not_set) {
1172         gfp->short_blocks = short_block_allowed;
1173     }
1174
1175     /*Note Jan/2003: Many hardware decoders cannot handle short blocks in regular
1176        stereo mode unless they are coupled (same type in both channels)
1177        it is a rare event (1 frame per min. or so) that LAME would use
1178        uncoupled short blocks, so lets turn them off until we decide
1179        how to handle this.  No other encoders allow uncoupled short blocks,
1180        even though it is in the standard.  */
1181     /* rh 20040217: coupling makes no sense for mono and dual-mono streams
1182      */
1183     if (gfp->short_blocks == short_block_allowed
1184         && (cfg->mode == JOINT_STEREO || cfg->mode == STEREO)) {
1185         gfp->short_blocks = short_block_coupled;
1186     }
1187
1188     cfg->short_blocks = gfp->short_blocks;
1189
1190
1191     if (lame_get_quant_comp(gfp) < 0)
1192         (void) lame_set_quant_comp(gfp, 1);
1193     if (lame_get_quant_comp_short(gfp) < 0)
1194         (void) lame_set_quant_comp_short(gfp, 0);
1195
1196     if (lame_get_msfix(gfp) < 0)
1197         lame_set_msfix(gfp, 0);
1198
1199     /* select psychoacoustic model */
1200     (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 1);
1201
1202     if (gfp->ATHtype < 0)
1203         gfp->ATHtype = 4;
1204
1205     if (gfp->ATHcurve < 0)
1206         gfp->ATHcurve = 4;
1207
1208     if (gfp->interChRatio < 0)
1209         gfp->interChRatio = 0;
1210
1211     if (gfp->useTemporal < 0)
1212         gfp->useTemporal = 1; /* on by default */
1213
1214
1215     cfg->interChRatio = gfp->interChRatio;
1216     cfg->msfix = gfp->msfix;
1217     cfg->ATH_offset_db = 0-gfp->ATH_lower_db;
1218     cfg->ATH_offset_factor = powf(10.f, cfg->ATH_offset_db * 0.1f);
1219     cfg->ATHcurve = gfp->ATHcurve;
1220     cfg->ATHtype = gfp->ATHtype;
1221     cfg->ATHonly = gfp->ATHonly;
1222     cfg->ATHshort = gfp->ATHshort;
1223     cfg->noATH = gfp->noATH;
1224
1225     cfg->quant_comp = gfp->quant_comp;
1226     cfg->quant_comp_short = gfp->quant_comp_short;
1227
1228     cfg->use_temporal_masking_effect = gfp->useTemporal;
1229     cfg->use_safe_joint_stereo = gfp->exp_nspsytune & 2;
1230     {
1231         cfg->adjust_bass_db = (gfp->exp_nspsytune >> 2) & 63;
1232         if (cfg->adjust_bass_db >= 32.f)
1233             cfg->adjust_bass_db -= 64.f;
1234         cfg->adjust_bass_db *= 0.25f;
1235
1236         cfg->adjust_alto_db = (gfp->exp_nspsytune >> 8) & 63;
1237         if (cfg->adjust_alto_db >= 32.f)
1238             cfg->adjust_alto_db -= 64.f;
1239         cfg->adjust_alto_db *= 0.25f;
1240
1241         cfg->adjust_treble_db = (gfp->exp_nspsytune >> 14) & 63;
1242         if (cfg->adjust_treble_db >= 32.f)
1243             cfg->adjust_treble_db -= 64.f;
1244         cfg->adjust_treble_db *= 0.25f;
1245
1246         /*  to be compatible with Naoki's original code, the next 6 bits
1247          *  define only the amount of changing treble for sfb21 */
1248         cfg->adjust_sfb21_db = (gfp->exp_nspsytune >> 20) & 63;
1249         if (cfg->adjust_sfb21_db >= 32.f)
1250             cfg->adjust_sfb21_db -= 64.f;
1251         cfg->adjust_sfb21_db *= 0.25f;
1252         cfg->adjust_sfb21_db += cfg->adjust_treble_db;
1253     }
1254
1255     /* Setting up the PCM input data transform matrix, to apply 
1256      * user defined re-scaling, and or two-to-one channel downmix.
1257      */
1258     {
1259         FLOAT   m[2][2] = { {1.0f, 0.0f}, {0.0f, 1.0f} };
1260
1261         /* user selected scaling of the samples */
1262         m[0][0] *= gfp->scale;
1263         m[0][1] *= gfp->scale;
1264         m[1][0] *= gfp->scale;
1265         m[1][1] *= gfp->scale;
1266         /* user selected scaling of the channel 0 (left) samples */
1267         m[0][0] *= gfp->scale_left;
1268         m[0][1] *= gfp->scale_left;
1269         /* user selected scaling of the channel 1 (right) samples */
1270         m[1][0] *= gfp->scale_right;
1271         m[1][1] *= gfp->scale_right;
1272         /* Downsample to Mono if 2 channels in and 1 channel out */
1273         if (cfg->channels_in == 2 && cfg->channels_out == 1) {
1274             m[0][0] = 0.5f * (m[0][0] + m[1][0]);
1275             m[0][1] = 0.5f * (m[0][1] + m[1][1]);
1276             m[1][0] = 0;
1277             m[1][1] = 0;
1278         }
1279         cfg->pcm_transform[0][0] = m[0][0];
1280         cfg->pcm_transform[0][1] = m[0][1];
1281         cfg->pcm_transform[1][0] = m[1][0];
1282         cfg->pcm_transform[1][1] = m[1][1];
1283     }
1284
1285     /* padding method as described in
1286      * "MPEG-Layer3 / Bitstream Syntax and Decoding"
1287      * by Martin Sieler, Ralph Sperschneider
1288      *
1289      * note: there is no padding for the very first frame
1290      *
1291      * Robert Hegemann 2000-06-22
1292      */
1293     gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF = 0;
1294     if (cfg->vbr == vbr_off)
1295         gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF
1296             = ((cfg->version + 1) * 72000L * cfg->avg_bitrate) % cfg->samplerate_out;
1297
1298     (void) lame_init_bitstream(gfp);
1299
1300     iteration_init(gfc);
1301     (void) psymodel_init(gfp);
1302
1303     cfg->buffer_constraint = get_max_frame_buffer_size_by_constraint(cfg, gfp->strict_ISO);
1304     return 0;
1305 }
1306
1307 static void
1308 concatSep(char* dest, char const* sep, char const* str)
1309 {
1310     if (*dest != 0) strcat(dest, sep);
1311     strcat(dest, str);
1312 }
1313
1314 /*
1315  *  print_config
1316  *
1317  *  Prints some selected information about the coding parameters via
1318  *  the macro command MSGF(), which is currently mapped to lame_errorf
1319  *  (reports via a error function?), which is a printf-like function
1320  *  for <stderr>.
1321  */
1322
1323 void
1324 lame_print_config(const lame_global_flags * gfp)
1325 {
1326     lame_internal_flags const *const gfc = gfp->internal_flags;
1327     SessionConfig_t const *const cfg = &gfc->cfg;
1328     double const out_samplerate = cfg->samplerate_out;
1329     double const in_samplerate = cfg->samplerate_in;
1330
1331     MSGF(gfc, "LAME %s %s (%s)\n", get_lame_version(), get_lame_os_bitness(), get_lame_url());
1332
1333 #if (LAME_ALPHA_VERSION)
1334     MSGF(gfc, "warning: alpha versions should be used for testing only\n");
1335 #endif
1336     if (gfc->CPU_features.MMX
1337         || gfc->CPU_features.AMD_3DNow || gfc->CPU_features.SSE || gfc->CPU_features.SSE2) {
1338         char    text[256] = { 0 };
1339         int     fft_asm_used = 0;
1340 #ifdef HAVE_NASM
1341         if (gfc->CPU_features.AMD_3DNow) {
1342             fft_asm_used = 1;
1343         }
1344         else if (gfc->CPU_features.SSE) {
1345             fft_asm_used = 2;
1346         }
1347 #else
1348 # if defined( HAVE_XMMINTRIN_H ) && defined( MIN_ARCH_SSE )
1349         {
1350             fft_asm_used = 3;
1351         }
1352 # endif
1353 #endif
1354         if (gfc->CPU_features.MMX) {
1355 #ifdef MMX_choose_table
1356             concatSep(text, ", ", "MMX (ASM used)");
1357 #else
1358             concatSep(text, ", ", "MMX");
1359 #endif
1360         }
1361         if (gfc->CPU_features.AMD_3DNow) {
1362             concatSep(text, ", ", (fft_asm_used == 1) ? "3DNow! (ASM used)" : "3DNow!");
1363         }
1364         if (gfc->CPU_features.SSE) {
1365 #if defined(HAVE_XMMINTRIN_H)
1366             concatSep(text, ", ", "SSE (ASM used)");
1367 #else
1368             concatSep(text, ", ", (fft_asm_used == 2) ? "SSE (ASM used)" : "SSE");
1369 #endif
1370         }
1371         if (gfc->CPU_features.SSE2) {
1372             concatSep(text, ", ", (fft_asm_used == 3) ? "SSE2 (ASM used)" : "SSE2");
1373         }
1374         MSGF(gfc, "CPU features: %s\n", text);
1375     }
1376
1377     if (cfg->channels_in == 2 && cfg->channels_out == 1 /* mono */ ) {
1378         MSGF(gfc, "Autoconverting from stereo to mono. Setting encoding to mono mode.\n");
1379     }
1380
1381     if (isResamplingNecessary(cfg)) {
1382         MSGF(gfc, "Resampling:  input %g kHz  output %g kHz\n",
1383              1.e-3 * in_samplerate, 1.e-3 * out_samplerate);
1384     }
1385
1386     if (cfg->highpass2 > 0.)
1387         MSGF(gfc,
1388              "Using polyphase highpass filter, transition band: %5.0f Hz - %5.0f Hz\n",
1389              0.5 * cfg->highpass1 * out_samplerate, 0.5 * cfg->highpass2 * out_samplerate);
1390     if (0. < cfg->lowpass1 || 0. < cfg->lowpass2) {
1391         MSGF(gfc,
1392              "Using polyphase lowpass filter, transition band: %5.0f Hz - %5.0f Hz\n",
1393              0.5 * cfg->lowpass1 * out_samplerate, 0.5 * cfg->lowpass2 * out_samplerate);
1394     }
1395     else {
1396         MSGF(gfc, "polyphase lowpass filter disabled\n");
1397     }
1398
1399     if (cfg->free_format) {
1400         MSGF(gfc, "Warning: many decoders cannot handle free format bitstreams\n");
1401         if (cfg->avg_bitrate > 320) {
1402             MSGF(gfc,
1403                  "Warning: many decoders cannot handle free format bitrates >320 kbps (see documentation)\n");
1404         }
1405     }
1406 }
1407
1408
1409 /**     rh:
1410  *      some pretty printing is very welcome at this point!
1411  *      so, if someone is willing to do so, please do it!
1412  *      add more, if you see more...
1413  */
1414 void
1415 lame_print_internals(const lame_global_flags * gfp)
1416 {
1417     lame_internal_flags const *const gfc = gfp->internal_flags;
1418     SessionConfig_t const *const cfg = &gfc->cfg;
1419     const char *pc = "";
1420
1421     /*  compiler/processor optimizations, operational, etc.
1422      */
1423     MSGF(gfc, "\nmisc:\n\n");
1424
1425     MSGF(gfc, "\tscaling: %g\n", gfp->scale);
1426     MSGF(gfc, "\tch0 (left) scaling: %g\n", gfp->scale_left);
1427     MSGF(gfc, "\tch1 (right) scaling: %g\n", gfp->scale_right);
1428     switch (cfg->use_best_huffman) {
1429     default:
1430         pc = "normal";
1431         break;
1432     case 1:
1433         pc = "best (outside loop)";
1434         break;
1435     case 2:
1436         pc = "best (inside loop, slow)";
1437         break;
1438     }
1439     MSGF(gfc, "\thuffman search: %s\n", pc);
1440     MSGF(gfc, "\texperimental Y=%d\n", gfp->experimentalY);
1441     MSGF(gfc, "\t...\n");
1442
1443     /*  everything controlling the stream format
1444      */
1445     MSGF(gfc, "\nstream format:\n\n");
1446     switch (cfg->version) {
1447     case 0:
1448         pc = "2.5";
1449         break;
1450     case 1:
1451         pc = "1";
1452         break;
1453     case 2:
1454         pc = "2";
1455         break;
1456     default:
1457         pc = "?";
1458         break;
1459     }
1460     MSGF(gfc, "\tMPEG-%s Layer 3\n", pc);
1461     switch (cfg->mode) {
1462     case JOINT_STEREO:
1463         pc = "joint stereo";
1464         break;
1465     case STEREO:
1466         pc = "stereo";
1467         break;
1468     case DUAL_CHANNEL:
1469         pc = "dual channel";
1470         break;
1471     case MONO:
1472         pc = "mono";
1473         break;
1474     case NOT_SET:
1475         pc = "not set (error)";
1476         break;
1477     default:
1478         pc = "unknown (error)";
1479         break;
1480     }
1481     MSGF(gfc, "\t%d channel - %s\n", cfg->channels_out, pc);
1482
1483     switch (cfg->vbr) {
1484     case vbr_off:
1485         pc = "off";
1486         break;
1487     default:
1488         pc = "all";
1489         break;
1490     }
1491     MSGF(gfc, "\tpadding: %s\n", pc);
1492
1493     if (vbr_default == cfg->vbr)
1494         pc = "(default)";
1495     else if (cfg->free_format)
1496         pc = "(free format)";
1497     else
1498         pc = "";
1499     switch (cfg->vbr) {
1500     case vbr_off:
1501         MSGF(gfc, "\tconstant bitrate - CBR %s\n", pc);
1502         break;
1503     case vbr_abr:
1504         MSGF(gfc, "\tvariable bitrate - ABR %s\n", pc);
1505         break;
1506     case vbr_rh:
1507         MSGF(gfc, "\tvariable bitrate - VBR rh %s\n", pc);
1508         break;
1509     case vbr_mt:
1510         MSGF(gfc, "\tvariable bitrate - VBR mt %s\n", pc);
1511         break;
1512     case vbr_mtrh:
1513         MSGF(gfc, "\tvariable bitrate - VBR mtrh %s\n", pc);
1514         break;
1515     default:
1516         MSGF(gfc, "\t ?? oops, some new one ?? \n");
1517         break;
1518     }
1519     if (cfg->write_lame_tag)
1520         MSGF(gfc, "\tusing LAME Tag\n");
1521     MSGF(gfc, "\t...\n");
1522
1523     /*  everything controlling psychoacoustic settings, like ATH, etc.
1524      */
1525     MSGF(gfc, "\npsychoacoustic:\n\n");
1526
1527     switch (cfg->short_blocks) {
1528     default:
1529     case short_block_not_set:
1530         pc = "?";
1531         break;
1532     case short_block_allowed:
1533         pc = "allowed";
1534         break;
1535     case short_block_coupled:
1536         pc = "channel coupled";
1537         break;
1538     case short_block_dispensed:
1539         pc = "dispensed";
1540         break;
1541     case short_block_forced:
1542         pc = "forced";
1543         break;
1544     }
1545     MSGF(gfc, "\tusing short blocks: %s\n", pc);
1546     MSGF(gfc, "\tsubblock gain: %d\n", cfg->subblock_gain);
1547     MSGF(gfc, "\tadjust masking: %g dB\n", gfc->sv_qnt.mask_adjust);
1548     MSGF(gfc, "\tadjust masking short: %g dB\n", gfc->sv_qnt.mask_adjust_short);
1549     MSGF(gfc, "\tquantization comparison: %d\n", cfg->quant_comp);
1550     MSGF(gfc, "\t ^ comparison short blocks: %d\n", cfg->quant_comp_short);
1551     MSGF(gfc, "\tnoise shaping: %d\n", cfg->noise_shaping);
1552     MSGF(gfc, "\t ^ amplification: %d\n", cfg->noise_shaping_amp);
1553     MSGF(gfc, "\t ^ stopping: %d\n", cfg->noise_shaping_stop);
1554
1555     pc = "using";
1556     if (cfg->ATHshort)
1557         pc = "the only masking for short blocks";
1558     if (cfg->ATHonly)
1559         pc = "the only masking";
1560     if (cfg->noATH)
1561         pc = "not used";
1562     MSGF(gfc, "\tATH: %s\n", pc);
1563     MSGF(gfc, "\t ^ type: %d\n", cfg->ATHtype);
1564     MSGF(gfc, "\t ^ shape: %g%s\n", cfg->ATHcurve, " (only for type 4)");
1565     MSGF(gfc, "\t ^ level adjustement: %g dB\n", cfg->ATH_offset_db);
1566     MSGF(gfc, "\t ^ adjust type: %d\n", gfc->ATH->use_adjust);
1567     MSGF(gfc, "\t ^ adjust sensitivity power: %f\n", gfc->ATH->aa_sensitivity_p);
1568
1569     MSGF(gfc, "\texperimental psy tunings by Naoki Shibata\n");
1570     MSGF(gfc, "\t   adjust masking bass=%g dB, alto=%g dB, treble=%g dB, sfb21=%g dB\n",
1571          10 * log10(gfc->sv_qnt.longfact[0]),
1572          10 * log10(gfc->sv_qnt.longfact[7]),
1573          10 * log10(gfc->sv_qnt.longfact[14]), 10 * log10(gfc->sv_qnt.longfact[21]));
1574
1575     pc = cfg->use_temporal_masking_effect ? "yes" : "no";
1576     MSGF(gfc, "\tusing temporal masking effect: %s\n", pc);
1577     MSGF(gfc, "\tinterchannel masking ratio: %g\n", cfg->interChRatio);
1578     MSGF(gfc, "\t...\n");
1579
1580     /*  that's all ?
1581      */
1582     MSGF(gfc, "\n");
1583     return;
1584 }
1585
1586
1587 static void
1588 save_gain_values(lame_internal_flags * gfc)
1589 {
1590     SessionConfig_t const *const cfg = &gfc->cfg;
1591     RpgStateVar_t const *const rsv = &gfc->sv_rpg;
1592     RpgResult_t *const rov = &gfc->ov_rpg;
1593     /* save the ReplayGain value */
1594     if (cfg->findReplayGain) {
1595         FLOAT const RadioGain = (FLOAT) GetTitleGain(rsv->rgdata);
1596         if (NEQ(RadioGain, GAIN_NOT_ENOUGH_SAMPLES)) {
1597             rov->RadioGain = (int) floor(RadioGain * 10.0 + 0.5); /* round to nearest */
1598         }
1599         else {
1600             rov->RadioGain = 0;
1601         }
1602     }
1603
1604     /* find the gain and scale change required for no clipping */
1605     if (cfg->findPeakSample) {
1606         rov->noclipGainChange = (int) ceil(log10(rov->PeakSample / 32767.0) * 20.0 * 10.0); /* round up */
1607
1608         if (rov->noclipGainChange > 0) { /* clipping occurs */
1609             rov->noclipScale = floor((32767.0f / rov->PeakSample) * 100.0f) / 100.0f; /* round down */
1610         }
1611         else            /* no clipping */
1612             rov->noclipScale = -1.0f;
1613     }
1614 }
1615
1616
1617
1618 static int
1619 update_inbuffer_size(lame_internal_flags * gfc, const int nsamples)
1620 {
1621     EncStateVar_t *const esv = &gfc->sv_enc;
1622     if (esv->in_buffer_0 == 0 || esv->in_buffer_nsamples < nsamples) {
1623         if (esv->in_buffer_0) {
1624             free(esv->in_buffer_0);
1625         }
1626         if (esv->in_buffer_1) {
1627             free(esv->in_buffer_1);
1628         }
1629         esv->in_buffer_0 = calloc(nsamples, sizeof(sample_t));
1630         esv->in_buffer_1 = calloc(nsamples, sizeof(sample_t));
1631         esv->in_buffer_nsamples = nsamples;
1632     }
1633     if (esv->in_buffer_0 == NULL || esv->in_buffer_1 == NULL) {
1634         if (esv->in_buffer_0) {
1635             free(esv->in_buffer_0);
1636         }
1637         if (esv->in_buffer_1) {
1638             free(esv->in_buffer_1);
1639         }
1640         esv->in_buffer_0 = 0;
1641         esv->in_buffer_1 = 0;
1642         esv->in_buffer_nsamples = 0;
1643         ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
1644         return -2;
1645     }
1646     return 0;
1647 }
1648
1649
1650 static int
1651 calcNeeded(SessionConfig_t const * cfg)
1652 {
1653     int     mf_needed;
1654     int     pcm_samples_per_frame = 576 * cfg->mode_gr;
1655
1656     /* some sanity checks */
1657 #if ENCDELAY < MDCTDELAY
1658 # error ENCDELAY is less than MDCTDELAY, see encoder.h
1659 #endif
1660 #if FFTOFFSET > BLKSIZE
1661 # error FFTOFFSET is greater than BLKSIZE, see encoder.h
1662 #endif
1663
1664     mf_needed = BLKSIZE + pcm_samples_per_frame - FFTOFFSET; /* amount needed for FFT */
1665     /*mf_needed = Max(mf_needed, 286 + 576 * (1 + gfc->mode_gr)); */
1666     mf_needed = Max(mf_needed, 512 + pcm_samples_per_frame - 32);
1667
1668     assert(MFSIZE >= mf_needed);
1669     
1670     return mf_needed;
1671 }
1672
1673
1674 /*
1675  * THE MAIN LAME ENCODING INTERFACE
1676  * mt 3/00
1677  *
1678  * input pcm data, output (maybe) mp3 frames.
1679  * This routine handles all buffering, resampling and filtering for you.
1680  * The required mp3buffer_size can be computed from num_samples,
1681  * samplerate and encoding rate, but here is a worst case estimate:
1682  *
1683  * mp3buffer_size in bytes = 1.25*num_samples + 7200
1684  *
1685  * return code = number of bytes output in mp3buffer.  can be 0
1686  *
1687  * NOTE: this routine uses LAME's internal PCM data representation,
1688  * 'sample_t'.  It should not be used by any application.
1689  * applications should use lame_encode_buffer(),
1690  *                         lame_encode_buffer_float()
1691  *                         lame_encode_buffer_int()
1692  * etc... depending on what type of data they are working with.
1693 */
1694 /* DEBUG ME:::::::::::: THIS CODE IS CAUSING STACK AND MEMORY CORRUPTION WHEN COMPILED WITH WATCOM C/C++
1695  *                      I HAVE SO FAR TRACED IT DOWN TO THIS FUNCTION CALL, SOMEWHERE BETWEEN fill_buffer
1696  *                      AND lame_encode() CALLS. YOU KNOW IT HAPPENS WHEN DOSBox COMPLAINS ABOUT ILLEGAL
1697  *                      MEMORY REFERENCES */
1698 static int
1699 lame_encode_buffer_sample_t(lame_internal_flags * gfc,
1700                             int nsamples, unsigned char *mp3buf, const int mp3buf_size)
1701 {
1702     SessionConfig_t const *const cfg = &gfc->cfg;
1703     EncStateVar_t *const esv = &gfc->sv_enc;
1704     int     pcm_samples_per_frame = 576 * cfg->mode_gr;
1705     int     mp3size = 0, ret, i, ch, mf_needed;
1706     int     mp3out;
1707     sample_t *mfbuf[2];
1708     sample_t *in_buffer[2];
1709
1710     esv->canary = 0x1234;
1711
1712     if (gfc->class_id != LAME_ID)
1713         return -3;
1714
1715     if (nsamples == 0)
1716         return 0;
1717
1718     /* copy out any tags that may have been written into bitstream */
1719     mp3out = copy_buffer(gfc, mp3buf, mp3buf_size, 0);
1720     if (mp3out < 0)
1721         return mp3out;  /* not enough buffer space */
1722     mp3buf += mp3out;
1723     mp3size += mp3out;
1724
1725     in_buffer[0] = esv->in_buffer_0;
1726     in_buffer[1] = esv->in_buffer_1;
1727
1728     mf_needed = calcNeeded(cfg);
1729
1730     mfbuf[0] = esv->mfbuf[0];
1731     mfbuf[1] = esv->mfbuf[1];
1732 #if 0
1733     fprintf(stderr,"gfc %p esv %p mf %p-%p %p-%p\n",gfc,esv,mfbuf[0],&(esv->mfbuf[0]),mfbuf[1],&(esv->mfbuf[1]));
1734 #endif
1735
1736     while (nsamples > 0) {
1737         sample_t const *in_buffer_ptr[2];
1738         int     n_in = 0;    /* number of input samples processed with fill_buffer */
1739         int     n_out = 0;   /* number of samples output with fill_buffer */
1740         /* n_in <> n_out if we are resampling */
1741
1742         in_buffer_ptr[0] = in_buffer[0];
1743         in_buffer_ptr[1] = in_buffer[1];
1744         /* copy in new samples into mfbuf, with resampling */
1745         fill_buffer(gfc, mfbuf, &in_buffer_ptr[0], nsamples, &n_in, &n_out);
1746
1747 #if 0
1748         /* DEBUG */
1749         fprintf(stderr,"rem=%d in=%d out=%d mf_size=%d(0x%X) mf_need=%d mf_enc=%d sz=%d MFSIZE=%d\n",nsamples,n_in,n_out,esv->mf_size,esv->mf_size,mf_needed,esv->mf_samples_to_encode,esv->in_buffer_nsamples,MFSIZE);
1750         fprintf(stderr,"    %p!=%p %p!=%p\n",esv->mfbuf[0],mfbuf[0],esv->mfbuf[1],mfbuf[1]);
1751         if (esv->canary != 0x1234) {
1752                 fprintf(stderr,"Canary died, mfbuf[] overrun\n");
1753                 abort();
1754         }
1755         getch();
1756 #endif
1757
1758         assert(esv->mf_size >= 0);
1759         assert(esv->mf_size <= MFSIZE);
1760         assert(n_in <= esv->in_buffer_nsamples);
1761         assert(n_out >= 0);
1762         assert(n_in >= 0);
1763
1764         /* compute ReplayGain of resampled input if requested */
1765         if (cfg->findReplayGain && !cfg->decode_on_the_fly)
1766             if (AnalyzeSamples
1767                 (gfc->sv_rpg.rgdata, &mfbuf[0][esv->mf_size], &mfbuf[1][esv->mf_size], n_out,
1768                  cfg->channels_out) == GAIN_ANALYSIS_ERROR)
1769                 return -6;
1770
1771
1772         /* update in_buffer counters */
1773         nsamples -= n_in;
1774         in_buffer[0] += n_in;
1775         if (cfg->channels_out == 2)
1776             in_buffer[1] += n_in;
1777
1778         assert(in_buffer[0] >= esv->in_buffer_0 && in_buffer[0] <= (esv->in_buffer_0 + esv->in_buffer_nsamples));
1779         if (in_buffer[1] != NULL)
1780                 assert(in_buffer[1] >= esv->in_buffer_1 && in_buffer[1] <= (esv->in_buffer_1 + esv->in_buffer_nsamples));
1781
1782         /* update mfbuf[] counters */
1783         esv->mf_size += n_out;
1784         assert(esv->mf_size >= 0);
1785         assert(esv->mf_size <= MFSIZE);
1786        
1787         /* lame_encode_flush may have set gfc->mf_sample_to_encode to 0
1788          * so we have to reinitialize it here when that happened.
1789          */
1790         if (esv->mf_samples_to_encode < 1) {
1791             esv->mf_samples_to_encode = ENCDELAY + POSTDELAY;
1792         }        
1793         esv->mf_samples_to_encode += n_out;
1794
1795         if (esv->mf_size >= mf_needed) {
1796             /* encode the frame.  */
1797             /* mp3buf              = pointer to current location in buffer */
1798             /* mp3buf_size         = size of original mp3 output buffer */
1799             /*                     = 0 if we should not worry about the */
1800             /*                       buffer size because calling program is  */
1801             /*                       to lazy to compute it */
1802             /* mp3size             = size of data written to buffer so far */
1803             /* mp3buf_size-mp3size = amount of space avalable  */
1804
1805             int     buf_size = mp3buf_size - mp3size;
1806             if (mp3buf_size == 0)
1807                 buf_size = 0;
1808
1809             ret = lame_encode_mp3_frame(gfc, mfbuf[0], mfbuf[1], mp3buf, buf_size);
1810
1811             if (ret < 0)
1812                 return ret;
1813             mp3buf += ret;
1814             mp3size += ret;
1815
1816             /* shift out old samples */
1817             esv->mf_size -= pcm_samples_per_frame;
1818             esv->mf_samples_to_encode -= pcm_samples_per_frame;
1819             for (ch = 0; ch < cfg->channels_out; ch++)
1820                 for (i = 0; i < esv->mf_size; i++)
1821                     mfbuf[ch][i] = mfbuf[ch][i + pcm_samples_per_frame];
1822         }
1823     }
1824     assert(nsamples == 0);
1825
1826     return mp3size;
1827 }
1828
1829 enum PCMSampleType 
1830 {   pcm_short_type
1831 ,   pcm_int_type
1832 ,   pcm_long_type
1833 ,   pcm_float_type
1834 ,   pcm_double_type
1835 };
1836
1837 static void
1838 lame_copy_inbuffer(lame_internal_flags* gfc, 
1839                    void const* l, void const* r, int nsamples,
1840                    enum PCMSampleType pcm_type, int jump, FLOAT s)
1841 {
1842     SessionConfig_t const *const cfg = &gfc->cfg;
1843     EncStateVar_t *const esv = &gfc->sv_enc;
1844     sample_t* ib0 = esv->in_buffer_0;
1845     sample_t* ib1 = esv->in_buffer_1;
1846     FLOAT   m[2][2];
1847
1848     /* Apply user defined re-scaling */
1849     m[0][0] = s * cfg->pcm_transform[0][0];
1850     m[0][1] = s * cfg->pcm_transform[0][1];
1851     m[1][0] = s * cfg->pcm_transform[1][0];
1852     m[1][1] = s * cfg->pcm_transform[1][1];
1853
1854     /* make a copy of input buffer, changing type to sample_t */
1855 #define COPY_AND_TRANSFORM(T) \
1856 { \
1857     T const *bl = l, *br = r; \
1858     int     i; \
1859     for (i = 0; i < nsamples; i++) { \
1860         sample_t const xl = *bl; \
1861         sample_t const xr = *br; \
1862         sample_t const u = xl * m[0][0] + xr * m[0][1]; \
1863         sample_t const v = xl * m[1][0] + xr * m[1][1]; \
1864         ib0[i] = u; \
1865         ib1[i] = v; \
1866         bl += jump; \
1867         br += jump; \
1868     } \
1869 }
1870     switch ( pcm_type ) {
1871     case pcm_short_type: 
1872         COPY_AND_TRANSFORM(short int);
1873         break;
1874     case pcm_int_type:
1875         COPY_AND_TRANSFORM(int);
1876         break;
1877     case pcm_long_type:
1878         COPY_AND_TRANSFORM(long int);
1879         break;
1880     case pcm_float_type:
1881         COPY_AND_TRANSFORM(float);
1882         break;
1883     case pcm_double_type:
1884         COPY_AND_TRANSFORM(double);
1885         break;
1886     }
1887 }
1888
1889
1890 static int
1891 lame_encode_buffer_template(lame_global_flags * gfp,
1892                             void const* buffer_l, void const* buffer_r, const int nsamples,
1893                             unsigned char *mp3buf, const int mp3buf_size, enum PCMSampleType pcm_type, int aa, FLOAT norm)
1894 {
1895     if (is_lame_global_flags_valid(gfp)) {
1896         lame_internal_flags *const gfc = gfp->internal_flags;
1897         if (is_lame_internal_flags_valid(gfc)) {
1898             SessionConfig_t const *const cfg = &gfc->cfg;
1899
1900             if (nsamples == 0)
1901                 return 0;
1902
1903             if (update_inbuffer_size(gfc, nsamples) != 0) {
1904                 return -2;
1905             }
1906             /* make a copy of input buffer, changing type to sample_t */
1907             if (cfg->channels_in > 1) {
1908                 if (buffer_l == 0 || buffer_r == 0) {
1909                     return 0;
1910                 }
1911                 lame_copy_inbuffer(gfc, buffer_l, buffer_r, nsamples, pcm_type, aa, norm);
1912             }
1913             else {
1914                 if (buffer_l == 0) {
1915                     return 0;
1916                 }
1917                 lame_copy_inbuffer(gfc, buffer_l, buffer_l, nsamples, pcm_type, aa, norm);
1918             }
1919
1920             return lame_encode_buffer_sample_t(gfc, nsamples, mp3buf, mp3buf_size);
1921         }
1922     }
1923     return -3;
1924 }
1925
1926 int
1927 lame_encode_buffer(lame_global_flags * gfp,
1928                    const short int pcm_l[], const short int pcm_r[], const int nsamples,
1929                    unsigned char *mp3buf, const int mp3buf_size)
1930 {
1931     return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_short_type, 1, 1.0);
1932 }
1933
1934
1935 int
1936 lame_encode_buffer_float(lame_global_flags * gfp,
1937                          const float pcm_l[], const float pcm_r[], const int nsamples,
1938                          unsigned char *mp3buf, const int mp3buf_size)
1939 {
1940     /* input is assumed to be normalized to +/- 32768 for full scale */
1941     return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 1.0);
1942 }
1943
1944
1945 int
1946 lame_encode_buffer_ieee_float(lame_t gfp,
1947                          const float pcm_l[], const float pcm_r[], const int nsamples,
1948                          unsigned char *mp3buf, const int mp3buf_size)
1949 {
1950     /* input is assumed to be normalized to +/- 1.0 for full scale */
1951     return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 32767.0);
1952 }
1953
1954
1955 int
1956 lame_encode_buffer_interleaved_ieee_float(lame_t gfp,
1957                          const float pcm[], const int nsamples,
1958                          unsigned char *mp3buf, const int mp3buf_size)
1959 {
1960     /* input is assumed to be normalized to +/- 1.0 for full scale */
1961     return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_float_type, 2, 32767.0);
1962 }
1963
1964
1965 int
1966 lame_encode_buffer_ieee_double(lame_t gfp,
1967                          const double pcm_l[], const double pcm_r[], const int nsamples,
1968                          unsigned char *mp3buf, const int mp3buf_size)
1969 {
1970     /* input is assumed to be normalized to +/- 1.0 for full scale */
1971     return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_double_type, 1, 32767.0);
1972 }
1973
1974
1975 int
1976 lame_encode_buffer_interleaved_ieee_double(lame_t gfp,
1977                          const double pcm[], const int nsamples,
1978                          unsigned char *mp3buf, const int mp3buf_size)
1979 {
1980     /* input is assumed to be normalized to +/- 1.0 for full scale */
1981     return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_double_type, 2, 32767.0);
1982 }
1983
1984
1985 int
1986 lame_encode_buffer_int(lame_global_flags * gfp,
1987                        const int pcm_l[], const int pcm_r[], const int nsamples,
1988                        unsigned char *mp3buf, const int mp3buf_size)
1989 {
1990     /* input is assumed to be normalized to +/- MAX_INT for full scale */
1991     FLOAT const norm = (1.0 / (1L << (8 * sizeof(int) - 16)));
1992     return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_int_type, 1, norm);
1993 }
1994
1995
1996 int
1997 lame_encode_buffer_long2(lame_global_flags * gfp,
1998                          const long pcm_l[],  const long pcm_r[], const int nsamples,
1999                          unsigned char *mp3buf, const int mp3buf_size)
2000 {
2001     /* input is assumed to be normalized to +/- MAX_LONG for full scale */
2002     FLOAT const norm = (1.0 / (1L << (8 * sizeof(long) - 16)));
2003     return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, norm);
2004 }
2005
2006
2007 int
2008 lame_encode_buffer_long(lame_global_flags * gfp,
2009                         const long pcm_l[], const long pcm_r[], const int nsamples,
2010                         unsigned char *mp3buf, const int mp3buf_size)
2011 {
2012     /* input is assumed to be normalized to +/- 32768 for full scale */
2013     return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, 1.0);
2014 }
2015
2016
2017
2018 int
2019 lame_encode_buffer_interleaved(lame_global_flags * gfp,
2020                                short int pcm[], int nsamples,
2021                                unsigned char *mp3buf, int mp3buf_size)
2022 {
2023     /* input is assumed to be normalized to +/- MAX_SHORT for full scale */
2024     return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_short_type, 2, 1.0);
2025 }
2026
2027
2028
2029
2030 /*****************************************************************
2031  Flush mp3 buffer, pad with ancillary data so last frame is complete.
2032  Reset reservoir size to 0
2033  but keep all PCM samples and MDCT data in memory
2034  This option is used to break a large file into several mp3 files
2035  that when concatenated together will decode with no gaps
2036  Because we set the reservoir=0, they will also decode seperately
2037  with no errors.
2038 *********************************************************************/
2039 int
2040 lame_encode_flush_nogap(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
2041 {
2042     int     rc = -3;
2043     if (is_lame_global_flags_valid(gfp)) {
2044         lame_internal_flags *const gfc = gfp->internal_flags;
2045         if (is_lame_internal_flags_valid(gfc)) {
2046             flush_bitstream(gfc);
2047             rc = copy_buffer(gfc, mp3buffer, mp3buffer_size, 1);
2048             save_gain_values(gfc);
2049         }
2050     }
2051     return rc;
2052 }
2053
2054
2055 /* called by lame_init_params.  You can also call this after flush_nogap
2056    if you want to write new id3v2 and Xing VBR tags into the bitstream */
2057 int
2058 lame_init_bitstream(lame_global_flags * gfp)
2059 {
2060     if (is_lame_global_flags_valid(gfp)) {
2061         lame_internal_flags *const gfc = gfp->internal_flags;
2062         if (gfc != 0) {
2063             gfc->ov_enc.frame_number = 0;
2064
2065             if (gfp->write_id3tag_automatic) {
2066                 (void) id3tag_write_v2(gfp);
2067             }
2068             /* initialize histogram data optionally used by frontend */
2069             memset(gfc->ov_enc.bitrate_channelmode_hist, 0,
2070                    sizeof(gfc->ov_enc.bitrate_channelmode_hist));
2071             memset(gfc->ov_enc.bitrate_blocktype_hist, 0,
2072                    sizeof(gfc->ov_enc.bitrate_blocktype_hist));
2073
2074             gfc->ov_rpg.PeakSample = 0.0;
2075
2076             /* Write initial VBR Header to bitstream and init VBR data */
2077             if (gfc->cfg.write_lame_tag)
2078                 (void) InitVbrTag(gfp);
2079
2080
2081             return 0;
2082         }
2083     }
2084     return -3;
2085 }
2086
2087
2088 /*****************************************************************/
2089 /* flush internal PCM sample buffers, then mp3 buffers           */
2090 /* then write id3 v1 tags into bitstream.                        */
2091 /*****************************************************************/
2092
2093 int
2094 lame_encode_flush(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
2095 {
2096     lame_internal_flags *gfc;
2097     SessionConfig_t const *cfg;
2098     EncStateVar_t *esv;
2099     short int buffer[2][1152];
2100     int     imp3 = 0, mp3count, mp3buffer_size_remaining;
2101
2102     /* we always add POSTDELAY=288 padding to make sure granule with real
2103      * data can be complety decoded (because of 50% overlap with next granule */
2104     int     end_padding;
2105     int     frames_left;
2106     int     samples_to_encode;
2107     int     pcm_samples_per_frame;
2108     int     mf_needed;
2109     int     is_resampling_necessary;
2110     double  resample_ratio = 1;
2111
2112     if (!is_lame_global_flags_valid(gfp)) {
2113         return -3;
2114     }
2115     gfc = gfp->internal_flags;
2116     if (!is_lame_internal_flags_valid(gfc)) {
2117         return -3;
2118     }
2119     cfg = &gfc->cfg;
2120     esv = &gfc->sv_enc;
2121     
2122     /* Was flush already called? */
2123     if (esv->mf_samples_to_encode < 1) {
2124         return 0;
2125     }
2126     pcm_samples_per_frame = 576 * cfg->mode_gr;
2127     mf_needed = calcNeeded(cfg);
2128
2129     samples_to_encode = esv->mf_samples_to_encode - POSTDELAY;
2130
2131     memset(buffer, 0, sizeof(buffer));
2132     mp3count = 0;
2133
2134     is_resampling_necessary = isResamplingNecessary(cfg);
2135     if (is_resampling_necessary) {
2136         resample_ratio = (double)cfg->samplerate_in / (double)cfg->samplerate_out;
2137         /* delay due to resampling; needs to be fixed, if resampling code gets changed */
2138         samples_to_encode += 16. / resample_ratio;
2139     }
2140     end_padding = pcm_samples_per_frame - (samples_to_encode % pcm_samples_per_frame);
2141     if (end_padding < 576)
2142         end_padding += pcm_samples_per_frame;
2143     gfc->ov_enc.encoder_padding = end_padding;
2144     
2145     frames_left = (samples_to_encode + end_padding) / pcm_samples_per_frame;
2146     while (frames_left > 0 && imp3 >= 0) {
2147         int const frame_num = gfc->ov_enc.frame_number;
2148         int     bunch = mf_needed - esv->mf_size;
2149
2150         bunch *= resample_ratio;
2151         if (bunch > 1152) bunch = 1152;
2152         if (bunch < 1) bunch = 1;
2153
2154         mp3buffer_size_remaining = mp3buffer_size - mp3count;
2155
2156         /* if user specifed buffer size = 0, dont check size */
2157         if (mp3buffer_size == 0)
2158             mp3buffer_size_remaining = 0;
2159
2160         /* send in a frame of 0 padding until all internal sample buffers
2161          * are flushed
2162          */
2163         imp3 = lame_encode_buffer(gfp, buffer[0], buffer[1], bunch,
2164                                   mp3buffer, mp3buffer_size_remaining);
2165
2166         mp3buffer += imp3;
2167         mp3count += imp3;
2168         frames_left -= ((frame_num != gfc->ov_enc.frame_number) ? 1 : 0);
2169     }
2170     /* Set esv->mf_samples_to_encode to 0, so we may detect
2171      * and break loops calling it more than once in a row.
2172      */
2173     esv->mf_samples_to_encode = 0;
2174
2175     if (imp3 < 0) {
2176         /* some type of fatal error */
2177         return imp3;
2178     }
2179
2180     mp3buffer_size_remaining = mp3buffer_size - mp3count;
2181     /* if user specifed buffer size = 0, dont check size */
2182     if (mp3buffer_size == 0)
2183         mp3buffer_size_remaining = 0;
2184
2185     /* mp3 related stuff.  bit buffer might still contain some mp3 data */
2186     flush_bitstream(gfc);
2187     imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 1);
2188     save_gain_values(gfc);
2189     if (imp3 < 0) {
2190         /* some type of fatal error */
2191         return imp3;
2192     }
2193     mp3buffer += imp3;
2194     mp3count += imp3;
2195     mp3buffer_size_remaining = mp3buffer_size - mp3count;
2196     /* if user specifed buffer size = 0, dont check size */
2197     if (mp3buffer_size == 0)
2198         mp3buffer_size_remaining = 0;
2199
2200     if (gfp->write_id3tag_automatic) {
2201         /* write a id3 tag to the bitstream */
2202         (void) id3tag_write_v1(gfp);
2203
2204         imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 0);
2205
2206         if (imp3 < 0) {
2207             return imp3;
2208         }
2209         mp3count += imp3;
2210     }
2211 #if 0
2212     {
2213         int const ed = gfc->ov_enc.encoder_delay;
2214         int const ep = gfc->ov_enc.encoder_padding;
2215         int const ns = (gfc->ov_enc.frame_number * pcm_samples_per_frame) - (ed + ep);
2216         double  duration = ns;
2217         duration /= cfg->samplerate_out;
2218         MSGF(gfc, "frames=%d\n", gfc->ov_enc.frame_number);
2219         MSGF(gfc, "pcm_samples_per_frame=%d\n", pcm_samples_per_frame);
2220         MSGF(gfc, "encoder delay=%d\n", ed);
2221         MSGF(gfc, "encoder padding=%d\n", ep);
2222         MSGF(gfc, "sample count=%d (%g)\n", ns, cfg->samplerate_in * duration);
2223         MSGF(gfc, "duration=%g sec\n", duration);
2224     }
2225 #endif
2226     return mp3count;
2227 }
2228
2229 /***********************************************************************
2230  *
2231  *      lame_close ()
2232  *
2233  *  frees internal buffers
2234  *
2235  ***********************************************************************/
2236
2237 int
2238 lame_close(lame_global_flags * gfp)
2239 {
2240     int     ret = 0;
2241     if (gfp && gfp->class_id == LAME_ID) {
2242         lame_internal_flags *const gfc = gfp->internal_flags;
2243         gfp->class_id = 0;
2244         if (NULL == gfc || gfc->class_id != LAME_ID) {
2245             ret = -3;
2246         }
2247         if (NULL != gfc) {
2248             gfc->class_id = 0;
2249             /* this routine will free all malloc'd data in gfc, and then free gfc: */
2250             freegfc(gfc);
2251             gfp->internal_flags = NULL;
2252         }
2253         if (gfp->lame_allocated_gfp) {
2254             gfp->lame_allocated_gfp = 0;
2255             free(gfp);
2256         }
2257     }
2258     return ret;
2259 }
2260
2261 /*****************************************************************/
2262 /* flush internal mp3 buffers, and free internal buffers         */
2263 /*****************************************************************/
2264 #if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
2265 int CDECL
2266 lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size);
2267 #else
2268 #endif
2269
2270 int
2271 lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
2272 {
2273     int const ret = lame_encode_flush(gfp, mp3buffer, mp3buffer_size);
2274
2275     (void) lame_close(gfp);
2276
2277     return ret;
2278 }
2279
2280 /*****************************************************************/
2281 /* write VBR Xing header, and ID3 version 1 tag, if asked for    */
2282 /*****************************************************************/
2283 void    lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream);
2284
2285 void
2286 lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream)
2287 {
2288     lame_internal_flags *gfc;
2289     SessionConfig_t const *cfg;
2290     if (!is_lame_global_flags_valid(gfp)) {
2291         return;
2292     }
2293     gfc = gfp->internal_flags;
2294     if (!is_lame_internal_flags_valid(gfc)) {
2295         return;
2296     }
2297     cfg = &gfc->cfg;
2298     if (!cfg->write_lame_tag) {
2299         return;
2300     }
2301     /* Write Xing header again */
2302     if (fpStream && !fseek(fpStream, 0, SEEK_SET)) {
2303         int     rc = PutVbrTag(gfp, fpStream);
2304         switch (rc) {
2305         default:
2306             /* OK */
2307             break;
2308
2309         case -1:
2310             ERRORF(gfc, "Error: could not update LAME tag.\n");
2311             break;
2312
2313         case -2:
2314             ERRORF(gfc, "Error: could not update LAME tag, file not seekable.\n");
2315             break;
2316
2317         case -3:
2318             ERRORF(gfc, "Error: could not update LAME tag, file not readable.\n");
2319             break;
2320         }
2321     }
2322 }
2323
2324
2325
2326 /* initialize mp3 encoder */
2327 #if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
2328 static
2329 #else
2330 #endif
2331 int
2332 lame_init_old(lame_global_flags * gfp)
2333 {
2334     lame_internal_flags *gfc;
2335     SessionConfig_t *cfg;
2336
2337     disable_FPE();      /* disable floating point exceptions */
2338
2339     memset(gfp, 0, sizeof(lame_global_flags));
2340
2341     gfp->class_id = LAME_ID;
2342
2343     if (NULL == (gfc = gfp->internal_flags = calloc(1, sizeof(lame_internal_flags))))
2344         return -1;
2345
2346     cfg = &gfc->cfg;
2347
2348     /* Global flags.  set defaults here for non-zero values */
2349     /* see lame.h for description */
2350     /* set integer values to -1 to mean that LAME will compute the
2351      * best value, UNLESS the calling program as set it
2352      * (and the value is no longer -1)
2353      */
2354     gfp->strict_ISO = MDB_MAXIMUM;
2355
2356     gfp->mode = NOT_SET;
2357     gfp->original = 1;
2358     gfp->samplerate_in = 44100;
2359     gfp->num_channels = 2;
2360     gfp->num_samples = MAX_U_32_NUM;
2361
2362     gfp->write_lame_tag = 1;
2363     gfp->quality = -1;
2364     gfp->short_blocks = short_block_not_set;
2365     gfp->subblock_gain = -1;
2366
2367     gfp->lowpassfreq = 0;
2368     gfp->highpassfreq = 0;
2369     gfp->lowpasswidth = -1;
2370     gfp->highpasswidth = -1;
2371
2372     gfp->VBR = vbr_off;
2373     gfp->VBR_q = 4;
2374     gfp->ATHcurve = -1;
2375     gfp->VBR_mean_bitrate_kbps = 128;
2376     gfp->VBR_min_bitrate_kbps = 0;
2377     gfp->VBR_max_bitrate_kbps = 0;
2378     gfp->VBR_hard_min = 0;
2379     cfg->vbr_min_bitrate_index = 1; /* not  0 ????? */
2380     cfg->vbr_max_bitrate_index = 13; /* not 14 ????? */
2381
2382     gfp->quant_comp = -1;
2383     gfp->quant_comp_short = -1;
2384
2385     gfp->msfix = -1;
2386
2387     gfc->sv_qnt.OldValue[0] = 180;
2388     gfc->sv_qnt.OldValue[1] = 180;
2389     gfc->sv_qnt.CurrentStep[0] = 4;
2390     gfc->sv_qnt.CurrentStep[1] = 4;
2391     gfc->sv_qnt.masking_lower = 1;
2392
2393     gfp->attackthre = -1;
2394     gfp->attackthre_s = -1;
2395
2396     gfp->scale = 1;
2397     gfp->scale_left = 1;
2398     gfp->scale_right = 1;
2399
2400     gfp->athaa_type = -1;
2401     gfp->ATHtype = -1;  /* default = -1 = set in lame_init_params */
2402     /* 2 = equal loudness curve */
2403     gfp->athaa_sensitivity = 0.0; /* no offset */
2404     gfp->useTemporal = -1;
2405     gfp->interChRatio = -1;
2406
2407     /* The reason for
2408      *       int mf_samples_to_encode = ENCDELAY + POSTDELAY;
2409      * ENCDELAY = internal encoder delay.  And then we have to add POSTDELAY=288
2410      * because of the 50% MDCT overlap.  A 576 MDCT granule decodes to
2411      * 1152 samples.  To synthesize the 576 samples centered under this granule
2412      * we need the previous granule for the first 288 samples (no problem), and
2413      * the next granule for the next 288 samples (not possible if this is last
2414      * granule).  So we need to pad with 288 samples to make sure we can
2415      * encode the 576 samples we are interested in.
2416      */
2417     gfc->sv_enc.mf_samples_to_encode = ENCDELAY + POSTDELAY;
2418     gfc->ov_enc.encoder_padding = 0;
2419     gfc->sv_enc.mf_size = ENCDELAY - MDCTDELAY; /* we pad input with this many 0's */
2420
2421     gfp->findReplayGain = 0;
2422     gfp->decode_on_the_fly = 0;
2423
2424     gfc->cfg.decode_on_the_fly = 0;
2425     gfc->cfg.findReplayGain = 0;
2426     gfc->cfg.findPeakSample = 0;
2427
2428     gfc->ov_rpg.RadioGain = 0;
2429     gfc->ov_rpg.noclipGainChange = 0;
2430     gfc->ov_rpg.noclipScale = -1.0;
2431
2432     gfp->asm_optimizations.mmx = 1;
2433     gfp->asm_optimizations.amd3dnow = 1;
2434     gfp->asm_optimizations.sse = 1;
2435
2436     gfp->preset = 0;
2437
2438     gfp->write_id3tag_automatic = 1;
2439
2440     gfp->report.debugf = &lame_report_def;
2441     gfp->report.errorf = &lame_report_def;
2442     gfp->report.msgf = &lame_report_def;
2443     return 0;
2444 }
2445
2446
2447 lame_global_flags *
2448 lame_init(void)
2449 {
2450     lame_global_flags *gfp;
2451     int     ret;
2452
2453     init_log_table();
2454
2455     gfp = calloc(1, sizeof(lame_global_flags));
2456     if (gfp == NULL)
2457         return NULL;
2458
2459     ret = lame_init_old(gfp);
2460     if (ret != 0) {
2461         free(gfp);
2462         return NULL;
2463     }
2464
2465     gfp->lame_allocated_gfp = 1;
2466     return gfp;
2467 }
2468
2469
2470 /***********************************************************************
2471  *
2472  *  some simple statistics
2473  *
2474  *  Robert Hegemann 2000-10-11
2475  *
2476  ***********************************************************************/
2477
2478 /*  histogram of used bitrate indexes:
2479  *  One has to weight them to calculate the average bitrate in kbps
2480  *
2481  *  bitrate indices:
2482  *  there are 14 possible bitrate indices, 0 has the special meaning
2483  *  "free format" which is not possible to mix with VBR and 15 is forbidden
2484  *  anyway.
2485  *
2486  *  stereo modes:
2487  *  0: LR   number of left-right encoded frames
2488  *  1: LR-I number of left-right and intensity encoded frames
2489  *  2: MS   number of mid-side encoded frames
2490  *  3: MS-I number of mid-side and intensity encoded frames
2491  *
2492  *  4: number of encoded frames
2493  *
2494  */
2495
2496 void
2497 lame_bitrate_kbps(const lame_global_flags * gfp, int bitrate_kbps[14])
2498 {
2499     if (is_lame_global_flags_valid(gfp)) {
2500         lame_internal_flags const *const gfc = gfp->internal_flags;
2501         if (is_lame_internal_flags_valid(gfc)) {
2502             SessionConfig_t const *const cfg = &gfc->cfg;
2503             int     i;
2504             if (cfg->free_format) {
2505                 for (i = 0; i < 14; i++)
2506                     bitrate_kbps[i] = -1;
2507                 bitrate_kbps[0] = cfg->avg_bitrate;
2508             }
2509             else {
2510                 for (i = 0; i < 14; i++)
2511                     bitrate_kbps[i] = bitrate_table[cfg->version][i + 1];
2512             }
2513         }
2514     }
2515 }
2516
2517
2518 void
2519 lame_bitrate_hist(const lame_global_flags * gfp, int bitrate_count[14])
2520 {
2521     if (is_lame_global_flags_valid(gfp)) {
2522         lame_internal_flags const *const gfc = gfp->internal_flags;
2523         if (is_lame_internal_flags_valid(gfc)) {
2524             SessionConfig_t const *const cfg = &gfc->cfg;
2525             EncResult_t const *const eov = &gfc->ov_enc;
2526             int     i;
2527
2528             if (cfg->free_format) {
2529                 for (i = 0; i < 14; i++) {
2530                     bitrate_count[i] = 0;
2531                 }
2532                 bitrate_count[0] = eov->bitrate_channelmode_hist[0][4];
2533             }
2534             else {
2535                 for (i = 0; i < 14; i++) {
2536                     bitrate_count[i] = eov->bitrate_channelmode_hist[i + 1][4];
2537                 }
2538             }
2539         }
2540     }
2541 }
2542
2543
2544 void
2545 lame_stereo_mode_hist(const lame_global_flags * gfp, int stmode_count[4])
2546 {
2547     if (is_lame_global_flags_valid(gfp)) {
2548         lame_internal_flags const *const gfc = gfp->internal_flags;
2549         if (is_lame_internal_flags_valid(gfc)) {
2550             EncResult_t const *const eov = &gfc->ov_enc;
2551             int     i;
2552
2553             for (i = 0; i < 4; i++) {
2554                 stmode_count[i] = eov->bitrate_channelmode_hist[15][i];
2555             }
2556         }
2557     }
2558 }
2559
2560
2561
2562 void
2563 lame_bitrate_stereo_mode_hist(const lame_global_flags * gfp, int bitrate_stmode_count[14][4])
2564 {
2565     if (is_lame_global_flags_valid(gfp)) {
2566         lame_internal_flags const *const gfc = gfp->internal_flags;
2567         if (is_lame_internal_flags_valid(gfc)) {
2568             SessionConfig_t const *const cfg = &gfc->cfg;
2569             EncResult_t const *const eov = &gfc->ov_enc;
2570             int     i;
2571             int     j;
2572
2573             if (cfg->free_format) {
2574                 for (j = 0; j < 14; j++)
2575                     for (i = 0; i < 4; i++) {
2576                         bitrate_stmode_count[j][i] = 0;
2577                     }
2578                 for (i = 0; i < 4; i++) {
2579                     bitrate_stmode_count[0][i] = eov->bitrate_channelmode_hist[0][i];
2580                 }
2581             }
2582             else {
2583                 for (j = 0; j < 14; j++) {
2584                     for (i = 0; i < 4; i++) {
2585                         bitrate_stmode_count[j][i] = eov->bitrate_channelmode_hist[j + 1][i];
2586                     }
2587                 }
2588             }
2589         }
2590     }
2591 }
2592
2593
2594 void
2595 lame_block_type_hist(const lame_global_flags * gfp, int btype_count[6])
2596 {
2597     if (is_lame_global_flags_valid(gfp)) {
2598         lame_internal_flags const *const gfc = gfp->internal_flags;
2599         if (is_lame_internal_flags_valid(gfc)) {
2600             EncResult_t const *const eov = &gfc->ov_enc;
2601             int     i;
2602
2603             for (i = 0; i < 6; ++i) {
2604                 btype_count[i] = eov->bitrate_blocktype_hist[15][i];
2605             }
2606         }
2607     }
2608 }
2609
2610
2611
2612 void
2613 lame_bitrate_block_type_hist(const lame_global_flags * gfp, int bitrate_btype_count[14][6])
2614 {
2615     if (is_lame_global_flags_valid(gfp)) {
2616         lame_internal_flags const *const gfc = gfp->internal_flags;
2617         if (is_lame_internal_flags_valid(gfc)) {
2618             SessionConfig_t const *const cfg = &gfc->cfg;
2619             EncResult_t const *const eov = &gfc->ov_enc;
2620             int     i, j;
2621
2622             if (cfg->free_format) {
2623                 for (j = 0; j < 14; ++j) {
2624                     for (i = 0; i < 6; ++i) {
2625                         bitrate_btype_count[j][i] = 0;
2626                     }
2627                 }
2628                 for (i = 0; i < 6; ++i) {
2629                     bitrate_btype_count[0][i] = eov->bitrate_blocktype_hist[0][i];
2630                 }
2631             }
2632             else {
2633                 for (j = 0; j < 14; ++j) {
2634                     for (i = 0; i < 6; ++i) {
2635                         bitrate_btype_count[j][i] = eov->bitrate_blocktype_hist[j + 1][i];
2636                     }
2637                 }
2638             }
2639         }
2640     }
2641 }
2642
2643 /* end of lame.c */