2 * LAME MP3 encoding engine
4 * Copyright (c) 1999 Mark Taylor
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
22 /* $Id: encoder.c,v 1.1 2002/04/28 17:30:18 kramm Exp $ */
24 #include "config_static.h"
33 #include "quantize_pvt.h"
34 #include "bitstream.h"
36 #include "vbrquantize.h"
44 * auto-adjust of ATH, useful for low volume
45 * Gabriel Bouvigne 3 feb 2001
47 * modifies some values in
48 * gfp->internal_flags->ATH
52 adjust_ATH( lame_global_flags* const gfp,
53 FLOAT8 tot_ener[2][4] )
55 lame_internal_flags* const gfc = gfp->internal_flags;
57 FLOAT max_pow, max_pow_alt;
60 if (gfc->ATH->use_adjust == 0) {
61 gfc->ATH->adjust = 1.0; /* no adjustment */
65 switch( gfp->athaa_loudapprox ) {
67 /* flat approximation for loudness (squared) */
69 for ( gr = 0; gr < gfc->mode_gr; ++gr )
70 for ( channel = 0; channel < gfc->channels_out; ++channel )
71 max_pow = Max( max_pow, tot_ener[gr][channel] );
72 max_pow *= 0.25/ 5.6e13; /* scale to 0..1 (5.6e13), and tune (0.25) */
75 case 2: /* jd - 2001 mar 12, 27, jun 30 */
76 { /* loudness based on equal loudness curve; */
77 /* use granule with maximum combined loudness*/
79 max_pow = gfc->loudness_sq[0][0];
80 if( gfc->channels_out == 2 ) {
81 max_pow += gfc->loudness_sq[0][1];
82 gr2_max = gfc->loudness_sq[1][0] + gfc->loudness_sq[1][1];
84 gr2_max = gfc->loudness_sq[1][0];
88 if( gfc->mode_gr == 2 ) {
89 max_pow = Max( max_pow, gr2_max );
91 max_pow *= 0.5; /* max_pow approaches 1.0 for full band noise*/
95 default: /* jd - 2001 mar 27, 31, jun 30 */
96 /* no adaptive threshold */
97 max_pow = 1.0 / gfc->athaa_sensitivity_p;
101 /* jd - 2001 mar 31, jun 30 */
102 /* user tuning of ATH adjustment region */
103 max_pow_alt = max_pow;
104 max_pow *= gfc->athaa_sensitivity_p;
105 if (gfc->presetTune.use)
106 max_pow_alt *= pow( 10.0, gfc->presetTune.athadjust_safe_athaasensitivity / -10.0 );
108 /* adjust ATH depending on range of maximum value
110 switch ( gfc->ATH->use_adjust ) {
113 max_val = sqrt( max_pow ); /* GB's original code requires a maximum */
114 max_val *= 32768; /* sample or loudness value up to 32768 */
116 /* by Gabriel Bouvigne */
117 if (0.5 < max_val / 32768) { /* value above 50 % */
118 gfc->ATH->adjust = 1.0; /* do not reduce ATH */
120 else if (0.3 < max_val / 32768) { /* value above 30 % */
121 gfc->ATH->adjust *= 0.955; /* reduce by ~0.2 dB */
122 if (gfc->ATH->adjust < 0.3) /* but ~5 dB in maximum */
123 gfc->ATH->adjust = 0.3;
125 else { /* value below 30 % */
126 gfc->ATH->adjust *= 0.93; /* reduce by ~0.3 dB */
127 if (gfc->ATH->adjust < 0.01) /* but 20 dB in maximum */
128 gfc->ATH->adjust = 0.01;
133 max_val = Min( max_pow, 1.0 ) * 32768; /* adapt for RH's adjust */
135 { /* by Robert Hegemann */
136 /* this code reduces slowly the ATH (speed of 12 dB per second)
139 //x = Max (640, 320*(int)(max_val/320));
140 x = Max (32, 32*(int)(max_val/32));
142 gfc->ATH->adjust *= gfc->ATH->decay;
143 if (gfc->ATH->adjust < x) /* but not more than f(x) dB */
144 gfc->ATH->adjust = x;
149 { /* jd - 2001 feb27, mar12,20, jun30, jul22 */
150 /* continuous curves based on approximation */
151 /* to GB's original values. */
153 /* For an increase in approximate loudness, */
154 /* set ATH adjust to adjust_limit immediately*/
155 /* after a delay of one frame. */
156 /* For a loudness decrease, reduce ATH adjust*/
157 /* towards adjust_limit gradually. */
158 /* max_pow is a loudness squared or a power. */
159 if( max_pow > 0.03125) { /* ((1 - 0.000625)/ 31.98) from curve below */
160 if( gfc->ATH->adjust >= 1.0) {
161 gfc->ATH->adjust = 1.0;
162 if (gfc->presetTune.use) {
163 if (max_pow_alt > gfc->presetTune.athadjust_safe_noiseshaping_thre)
164 gfc->presetTune.athadjust_safe_noiseshaping = 1;
166 gfc->presetTune.athadjust_safe_noiseshaping = 0;
169 /* preceding frame has lower ATH adjust; */
170 /* ascend only to the preceding adjust_limit */
171 /* in case there is leading low volume */
172 if( gfc->ATH->adjust < gfc->ATH->adjust_limit) {
173 gfc->ATH->adjust = gfc->ATH->adjust_limit;
174 if (gfc->presetTune.use) {
175 if (max_pow_alt > gfc->presetTune.athadjust_safe_noiseshaping_thre)
176 gfc->presetTune.athadjust_safe_noiseshaping = 1;
178 gfc->presetTune.athadjust_safe_noiseshaping = 0;
182 gfc->ATH->adjust_limit = 1.0;
183 } else { /* adjustment curve */
184 /* about 32 dB maximum adjust (0.000625) */
185 adj_lim_new = 31.98 * max_pow + 0.000625;
186 if( gfc->ATH->adjust >= adj_lim_new) { /* descend gradually */
187 gfc->ATH->adjust *= adj_lim_new * 0.075 + 0.925;
188 if( gfc->ATH->adjust < adj_lim_new) { /* stop descent */
189 gfc->ATH->adjust = adj_lim_new;
191 } else { /* ascend */
192 if( gfc->ATH->adjust_limit >= adj_lim_new) {
193 gfc->ATH->adjust = adj_lim_new;
194 } else { /* preceding frame has lower ATH adjust; */
195 /* ascend only to the preceding adjust_limit */
196 if( gfc->ATH->adjust < gfc->ATH->adjust_limit) {
197 gfc->ATH->adjust = gfc->ATH->adjust_limit;
201 gfc->ATH->adjust_limit = adj_lim_new;
207 gfc->ATH->adjust = 1.0; /* no adjustment */
212 /************************************************************************
214 * encodeframe() Layer 3
216 * encode a single frame
218 ************************************************************************
223 inbuf: |--------------|---------------|-------------|
224 MDCT output: |--------------|---------------|-------------|
226 FFT's <---------1024---------->
227 <---------1024-------->
231 inbuf = buffer of PCM data size=MP3 framesize
232 encoder acts on inbuf[ch][0], but output is delayed by MDCTDELAY
233 so the MDCT coefficints are from inbuf[ch][-MDCTDELAY]
235 psy-model FFT has a 1 granule delay, so we feed it data for the
237 FFT is centered over granule: 224+576+224
238 So FFT starts at: 576-224-MDCTDELAY
240 MPEG2: FFT ends at: BLKSIZE+576-224-MDCTDELAY
241 MPEG1: FFT ends at: BLKSIZE+2*576-224-MDCTDELAY (1904)
243 FFT starts at 576-224-MDCTDELAY (304) = 576-FFTOFFSET
247 typedef FLOAT8 chgrdata[2][2];
249 int lame_encode_mp3_frame ( // Output
250 lame_global_flags* const gfp, // Context
251 sample_t* inbuf_l, // Input
252 sample_t* inbuf_r, // Input
253 unsigned char* mp3buf, // Output
254 int mp3buf_size ) // Output
256 #ifdef macintosh /* PLL 14/04/2000 */
257 static FLOAT8 xr[2][2][576];
258 static int l3_enc[2][2][576];
260 FLOAT8 xr[2][2][576];
261 int l3_enc[2][2][576];
264 III_psy_ratio masking_LR[2][2]; /*LR masking & energy */
265 III_psy_ratio masking_MS[2][2]; /*MS masking & energy */
266 III_psy_ratio (*masking)[2][2]; /*pointer to selected maskings*/
267 III_scalefac_t scalefac[2][2];
268 const sample_t *inbuf[2];
269 lame_internal_flags *gfc=gfp->internal_flags;
271 FLOAT8 tot_ener[2][4];
272 FLOAT8 ms_ener_ratio[2]={.5,.5};
280 FLOAT8 ms_ratio_next = 0.;
281 FLOAT8 ms_ratio_prev = 0.;
284 memset((char *) masking_LR, 0, sizeof(masking_LR));
285 memset((char *) masking_MS, 0, sizeof(masking_MS));
286 memset((char *) scalefac, 0, sizeof(scalefac));
290 check_ms_stereo = (gfp->mode == JOINT_STEREO);
291 gfc->mode_ext = MPG_MD_LR_LR;
293 if (gfc->lame_encode_frame_init==0 ) {
294 gfc->lame_encode_frame_init=1;
296 /* padding method as described in
297 * "MPEG-Layer3 / Bitstream Syntax and Decoding"
298 * by Martin Sieler, Ralph Sperschneider
300 * note: there is no padding for the very first frame
302 * Robert.Hegemann@gmx.de 2000-06-22
305 gfc->frac_SpF = ((gfp->version+1)*72000L*gfp->brate) % gfp->out_samplerate;
306 gfc->slot_lag = gfc->frac_SpF;
308 /* check FFT will not use a negative starting offset */
310 # error FFTOFFSET greater than 576: FFT uses a negative offset
312 /* check if we have enough data for FFT */
313 assert(gfc->mf_size>=(BLKSIZE+gfp->framesize-FFTOFFSET));
314 /* check if we have enough data for polyphase filterbank */
315 /* it needs 1152 samples + 286 samples ignored for one granule */
316 /* 1152+576+286 samples for two granules */
317 assert(gfc->mf_size>=(286+576*(1+gfc->mode_gr)));
319 /* prime the MDCT/polyphase filterbank with a short block */
322 sample_t primebuff0[286+1152+576];
323 sample_t primebuff1[286+1152+576];
324 for (i=0, j=0; i<286+576*(1+gfc->mode_gr); ++i) {
325 if (i<576*gfc->mode_gr) {
327 if (gfc->channels_out==2)
330 primebuff0[i]=inbuf[0][j];
331 if (gfc->channels_out==2)
332 primebuff1[i]=inbuf[1][j];
336 /* polyphase filtering / mdct */
337 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
338 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
339 gfc->l3_side.gr[gr].ch[ch].tt.block_type=SHORT_TYPE;
342 mdct_sub48(gfc, primebuff0, primebuff1, xr);
347 /* prepare for ATH auto adjustment:
348 * we want to decrease the ATH by 12 dB per second
350 FLOAT8 frame_duration = 576. * gfc->mode_gr / gfp->out_samplerate;
351 gfc->ATH->decay = pow(10., -12./10. * frame_duration);
352 gfc->ATH->adjust = 0.01; /* minimum, for leading low loudness */
353 gfc->ATH->adjust_limit = 1.0; /* on lead, allow adjust up to maximum */
358 /********************** padding *****************************/
359 switch (gfp->padding_type) {
361 gfc->padding = FALSE;
368 if (gfp->VBR!=vbr_off) {
369 gfc->padding = FALSE;
371 if (gfp->disable_reservoir) {
372 gfc->padding = FALSE;
373 /* if the user specified --nores, dont very gfc->padding either */
374 /* tiny changes in frac_SpF rounding will cause file differences */
376 /* padding method as described in
377 * "MPEG-Layer3 / Bitstream Syntax and Decoding"
378 * by Martin Sieler, Ralph Sperschneider
380 * note: there is no padding for the very first frame
382 * Robert.Hegemann@gmx.de 2000-06-22
385 gfc->slot_lag -= gfc->frac_SpF;
386 if (gfc->slot_lag < 0) {
387 gfc->slot_lag += gfp->out_samplerate;
390 gfc->padding = FALSE;
392 } /* reservoir enabled */
398 /* psychoacoustic model
399 * psy model has a 1 granule (576) delay that we must compensate for
403 const sample_t *bufp[2]; /* address of beginning of left & right granule */
406 ms_ratio_prev=gfc->ms_ratio[gfc->mode_gr-1];
407 for (gr=0; gr < gfc->mode_gr ; gr++) {
409 for ( ch = 0; ch < gfc->channels_out; ch++ )
410 bufp[ch] = &inbuf[ch][576 + gr*576-FFTOFFSET];
412 if (gfc->nsPsy.use) {
413 ret=L3psycho_anal_ns( gfp, bufp, gr,
414 &gfc->ms_ratio[gr],&ms_ratio_next,
415 masking_LR, masking_MS,
416 pe[gr],pe_MS[gr],tot_ener[gr],blocktype);
418 ret=L3psycho_anal( gfp, bufp, gr,
419 &gfc->ms_ratio[gr],&ms_ratio_next,
420 masking_LR, masking_MS,
421 pe[gr],pe_MS[gr],tot_ener[gr],blocktype);
423 if (ret!=0) return -4;
425 for ( ch = 0; ch < gfc->channels_out; ch++ )
426 gfc->l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
428 if (check_ms_stereo) {
429 ms_ener_ratio[gr] = tot_ener[gr][2]+tot_ener[gr][3];
430 if (ms_ener_ratio[gr]>0)
431 ms_ener_ratio[gr] = tot_ener[gr][3]/ms_ener_ratio[gr];
436 for (gr=0; gr < gfc->mode_gr ; gr++)
437 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
438 gfc->l3_side.gr[gr].ch[ch].tt.block_type=NORM_TYPE;
439 pe_MS[gr][ch]=pe[gr][ch]=700;
445 /* auto-adjust of ATH, useful for low volume */
446 adjust_ATH( gfp, tot_ener );
450 /* block type flags */
451 for( gr = 0; gr < gfc->mode_gr; gr++ ) {
452 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
453 gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
454 cod_info->mixed_block_flag = 0; /* never used by this model */
455 if (cod_info->block_type == NORM_TYPE )
456 cod_info->window_switching_flag = 0;
458 cod_info->window_switching_flag = 1;
463 /* polyphase filtering / mdct */
464 mdct_sub48(gfc, inbuf[0], inbuf[1], xr);
465 /* re-order the short blocks, for more efficient encoding below */
466 for (gr = 0; gr < gfc->mode_gr; gr++) {
467 for (ch = 0; ch < gfc->channels_out; ch++) {
468 gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
469 if (cod_info->block_type==SHORT_TYPE) {
470 freorder(gfc->scalefac_band.s,xr[gr][ch]);
476 /* use m/s gfc->channels_out? */
477 if (check_ms_stereo) {
478 int gr0 = 0, gr1 = gfc->mode_gr-1;
479 /* make sure block type is the same in each channel */
481 (gfc->l3_side.gr[gr0].ch[0].tt.block_type==gfc->l3_side.gr[gr0].ch[1].tt.block_type) &&
482 (gfc->l3_side.gr[gr1].ch[0].tt.block_type==gfc->l3_side.gr[gr1].ch[1].tt.block_type);
485 /* Here will be selected MS or LR coding of the 2 stereo channels */
487 assert ( gfc->mode_ext == MPG_MD_LR_LR );
488 gfc->mode_ext = MPG_MD_LR_LR;
491 gfc->mode_ext = MPG_MD_MS_LR;
492 } else if (check_ms_stereo) {
493 /* ms_ratio = is scaled, for historical reasons, to look like
494 a ratio of side_channel / total.
495 0 = signal is 100% mono
496 .5 = L & R uncorrelated
499 /* [0] and [1] are the results for the two granules in MPEG-1,
500 * in MPEG-2 it's only a faked averaging of the same value
501 * _prev is the value of the last granule of the previous frame
502 * _next is the value of the first granule of the next frame
504 FLOAT8 ms_ratio_ave1;
505 FLOAT8 ms_ratio_ave2;
506 FLOAT8 threshold1 = 0.35;
507 FLOAT8 threshold2 = 0.45;
509 /* take an average */
510 if (gfc->mode_gr==1) {
511 /* MPEG2 - no second granule */
512 ms_ratio_ave1 = 0.33 * ( gfc->ms_ratio[0] + ms_ratio_prev + ms_ratio_next );
513 ms_ratio_ave2 = gfc->ms_ratio[0];
515 ms_ratio_ave1 = 0.25 * ( gfc->ms_ratio[0] + gfc->ms_ratio[1] + ms_ratio_prev + ms_ratio_next );
516 ms_ratio_ave2 = 0.50 * ( gfc->ms_ratio[0] + gfc->ms_ratio[1] );
519 if (gfp->mode_automs) {
520 if ( gfp->compression_ratio < 11.025 ) {
521 /* 11.025 => 1, 6.3 => 0 */
522 double thr = (gfp->compression_ratio - 6.3) / (11.025 - 6.3);
529 if ((ms_ratio_ave1 < threshold1 && ms_ratio_ave2 < threshold2) || gfc->nsPsy.use) {
532 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
533 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
534 sum_pe_MS += pe_MS[gr][ch];
535 sum_pe_LR += pe[gr][ch];
539 /* based on PE: M/S coding would not use much more bits than L/R coding */
541 if (sum_pe_MS <= 1.07 * sum_pe_LR && !gfc->nsPsy.use) gfc->mode_ext = MPG_MD_MS_LR;
542 if (sum_pe_MS <= 1.00 * sum_pe_LR && gfc->nsPsy.use) gfc->mode_ext = MPG_MD_MS_LR;
547 #if defined(HAVE_GTK)
548 /* copy data for MP3 frame analyzer */
549 if (gfp->analysis && gfc->pinfo != NULL) {
550 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
551 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
552 gfc->pinfo->ms_ratio[gr]=gfc->ms_ratio[gr];
553 gfc->pinfo->ms_ener_ratio[gr]=ms_ener_ratio[gr];
554 gfc->pinfo->blocktype[gr][ch]=
555 gfc->l3_side.gr[gr].ch[ch].tt.block_type;
556 memcpy(gfc->pinfo->xr[gr][ch],xr[gr][ch],sizeof(xr[gr][ch]));
557 /* in psymodel, LR and MS data was stored in pinfo.
558 switch to MS data: */
559 if (gfc->mode_ext==MPG_MD_MS_LR) {
560 gfc->pinfo->pe[gr][ch]=gfc->pinfo->pe[gr][ch+2];
561 gfc->pinfo->ers[gr][ch]=gfc->pinfo->ers[gr][ch+2];
562 memcpy(gfc->pinfo->energy[gr][ch],gfc->pinfo->energy[gr][ch+2],
563 sizeof(gfc->pinfo->energy[gr][ch]));
573 /* bit and noise allocation */
574 if (MPG_MD_MS_LR == gfc->mode_ext) {
575 masking = &masking_MS; /* use MS masking */
578 masking = &masking_LR; /* use LR masking */
583 if (gfc->nsPsy.use && (gfp->VBR == vbr_off || gfp->VBR == vbr_abr)) {
584 static FLOAT fircoef[19] = {
585 -0.0207887,-0.0378413,-0.0432472,-0.031183,
586 7.79609e-18,0.0467745,0.10091,0.151365,
587 0.187098,0.2,0.187098,0.151365,
588 0.10091,0.0467745,7.79609e-18,-0.031183,
589 -0.0432472,-0.0378413,-0.0207887,
594 for(i=0;i<18;i++) gfc->nsPsy.pefirbuf[i] = gfc->nsPsy.pefirbuf[i+1];
597 gfc->nsPsy.pefirbuf[18] = 0;
598 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
599 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
600 gfc->nsPsy.pefirbuf[18] += (*pe_use)[gr][ch];
605 gfc->nsPsy.pefirbuf[18] = gfc->nsPsy.pefirbuf[18] / i;
607 for(i=0;i<19;i++) f += gfc->nsPsy.pefirbuf[i] * fircoef[i];
609 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
610 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
611 (*pe_use)[gr][ch] *= 670 / f;
619 iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
622 VBR_quantize( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
626 VBR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
629 ABR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
633 /* write the frame to the bitstream */
634 getframebits(gfp, &bitsPerFrame, &mean_bits);
636 format_bitstream( gfp, bitsPerFrame, l3_enc, scalefac);
638 /* copy mp3 bit buffer into array */
639 mp3count = copy_buffer(gfc,mp3buf,mp3buf_size,1);
644 if (gfp->bWriteVbrTag) AddVbrFrame(gfp);
647 #if defined(HAVE_GTK)
648 /* copy data for MP3 frame analyzer */
649 if (gfp->analysis && gfc->pinfo != NULL) {
651 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
652 for ( j = 0; j < FFTOFFSET; j++ )
653 gfc->pinfo->pcmdata[ch][j] = gfc->pinfo->pcmdata[ch][j+gfp->framesize];
654 for ( j = FFTOFFSET; j < 1600; j++ ) {
655 gfc->pinfo->pcmdata[ch][j] = inbuf[ch][j-FFTOFFSET];
658 set_frame_pinfo (gfp, xr, *masking, l3_enc, scalefac);