1 /*
2 * LAME MP3 encoding engine
3 *
4 * Copyright (c) 1999 Mark Taylor
5 *
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.
10 *
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.
15 *
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.
20 */
21
22 /* $Id: encoder.c,v 1.43 2001/03/12 04:38:35 markt Exp $ */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <assert.h>
29
30 #include "lame.h"
31 #include "util.h"
32 #include "newmdct.h"
33 #include "psymodel.h"
34 #include "quantize.h"
35 #include "quantize_pvt.h"
36 #include "bitstream.h"
37 #include "VbrTag.h"
38
39 #ifdef WITH_DMALLOC
40 #include <dmalloc.h>
41 #endif
42
43
44 /*
45 * auto-adjust of ATH, useful for low volume
46 * Gabriel Bouvigne 3 feb 2001
47 *
48 * modifies some values in
49 * gfp->internal_flags->ATH
50 * (gfc->ATH)
51 */
52 void
adjust_ATH(lame_global_flags * const gfp,FLOAT8 tot_ener[2][4])53 adjust_ATH( lame_global_flags* const gfp,
54 FLOAT8 tot_ener[2][4] )
55 {
56 lame_internal_flags* const gfc = gfp->internal_flags;
57 int gr, channel;
58
59 if (gfc->ATH->use_adjust) {
60 FLOAT8 max_val = 0;
61
62 for ( gr = 0; gr < gfc->mode_gr; ++gr )
63 for ( channel = 0; channel < gfc->channels_out; ++channel )
64 max_val = Max( max_val, tot_ener[gr][channel] );
65 /* scale to 0..1, and then rescale to 0..32767 */
66 max_val *= 32767/1e13;
67
68 /* adjust ATH depending on range of maximum value
69 */
70 if (vbr_mtrh == gfp->VBR) {
71 /* this code reduces slowly the ATH (speed of 12 dB per second)
72 * with some supporting stages to limit the reduction
73 * 640 -> ~17 dB
74 * :
75 * 32640 -> ~0.01 dB
76 */
77 FLOAT8
78 x = Max (640, 320*(int)(max_val/320));
79 x = x/32768;
80 gfc->ATH->adjust *= gfc->ATH->decay;
81 if (gfc->ATH->adjust < x) /* but not more than f(x) dB */
82 gfc->ATH->adjust = x;
83 }
84 else {
85 #ifdef OLD_ATH_AUTO_ADJUST
86 if (0.5 < max_val / 32768) { /* value above 50 % */
87 gfc->ATH->adjust = 1.0; /* do not reduce ATH */
88 }
89 else if (0.3 < max_val / 32768) { /* value above 30 % */
90 gfc->ATH->adjust *= 0.955; /* reduce by ~0.2 dB */
91 if (gfc->ATH->adjust < 0.3) /* but ~5 dB in maximum */
92 gfc->ATH->adjust = 0.3;
93 }
94 else { /* value below 30 % */
95 gfc->ATH->adjust *= 0.93; /* reduce by ~0.3 dB */
96 if (gfc->ATH->adjust < 0.01) /* but 20 dB in maximum */
97 gfc->ATH->adjust = 0.01;
98 }
99 #else /* jd - 27 feb 2001 */
100 /* continuous curves based on approximation */
101 /* to GB's original values */
102 FLOAT8 max_val_n = max_val / 32768;
103 FLOAT8 adj_lim_new;
104 /* For an increase in approximate loudness, */
105 /* set ATH adjust to adjust_limit immediately*/
106 /* after a delay of one frame. */
107 /* For a loudness decrease, reduce ATH adjust*/
108 /* towards adjust_limit gradually. */
109 if( max_val_n > 0.25) { /* sqrt((1 - 0.01) / 15.84) from curve below*/
110 if( gfc->ATH->adjust >= 1.0) {
111 gfc->ATH->adjust = 1.0;
112 } else { /* preceding frame has lower ATH adjust; */
113 /* ascend only to the preceding adjust_limit */
114 /* in case there is leading low volume */
115 if( gfc->ATH->adjust < gfc->ATH->adjust_limit) {
116 gfc->ATH->adjust = gfc->ATH->adjust_limit;
117 }
118 }
119 gfc->ATH->adjust_limit = 1.0;
120 } else { /* adjustment curve (parabolic) */
121 adj_lim_new = 15.84 * (max_val_n * max_val_n) + 0.01;
122 if( gfc->ATH->adjust >= adj_lim_new) { /* descend gradually */
123 gfc->ATH->adjust *= adj_lim_new * 0.075 + 0.925;
124 if( gfc->ATH->adjust < adj_lim_new) { /* stop descent */
125 gfc->ATH->adjust = adj_lim_new;
126 }
127 } else { /* ascend */
128 if( gfc->ATH->adjust_limit >= adj_lim_new) {
129 gfc->ATH->adjust = adj_lim_new;
130 } else { /* preceding frame has lower ATH adjust; */
131 /* ascend only to the preceding adjust_limit */
132 if( gfc->ATH->adjust < gfc->ATH->adjust_limit) {
133 gfc->ATH->adjust = gfc->ATH->adjust_limit;
134 }
135 }
136 }
137 gfc->ATH->adjust_limit = adj_lim_new;
138 }
139 #endif
140 }
141 }
142 }
143
144 /************************************************************************
145 *
146 * encodeframe() Layer 3
147 *
148 * encode a single frame
149 *
150 ************************************************************************
151 lame_encode_frame()
152
153
154 gr 0 gr 1
155 inbuf: |--------------|---------------|-------------|
156 MDCT output: |--------------|---------------|-------------|
157
158 FFT's <---------1024---------->
159 <---------1024-------->
160
161
162
163 inbuf = buffer of PCM data size=MP3 framesize
164 encoder acts on inbuf[ch][0], but output is delayed by MDCTDELAY
165 so the MDCT coefficints are from inbuf[ch][-MDCTDELAY]
166
167 psy-model FFT has a 1 granule delay, so we feed it data for the
168 next granule.
169 FFT is centered over granule: 224+576+224
170 So FFT starts at: 576-224-MDCTDELAY
171
172 MPEG2: FFT ends at: BLKSIZE+576-224-MDCTDELAY
173 MPEG1: FFT ends at: BLKSIZE+2*576-224-MDCTDELAY (1904)
174
175 FFT starts at 576-224-MDCTDELAY (304) = 576-FFTOFFSET
176
177 */
178
179 typedef FLOAT8 chgrdata[2][2];
180
lame_encode_mp3_frame(lame_global_flags * const gfp,sample_t * inbuf_l,sample_t * inbuf_r,unsigned char * mp3buf,int mp3buf_size)181 int lame_encode_mp3_frame ( // Output
182 lame_global_flags* const gfp, // Context
183 sample_t* inbuf_l, // Input
184 sample_t* inbuf_r, // Input
185 unsigned char* mp3buf, // Output
186 int mp3buf_size ) // Output
187 {
188 #ifdef macintosh /* PLL 14/04/2000 */
189 static FLOAT8 xr[2][2][576];
190 static int l3_enc[2][2][576];
191 #else
192 FLOAT8 xr[2][2][576];
193 int l3_enc[2][2][576];
194 #endif
195 int mp3count;
196 III_psy_ratio masking_LR[2][2]; /*LR masking & energy */
197 III_psy_ratio masking_MS[2][2]; /*MS masking & energy */
198 III_psy_ratio (*masking)[2][2]; /*pointer to selected maskings*/
199 III_scalefac_t scalefac[2][2];
200 const sample_t *inbuf[2];
201 lame_internal_flags *gfc=gfp->internal_flags;
202
203 FLOAT8 tot_ener[2][4];
204 FLOAT8 ms_ener_ratio[2]={.5,.5};
205 chgrdata pe,pe_MS;
206 chgrdata *pe_use;
207
208 int ch,gr,mean_bits;
209 int bitsPerFrame;
210
211 int check_ms_stereo;
212 FLOAT8 ms_ratio_next = 0.;
213 FLOAT8 ms_ratio_prev = 0.;
214
215
216 memset((char *) masking_LR, 0, sizeof(masking_LR));
217 memset((char *) masking_MS, 0, sizeof(masking_MS));
218 memset((char *) scalefac, 0, sizeof(scalefac));
219 inbuf[0]=inbuf_l;
220 inbuf[1]=inbuf_r;
221
222 check_ms_stereo = (gfp->mode == JOINT_STEREO);
223 gfc->mode_ext = MPG_MD_LR_LR;
224
225 if (gfc->lame_encode_frame_init==0 ) {
226 gfc->lame_encode_frame_init=1;
227
228 /* padding method as described in
229 * "MPEG-Layer3 / Bitstream Syntax and Decoding"
230 * by Martin Sieler, Ralph Sperschneider
231 *
232 * note: there is no padding for the very first frame
233 *
234 * Robert.Hegemann@gmx.de 2000-06-22
235 */
236
237 gfc->frac_SpF = ((gfp->version+1)*72000L*gfp->brate) % gfp->out_samplerate;
238 gfc->slot_lag = gfc->frac_SpF;
239
240 /* check FFT will not use a negative starting offset */
241 #if 576 < FFTOFFSET
242 # error FFTOFFSET greater than 576: FFT uses a negative offset
243 #endif
244 /* check if we have enough data for FFT */
245 assert(gfc->mf_size>=(BLKSIZE+gfp->framesize-FFTOFFSET));
246 /* check if we have enough data for polyphase filterbank */
247 /* it needs 1152 samples + 286 samples ignored for one granule */
248 /* 1152+576+286 samples for two granules */
249 assert(gfc->mf_size>=(286+576*(1+gfc->mode_gr)));
250
251 /* prime the MDCT/polyphase filterbank with a short block */
252 {
253 int i,j;
254 sample_t primebuff0[286+1152+576];
255 sample_t primebuff1[286+1152+576];
256 for (i=0, j=0; i<286+576*(1+gfc->mode_gr); ++i) {
257 if (i<576*gfc->mode_gr) {
258 primebuff0[i]=0;
259 if (gfc->channels_out==2)
260 primebuff1[i]=0;
261 }else{
262 primebuff0[i]=inbuf[0][j];
263 if (gfc->channels_out==2)
264 primebuff1[i]=inbuf[1][j];
265 ++j;
266 }
267 }
268 /* polyphase filtering / mdct */
269 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
270 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
271 gfc->l3_side.gr[gr].ch[ch].tt.block_type=SHORT_TYPE;
272 }
273 }
274 mdct_sub48(gfc, primebuff0, primebuff1, xr);
275 }
276
277 iteration_init(gfp);
278
279 /* prepare for ATH auto adjustment:
280 * we want to decrease the ATH by 12 dB per second
281 */ {
282 FLOAT8 frame_duration = 576. * gfc->mode_gr / gfp->out_samplerate;
283 gfc->ATH->decay = pow(10., -12./10. * frame_duration);
284 gfc->ATH->adjust = 1.0;
285 gfc->ATH->adjust_limit = 0.01;
286 }
287 }
288
289
290 /********************** padding *****************************/
291 switch (gfp->padding_type) {
292 case 0:
293 gfc->padding=0;
294 break;
295 case 1:
296 gfc->padding=1;
297 break;
298 case 2:
299 default:
300 if (gfp->VBR!=vbr_off) {
301 gfc->padding=0;
302 } else {
303 if (gfp->disable_reservoir) {
304 gfc->padding = 0;
305 /* if the user specified --nores, dont very gfc->padding either */
306 /* tiny changes in frac_SpF rounding will cause file differences */
307 }else{
308 /* padding method as described in
309 * "MPEG-Layer3 / Bitstream Syntax and Decoding"
310 * by Martin Sieler, Ralph Sperschneider
311 *
312 * note: there is no padding for the very first frame
313 *
314 * Robert.Hegemann@gmx.de 2000-06-22
315 */
316
317 gfc->slot_lag -= gfc->frac_SpF;
318 if (gfc->slot_lag < 0) {
319 gfc->slot_lag += gfp->out_samplerate;
320 gfc->padding = 1;
321 } else {
322 gfc->padding = 0;
323 }
324 } /* reservoir enabled */
325 }
326 }
327
328
329 if (gfc->psymodel) {
330 /* psychoacoustic model
331 * psy model has a 1 granule (576) delay that we must compensate for
332 * (mt 6/99).
333 */
334 int ret;
335 const sample_t *bufp[2]; /* address of beginning of left & right granule */
336 int blocktype[2];
337
338 ms_ratio_prev=gfc->ms_ratio[gfc->mode_gr-1];
339 for (gr=0; gr < gfc->mode_gr ; gr++) {
340
341 for ( ch = 0; ch < gfc->channels_out; ch++ )
342 bufp[ch] = &inbuf[ch][576 + gr*576-FFTOFFSET];
343
344 if (gfc->nsPsy.use) {
345 ret=L3psycho_anal_ns( gfp, bufp, gr,
346 &gfc->ms_ratio[gr],&ms_ratio_next,
347 masking_LR, masking_MS,
348 pe[gr],pe_MS[gr],tot_ener[gr],blocktype);
349 } else {
350 ret=L3psycho_anal( gfp, bufp, gr,
351 &gfc->ms_ratio[gr],&ms_ratio_next,
352 masking_LR, masking_MS,
353 pe[gr],pe_MS[gr],tot_ener[gr],blocktype);
354 }
355 if (ret!=0) return -4;
356
357 for ( ch = 0; ch < gfc->channels_out; ch++ )
358 gfc->l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
359
360 if (check_ms_stereo) {
361 ms_ener_ratio[gr] = tot_ener[gr][2]+tot_ener[gr][3];
362 if (ms_ener_ratio[gr]>0)
363 ms_ener_ratio[gr] = tot_ener[gr][3]/ms_ener_ratio[gr];
364 }
365
366 }
367 }else{
368 for (gr=0; gr < gfc->mode_gr ; gr++)
369 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
370 gfc->l3_side.gr[gr].ch[ch].tt.block_type=NORM_TYPE;
371 pe_MS[gr][ch]=pe[gr][ch]=700;
372 }
373 }
374
375
376
377 /* auto-adjust of ATH, useful for low volume */
378 adjust_ATH( gfp, tot_ener );
379
380
381
382 /* block type flags */
383 for( gr = 0; gr < gfc->mode_gr; gr++ ) {
384 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
385 gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
386 cod_info->mixed_block_flag = 0; /* never used by this model */
387 if (cod_info->block_type == NORM_TYPE )
388 cod_info->window_switching_flag = 0;
389 else
390 cod_info->window_switching_flag = 1;
391 }
392 }
393
394
395 /* polyphase filtering / mdct */
396 mdct_sub48(gfc, inbuf[0], inbuf[1], xr);
397 /* re-order the short blocks, for more efficient encoding below */
398 for (gr = 0; gr < gfc->mode_gr; gr++) {
399 for (ch = 0; ch < gfc->channels_out; ch++) {
400 gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
401 if (cod_info->block_type==SHORT_TYPE) {
402 freorder(gfc->scalefac_band.s,xr[gr][ch]);
403 }
404 }
405 }
406
407
408 /* use m/s gfc->channels_out? */
409 if (check_ms_stereo) {
410 int gr0 = 0, gr1 = gfc->mode_gr-1;
411 /* make sure block type is the same in each channel */
412 check_ms_stereo =
413 (gfc->l3_side.gr[gr0].ch[0].tt.block_type==gfc->l3_side.gr[gr0].ch[1].tt.block_type) &&
414 (gfc->l3_side.gr[gr1].ch[0].tt.block_type==gfc->l3_side.gr[gr1].ch[1].tt.block_type);
415 }
416
417 /* Here will be selected MS or LR coding of the 2 stereo channels */
418
419 assert ( gfc->mode_ext == MPG_MD_LR_LR );
420 gfc->mode_ext = MPG_MD_LR_LR;
421
422 if (gfp->force_ms) {
423 gfc->mode_ext = MPG_MD_MS_LR;
424 } else if (check_ms_stereo) {
425 /* ms_ratio = is scaled, for historical reasons, to look like
426 a ratio of side_channel / total.
427 0 = signal is 100% mono
428 .5 = L & R uncorrelated
429 */
430
431 /* [0] and [1] are the results for the two granules in MPEG-1,
432 * in MPEG-2 it's only a faked averaging of the same value
433 * _prev is the value of the last granule of the previous frame
434 * _next is the value of the first granule of the next frame
435 */
436 FLOAT8 ms_ratio_ave1;
437 FLOAT8 ms_ratio_ave2;
438 FLOAT8 threshold1 = 0.35;
439 FLOAT8 threshold2 = 0.45;
440
441 /* take an average */
442 if (gfc->mode_gr==1) {
443 /* MPEG2 - no second granule */
444 ms_ratio_ave1 = 0.33 * ( gfc->ms_ratio[0] + ms_ratio_prev + ms_ratio_next );
445 ms_ratio_ave2 = gfc->ms_ratio[0];
446 }else{
447 ms_ratio_ave1 = 0.25 * ( gfc->ms_ratio[0] + gfc->ms_ratio[1] + ms_ratio_prev + ms_ratio_next );
448 ms_ratio_ave2 = 0.50 * ( gfc->ms_ratio[0] + gfc->ms_ratio[1] );
449 }
450
451 if (gfp->mode_automs) {
452 if ( gfp->compression_ratio < 11.025 ) {
453 /* 11.025 => 1, 6.3 => 0 */
454 double thr = (gfp->compression_ratio - 6.3) / (11.025 - 6.3);
455 if (thr<0) thr=0;
456 threshold1 *= thr;
457 threshold2 *= thr;
458 }
459 }
460
461 if ((ms_ratio_ave1 < threshold1 && ms_ratio_ave2 < threshold2) || gfc->nsPsy.use) {
462 int sum_pe_MS = pe_MS[0][0] + pe_MS[0][1] + pe_MS[1][0] + pe_MS[1][1];
463 int sum_pe_LR = pe [0][0] + pe [0][1] + pe [1][0] + pe [1][1];
464
465 /* based on PE: M/S coding would not use much more bits than L/R coding */
466
467 if (sum_pe_MS <= 1.07 * sum_pe_LR && !gfc->nsPsy.use) gfc->mode_ext = MPG_MD_MS_LR;
468 if (sum_pe_MS <= 1.00 * sum_pe_LR && gfc->nsPsy.use) gfc->mode_ext = MPG_MD_MS_LR;
469 }
470 }
471
472
473 /* copy data for MP3 frame analyzer */
474 if (gfp->analysis && gfc->pinfo != NULL) {
475 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
476 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
477 gfc->pinfo->ms_ratio[gr]=gfc->ms_ratio[gr];
478 gfc->pinfo->ms_ener_ratio[gr]=ms_ener_ratio[gr];
479 gfc->pinfo->blocktype[gr][ch]=
480 gfc->l3_side.gr[gr].ch[ch].tt.block_type;
481 memcpy(gfc->pinfo->xr[gr][ch],xr[gr][ch],sizeof(xr[gr][ch]));
482 /* in psymodel, LR and MS data was stored in pinfo.
483 switch to MS data: */
484 if (gfc->mode_ext==MPG_MD_MS_LR) {
485 gfc->pinfo->pe[gr][ch]=gfc->pinfo->pe[gr][ch+2];
486 gfc->pinfo->ers[gr][ch]=gfc->pinfo->ers[gr][ch+2];
487 memcpy(gfc->pinfo->energy[gr][ch],gfc->pinfo->energy[gr][ch+2],
488 sizeof(gfc->pinfo->energy[gr][ch]));
489 }
490 }
491 }
492 }
493
494
495
496
497 /* bit and noise allocation */
498 if (MPG_MD_MS_LR == gfc->mode_ext) {
499 masking = &masking_MS; /* use MS masking */
500 pe_use = &pe_MS;
501 } else {
502 masking = &masking_LR; /* use LR masking */
503 pe_use = &pe;
504 }
505
506
507 if (gfc->nsPsy.use && (gfp->VBR == vbr_off || gfp->VBR == vbr_abr)) {
508 static FLOAT fircoef[19] = {
509 -0.0207887,-0.0378413,-0.0432472,-0.031183,
510 7.79609e-18,0.0467745,0.10091,0.151365,
511 0.187098,0.2,0.187098,0.151365,
512 0.10091,0.0467745,7.79609e-18,-0.031183,
513 -0.0432472,-0.0378413,-0.0207887,
514 };
515 int i;
516 FLOAT8 f;
517
518 for(i=0;i<18;i++) gfc->nsPsy.pefirbuf[i] = gfc->nsPsy.pefirbuf[i+1];
519
520 i=0;
521 gfc->nsPsy.pefirbuf[18] = 0;
522 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
523 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
524 gfc->nsPsy.pefirbuf[18] += (*pe_use)[gr][ch];
525 i++;
526 }
527 }
528
529 gfc->nsPsy.pefirbuf[18] = gfc->nsPsy.pefirbuf[18] / i;
530 f = 0;
531 for(i=0;i<19;i++) f += gfc->nsPsy.pefirbuf[i] * fircoef[i];
532
533 for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
534 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
535 (*pe_use)[gr][ch] *= 670 / f;
536 }
537 }
538 }
539
540 switch (gfp->VBR){
541 default:
542 case vbr_off:
543 iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
544 break;
545 case vbr_mt:
546 VBR_quantize( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
547 break;
548 case vbr_rh:
549 case vbr_mtrh:
550 VBR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
551 break;
552 case vbr_abr:
553 ABR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
554 break;
555 }
556
557 /* write the frame to the bitstream */
558 getframebits(gfp, &bitsPerFrame, &mean_bits);
559
560 format_bitstream( gfp, bitsPerFrame, l3_enc, scalefac);
561
562 /* copy mp3 bit buffer into array */
563 mp3count = copy_buffer(mp3buf,mp3buf_size,&gfc->bs);
564
565 if (gfp->bWriteVbrTag) AddVbrFrame(gfp);
566
567
568 /* copy data for MP3 frame analyzer */
569 if (gfp->analysis && gfc->pinfo != NULL) {
570 int j;
571 for ( ch = 0; ch < gfc->channels_out; ch++ ) {
572 for ( j = 0; j < FFTOFFSET; j++ )
573 gfc->pinfo->pcmdata[ch][j] = gfc->pinfo->pcmdata[ch][j+gfp->framesize];
574 for ( j = FFTOFFSET; j < 1600; j++ ) {
575 gfc->pinfo->pcmdata[ch][j] = inbuf[ch][j-FFTOFFSET];
576 }
577 }
578 set_frame_pinfo (gfp, xr, *masking, l3_enc, scalefac);
579 }
580
581 updateStats( gfc );
582
583 return mp3count;
584 }
585