polygon intersector: added horizontal line reconstruction
[swftools.git] / lib / lame / encoder.c
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.2 2006/02/09 16:56:23 kramm Exp $ */
23
24 #include <stdlib.h>
25 #include "config_static.h"
26
27 #include <assert.h>
28
29 #include "lame.h"
30 #include "util.h"
31 #include "newmdct.h"
32 #include "psymodel.h"
33 #include "quantize.h"
34 #include "quantize_pvt.h"
35 #include "bitstream.h"
36 #include "VbrTag.h"
37 #include "vbrquantize.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
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     FLOAT max_pow, max_pow_alt;
59     FLOAT8 max_val;
60
61     if (gfc->ATH->use_adjust == 0) {
62         gfc->ATH->adjust = 1.0; /* no adjustment */
63         return;
64     }
65     
66     switch( gfp->athaa_loudapprox ) {
67     case 1:
68                                 /* flat approximation for loudness (squared) */
69         max_pow = 0;
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) */
74         break;
75     
76     case 2:                     /* jd - 2001 mar 12, 27, jun 30 */
77     {                           /* loudness based on equal loudness curve; */
78                                 /* use granule with maximum combined loudness*/
79         FLOAT gr2_max;
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];
84         } else {
85             gr2_max = gfc->loudness_sq[1][0];
86             max_pow += max_pow;
87             gr2_max += gr2_max;
88         }
89         if( gfc->mode_gr == 2 ) {
90             max_pow = Max( max_pow, gr2_max );
91         }
92         max_pow *= 0.5;         /* max_pow approaches 1.0 for full band noise*/
93         break;
94     }
95
96     default:                    /* jd - 2001 mar 27, 31, jun 30 */
97                                 /* no adaptive threshold */
98         max_pow = 1.0 / gfc->athaa_sensitivity_p;
99         break;
100     }
101
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 );
108
109     /*  adjust ATH depending on range of maximum value
110      */
111     switch ( gfc->ATH->use_adjust ) {
112
113     case  1:
114         max_val = sqrt( max_pow ); /* GB's original code requires a maximum */
115         max_val *= 32768;          /*  sample or loudness value up to 32768 */
116
117                                 /* by Gabriel Bouvigne */
118         if      (0.5 < max_val / 32768) {       /* value above 50 % */
119                 gfc->ATH->adjust = 1.0;         /* do not reduce ATH */
120         }
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;            
125         }
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;
130         }
131         break;
132
133     case  2:   
134         max_val = Min( max_pow, 1.0 ) * 32768; /* adapt for RH's adjust */
135
136       {                         /* by Robert Hegemann */
137         /*  this code reduces slowly the ATH (speed of 12 dB per second)
138          */
139         FLOAT8 
140         //x = Max (640, 320*(int)(max_val/320));
141         x = Max (32, 32*(int)(max_val/32));
142         x = x/32768;
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;
146       }
147         break;
148
149     case  3:
150       {                         /* jd - 2001 feb27, mar12,20, jun30, jul22 */
151                                 /* continuous curves based on approximation */
152                                 /* to GB's original values. */
153         FLOAT8 adj_lim_new;
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;
166                         else
167                               gfc->presetTune.athadjust_safe_noiseshaping = 0;
168                 }
169             } else {
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;
178                         else
179                             gfc->presetTune.athadjust_safe_noiseshaping = 0;
180                     }
181                 }
182             }
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;
191                 }
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;
199                     }
200                 }
201             }
202             gfc->ATH->adjust_limit = adj_lim_new;
203         }
204       }
205         break;
206         
207     default:
208         gfc->ATH->adjust = 1.0; /* no adjustment */
209         break;
210     }   /* switch */
211 }
212
213 /************************************************************************
214 *
215 * encodeframe()           Layer 3
216 *
217 * encode a single frame
218 *
219 ************************************************************************
220 lame_encode_frame()
221
222
223                        gr 0            gr 1
224 inbuf:           |--------------|---------------|-------------|
225 MDCT output:  |--------------|---------------|-------------|
226
227 FFT's                    <---------1024---------->
228                                          <---------1024-------->
229
230
231
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]
235
236     psy-model FFT has a 1 granule delay, so we feed it data for the 
237     next granule.
238     FFT is centered over granule:  224+576+224
239     So FFT starts at:   576-224-MDCTDELAY
240
241     MPEG2:  FFT ends at:  BLKSIZE+576-224-MDCTDELAY
242     MPEG1:  FFT ends at:  BLKSIZE+2*576-224-MDCTDELAY    (1904)
243
244     FFT starts at 576-224-MDCTDELAY (304)  = 576-FFTOFFSET
245
246 */
247
248 typedef FLOAT8 chgrdata[2][2];
249
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
256 {
257 #ifdef macintosh /* PLL 14/04/2000 */
258   static FLOAT8 xr[2][2][576];
259   static int l3_enc[2][2][576];
260 #else
261   FLOAT8 xr[2][2][576];
262   int l3_enc[2][2][576];
263 #endif
264   int mp3count;
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;
271
272   FLOAT8 tot_ener[2][4];   
273   FLOAT8 ms_ener_ratio[2]={.5,.5};
274   chgrdata pe,pe_MS;
275   chgrdata *pe_use;
276
277   int ch,gr,mean_bits;
278   int bitsPerFrame;
279
280   int check_ms_stereo;
281   FLOAT8 ms_ratio_next = 0.;
282   FLOAT8 ms_ratio_prev = 0.;
283
284
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));
288   inbuf[0]=inbuf_l;
289   inbuf[1]=inbuf_r;
290
291   check_ms_stereo =  (gfp->mode == JOINT_STEREO);
292   gfc->mode_ext = MPG_MD_LR_LR;
293
294   if (gfc->lame_encode_frame_init==0 )  {
295     gfc->lame_encode_frame_init=1;
296     
297     /* padding method as described in 
298      * "MPEG-Layer3 / Bitstream Syntax and Decoding"
299      * by Martin Sieler, Ralph Sperschneider
300      *
301      * note: there is no padding for the very first frame
302      *
303      * Robert.Hegemann@gmx.de 2000-06-22
304      */
305         
306     gfc->frac_SpF = ((gfp->version+1)*72000L*gfp->brate) % gfp->out_samplerate;
307     gfc->slot_lag  = gfc->frac_SpF;
308     
309     /* check FFT will not use a negative starting offset */
310 #if 576 < FFTOFFSET
311 # error FFTOFFSET greater than 576: FFT uses a negative offset
312 #endif
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)));
319
320     /* prime the MDCT/polyphase filterbank with a short block */
321     { 
322       int i,j;
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) {
327           primebuff0[i]=0;
328           if (gfc->channels_out==2) 
329             primebuff1[i]=0;
330         }else{
331           primebuff0[i]=inbuf[0][j];
332           if (gfc->channels_out==2) 
333             primebuff1[i]=inbuf[1][j];
334           ++j;
335         }
336       }
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;
341         }
342       }
343       mdct_sub48(gfc, primebuff0, primebuff1, xr);
344     }
345     
346     iteration_init(gfp);
347     
348     /*  prepare for ATH auto adjustment:
349      *  we want to decrease the ATH by 12 dB per second
350      */ {
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 */
355     }
356   }
357
358
359   /********************** padding *****************************/
360   switch (gfp->padding_type) {
361   case PAD_NO:
362     gfc->padding = FALSE;
363     break;
364   case PAD_ALL:
365     gfc->padding = TRUE;
366     break;
367   case PAD_ADJUST:
368   default:
369     if (gfp->VBR!=vbr_off) {
370       gfc->padding = FALSE;
371     } else {
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 */
376       }else{
377         /* padding method as described in 
378          * "MPEG-Layer3 / Bitstream Syntax and Decoding"
379          * by Martin Sieler, Ralph Sperschneider
380          *
381          * note: there is no padding for the very first frame
382          *
383          * Robert.Hegemann@gmx.de 2000-06-22
384          */
385
386         gfc->slot_lag -= gfc->frac_SpF;
387         if (gfc->slot_lag < 0) {
388           gfc->slot_lag += gfp->out_samplerate;
389           gfc->padding = TRUE;
390         } else {
391           gfc->padding = FALSE;
392         }
393       } /* reservoir enabled */
394     }
395   }
396
397
398   if (gfc->psymodel) {
399     /* psychoacoustic model
400      * psy model has a 1 granule (576) delay that we must compensate for
401      * (mt 6/99).
402      */
403     int ret;
404     const sample_t *bufp[2];  /* address of beginning of left & right granule */
405     int blocktype[2];
406
407     ms_ratio_prev=gfc->ms_ratio[gfc->mode_gr-1];
408     for (gr=0; gr < gfc->mode_gr ; gr++) {
409
410       for ( ch = 0; ch < gfc->channels_out; ch++ )
411         bufp[ch] = &inbuf[ch][576 + gr*576-FFTOFFSET];
412
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);
418       } else {
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);
423       }
424       if (ret!=0) return -4;
425
426       for ( ch = 0; ch < gfc->channels_out; ch++ )
427         gfc->l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
428
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];
433       }
434
435     }
436   }else{
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;
441       }
442   }
443
444
445
446   /* auto-adjust of ATH, useful for low volume */
447   adjust_ATH( gfp, tot_ener );
448
449
450
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;
458       else
459         cod_info->window_switching_flag = 1;
460     }
461   }
462
463
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]);
472       }
473     }
474   }
475   
476
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 */
481     check_ms_stereo =
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);
484   }
485   
486   /* Here will be selected MS or LR coding of the 2 stereo channels */
487
488   assert (  gfc->mode_ext == MPG_MD_LR_LR );
489   gfc->mode_ext = MPG_MD_LR_LR;
490   
491   if (gfp->force_ms) {
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
498       */
499       
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
504        */
505       FLOAT8  ms_ratio_ave1;
506       FLOAT8  ms_ratio_ave2;
507       FLOAT8  threshold1    = 0.35;
508       FLOAT8  threshold2    = 0.45;
509
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];
515       }else{
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] );
518       }
519       
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);
524               if (thr<0) thr=0;
525               threshold1   *= thr;
526               threshold2   *= thr;
527           }
528       }
529       
530       if ((ms_ratio_ave1 < threshold1  &&  ms_ratio_ave2 < threshold2) || gfc->nsPsy.use) {
531           int  sum_pe_MS = 0;
532           int  sum_pe_LR = 0;
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];
537               }
538           }
539           
540           /* based on PE: M/S coding would not use much more bits than L/R coding */
541           
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;
544       }
545   }
546
547
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]));
565         }
566       }
567     }
568   }
569 #endif
570
571
572
573
574   /* bit and noise allocation */
575   if (MPG_MD_MS_LR == gfc->mode_ext) {
576     masking = &masking_MS;    /* use MS masking */
577     pe_use = &pe_MS;
578   } else {
579     masking = &masking_LR;    /* use LR masking */
580     pe_use = &pe;
581   }
582
583
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,
591     };
592     int i;
593     FLOAT8 f;
594
595     for(i=0;i<18;i++) gfc->nsPsy.pefirbuf[i] = gfc->nsPsy.pefirbuf[i+1];
596
597     i=0;
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];
602         i++;
603       }
604     }
605
606     gfc->nsPsy.pefirbuf[18] = gfc->nsPsy.pefirbuf[18] / i;
607     f = 0;
608     for(i=0;i<19;i++) f += gfc->nsPsy.pefirbuf[i] * fircoef[i];
609
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;
613       }
614     }
615   }
616
617   switch (gfp->VBR){ 
618   default:
619   case vbr_off:
620     iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
621     break;
622   case vbr_mt:
623     VBR_quantize( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
624     break;
625   case vbr_rh:
626   case vbr_mtrh:
627     VBR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
628     break;
629   case vbr_abr:
630     ABR_iteration_loop( gfp,*pe_use,ms_ener_ratio, xr, *masking, l3_enc, scalefac);
631     break;
632   }
633
634   /*  write the frame to the bitstream  */
635   getframebits(gfp, &bitsPerFrame, &mean_bits);
636
637   format_bitstream( gfp, bitsPerFrame, l3_enc, scalefac);
638
639   /* copy mp3 bit buffer into array */
640   mp3count = copy_buffer(gfc,mp3buf,mp3buf_size,1);
641
642
643
644
645   if (gfp->bWriteVbrTag) AddVbrFrame(gfp);
646
647
648 #if defined(HAVE_GTK)
649   /* copy data for MP3 frame analyzer */
650   if (gfp->analysis && gfc->pinfo != NULL) {
651     int j;
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];
657       }
658     }
659     set_frame_pinfo (gfp, xr, *masking, l3_enc, scalefac);
660   }
661 #endif
662   
663   updateStats( gfc );
664
665   return mp3count;
666 }