1 /* -*- mode: C; mode: fold -*- */
3 * LAME MP3 encoding engine
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
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.
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.
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.
27 /* $Id: lame.c,v 1.365 2011/10/18 21:51:20 robert Exp $ */
39 #include "lame_global_flags.h"
40 #include "gain_analysis.h"
41 #include "bitstream.h"
42 #include "quantize_pvt.h"
51 #if defined(__FreeBSD__) && !defined(__alpha__)
52 #include <floatingpoint.h>
59 /* woraround for SunOS 4.x, it has SEEK_* defined here */
64 #define LAME_DEFAULT_QUALITY 3
69 is_lame_global_flags_valid(const lame_global_flags * gfp)
73 if (gfp->class_id != LAME_ID)
80 is_lame_internal_flags_valid(const lame_internal_flags * gfc)
84 if (gfc->class_id != LAME_ID)
99 return cos(PI / 2 * x);
103 lame_init_params_ppflt(lame_internal_flags * gfc)
105 SessionConfig_t *const cfg = &gfc->cfg;
107 /***************************************************************/
108 /* compute info needed for polyphase filter (filter type==0, default) */
109 /***************************************************************/
111 int band, maxband, minband;
113 int lowpass_band = 32;
114 int highpass_band = -1;
116 if (cfg->lowpass1 > 0) {
118 for (band = 0; band <= 31; band++) {
120 /* this band and above will be zeroed: */
121 if (freq >= cfg->lowpass2) {
122 lowpass_band = Min(lowpass_band, band);
124 if (cfg->lowpass1 < freq && freq < cfg->lowpass2) {
125 minband = Min(minband, band);
129 /* compute the *actual* transition band implemented by
130 * the polyphase filter */
131 if (minband == 999) {
132 cfg->lowpass1 = (lowpass_band - .75) / 31.0;
135 cfg->lowpass1 = (minband - .75) / 31.0;
137 cfg->lowpass2 = lowpass_band / 31.0;
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)) {
146 MSGF(gfc, "Warning: highpass filter disabled. " "highpass frequency too small\n");
150 if (cfg->highpass2 > 0) {
152 for (band = 0; band <= 31; band++) {
154 /* this band and below will be zereod */
155 if (freq <= cfg->highpass1) {
156 highpass_band = Max(highpass_band, band);
158 if (cfg->highpass1 < freq && freq < cfg->highpass2) {
159 maxband = Max(maxband, band);
162 /* compute the *actual* transition band implemented by
163 * the polyphase filter */
164 cfg->highpass1 = highpass_band / 31.0;
166 cfg->highpass2 = (highpass_band + .75) / 31.0;
169 cfg->highpass2 = (maxband + .75) / 31.0;
173 for (band = 0; band < 32; band++) {
176 if (cfg->highpass2 > cfg->highpass1) {
177 fc1 = filter_coef((cfg->highpass2 - freq) / (cfg->highpass2 - cfg->highpass1 + 1e-20));
182 if (cfg->lowpass2 > cfg->lowpass1) {
183 fc2 = filter_coef((freq - cfg->lowpass1) / (cfg->lowpass2 - cfg->lowpass1 + 1e-20));
188 gfc->sv_enc.amp_filter[band] = fc1 * fc2;
194 optimum_bandwidth(double *const lowerlimit, double *const upperlimit, const unsigned bitrate)
198 * bitrate total bitrate in kbps
201 * lowerlimit: best lowpass frequency limit for input filter in Hz
202 * upperlimit: best highpass frequency limit for input filter in Hz
207 int bitrate; /* only indicative value */
211 static const band_pass_t freq_map[] = {
232 table_index = nearestBitrateFullIndex(bitrate);
234 (void) freq_map[table_index].bitrate;
235 *lowerlimit = freq_map[table_index].lowpass;
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
253 * These are ad hoc values and these can be optimized if a high pass is available.
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;
263 * When we sometimes have a good highpass filter, we can add the highpass
264 * frequency to the lowpass frequency
267 /*if (upperlimit != NULL)
268 *upperlimit = f_high;*/
274 optimum_samplefreq(int lowpassfreq, int input_samplefreq)
278 * - if possible, sfb21 should NOT be used
281 int suggested_samplefreq = 44100;
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;
302 if (lowpassfreq == -1)
303 return suggested_samplefreq;
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;
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
327 if (input_samplefreq > 44100) {
330 if (input_samplefreq > 32000) {
333 if (input_samplefreq > 24000) {
336 if (input_samplefreq > 22050) {
339 if (input_samplefreq > 16000) {
342 if (input_samplefreq > 12000) {
345 if (input_samplefreq > 11025) {
348 if (input_samplefreq > 8000) {
353 return suggested_samplefreq;
360 /* set internal feature flags. USER should not access these since
361 * some combinations will produce strange results */
363 lame_init_qval(lame_global_flags * gfp)
365 lame_internal_flags *const gfc = gfp->internal_flags;
366 SessionConfig_t *const cfg = &gfc->cfg;
368 switch (gfp->quality) {
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;
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;
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;
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;
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;
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;
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;
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;
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;
482 linear_int(double a, double b, double m)
484 return a + m * (b - a);
489 /********************************************************************
490 * initialize internal params based on data in gf
491 * (globalflags struct filled in by calling program)
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:
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
510 * The remaining code is much simpler - it just sets options
511 * based on the mode & compression ratio:
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
523 * estimate the number of frames (based on a lot of data)
525 * now we set more flags:
533 * Finally, we set the algorithm flags based on the gfp->quality value
534 * lame_init_qval(gfp);
536 ********************************************************************/
538 lame_init_params(lame_global_flags * gfp)
543 lame_internal_flags *const gfc = gfp->internal_flags;
544 SessionConfig_t *const cfg = &gfc->cfg;
548 cfg->enforce_min_bitrate = gfp->VBR_hard_min;
549 cfg->analysis = gfp->analysis;
551 gfp->write_lame_tag = 0;
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 */
557 /* report functions */
558 gfc->report_msg = gfp->report.msgf;
559 gfc->report_dbg = gfp->report.debugf;
560 gfc->report_err = gfp->report.errorf;
562 if (gfp->asm_optimizations.amd3dnow)
563 gfc->CPU_features.AMD_3DNow = has_3DNow();
565 gfc->CPU_features.AMD_3DNow = 0;
567 if (gfp->asm_optimizations.mmx)
568 gfc->CPU_features.MMX = has_MMX();
570 gfc->CPU_features.MMX = 0;
572 if (gfp->asm_optimizations.sse) {
573 gfc->CPU_features.SSE = has_SSE();
574 gfc->CPU_features.SSE2 = has_SSE2();
577 gfc->CPU_features.SSE = 0;
578 gfc->CPU_features.SSE2 = 0;
582 if (NULL == gfc->ATH)
583 gfc->ATH = calloc(1, sizeof(ATH_t));
585 if (NULL == gfc->ATH)
586 return -2; /* maybe error codes should be enumerated in lame.h ?? */
588 if (NULL == gfc->sv_rpg.rgdata)
589 gfc->sv_rpg.rgdata = calloc(1, sizeof(replaygain_t));
590 if (NULL == gfc->sv_rpg.rgdata) {
592 gfp->internal_flags = NULL;
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;
602 cfg->channels_in = gfp->num_channels;
603 if (cfg->channels_in == 1)
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;
610 if (gfp->VBR == vbr_off && gfp->VBR_mean_bitrate_kbps != 128 && gfp->brate == 0)
611 gfp->brate = gfp->VBR_mean_bitrate_kbps;
617 /* these modes can handle free format condition */
620 gfp->free_format = 0; /* mode can't be mixed with free format */
624 cfg->free_format = gfp->free_format;
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 */
632 /* find bitrate if user specify a compression ratio */
633 if (gfp->VBR == vbr_off && gfp->compression_ratio > 0) {
635 if (gfp->samplerate_out == 0)
636 gfp->samplerate_out = map2MP3Frequency((int) (0.97 * gfp->samplerate_in)); /* round up with a margin of 3% */
638 /* choose a bitrate for the output samplerate which achieves
639 * specified compression ratio
641 gfp->brate = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->compression_ratio);
643 /* we need the version for the bitrate table look up */
644 cfg->samplerate_index = SmpFrqIndex(gfp->samplerate_out, &cfg->version);
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);
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);
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);
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);
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}
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;
685 gfp->VBR_q_frac = d - gfp->VBR_q;
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_;
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;
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;
714 optimum_bandwidth(&lowpass, &highpass, gfp->brate);
718 optimum_bandwidth(&lowpass, &highpass, gfp->VBR_mean_bitrate_kbps);
723 19500, 19000, 18600, 18000, 17500, 16000, 15600, 14900, 12500, 10000, 3950
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);
737 24000, 19500, 18500, 18000, 17500, 17000, 16500, 15600, 15200, 7230, 3950
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);
750 19500, 19000, 18500, 18000, 17500, 16500, 15500, 14500, 12500, 9500, 3950
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);
762 if (gfp->mode == MONO && (gfp->VBR == vbr_off || gfp->VBR == vbr_abr))
765 gfp->lowpassfreq = lowpass;
768 if (gfp->samplerate_out == 0) {
769 if (2 * gfp->lowpassfreq > gfp->samplerate_in) {
770 gfp->lowpassfreq = gfp->samplerate_in / 2;
772 gfp->samplerate_out = optimum_samplefreq((int) gfp->lowpassfreq, gfp->samplerate_in);
774 if (gfp->VBR == vbr_mt || gfp->VBR == vbr_mtrh) {
775 gfp->lowpassfreq = Min(24000, gfp->lowpassfreq);
778 gfp->lowpassfreq = Min(20500, gfp->lowpassfreq);
780 gfp->lowpassfreq = Min(gfp->samplerate_out / 2, gfp->lowpassfreq);
782 if (gfp->VBR == vbr_off) {
783 gfp->compression_ratio = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
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);
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;
798 cfg->findReplayGain = gfp->findReplayGain;
799 cfg->decode_on_the_fly = gfp->decode_on_the_fly;
801 if (cfg->decode_on_the_fly)
802 cfg->findPeakSample = 1;
804 if (cfg->findReplayGain) {
805 if (InitGainAnalysis(gfc->sv_rpg.rgdata, gfp->samplerate_out) == INIT_GAIN_ANALYSIS_ERROR) {
807 gfp->internal_flags = NULL;
812 #ifdef DECODE_ON_THE_FLY
813 if (cfg->decode_on_the_fly && !gfp->decode_only) {
815 hip_decode_exit(gfc->hip);
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);
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;
835 * sample freq bitrate compression ratio
836 * [kHz] [kbps/channel] for 16 bit input
848 * For VBR, take a guess at the compression_ratio.
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
859 * for lower bitrates, downsample with --resample
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];
873 gfp->compression_ratio =
874 cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);
877 gfp->compression_ratio = cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
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
886 if (gfp->mode == NOT_SET) {
887 gfp->mode = JOINT_STEREO;
890 cfg->mode = gfp->mode;
893 /* apply user driven high pass filter */
894 if (cfg->highpassfreq > 0) {
895 cfg->highpass1 = 2. * cfg->highpassfreq;
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;
902 cfg->highpass1 /= cfg->samplerate_out;
903 cfg->highpass2 /= cfg->samplerate_out;
909 /* apply user driven low pass filter */
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 */
919 else { /* 0% below on default */
920 cfg->lowpass1 = (1 - 0.00) * 2. * cfg->lowpassfreq;
922 cfg->lowpass1 /= cfg->samplerate_out;
923 cfg->lowpass2 /= cfg->samplerate_out;
929 /**********************************************************************/
930 /* compute info needed for polyphase filter (filter type==0, default) */
931 /**********************************************************************/
932 lame_init_params_ppflt(gfc);
935 /*******************************************************
936 * samplerate and bitrate index
937 *******************************************************/
938 cfg->samplerate_index = SmpFrqIndex(cfg->samplerate_out, &cfg->version);
939 if (cfg->samplerate_index < 0) {
941 gfp->internal_flags = NULL;
945 if (gfp->VBR == vbr_off) {
946 if (cfg->free_format) {
947 gfc->ov_enc.bitrate_index = 0;
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) {
954 gfp->internal_flags = NULL;
960 gfc->ov_enc.bitrate_index = 1;
963 init_bit_stream_w(gfc);
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];
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;
974 gfc->scalefac_band.psfb21[PSFB21] = 576;
976 for (i = 0; i < SBMAX_s + 1; i++)
977 gfc->scalefac_band.s[i] = sfBandIndex[j].s[i];
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;
984 gfc->scalefac_band.psfb12[PSFB12] = 192;
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;
990 cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 9 : 4 + 17;
992 if (cfg->error_protection)
993 cfg->sideinfo_len += 2;
995 gfc->class_id = LAME_ID;
1000 for (k = 0; k < 19; k++)
1001 gfc->sv_enc.pefirbuf[k] = 700 * cfg->mode_gr * cfg->channels_out;
1003 if (gfp->ATHtype == -1)
1007 assert(gfp->VBR_q <= 9);
1008 assert(gfp->VBR_q >= 0);
1014 if (gfp->strict_ISO < 0) {
1015 gfp->strict_ISO = MDB_MAXIMUM;
1017 if (gfp->useTemporal < 0) {
1018 gfp->useTemporal = 0; /* off by default for this VBR mode */
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
1027 if (gfp->quality < 0)
1028 gfp->quality = LAME_DEFAULT_QUALITY;
1029 if (gfp->quality < 5)
1031 if (gfp->quality > 7)
1034 /* sfb21 extra only with MPEG-1 at higher sampling rates
1036 if (gfp->experimentalY)
1037 gfc->sv_qnt.sfb21_extra = 0;
1039 gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
1041 gfc->iteration_loop = VBR_new_iteration_loop;
1047 (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);
1049 /* sfb21 extra only with MPEG-1 at higher sampling rates
1051 if (gfp->experimentalY)
1052 gfc->sv_qnt.sfb21_extra = 0;
1054 gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
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.
1061 if (gfp->quality > 6)
1065 if (gfp->quality < 0)
1066 gfp->quality = LAME_DEFAULT_QUALITY;
1068 gfc->iteration_loop = VBR_old_iteration_loop;
1072 default: /* cbr/abr */ {
1075 /* no sfb21 extra with CBR code
1077 gfc->sv_qnt.sfb21_extra = 0;
1079 if (gfp->quality < 0)
1080 gfp->quality = LAME_DEFAULT_QUALITY;
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);
1090 if (vbrmode == vbr_off) {
1091 gfc->iteration_loop = CBR_iteration_loop;
1094 gfc->iteration_loop = ABR_iteration_loop;
1100 /*initialize default values common for all modes */
1102 gfc->sv_qnt.mask_adjust = gfp->maskingadjust;
1103 gfc->sv_qnt.mask_adjust_short = gfp->maskingadjust_short;
1105 /* just another daily changing developer switch */
1107 gfc->sv_qnt.mask_adjust += gfp->tune_value_a;
1108 gfc->sv_qnt.mask_adjust_short += gfp->tune_value_a;
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)
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)
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);
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;
1155 /* initialize internal qval settings */
1156 lame_init_qval(gfp);
1159 /* automatic ATH adjustment on
1161 if (gfp->athaa_type < 0)
1162 gfc->ATH->use_adjust = 3;
1164 gfc->ATH->use_adjust = gfp->athaa_type;
1167 /* initialize internal adaptive ATH settings -jd */
1168 gfc->ATH->aa_sensitivity_p = pow(10.0, gfp->athaa_sensitivity / -10.0);
1171 if (gfp->short_blocks == short_block_not_set) {
1172 gfp->short_blocks = short_block_allowed;
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
1183 if (gfp->short_blocks == short_block_allowed
1184 && (cfg->mode == JOINT_STEREO || cfg->mode == STEREO)) {
1185 gfp->short_blocks = short_block_coupled;
1188 cfg->short_blocks = gfp->short_blocks;
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);
1196 if (lame_get_msfix(gfp) < 0)
1197 lame_set_msfix(gfp, 0);
1199 /* select psychoacoustic model */
1200 (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 1);
1202 if (gfp->ATHtype < 0)
1205 if (gfp->ATHcurve < 0)
1208 if (gfp->interChRatio < 0)
1209 gfp->interChRatio = 0;
1211 if (gfp->useTemporal < 0)
1212 gfp->useTemporal = 1; /* on by default */
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;
1225 cfg->quant_comp = gfp->quant_comp;
1226 cfg->quant_comp_short = gfp->quant_comp_short;
1228 cfg->use_temporal_masking_effect = gfp->useTemporal;
1229 cfg->use_safe_joint_stereo = gfp->exp_nspsytune & 2;
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;
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;
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;
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;
1255 /* Setting up the PCM input data transform matrix, to apply
1256 * user defined re-scaling, and or two-to-one channel downmix.
1259 FLOAT m[2][2] = { {1.0f, 0.0f}, {0.0f, 1.0f} };
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]);
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];
1285 /* padding method as described in
1286 * "MPEG-Layer3 / Bitstream Syntax and Decoding"
1287 * by Martin Sieler, Ralph Sperschneider
1289 * note: there is no padding for the very first frame
1291 * Robert Hegemann 2000-06-22
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;
1298 (void) lame_init_bitstream(gfp);
1300 iteration_init(gfc);
1301 (void) psymodel_init(gfp);
1303 cfg->buffer_constraint = get_max_frame_buffer_size_by_constraint(cfg, gfp->strict_ISO);
1308 concatSep(char* dest, char const* sep, char const* str)
1310 if (*dest != 0) strcat(dest, sep);
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
1324 lame_print_config(const lame_global_flags * gfp)
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;
1331 MSGF(gfc, "LAME %s %s (%s)\n", get_lame_version(), get_lame_os_bitness(), get_lame_url());
1333 #if (LAME_ALPHA_VERSION)
1334 MSGF(gfc, "warning: alpha versions should be used for testing only\n");
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;
1341 if (gfc->CPU_features.AMD_3DNow) {
1344 else if (gfc->CPU_features.SSE) {
1348 # if defined( HAVE_XMMINTRIN_H ) && defined( MIN_ARCH_SSE )
1354 if (gfc->CPU_features.MMX) {
1355 #ifdef MMX_choose_table
1356 concatSep(text, ", ", "MMX (ASM used)");
1358 concatSep(text, ", ", "MMX");
1361 if (gfc->CPU_features.AMD_3DNow) {
1362 concatSep(text, ", ", (fft_asm_used == 1) ? "3DNow! (ASM used)" : "3DNow!");
1364 if (gfc->CPU_features.SSE) {
1365 #if defined(HAVE_XMMINTRIN_H)
1366 concatSep(text, ", ", "SSE (ASM used)");
1368 concatSep(text, ", ", (fft_asm_used == 2) ? "SSE (ASM used)" : "SSE");
1371 if (gfc->CPU_features.SSE2) {
1372 concatSep(text, ", ", (fft_asm_used == 3) ? "SSE2 (ASM used)" : "SSE2");
1374 MSGF(gfc, "CPU features: %s\n", text);
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");
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);
1386 if (cfg->highpass2 > 0.)
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) {
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);
1396 MSGF(gfc, "polyphase lowpass filter disabled\n");
1399 if (cfg->free_format) {
1400 MSGF(gfc, "Warning: many decoders cannot handle free format bitstreams\n");
1401 if (cfg->avg_bitrate > 320) {
1403 "Warning: many decoders cannot handle free format bitrates >320 kbps (see documentation)\n");
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...
1415 lame_print_internals(const lame_global_flags * gfp)
1417 lame_internal_flags const *const gfc = gfp->internal_flags;
1418 SessionConfig_t const *const cfg = &gfc->cfg;
1419 const char *pc = "";
1421 /* compiler/processor optimizations, operational, etc.
1423 MSGF(gfc, "\nmisc:\n\n");
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) {
1433 pc = "best (outside loop)";
1436 pc = "best (inside loop, slow)";
1439 MSGF(gfc, "\thuffman search: %s\n", pc);
1440 MSGF(gfc, "\texperimental Y=%d\n", gfp->experimentalY);
1441 MSGF(gfc, "\t...\n");
1443 /* everything controlling the stream format
1445 MSGF(gfc, "\nstream format:\n\n");
1446 switch (cfg->version) {
1460 MSGF(gfc, "\tMPEG-%s Layer 3\n", pc);
1461 switch (cfg->mode) {
1463 pc = "joint stereo";
1469 pc = "dual channel";
1475 pc = "not set (error)";
1478 pc = "unknown (error)";
1481 MSGF(gfc, "\t%d channel - %s\n", cfg->channels_out, pc);
1491 MSGF(gfc, "\tpadding: %s\n", pc);
1493 if (vbr_default == cfg->vbr)
1495 else if (cfg->free_format)
1496 pc = "(free format)";
1501 MSGF(gfc, "\tconstant bitrate - CBR %s\n", pc);
1504 MSGF(gfc, "\tvariable bitrate - ABR %s\n", pc);
1507 MSGF(gfc, "\tvariable bitrate - VBR rh %s\n", pc);
1510 MSGF(gfc, "\tvariable bitrate - VBR mt %s\n", pc);
1513 MSGF(gfc, "\tvariable bitrate - VBR mtrh %s\n", pc);
1516 MSGF(gfc, "\t ?? oops, some new one ?? \n");
1519 if (cfg->write_lame_tag)
1520 MSGF(gfc, "\tusing LAME Tag\n");
1521 MSGF(gfc, "\t...\n");
1523 /* everything controlling psychoacoustic settings, like ATH, etc.
1525 MSGF(gfc, "\npsychoacoustic:\n\n");
1527 switch (cfg->short_blocks) {
1529 case short_block_not_set:
1532 case short_block_allowed:
1535 case short_block_coupled:
1536 pc = "channel coupled";
1538 case short_block_dispensed:
1541 case short_block_forced:
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);
1557 pc = "the only masking for short blocks";
1559 pc = "the only masking";
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);
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]));
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");
1588 save_gain_values(lame_internal_flags * gfc)
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 */
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 */
1608 if (rov->noclipGainChange > 0) { /* clipping occurs */
1609 rov->noclipScale = floor((32767.0f / rov->PeakSample) * 100.0f) / 100.0f; /* round down */
1611 else /* no clipping */
1612 rov->noclipScale = -1.0f;
1619 update_inbuffer_size(lame_internal_flags * gfc, const int nsamples)
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);
1626 if (esv->in_buffer_1) {
1627 free(esv->in_buffer_1);
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;
1633 if (esv->in_buffer_0 == NULL || esv->in_buffer_1 == NULL) {
1634 if (esv->in_buffer_0) {
1635 free(esv->in_buffer_0);
1637 if (esv->in_buffer_1) {
1638 free(esv->in_buffer_1);
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");
1651 calcNeeded(SessionConfig_t const * cfg)
1654 int pcm_samples_per_frame = 576 * cfg->mode_gr;
1656 /* some sanity checks */
1657 #if ENCDELAY < MDCTDELAY
1658 # error ENCDELAY is less than MDCTDELAY, see encoder.h
1660 #if FFTOFFSET > BLKSIZE
1661 # error FFTOFFSET is greater than BLKSIZE, see encoder.h
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);
1668 assert(MFSIZE >= mf_needed);
1675 * THE MAIN LAME ENCODING INTERFACE
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:
1683 * mp3buffer_size in bytes = 1.25*num_samples + 7200
1685 * return code = number of bytes output in mp3buffer. can be 0
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.
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 */
1699 lame_encode_buffer_sample_t(lame_internal_flags * gfc,
1700 int nsamples, unsigned char *mp3buf, const int mp3buf_size)
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;
1708 sample_t *in_buffer[2];
1710 esv->canary = 0x1234;
1712 if (gfc->class_id != LAME_ID)
1718 /* copy out any tags that may have been written into bitstream */
1719 mp3out = copy_buffer(gfc, mp3buf, mp3buf_size, 0);
1721 return mp3out; /* not enough buffer space */
1725 in_buffer[0] = esv->in_buffer_0;
1726 in_buffer[1] = esv->in_buffer_1;
1728 mf_needed = calcNeeded(cfg);
1730 mfbuf[0] = esv->mfbuf[0];
1731 mfbuf[1] = esv->mfbuf[1];
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]));
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 */
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);
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");
1758 assert(esv->mf_size >= 0);
1759 assert(esv->mf_size <= MFSIZE);
1760 assert(n_in <= esv->in_buffer_nsamples);
1764 /* compute ReplayGain of resampled input if requested */
1765 if (cfg->findReplayGain && !cfg->decode_on_the_fly)
1767 (gfc->sv_rpg.rgdata, &mfbuf[0][esv->mf_size], &mfbuf[1][esv->mf_size], n_out,
1768 cfg->channels_out) == GAIN_ANALYSIS_ERROR)
1772 /* update in_buffer counters */
1774 in_buffer[0] += n_in;
1775 if (cfg->channels_out == 2)
1776 in_buffer[1] += n_in;
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));
1782 /* update mfbuf[] counters */
1783 esv->mf_size += n_out;
1784 assert(esv->mf_size >= 0);
1785 assert(esv->mf_size <= MFSIZE);
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.
1790 if (esv->mf_samples_to_encode < 1) {
1791 esv->mf_samples_to_encode = ENCDELAY + POSTDELAY;
1793 esv->mf_samples_to_encode += n_out;
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 */
1805 int buf_size = mp3buf_size - mp3size;
1806 if (mp3buf_size == 0)
1809 ret = lame_encode_mp3_frame(gfc, mfbuf[0], mfbuf[1], mp3buf, buf_size);
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];
1824 assert(nsamples == 0);
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)
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;
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];
1854 /* make a copy of input buffer, changing type to sample_t */
1855 #define COPY_AND_TRANSFORM(T) \
1857 T const *bl = l, *br = r; \
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]; \
1870 switch ( pcm_type ) {
1871 case pcm_short_type:
1872 COPY_AND_TRANSFORM(short int);
1875 COPY_AND_TRANSFORM(int);
1878 COPY_AND_TRANSFORM(long int);
1880 case pcm_float_type:
1881 COPY_AND_TRANSFORM(float);
1883 case pcm_double_type:
1884 COPY_AND_TRANSFORM(double);
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)
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;
1903 if (update_inbuffer_size(gfc, nsamples) != 0) {
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) {
1911 lame_copy_inbuffer(gfc, buffer_l, buffer_r, nsamples, pcm_type, aa, norm);
1914 if (buffer_l == 0) {
1917 lame_copy_inbuffer(gfc, buffer_l, buffer_l, nsamples, pcm_type, aa, norm);
1920 return lame_encode_buffer_sample_t(gfc, nsamples, mp3buf, mp3buf_size);
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)
1931 return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_short_type, 1, 1.0);
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)
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);
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)
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);
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)
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);
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)
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);
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)
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);
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)
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);
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)
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);
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)
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);
2019 lame_encode_buffer_interleaved(lame_global_flags * gfp,
2020 short int pcm[], int nsamples,
2021 unsigned char *mp3buf, int mp3buf_size)
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);
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
2038 *********************************************************************/
2040 lame_encode_flush_nogap(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
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);
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 */
2058 lame_init_bitstream(lame_global_flags * gfp)
2060 if (is_lame_global_flags_valid(gfp)) {
2061 lame_internal_flags *const gfc = gfp->internal_flags;
2063 gfc->ov_enc.frame_number = 0;
2065 if (gfp->write_id3tag_automatic) {
2066 (void) id3tag_write_v2(gfp);
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));
2074 gfc->ov_rpg.PeakSample = 0.0;
2076 /* Write initial VBR Header to bitstream and init VBR data */
2077 if (gfc->cfg.write_lame_tag)
2078 (void) InitVbrTag(gfp);
2088 /*****************************************************************/
2089 /* flush internal PCM sample buffers, then mp3 buffers */
2090 /* then write id3 v1 tags into bitstream. */
2091 /*****************************************************************/
2094 lame_encode_flush(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
2096 lame_internal_flags *gfc;
2097 SessionConfig_t const *cfg;
2099 short int buffer[2][1152];
2100 int imp3 = 0, mp3count, mp3buffer_size_remaining;
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 */
2106 int samples_to_encode;
2107 int pcm_samples_per_frame;
2109 int is_resampling_necessary;
2110 double resample_ratio = 1;
2112 if (!is_lame_global_flags_valid(gfp)) {
2115 gfc = gfp->internal_flags;
2116 if (!is_lame_internal_flags_valid(gfc)) {
2122 /* Was flush already called? */
2123 if (esv->mf_samples_to_encode < 1) {
2126 pcm_samples_per_frame = 576 * cfg->mode_gr;
2127 mf_needed = calcNeeded(cfg);
2129 samples_to_encode = esv->mf_samples_to_encode - POSTDELAY;
2131 memset(buffer, 0, sizeof(buffer));
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;
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;
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;
2150 bunch *= resample_ratio;
2151 if (bunch > 1152) bunch = 1152;
2152 if (bunch < 1) bunch = 1;
2154 mp3buffer_size_remaining = mp3buffer_size - mp3count;
2156 /* if user specifed buffer size = 0, dont check size */
2157 if (mp3buffer_size == 0)
2158 mp3buffer_size_remaining = 0;
2160 /* send in a frame of 0 padding until all internal sample buffers
2163 imp3 = lame_encode_buffer(gfp, buffer[0], buffer[1], bunch,
2164 mp3buffer, mp3buffer_size_remaining);
2168 frames_left -= ((frame_num != gfc->ov_enc.frame_number) ? 1 : 0);
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.
2173 esv->mf_samples_to_encode = 0;
2176 /* some type of fatal error */
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;
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);
2190 /* some type of fatal error */
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;
2200 if (gfp->write_id3tag_automatic) {
2201 /* write a id3 tag to the bitstream */
2202 (void) id3tag_write_v1(gfp);
2204 imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 0);
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);
2229 /***********************************************************************
2233 * frees internal buffers
2235 ***********************************************************************/
2238 lame_close(lame_global_flags * gfp)
2241 if (gfp && gfp->class_id == LAME_ID) {
2242 lame_internal_flags *const gfc = gfp->internal_flags;
2244 if (NULL == gfc || gfc->class_id != LAME_ID) {
2249 /* this routine will free all malloc'd data in gfc, and then free gfc: */
2251 gfp->internal_flags = NULL;
2253 if (gfp->lame_allocated_gfp) {
2254 gfp->lame_allocated_gfp = 0;
2261 /*****************************************************************/
2262 /* flush internal mp3 buffers, and free internal buffers */
2263 /*****************************************************************/
2264 #if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
2266 lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size);
2271 lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
2273 int const ret = lame_encode_flush(gfp, mp3buffer, mp3buffer_size);
2275 (void) lame_close(gfp);
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);
2286 lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream)
2288 lame_internal_flags *gfc;
2289 SessionConfig_t const *cfg;
2290 if (!is_lame_global_flags_valid(gfp)) {
2293 gfc = gfp->internal_flags;
2294 if (!is_lame_internal_flags_valid(gfc)) {
2298 if (!cfg->write_lame_tag) {
2301 /* Write Xing header again */
2302 if (fpStream && !fseek(fpStream, 0, SEEK_SET)) {
2303 int rc = PutVbrTag(gfp, fpStream);
2310 ERRORF(gfc, "Error: could not update LAME tag.\n");
2314 ERRORF(gfc, "Error: could not update LAME tag, file not seekable.\n");
2318 ERRORF(gfc, "Error: could not update LAME tag, file not readable.\n");
2326 /* initialize mp3 encoder */
2327 #if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
2332 lame_init_old(lame_global_flags * gfp)
2334 lame_internal_flags *gfc;
2335 SessionConfig_t *cfg;
2337 disable_FPE(); /* disable floating point exceptions */
2339 memset(gfp, 0, sizeof(lame_global_flags));
2341 gfp->class_id = LAME_ID;
2343 if (NULL == (gfc = gfp->internal_flags = calloc(1, sizeof(lame_internal_flags))))
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)
2354 gfp->strict_ISO = MDB_MAXIMUM;
2356 gfp->mode = NOT_SET;
2358 gfp->samplerate_in = 44100;
2359 gfp->num_channels = 2;
2360 gfp->num_samples = MAX_U_32_NUM;
2362 gfp->write_lame_tag = 1;
2364 gfp->short_blocks = short_block_not_set;
2365 gfp->subblock_gain = -1;
2367 gfp->lowpassfreq = 0;
2368 gfp->highpassfreq = 0;
2369 gfp->lowpasswidth = -1;
2370 gfp->highpasswidth = -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 ????? */
2382 gfp->quant_comp = -1;
2383 gfp->quant_comp_short = -1;
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;
2393 gfp->attackthre = -1;
2394 gfp->attackthre_s = -1;
2397 gfp->scale_left = 1;
2398 gfp->scale_right = 1;
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;
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.
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 */
2421 gfp->findReplayGain = 0;
2422 gfp->decode_on_the_fly = 0;
2424 gfc->cfg.decode_on_the_fly = 0;
2425 gfc->cfg.findReplayGain = 0;
2426 gfc->cfg.findPeakSample = 0;
2428 gfc->ov_rpg.RadioGain = 0;
2429 gfc->ov_rpg.noclipGainChange = 0;
2430 gfc->ov_rpg.noclipScale = -1.0;
2432 gfp->asm_optimizations.mmx = 1;
2433 gfp->asm_optimizations.amd3dnow = 1;
2434 gfp->asm_optimizations.sse = 1;
2438 gfp->write_id3tag_automatic = 1;
2440 gfp->report.debugf = &lame_report_def;
2441 gfp->report.errorf = &lame_report_def;
2442 gfp->report.msgf = &lame_report_def;
2450 lame_global_flags *gfp;
2455 gfp = calloc(1, sizeof(lame_global_flags));
2459 ret = lame_init_old(gfp);
2465 gfp->lame_allocated_gfp = 1;
2470 /***********************************************************************
2472 * some simple statistics
2474 * Robert Hegemann 2000-10-11
2476 ***********************************************************************/
2478 /* histogram of used bitrate indexes:
2479 * One has to weight them to calculate the average bitrate in kbps
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
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
2492 * 4: number of encoded frames
2497 lame_bitrate_kbps(const lame_global_flags * gfp, int bitrate_kbps[14])
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;
2504 if (cfg->free_format) {
2505 for (i = 0; i < 14; i++)
2506 bitrate_kbps[i] = -1;
2507 bitrate_kbps[0] = cfg->avg_bitrate;
2510 for (i = 0; i < 14; i++)
2511 bitrate_kbps[i] = bitrate_table[cfg->version][i + 1];
2519 lame_bitrate_hist(const lame_global_flags * gfp, int bitrate_count[14])
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;
2528 if (cfg->free_format) {
2529 for (i = 0; i < 14; i++) {
2530 bitrate_count[i] = 0;
2532 bitrate_count[0] = eov->bitrate_channelmode_hist[0][4];
2535 for (i = 0; i < 14; i++) {
2536 bitrate_count[i] = eov->bitrate_channelmode_hist[i + 1][4];
2545 lame_stereo_mode_hist(const lame_global_flags * gfp, int stmode_count[4])
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;
2553 for (i = 0; i < 4; i++) {
2554 stmode_count[i] = eov->bitrate_channelmode_hist[15][i];
2563 lame_bitrate_stereo_mode_hist(const lame_global_flags * gfp, int bitrate_stmode_count[14][4])
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;
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;
2578 for (i = 0; i < 4; i++) {
2579 bitrate_stmode_count[0][i] = eov->bitrate_channelmode_hist[0][i];
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];
2595 lame_block_type_hist(const lame_global_flags * gfp, int btype_count[6])
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;
2603 for (i = 0; i < 6; ++i) {
2604 btype_count[i] = eov->bitrate_blocktype_hist[15][i];
2613 lame_bitrate_block_type_hist(const lame_global_flags * gfp, int bitrate_btype_count[14][6])
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;
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;
2628 for (i = 0; i < 6; ++i) {
2629 bitrate_btype_count[0][i] = eov->bitrate_blocktype_hist[0][i];
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];