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.2 2006/02/09 16:53:35 kramm Exp $ */
25 #include "config_static.h"
34 #include "quantize_pvt.h"
35 #include "bitstream.h"
37 #include "vbrquantize.h"
45 * auto-adjust of ATH, useful for low volume
46 * Gabriel Bouvigne 3 feb 2001
48 * modifies some values in
49 * gfp->internal_flags->ATH
53 adjust_ATH( lame_global_flags* const gfp,
54 FLOAT8 tot_ener[2][4] )
56 lame_internal_flags* const gfc = gfp->internal_flags;
58 FLOAT max_pow, max_pow_alt;
61 if (gfc->ATH->use_adjust == 0) {
62 gfc->ATH->adjust = 1.0; /* no adjustment */
66 switch( gfp->athaa_loudapprox ) {
68 /* flat approximation for loudness (squared) */
70 for ( gr = 0; gr < gfc->mode_gr; ++gr )
71 for ( channel = 0; channel < gfc->channels_out; ++channel )
72 max_pow = Max( max_pow, tot_ener[gr][channel] );
73 max_pow *= 0.25/ 5.6e13; /* scale to 0..1 (5.6e13), and tune (0.25) */
76 case 2: /* jd - 2001 mar 12, 27, jun 30 */
77 { /* loudness based on equal loudness curve; */
78 /* use granule with maximum combined loudness*/
80 max_pow = gfc->loudness_sq[0][0];
81 if( gfc->channels_out == 2 ) {
82 max_pow += gfc->loudness_sq[0][1];
83 gr2_max = gfc->loudness_sq[1][0] + gfc->loudness_sq[1][1];
85 gr2_max = gfc->loudness_sq[1][0];
89 if( gfc->mode_gr == 2 ) {
90 max_pow = Max( max_pow, gr2_max );
92 max_pow *= 0.5; /* max_pow approaches 1.0 for full band noise*/
96 default: /* jd - 2001 mar 27, 31, jun 30 */
97 /* no adaptive threshold */
98 max_pow = 1.0 / gfc->athaa_sensitivity_p;
102 /* jd - 2001 mar 31, jun 30 */
103 /* user tuning of ATH adjustment region */
104 max_pow_alt = max_pow;
105 max_pow *= gfc->athaa_sensitivity_p;
106 if (gfc->presetTune.use)
107 max_pow_alt *= pow( 10.0, gfc->presetTune.athadjust_safe_athaasensitivity / -10.0 );
109 /* adjust ATH depending on range of maximum value
111 switch ( gfc->ATH->use_adjust ) {
114 max_val = sqrt( max_pow ); /* GB's original code requires a maximum */
115 max_val *= 32768; /* sample or loudness value up to 32768 */
117 /* by Gabriel Bouvigne */
118 if (0.5 < max_val / 32768) { /* value above 50 % */
119 gfc->ATH->adjust = 1.0; /* do not reduce ATH */
121 else if (0.3 < max_val / 32768) { /* value above 30 % */
122 gfc->ATH->adjust *= 0.955; /* reduce by ~0.2 dB */
123 if (gfc->ATH->adjust < 0.3) /* but ~5 dB in maximum */
124 gfc->ATH->adjust = 0.3;
126 else { /* value below 30 % */
127 gfc->ATH->adjust *= 0.93; /* reduce by ~0.3 dB */
128 if (gfc->ATH->adjust < 0.01) /* but 20 dB in maximum */
129 gfc->ATH->adjust = 0.01;
134 max_val = Min( max_pow, 1.0 ) * 32768; /* adapt for RH's adjust */
136 { /* by Robert Hegemann */
137 /* this code reduces slowly the ATH (speed of 12 dB per second)
140 //x = Max (640, 320*(int)(max_val/320));
141 x = Max (32, 32*(int)(max_val/32));
143 gfc->ATH->adjust *= gfc->ATH->decay;
144 if (gfc->ATH->adjust < x) /* but not more than f(x) dB */
145 gfc->ATH->adjust = x;
150 { /* jd - 2001 feb27, mar12,20, jun30, jul22 */
151 /* continuous curves based on approximation */
152 /* to GB's original values. */
154 /* For an increase in approximate loudness, */
155 /* set ATH adjust to adjust_limit immediately*/
156 /* after a delay of one frame. */
157 /* For a loudness decrease, reduce ATH adjust*/
158 /* towards adjust_limit gradually. */
159 /* max_pow is a loudness squared or a power. */
160 if( max_pow > 0.03125) { /* ((1 - 0.000625)/ 31.98) from curve below */
161 if( gfc->ATH->adjust >= 1.0) {
162 gfc->ATH->adjust = 1.0;
163 if (gfc->presetTune.use) {
164 if (max_pow_alt > gfc->presetTune.athadjust_safe_noiseshaping_thre)
165 gfc->presetTune.athadjust_safe_noiseshaping = 1;
167 gfc->presetTune.athadjust_safe_noiseshaping = 0;
170 /* preceding frame has lower ATH adjust; */
171 /* ascend only to the preceding adjust_limit */
172 /* in case there is leading low volume */
173 if( gfc->ATH->adjust < gfc->ATH->adjust_limit) {
174 gfc->ATH->adjust = gfc->ATH->adjust_limit;
175 if (gfc->presetTune.use) {
176 if (max_pow_alt > gfc->presetTune.athadjust_safe_noiseshaping_thre)
177 gfc->presetTune.athadjust_safe_noiseshaping = 1;
179 gfc->presetTune.athadjust_safe_noiseshaping = 0;
183 gfc->ATH->adjust_limit = 1.0;
184 } else { /* adjustment curve */
185 /* about 32 dB maximum adjust (0.000625) */
186 adj_lim_new = 31.98 * max_pow + 0.000625;
187 if( gfc->ATH->adjust >= adj_lim_new) { /* descend gradually */
188 gfc->ATH->adjust *= adj_lim_new * 0.075 + 0.925;
189 if( gfc->ATH->adjust < adj_lim_new) { /* stop descent */
190 gfc->ATH->adjust = adj_lim_new;
192 } else { /* ascend */
193 if( gfc->ATH->adjust_limit >= adj_lim_new) {
194 gfc->ATH->adjust = adj_lim_new;
195 } else { /* preceding frame has lower ATH adjust; */
196 /* ascend only to the preceding adjust_limit */
197 if( gfc->ATH->adjust < gfc->ATH->adjust_limit) {
198 gfc->ATH->adjust = gfc->ATH->adjust_limit;
202 gfc->ATH->adjust_limit = adj_lim_new;
208 gfc->ATH->adjust = 1.0; /* no adjustment */
213 /************************************************************************
215 * encodeframe() Layer 3
217 * encode a single frame
219 ************************************************************************
224 inbuf: |--------------|---------------|-------------|
225 MDCT output: |--------------|---------------|-------------|
227 FFT's <---------1024---------->
228 <---------1024-------->
232 inbuf = buffer of PCM data size=MP3 framesize
233 encoder acts on inbuf[ch][0], but output is delayed by MDCTDELAY
234 so the MDCT coefficints are from inbuf[ch][-MDCTDELAY]
236 psy-model FFT has a 1 granule delay, so we feed it data for the
238 FFT is centered over granule: 224+576+224
239 So FFT starts at: 576-224-MDCTDELAY
241 MPEG2: FFT ends at: BLKSIZE+576-224-MDCTDELAY
242 MPEG1: FFT ends at: BLKSIZE+2*576-224-MDCTDELAY (1904)
244 FFT starts at 576-224-MDCTDELAY (304) = 576-FFTOFFSET
248 typedef FLOAT8 chgrdata[2][2];
250 int lame_encode_mp3_frame ( // Output
251 lame_global_flags* const gfp, // Context
252 sample_t* inbuf_l, // Input
253 sample_t* inbuf_r, // Input
254 unsigned char* mp3buf, // Output
255 int mp3buf_size ) // Output
257 #ifdef macintosh /* PLL 14/04/2000 */
258 static FLOAT8 xr[2][2][576];
259 static int l3_enc[2][2][576];
261 FLOAT8 xr[2][2][576];
262 int l3_enc[2][2][576];
265 III_psy_ratio masking_LR[2][2]; /*LR masking & energy */
266 III_psy_ratio masking_MS[2][2]; /*MS masking & energy */
267 III_psy_ratio (*masking)[2][2]; /*pointer to selected maskings*/
268 III_scalefac_t scalefac[2][2];
269 const sample_t *inbuf[2];
270 lame_internal_flags *gfc=gfp->internal_flags;
272 FLOAT8 tot_ener[2][4];
273 FLOAT8 ms_ener_ratio[2]={.5,.5};
281 FLOAT8 ms_ratio_next = 0.;
282 FLOAT8 ms_ratio_prev = 0.;
285 memset((char *) masking_LR, 0, sizeof(masking_LR));
286 memset((char *) masking_MS, 0, sizeof(masking_MS));
287 memset((char *) scalefac, 0, sizeof(scalefac));
291 check_ms_stereo = (gfp->mode == JOINT_STEREO);
292 gfc->mode_ext = MPG_MD_LR_LR;
294 if (gfc->lame_encode_frame_init==0 ) {
295 gfc->lame_encode_frame_init=1;
297 /* padding method as described in
298 * "MPEG-Layer3 / Bitstream Syntax and Decoding"
299 * by Martin Sieler, Ralph Sperschneider
301 * note: there is no padding for the very first frame
303 * Robert.Hegemann@gmx.de 2000-06-22
306 gfc->frac_SpF = ((gfp->version+1)*72000L*gfp->brate) % gfp->out_samplerate;
307 gfc->slot_lag = gfc->frac_SpF;
309 /* check FFT will not use a negative starting offset */
311 # error FFTOFFSET greater than 576: FFT uses a negative offset
313 /* check if we have enough data for FFT */
314 assert(gfc->mf_size>=(BLKSIZE+gfp->framesize-FFTOFFSET));
315 /* check if we have enough data for polyphase filterbank */
316 /* it needs 1152 samples + 286 samples ignored for one granule */
317 /* 1152+576+286 samples for two granules */
318 assert(gfc->mf_size>=(286+576*(1+gfc->mode_gr)));
320 /* prime the MDCT/polyphase filterbank with a short block */
323 sample_t primebuff0[286+1152+576];
324 sample_t primebuff1[286+1152+576];
325 for (i=0, j=0; i<286+576*(1+gfc->mode_gr); ++i) {
326 if (i<576*gfc->mode_gr) {
328 if (gfc->channels_out==2)
331 primebuff0[i]=inbuf[0][j];
332 if (gfc->channels_out==2)
333 primebuff1[i]=inbuf[1][j];
337 /* polyphase filtering / mdct */
338 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
339 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
340 gfc->l3_side.gr[gr].ch[ch].tt.block_type=SHORT_TYPE;
343 mdct_sub48(gfc, primebuff0, primebuff1, xr);
348 /* prepare for ATH auto adjustment:
349 * we want to decrease the ATH by 12 dB per second
351 FLOAT8 frame_duration = 576. * gfc->mode_gr / gfp->out_samplerate;
352 gfc->ATH->decay = pow(10., -12./10. * frame_duration);
353 gfc->ATH->adjust = 0.01; /* minimum, for leading low loudness */
354 gfc->ATH->adjust_limit = 1.0; /* on lead, allow adjust up to maximum */
359 /********************** padding *****************************/
360 switch (gfp->padding_type) {
362 gfc->padding = FALSE;
369 if (gfp->VBR!=vbr_off) {
370 gfc->padding = FALSE;
372 if (gfp->disable_reservoir) {
373 gfc->padding = FALSE;
374 /* if the user specified --nores, dont very gfc->padding either */
375 /* tiny changes in frac_SpF rounding will cause file differences */
377 /* padding method as described in
378 * "MPEG-Layer3 / Bitstream Syntax and Decoding"
379 * by Martin Sieler, Ralph Sperschneider
381 * note: there is no padding for the very first frame
383 * Robert.Hegemann@gmx.de 2000-06-22
386 gfc->slot_lag -= gfc->frac_SpF;
387 if (gfc->slot_lag < 0) {
388 gfc->slot_lag += gfp->out_samplerate;
391 gfc->padding = FALSE;
393 } /* reservoir enabled */
399 /* psychoacoustic model
400 * psy model has a 1 granule (576) delay that we must compensate for
404 const sample_t *bufp[2]; /* address of beginning of left & right granule */
407 ms_ratio_prev=gfc->ms_ratio[gfc->mode_gr-1];
408 for (gr=0; gr < gfc->mode_gr ; gr++) {
410 for ( ch = 0; ch < gfc->channels_out; ch++ )
411 bufp[ch] = &inbuf[ch][576 + gr*576-FFTOFFSET];
413 if (gfc->nsPsy.use) {
414 ret=L3psycho_anal_ns( gfp, bufp, gr,
415 &gfc->ms_ratio[gr],&ms_ratio_next,
416 masking_LR, masking_MS,
417 pe[gr],pe_MS[gr],tot_ener[gr],blocktype);
419 ret=L3psycho_anal( gfp, bufp, gr,
420 &gfc->ms_ratio[gr],&ms_ratio_next,
421 masking_LR, masking_MS,
422 pe[gr],pe_MS[gr],tot_ener[gr],blocktype);
424 if (ret!=0) return -4;
426 for ( ch = 0; ch < gfc->channels_out; ch++ )
427 gfc->l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
429 if (check_ms_stereo) {
430 ms_ener_ratio[gr] = tot_ener[gr][2]+tot_ener[gr][3];
431 if (ms_ener_ratio[gr]>0)
432 ms_ener_ratio[gr] = tot_ener[gr][3]/ms_ener_ratio[gr];
437 for (gr=0; gr < gfc->mode_gr ; gr++)
438 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
439 gfc->l3_side.gr[gr].ch[ch].tt.block_type=NORM_TYPE;
440 pe_MS[gr][ch]=pe[gr][ch]=700;
446 /* auto-adjust of ATH, useful for low volume */
447 adjust_ATH( gfp, tot_ener );
451 /* block type flags */
452 for( gr = 0; gr < gfc->mode_gr; gr++ ) {
453 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
454 gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
455 cod_info->mixed_block_flag = 0; /* never used by this model */
456 if (cod_info->block_type == NORM_TYPE )
457 cod_info->window_switching_flag = 0;
459 cod_info->window_switching_flag = 1;
464 /* polyphase filtering / mdct */
465 mdct_sub48(gfc, inbuf[0], inbuf[1], xr);
466 /* re-order the short blocks, for more efficient encoding below */
467 for (gr = 0; gr < gfc->mode_gr; gr++) {
468 for (ch = 0; ch < gfc->channels_out; ch++) {
469 gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
470 if (cod_info->block_type==SHORT_TYPE) {
471 freorder(gfc->scalefac_band.s,xr[gr][ch]);
477 /* use m/s gfc->channels_out? */
478 if (check_ms_stereo) {
479 int gr0 = 0, gr1 = gfc->mode_gr-1;
480 /* make sure block type is the same in each channel */
482 (gfc->l3_side.gr[gr0].ch[0].tt.block_type==gfc->l3_side.gr[gr0].ch[1].tt.block_type) &&
483 (gfc->l3_side.gr[gr1].ch[0].tt.block_type==gfc->l3_side.gr[gr1].ch[1].tt.block_type);
486 /* Here will be selected MS or LR coding of the 2 stereo channels */
488 assert ( gfc->mode_ext == MPG_MD_LR_LR );
489 gfc->mode_ext = MPG_MD_LR_LR;
492 gfc->mode_ext = MPG_MD_MS_LR;
493 } else if (check_ms_stereo) {
494 /* ms_ratio = is scaled, for historical reasons, to look like
495 a ratio of side_channel / total.
496 0 = signal is 100% mono
497 .5 = L & R uncorrelated
500 /* [0] and [1] are the results for the two granules in MPEG-1,
501 * in MPEG-2 it's only a faked averaging of the same value
502 * _prev is the value of the last granule of the previous frame
503 * _next is the value of the first granule of the next frame
505 FLOAT8 ms_ratio_ave1;
506 FLOAT8 ms_ratio_ave2;
507 FLOAT8 threshold1 = 0.35;
508 FLOAT8 threshold2 = 0.45;
510 /* take an average */
511 if (gfc->mode_gr==1) {
512 /* MPEG2 - no second granule */
513 ms_ratio_ave1 = 0.33 * ( gfc->ms_ratio[0] + ms_ratio_prev + ms_ratio_next );
514 ms_ratio_ave2 = gfc->ms_ratio[0];
516 ms_ratio_ave1 = 0.25 * ( gfc->ms_ratio[0] + gfc->ms_ratio[1] + ms_ratio_prev + ms_ratio_next );
517 ms_ratio_ave2 = 0.50 * ( gfc->ms_ratio[0] + gfc->ms_ratio[1] );
520 if (gfp->mode_automs) {
521 if ( gfp->compression_ratio < 11.025 ) {
522 /* 11.025 => 1, 6.3 => 0 */
523 double thr = (gfp->compression_ratio - 6.3) / (11.025 - 6.3);
530 if ((ms_ratio_ave1 < threshold1 && ms_ratio_ave2 < threshold2) || gfc->nsPsy.use) {
533 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
534 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
535 sum_pe_MS += pe_MS[gr][ch];
536 sum_pe_LR += pe[gr][ch];
540 /* based on PE: M/S coding would not use much more bits than L/R coding */
542 if (sum_pe_MS <= 1.07 * sum_pe_LR && !gfc->nsPsy.use) gfc->mode_ext = MPG_MD_MS_LR;
543 if (sum_pe_MS <= 1.00 * sum_pe_LR && gfc->nsPsy.use) gfc->mode_ext = MPG_MD_MS_LR;
548 #if defined(HAVE_GTK)
549 /* copy data for MP3 frame analyzer */
550 if (gfp->analysis && gfc->pinfo != NULL) {
551 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
552 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
553 gfc->pinfo->ms_ratio[gr]=gfc->ms_ratio[gr];
554 gfc->pinfo->ms_ener_ratio[gr]=ms_ener_ratio[gr];
555 gfc->pinfo->blocktype[gr][ch]=
556 gfc->l3_side.gr[gr].ch[ch].tt.block_type;
557 memcpy(gfc->pinfo->xr[gr][ch],xr[gr][ch],sizeof(xr[gr][ch]));
558 /* in psymodel, LR and MS data was stored in pinfo.
559 switch to MS data: */
560 if (gfc->mode_ext==MPG_MD_MS_LR) {
561 gfc->pinfo->pe[gr][ch]=gfc->pinfo->pe[gr][ch+2];
562 gfc->pinfo->ers[gr][ch]=gfc->pinfo->ers[gr][ch+2];
563 memcpy(gfc->pinfo->energy[gr][ch],gfc->pinfo->energy[gr][ch+2],
564 sizeof(gfc->pinfo->energy[gr][ch]));
574 /* bit and noise allocation */
575 if (MPG_MD_MS_LR == gfc->mode_ext) {
576 masking = &masking_MS; /* use MS masking */
579 masking = &masking_LR; /* use LR masking */
584 if (gfc->nsPsy.use && (gfp->VBR == vbr_off || gfp->VBR == vbr_abr)) {
585 static FLOAT fircoef[19] = {
586 -0.0207887,-0.0378413,-0.0432472,-0.031183,
587 7.79609e-18,0.0467745,0.10091,0.151365,
588 0.187098,0.2,0.187098,0.151365,
589 0.10091,0.0467745,7.79609e-18,-0.031183,
590 -0.0432472,-0.0378413,-0.0207887,
595 for(i=0;i<18;i++) gfc->nsPsy.pefirbuf[i] = gfc->nsPsy.pefirbuf[i+1];
598 gfc->nsPsy.pefirbuf[18] = 0;
599 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
600 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
601 gfc->nsPsy.pefirbuf[18] += (*pe_use)[gr][ch];
606 gfc->nsPsy.pefirbuf[18] = gfc->nsPsy.pefirbuf[18] / i;
608 for(i=0;i<19;i++) f += gfc->nsPsy.pefirbuf[i] * fircoef[i];
610 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
611 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
612 (*pe_use)[gr][ch] *= 670 / f;
620 iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
623 VBR_quantize( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
627 VBR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
630 ABR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
634 /* write the frame to the bitstream */
635 getframebits(gfp, &bitsPerFrame, &mean_bits);
637 format_bitstream( gfp, bitsPerFrame, l3_enc, scalefac);
639 /* copy mp3 bit buffer into array */
640 mp3count = copy_buffer(gfc,mp3buf,mp3buf_size,1);
645 if (gfp->bWriteVbrTag) AddVbrFrame(gfp);
648 #if defined(HAVE_GTK)
649 /* copy data for MP3 frame analyzer */
650 if (gfp->analysis && gfc->pinfo != NULL) {
652 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
653 for ( j = 0; j < FFTOFFSET; j++ )
654 gfc->pinfo->pcmdata[ch][j] = gfc->pinfo->pcmdata[ch][j+gfp->framesize];
655 for ( j = FFTOFFSET; j < 1600; j++ ) {
656 gfc->pinfo->pcmdata[ch][j] = inbuf[ch][j-FFTOFFSET];
659 set_frame_pinfo (gfp, xr, *masking, l3_enc, scalefac);