more horizontal refactoring
[swftools.git] / lib / lame / quantize.c
1 /*
2  * MP3 quantization
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: quantize.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 <math.h>
28 #include <assert.h>
29 #include "util.h"
30 #include "l3side.h"
31 #include "quantize.h"
32 #include "reservoir.h"
33 #include "quantize_pvt.h"
34 #include "lame-analysis.h"
35 #include "vbrquantize.h"
36
37 #ifdef WITH_DMALLOC
38 #include <dmalloc.h>
39 #endif
40
41
42 /************************************************************************
43  *
44  *      init_outer_loop()
45  *  mt 6/99                                    
46  *
47  *  initializes cod_info, scalefac and xrpow
48  *
49  *  returns 0 if all energies in xr are zero, else 1                    
50  *
51  ************************************************************************/
52
53 static int 
54 init_outer_loop(
55     lame_internal_flags *gfc,
56     gr_info *const cod_info, 
57     III_scalefac_t *const scalefac, 
58     const FLOAT8 xr[576], 
59     FLOAT8 xrpow[576] )
60 {
61     FLOAT8 tmp, sum = 0;
62     int i;
63
64     /*  initialize fresh cod_info
65      */
66     cod_info->part2_3_length      = 0;
67     cod_info->big_values          = 0;
68     cod_info->count1              = 0;
69     cod_info->global_gain         = 210;
70     cod_info->scalefac_compress   = 0;
71     /* window_switching_flag was set in psymodel.c? */
72     /* block_type            was set in psymodel.c? */
73     /* mixed_block_flag      would be set in ^      */
74     cod_info->table_select [0]    = 0;
75     cod_info->table_select [1]    = 0;
76     cod_info->table_select [2]    = 0;
77     cod_info->subblock_gain[0]    = 0;
78     cod_info->subblock_gain[1]    = 0;
79     cod_info->subblock_gain[2]    = 0;
80     cod_info->region0_count       = 0;
81     cod_info->region1_count       = 0;
82     cod_info->preflag             = 0;
83     cod_info->scalefac_scale      = 0;
84     cod_info->count1table_select  = 0;
85     cod_info->part2_length        = 0;
86     if (cod_info->block_type == SHORT_TYPE) {
87         cod_info->sfb_lmax        = 0;
88         cod_info->sfb_smin        = 0;
89         if (cod_info->mixed_block_flag) {
90             /*
91              *  MPEG-1:      sfbs 0-7 long block, 3-12 short blocks 
92              *  MPEG-2(.5):  sfbs 0-5 long block, 3-12 short blocks
93              */ 
94             cod_info->sfb_lmax    = gfc->is_mpeg1 ? 8 : 6;
95             cod_info->sfb_smin    = 3;
96         }
97     } else {
98         cod_info->sfb_lmax        = SBPSY_l;
99         cod_info->sfb_smin        = SBPSY_s;
100     }   
101     cod_info->count1bits          = 0;  
102     cod_info->sfb_partition_table = nr_of_sfb_block[0][0];
103     cod_info->slen[0]             = 0;
104     cod_info->slen[1]             = 0;
105     cod_info->slen[2]             = 0;
106     cod_info->slen[3]             = 0;
107
108     /*  fresh scalefactors are all zero
109      */
110     memset(scalefac, 0, sizeof(III_scalefac_t));
111     memset(&gfc->pseudohalf, 0, sizeof(gfc->pseudohalf));
112
113     /*  check if there is some energy we have to quantize
114      *  and calculate xrpow matching our fresh scalefactors
115      */
116     for (i = 0; i < 576; ++i) {
117         tmp = fabs (xr[i]);
118         sum += tmp;
119         xrpow[i] = sqrt (tmp * sqrt(tmp));
120     }
121    /*  return 1 if we have something to quantize, else 0
122     */
123    return sum > (FLOAT8)1E-20;
124 }
125
126
127
128 /************************************************************************
129  *
130  *      bin_search_StepSize()
131  *
132  *  author/date??
133  *
134  *  binary step size search
135  *  used by outer_loop to get a quantizer step size to start with
136  *
137  ************************************************************************/
138
139 typedef enum {
140     BINSEARCH_NONE,
141     BINSEARCH_UP, 
142     BINSEARCH_DOWN
143 } binsearchDirection_t;
144
145 int 
146 bin_search_StepSize(
147           lame_internal_flags * const gfc,
148           gr_info * const cod_info,
149     const int             desired_rate, 
150     const int             start, 
151     const FLOAT8          xrpow [576],
152           int             l3enc [576] ) 
153 {
154     int nBits;
155     int CurrentStep;
156     int flag_GoneOver = 0;
157     int StepSize      = start;
158
159     binsearchDirection_t Direction = BINSEARCH_NONE;
160     assert(gfc->CurrentStep);
161     CurrentStep = gfc->CurrentStep;
162
163     do {
164         cod_info->global_gain = StepSize;
165         nBits = count_bits(gfc,l3enc,xrpow,cod_info);  
166
167         if (CurrentStep == 1) break; /* nothing to adjust anymore */
168     
169         if (flag_GoneOver) CurrentStep /= 2;
170  
171         if (nBits > desired_rate) {  
172             /* increase Quantize_StepSize */
173             if (Direction == BINSEARCH_DOWN && !flag_GoneOver) {
174                 flag_GoneOver = 1;
175                 CurrentStep  /= 2; /* late adjust */
176             }
177             Direction = BINSEARCH_UP;
178             StepSize += CurrentStep;
179             if (StepSize > 255) break;
180         }
181         else if (nBits < desired_rate) {
182             /* decrease Quantize_StepSize */
183             if (Direction == BINSEARCH_UP && !flag_GoneOver) {
184                 flag_GoneOver = 1;
185                 CurrentStep  /= 2; /* late adjust */
186             }
187             Direction = BINSEARCH_DOWN;
188             StepSize -= CurrentStep;
189             if (StepSize < 0) break;
190         }
191         else break; /* nBits == desired_rate;; most unlikely to happen.*/
192     } while (1); /* For-ever, break is adjusted. */
193
194     CurrentStep = start - StepSize;
195     
196     gfc->CurrentStep = CurrentStep/4 != 0 ? 4 : 2;
197
198     return nBits;
199 }
200
201
202
203
204 /*************************************************************************** 
205  *
206  *         inner_loop ()                                                     
207  *
208  *  author/date??
209  *
210  *  The code selects the best global gain for a particular set of scalefacs 
211  *
212  ***************************************************************************/ 
213
214 int 
215 inner_loop(
216           lame_internal_flags * const gfc,
217           gr_info * const cod_info,
218     const int             max_bits,
219     const FLOAT8          xrpow [576],
220           int             l3enc [576] )
221 {
222     int bits;
223     
224     assert(max_bits >= 0);
225
226     /*  scalefactors may have changed, so count bits
227      */
228     bits=count_bits(gfc,l3enc,xrpow,cod_info);
229
230     /*  increase quantizer stepsize until needed bits are below maximum
231      */
232     while (bits > max_bits) {
233         cod_info->global_gain++;
234         bits = count_bits (gfc, l3enc, xrpow, cod_info);
235     } 
236
237     return bits;
238 }
239
240
241
242 /*************************************************************************
243  *
244  *      loop_break()                                               
245  *
246  *  author/date??
247  *
248  *  Function: Returns zero if there is a scalefac which has not been
249  *            amplified. Otherwise it returns one. 
250  *
251  *************************************************************************/
252
253 inline 
254 static int
255 loop_break( 
256     const gr_info        * const cod_info,
257     const III_scalefac_t * const scalefac ) 
258 {
259     int i, sfb;
260
261     for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++)
262         if (scalefac->l[sfb] == 0)
263             return 0;
264
265     for (sfb = cod_info->sfb_smin; sfb < SBPSY_s; sfb++)
266         for (i = 0; i < 3; i++) 
267             if (scalefac->s[sfb][i] == 0 && cod_info->subblock_gain[i] == 0)
268                 return 0;
269
270     return 1;
271 }
272
273
274
275
276 /*************************************************************************
277  *
278  *      quant_compare()                                               
279  *
280  *  author/date??
281  *
282  *  several different codes to decide which quantization is better
283  *
284  *************************************************************************/
285
286 inline 
287 static int 
288 quant_compare(
289     const int                       experimentalX,
290           lame_internal_flags * const gfc,
291     const calc_noise_result * const best,
292     const calc_noise_result   * const calc,
293         const int                         block_type )
294 {
295     /*
296        noise is given in decibels (dB) relative to masking thesholds.
297
298        over_noise:  ??? (the previous comment is fully wrong)
299        tot_noise:   ??? (the previous comment is fully wrong)
300        max_noise:   max quantization noise 
301
302      */
303     int better;
304
305     switch (experimentalX) {
306         default:
307         case 0: 
308             better = calc->over_count  < best->over_count
309                ||  ( calc->over_count == best->over_count  &&
310                      calc->over_noise  < best->over_noise )
311                ||  ( calc->over_count == best->over_count  &&
312                      calc->over_noise == best->over_noise  &&
313                      calc->tot_noise   < best->tot_noise  ); 
314             break;
315         case 1: 
316             better = calc->max_noise < best->max_noise; 
317             break;
318         case 2: 
319             better = calc->tot_noise < best->tot_noise; 
320             break;
321         case 3: 
322                 better = ( calc->tot_noise < (gfc->presetTune.use &&
323                                       block_type != NORM_TYPE ? (best->tot_noise - gfc->presetTune.quantcomp_adjust_rh_tot)
324                                                           :  best->tot_noise ) &&
325                    calc->max_noise < (gfc->presetTune.use &&
326                                       block_type != NORM_TYPE ? (best->max_noise - gfc->presetTune.quantcomp_adjust_rh_max)
327                                                           :  best->max_noise ));
328             break;
329         case 4: 
330             better = ( calc->max_noise <= 0  &&
331                        best->max_noise >  2 )
332                  ||  ( calc->max_noise <= 0  &&
333                        best->max_noise <  0  &&
334                        best->max_noise >  calc->max_noise-2  &&
335                        calc->tot_noise <  best->tot_noise )
336                  ||  ( calc->max_noise <= 0  &&
337                        best->max_noise >  0  &&
338                        best->max_noise >  calc->max_noise-2  &&
339                        calc->tot_noise <  best->tot_noise+best->over_noise )
340                  ||  ( calc->max_noise >  0  &&
341                        best->max_noise > -0.5  &&
342                        best->max_noise >  calc->max_noise-1  &&
343                        calc->tot_noise+calc->over_noise < best->tot_noise+best->over_noise )
344                  ||  ( calc->max_noise >  0  &&
345                        best->max_noise > -1  &&
346                        best->max_noise >  calc->max_noise-1.5  &&
347                        calc->tot_noise+calc->over_noise+calc->over_noise < best->tot_noise+best->over_noise+best->over_noise );
348             break;
349         case 5: 
350             better =   calc->over_noise  < best->over_noise
351                  ||  ( calc->over_noise == best->over_noise  &&
352                        calc->tot_noise   < best->tot_noise ); 
353             break;
354         case 6: 
355             better =   calc->over_noise  < best->over_noise
356                  ||  ( calc->over_noise == best->over_noise  &&
357                      ( calc->max_noise   < best->max_noise  
358                      ||  ( calc->max_noise  == best->max_noise  &&
359                            calc->tot_noise  <= best->tot_noise )
360                       )); 
361             break;
362         case 7: 
363             better =   calc->over_count < best->over_count
364                    ||  calc->over_noise < best->over_noise; 
365             break;
366         case 8: 
367             better =   calc->klemm_noise < best->klemm_noise;
368             break;
369     }   
370
371     return better;
372 }
373
374
375
376 /*************************************************************************
377  *
378  *          amp_scalefac_bands() 
379  *
380  *  author/date??
381  *        
382  *  Amplify the scalefactor bands that violate the masking threshold.
383  *  See ISO 11172-3 Section C.1.5.4.3.5
384  * 
385  *  distort[] = noise/masking
386  *  distort[] > 1   ==> noise is not masked
387  *  distort[] < 1   ==> noise is masked
388  *  max_dist = maximum value of distort[]
389  *  
390  *  Three algorithms:
391  *  noise_shaping_amp
392  *        0             Amplify all bands with distort[]>1.
393  *
394  *        1             Amplify all bands with distort[] >= max_dist^(.5);
395  *                     ( 50% in the db scale)
396  *
397  *        2             Amplify first band with distort[] >= max_dist;
398  *                       
399  *
400  *  For algorithms 0 and 1, if max_dist < 1, then amplify all bands 
401  *  with distort[] >= .95*max_dist.  This is to make sure we always
402  *  amplify at least one band.  
403  * 
404  *
405  *************************************************************************/
406 static void 
407 amp_scalefac_bands(
408     lame_global_flags *gfp,
409     const gr_info  *const cod_info, 
410     III_scalefac_t *const scalefac,
411     III_psy_xmin *distort,
412     FLOAT8 xrpow[576] )
413 {
414   lame_internal_flags *gfc=gfp->internal_flags;
415   int start, end, l,i,j,sfb;
416   FLOAT8 ifqstep34, trigger;
417
418   if (cod_info->scalefac_scale == 0) {
419     ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5)*/
420   } else {
421     ifqstep34 = 1.68179283050742922612;  /* 2**(.75*1) */
422   }
423
424   /* compute maximum value of distort[]  */
425   trigger = 0;
426   for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {
427     if (trigger < distort->l[sfb])
428         trigger = distort->l[sfb];
429   }
430   for (sfb = cod_info->sfb_smin; sfb < SBPSY_s; sfb++) {
431     for (i = 0; i < 3; i++ ) {
432       if (trigger < distort->s[sfb][i])
433           trigger = distort->s[sfb][i];
434     }
435   }
436
437   switch (gfc->noise_shaping_amp) {
438
439   case 3:
440   case 2:
441     /* amplify exactly 1 band */
442     //trigger = distort_thresh;
443     break;
444
445   case 1:
446     /* amplify bands within 50% of max (on db scale) */
447     if (trigger>1.0)
448         trigger = pow(trigger, .5);
449     else
450       trigger *= .95;
451     break;
452
453   case 0:
454   default:
455     /* ISO algorithm.  amplify all bands with distort>1 */
456     if (trigger>1.0)
457         trigger=1.0;
458     else
459         trigger *= .95;
460     break;
461   }
462
463   for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++ ) {
464     start = gfc->scalefac_band.l[sfb];
465     end   = gfc->scalefac_band.l[sfb+1];
466     if (distort->l[sfb]>=trigger  ) {
467       if (gfc->noise_shaping_amp==3) {
468         if (gfc->pseudohalf.l[sfb]) {
469           gfc->pseudohalf.l[sfb] = 0;
470           goto done;
471         }
472         gfc->pseudohalf.l[sfb] = 1;
473       }
474       scalefac->l[sfb]++;
475       for ( l = start; l < end; l++ )
476         xrpow[l] *= ifqstep34;
477       if (gfc->noise_shaping_amp==2
478           ||gfc->noise_shaping_amp==3) goto done;
479     }
480   }
481   
482   for ( j=0,sfb = cod_info->sfb_smin; sfb < SBPSY_s; sfb++ ) {
483     start = gfc->scalefac_band.s[sfb];
484     end   = gfc->scalefac_band.s[sfb+1];
485     for ( i = 0; i < 3; i++ ) {
486       int j2 = j;
487       if ( distort->s[sfb][i]>=trigger) {
488         if (gfc->noise_shaping_amp==3) {
489           if (gfc->pseudohalf.s[sfb][i]) {
490             gfc->pseudohalf.s[sfb][i] = 0;
491             goto done;
492           }
493           gfc->pseudohalf.s[sfb][i] = 1;
494         }
495         scalefac->s[sfb][i]++;
496         for (l = start; l < end; l++) 
497           xrpow[j2++] *= ifqstep34;
498         if (gfc->noise_shaping_amp==2
499             ||gfc->noise_shaping_amp==3) goto done;
500       }
501       j += end-start;
502     }
503   }
504  done:
505  return;
506 }
507
508 /*************************************************************************
509  *
510  *      inc_scalefac_scale()
511  *
512  *  Takehiro Tominaga 2000-xx-xx
513  *
514  *  turns on scalefac scale and adjusts scalefactors
515  *
516  *************************************************************************/
517  
518 static void
519 inc_scalefac_scale (
520     const lame_internal_flags        * const gfc, 
521           gr_info        * const cod_info, 
522           III_scalefac_t * const scalefac,
523           FLOAT8                 xrpow[576] )
524 {
525     int start, end, l,i,j;
526     int sfb;
527     const FLOAT8 ifqstep34 = 1.29683955465100964055;
528
529     for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {
530         int s = scalefac->l[sfb] + (cod_info->preflag ? pretab[sfb] : 0);
531         if (s & 1) {
532             s++;
533             start = gfc->scalefac_band.l[sfb];
534             end   = gfc->scalefac_band.l[sfb+1];
535             for (l = start; l < end; l++) 
536                 xrpow[l] *= ifqstep34;
537         }
538         scalefac->l[sfb]  = s >> 1;
539         cod_info->preflag = 0;
540     }
541
542     for (j = 0, sfb = cod_info->sfb_smin; sfb < SBPSY_s; sfb++) {
543     start = gfc->scalefac_band.s[sfb];
544     end   = gfc->scalefac_band.s[sfb+1];
545     for (i = 0; i < 3; i++) {
546         int j2 = j;
547         if (scalefac->s[sfb][i] & 1) {
548         scalefac->s[sfb][i]++;
549         for (l = start; l < end; l++) 
550             xrpow[j2++] *= ifqstep34;
551         }
552         scalefac->s[sfb][i] >>= 1;
553         j += end-start;
554     }
555     }
556     cod_info->scalefac_scale = 1;
557 }
558
559
560
561 /*************************************************************************
562  *
563  *      inc_subblock_gain()
564  *
565  *  Takehiro Tominaga 2000-xx-xx
566  *
567  *  increases the subblock gain and adjusts scalefactors
568  *
569  *************************************************************************/
570  
571 static int 
572 inc_subblock_gain (
573     const lame_internal_flags        * const gfc,
574           gr_info        * const cod_info,
575           III_scalefac_t * const scalefac,
576           FLOAT8                 xrpow[576] )
577 {
578     int window;
579
580     for (window = 0; window < 3; window++) {
581         int s1, s2, l;
582         int sfb;
583         s1 = s2 = 0;
584
585         for (sfb = cod_info->sfb_smin; sfb < 6; sfb++) {
586             if (s1 < scalefac->s[sfb][window])
587             s1 = scalefac->s[sfb][window];
588         }
589         for (; sfb < SBPSY_s; sfb++) {
590             if (s2 < scalefac->s[sfb][window])
591             s2 = scalefac->s[sfb][window];
592         }
593
594         if (s1 < 16 && s2 < 8)
595             continue;
596
597         if (cod_info->subblock_gain[window] >= 7)
598             return 1;
599
600         /* even though there is no scalefactor for sfb12
601          * subblock gain affects upper frequencies too, that's why
602          * we have to go up to SBMAX_s
603          */
604         cod_info->subblock_gain[window]++;
605         for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
606             int i, width;
607             int s = scalefac->s[sfb][window];
608             FLOAT8 amp;
609
610             if (s < 0)
611                 continue;
612             s = s - (4 >> cod_info->scalefac_scale);
613             if (s >= 0) {
614                 scalefac->s[sfb][window] = s;
615                 continue;
616             }
617
618             scalefac->s[sfb][window] = 0;
619             width = gfc->scalefac_band.s[sfb] - gfc->scalefac_band.s[sfb+1];
620             i = gfc->scalefac_band.s[sfb] * 3 + width * window;
621             amp = IPOW20(210 + (s << (cod_info->scalefac_scale + 1)));
622             for (l = 0; l < width; l++) {
623                 xrpow[i++] *= amp;
624             }
625         }
626     }
627     return 0;
628 }
629
630
631
632 /********************************************************************
633  *
634  *      balance_noise()
635  *
636  *  Takehiro Tominaga /date??
637  *  Robert Hegemann 2000-09-06: made a function of it
638  *
639  *  amplifies scalefactor bands, 
640  *   - if all are already amplified returns 0
641  *   - if some bands are amplified too much:
642  *      * try to increase scalefac_scale
643  *      * if already scalefac_scale was set
644  *          try on short blocks to increase subblock gain
645  *
646  ********************************************************************/
647 inline
648 static int 
649 balance_noise (
650     lame_global_flags  *const gfp,
651     gr_info        * const cod_info,
652     III_scalefac_t * const scalefac, 
653     III_psy_xmin           *distort,
654     FLOAT8                 xrpow[576] )
655 {
656     lame_internal_flags *const gfc = (lame_internal_flags *)gfp->internal_flags;
657     int status;
658     
659     amp_scalefac_bands ( gfp, cod_info, scalefac, distort, xrpow);
660     
661     /* check to make sure we have not amplified too much 
662      * loop_break returns 0 if there is an unamplified scalefac
663      * scale_bitcount returns 0 if no scalefactors are too large
664      */
665     
666     status = loop_break (cod_info, scalefac);
667     
668     if (status) 
669         return 0; /* all bands amplified */
670     
671     /* not all scalefactors have been amplified.  so these 
672      * scalefacs are possibly valid.  encode them: 
673      */
674     if (gfc->is_mpeg1)
675         status = scale_bitcount (scalefac, cod_info);
676     else 
677         status = scale_bitcount_lsf (gfc, scalefac, cod_info);
678     
679     if (!status) 
680         return 1; /* amplified some bands not exceeding limits */
681     
682     /*  some scalefactors are too large.
683      *  lets try setting scalefac_scale=1 
684      */
685     if ((gfc->noise_shaping > 1) && (!(gfc->presetTune.use &&
686                                       gfc->ATH->adjust < gfc->presetTune.athadjust_switch_level))) {
687         memset(&gfc->pseudohalf, 0, sizeof(gfc->pseudohalf));
688         if (!cod_info->scalefac_scale) {
689             inc_scalefac_scale (gfc, cod_info, scalefac, xrpow);
690             status = 0;
691         } else {
692             if (cod_info->block_type == SHORT_TYPE ) {
693                 status = inc_subblock_gain (gfc, cod_info, scalefac, xrpow)
694                     || loop_break (cod_info, scalefac);
695             }
696         }
697     }
698
699     if (!status) {
700         if (gfc->is_mpeg1 == 1) 
701             status = scale_bitcount (scalefac, cod_info);
702         else 
703             status = scale_bitcount_lsf (gfc, scalefac, cod_info);
704     }
705     return !status;
706 }
707
708
709
710 /************************************************************************
711  *
712  *  outer_loop ()                                                       
713  *
714  *  Function: The outer iteration loop controls the masking conditions  
715  *  of all scalefactorbands. It computes the best scalefac and          
716  *  global gain. This module calls the inner iteration loop             
717  * 
718  *  mt 5/99 completely rewritten to allow for bit reservoir control,   
719  *  mid/side channels with L/R or mid/side masking thresholds, 
720  *  and chooses best quantization instead of last quantization when 
721  *  no distortion free quantization can be found.  
722  *  
723  *  added VBR support mt 5/99
724  *
725  *  some code shuffle rh 9/00
726  ************************************************************************/
727
728 static int 
729 outer_loop (
730    lame_global_flags *gfp,
731           gr_info        * const cod_info,
732     const FLOAT8                 xr[576],   /* magnitudes of spectral values */
733     const III_psy_xmin   * const l3_xmin,   /* allowed distortion of the scalefactor */
734           III_scalefac_t * const scalefac,  /* scalefactors */
735           FLOAT8                 xrpow[576], /* coloured magnitudes of spectral values */
736           int                    l3enc[576], /* vector of quantized values ix(0..575) */
737     const int                    ch, 
738     const int                    targ_bits )  /* maximum allowed bits */
739 {
740     lame_internal_flags *gfc=gfp->internal_flags;
741     III_scalefac_t save_scalefac;
742     gr_info save_cod_info;
743     FLOAT8 save_xrpow[576];
744     III_psy_xmin   distort;
745     calc_noise_result noise_info;
746     calc_noise_result best_noise_info;
747     int l3_enc_w[576]; 
748     int iteration = 0;
749     int bits_found;
750     int huff_bits;
751     int real_bits;
752     int better;
753     int over;
754
755     int copy = 0;
756     int age = 0;
757
758     noise_info.over_count = 100;
759     noise_info.max_noise  = 0;
760     noise_info.tot_noise  = 0;
761     noise_info.over_noise = 0;
762     
763     best_noise_info.over_count = 100;
764
765     bits_found = bin_search_StepSize (gfc, cod_info, targ_bits, 
766                                       gfc->OldValue[ch], xrpow, l3_enc_w);
767     gfc->OldValue[ch] = cod_info->global_gain;
768
769     /* BEGIN MAIN LOOP */
770     do {
771         iteration ++;
772
773         /* inner_loop starts with the initial quantization step computed above
774          * and slowly increases until the bits < huff_bits.
775          * Thus it is important not to start with too large of an inital
776          * quantization step.  Too small is ok, but inner_loop will take longer 
777          */
778         huff_bits = targ_bits - cod_info->part2_length;
779         if (huff_bits < 0) {
780             assert(iteration != 1);
781             /*  scale factors too large, not enough bits. 
782              *  use previous quantizaton */
783             break;
784         }
785         /*  if this is the first iteration, 
786          *  see if we can reuse the quantization computed in 
787          *  bin_search_StepSize above */
788
789         if (iteration == 1) {
790             if (bits_found > huff_bits) {
791                 cod_info->global_gain++;
792                 real_bits = inner_loop (gfc, cod_info, huff_bits, xrpow, 
793                                         l3_enc_w);
794             } else {
795                 real_bits = bits_found;
796             }
797         } else {
798             real_bits = inner_loop (gfc, cod_info, huff_bits, xrpow,
799                                     l3_enc_w);
800         }
801
802         cod_info->part2_3_length = real_bits;
803
804         /* compute the distortion in this quantization */
805         if (gfc->noise_shaping) 
806             /* coefficients and thresholds both l/r (or both mid/side) */
807             over = calc_noise (gfc, xr, l3_enc_w, cod_info, l3_xmin, 
808                                scalefac, &distort, &noise_info);
809         else {
810             /* fast mode, no noise shaping, we are ready */
811             best_noise_info = noise_info;
812             copy = 0;
813             memcpy(l3enc, l3_enc_w, sizeof(int)*576);
814             break;
815         }
816
817
818         /* check if this quantization is better
819          * than our saved quantization */
820         if (iteration == 1) /* the first iteration is always better */
821             better = 1;
822         else
823             better = quant_compare ((gfc->presetTune.use ? gfc->presetTune.quantcomp_current
824                                                          : gfp->experimentalX), 
825                                      gfc, &best_noise_info, &noise_info, cod_info->block_type);
826         
827         /* save data so we can restore this quantization later */    
828         if (better) {
829             copy = 0;
830             best_noise_info = noise_info;
831             memcpy(l3enc, l3_enc_w, sizeof(int)*576);
832             age = 0;
833         }
834         else
835             age ++;
836
837
838         /******************************************************************/
839         /* stopping criterion */
840         /******************************************************************/
841         /* if no bands with distortion and -X0, we are done */
842         if (0==gfc->noise_shaping_stop && 
843             0==gfp->experimentalX &&
844             (over == 0 || best_noise_info.over_count == 0) )
845             break;
846         /* Otherwise, allow up to 3 unsuccesful tries in serial, then stop 
847          * if our best quantization so far had no distorted bands. This
848          * gives us more possibilities for different quant_compare modes.
849          * Much more than 3 makes not a big difference, it is only slower.
850          */
851         if (age > 3 && best_noise_info.over_count == 0) 
852             break;    
853     
854         /* Check if the last scalefactor band is distorted.
855          * in VBR mode we can't get rid of the distortion, so quit now
856          * and VBR mode will try again with more bits.  
857          * (makes a 10% speed increase, the files I tested were
858          * binary identical, 2000/05/20 Robert.Hegemann@gmx.de)
859          * distort[] > 1 means noise > allowed noise
860          */
861         if (gfc->sfb21_extra) {
862             if (cod_info->block_type == SHORT_TYPE) {
863                 if (distort.s[SBMAX_s-1][0] > 1 ||
864                     distort.s[SBMAX_s-1][1] > 1 ||
865                     distort.s[SBMAX_s-1][2] > 1) break;
866             } else {
867                 if (distort.l[SBMAX_l-1] > 1) break;
868             }
869         }
870
871         /* save data so we can restore this quantization later */    
872         if (better) {
873             copy = 1;
874             save_scalefac = *scalefac;
875             save_cod_info = *cod_info;
876             if (gfp->VBR == vbr_rh || gfp->VBR == vbr_mtrh) {
877                 /* store for later reuse */
878                 memcpy(save_xrpow, xrpow, sizeof(FLOAT8)*576);
879             }
880         }
881             
882         if (balance_noise (gfp, cod_info, scalefac, &distort, xrpow) == 0) 
883             break;
884     }
885     while (1); /* main iteration loop, breaks adjusted */
886     
887     /*  finish up
888      */
889     if (copy) {
890         *cod_info = save_cod_info;
891         *scalefac = save_scalefac;
892         if (gfp->VBR == vbr_rh || gfp->VBR == vbr_mtrh)
893             /* restore for reuse on next try */
894             memcpy(xrpow, save_xrpow, sizeof(FLOAT8)*576);
895     }
896     cod_info->part2_3_length += cod_info->part2_length;
897     
898     assert (cod_info->global_gain < 256);
899     
900     return best_noise_info.over_count;
901 }
902
903
904
905
906 /************************************************************************
907  *
908  *      iteration_finish()                                                    
909  *
910  *  Robert Hegemann 2000-09-06
911  *
912  *  update reservoir status after FINAL quantization/bitrate 
913  *
914  *  rh 2000-09-06: it will not work with CBR due to the bitstream formatter
915  *            you will get "Error: MAX_HEADER_BUF too small in bitstream.c"
916  *
917  ************************************************************************/
918
919 static void 
920 iteration_finish (
921     lame_internal_flags *gfc,
922     FLOAT8          xr      [2][2][576],
923     int             l3_enc  [2][2][576],
924     III_scalefac_t  scalefac[2][2],
925     const int       mean_bits )
926 {
927     III_side_info_t *l3_side = &gfc->l3_side;
928     int gr, ch, i;
929     
930     for (gr = 0; gr < gfc->mode_gr; gr++) {
931         for (ch = 0; ch < gfc->channels_out; ch++) {
932             gr_info *cod_info = &l3_side->gr[gr].ch[ch].tt;
933
934             /*  try some better scalefac storage
935              */
936             best_scalefac_store (gfc, gr, ch, l3_enc, l3_side, scalefac);
937             
938             /*  best huffman_divide may save some bits too
939              */
940             if (gfc->use_best_huffman == 1) 
941                 best_huffman_divide (gfc, cod_info, l3_enc[gr][ch]);
942             
943             /*  update reservoir status after FINAL quantization/bitrate
944              */
945             ResvAdjust (gfc, cod_info, l3_side, mean_bits);
946       
947             /*  set the sign of l3_enc from the sign of xr
948              */
949             for (i = 0; i < 576; i++) {
950                 if (xr[gr][ch][i] < 0) l3_enc[gr][ch][i] *= -1; 
951             }
952         } /* for ch */
953     }    /* for gr */
954     
955     ResvFrameEnd (gfc, l3_side, mean_bits);
956 }
957
958
959
960 /*********************************************************************
961  *
962  *      VBR_encode_granule()
963  *
964  *  2000-09-04 Robert Hegemann
965  *
966  *********************************************************************/
967  
968 static void
969 VBR_encode_granule (
970           lame_global_flags *gfp,
971           gr_info        * const cod_info,
972           FLOAT8                 xr[576],     /* magnitudes of spectral values */
973     const III_psy_xmin   * const l3_xmin,     /* allowed distortion of the scalefactor */
974           III_scalefac_t * const scalefac,    /* scalefactors */
975           FLOAT8                 xrpow[576],  /* coloured magnitudes of spectral values */
976           int                    l3_enc[576], /* vector of quantized values ix(0..575) */
977     const int                    ch, 
978           int                    min_bits, 
979           int                    max_bits )
980 {
981     lame_internal_flags *gfc=gfp->internal_flags;
982     gr_info         bst_cod_info;
983     III_scalefac_t  bst_scalefac;
984     FLOAT8          bst_xrpow [576]; 
985     int             bst_l3_enc[576];
986     int Max_bits  = max_bits;
987     int real_bits = max_bits+1;
988     int this_bits = (max_bits+min_bits)/2;
989     int dbits, over, found = 0;
990     int sfb21_extra = gfc->sfb21_extra;
991
992     assert(Max_bits <= MAX_BITS);
993
994     /*  search within round about 40 bits of optimal
995      */
996     do {
997         assert(this_bits >= min_bits);
998         assert(this_bits <= max_bits);
999         assert(min_bits <= max_bits);
1000
1001         if (this_bits > Max_bits-42) 
1002             gfc->sfb21_extra = 0;
1003         else
1004             gfc->sfb21_extra = sfb21_extra;
1005
1006         over = outer_loop ( gfp, cod_info, xr, l3_xmin, scalefac,
1007                             xrpow, l3_enc, ch, this_bits );
1008
1009         /*  is quantization as good as we are looking for ?
1010          *  in this case: is no scalefactor band distorted?
1011          */
1012         if (over <= 0) {
1013             found = 1;
1014             /*  now we know it can be done with "real_bits"
1015              *  and maybe we can skip some iterations
1016              */
1017             real_bits = cod_info->part2_3_length;
1018
1019             /*  store best quantization so far
1020              */
1021             bst_cod_info = *cod_info;
1022             bst_scalefac = *scalefac;
1023             memcpy(bst_xrpow, xrpow, sizeof(FLOAT8)*576);
1024             memcpy(bst_l3_enc, l3_enc, sizeof(int)*576);
1025
1026             /*  try with fewer bits
1027              */
1028             max_bits  = real_bits-32;
1029             dbits     = max_bits-min_bits;
1030             this_bits = (max_bits+min_bits)/2;
1031         } 
1032         else {
1033             /*  try with more bits
1034              */
1035             min_bits  = this_bits+32;
1036             dbits     = max_bits-min_bits;
1037             this_bits = (max_bits+min_bits)/2;
1038             
1039             if (found) {
1040                 found = 2;
1041                 /*  start again with best quantization so far
1042                  */
1043                 *cod_info = bst_cod_info;
1044                 *scalefac = bst_scalefac;
1045                 memcpy(xrpow, bst_xrpow, sizeof(FLOAT8)*576);
1046             }
1047         }
1048     } while (dbits>12);
1049
1050     gfc->sfb21_extra = sfb21_extra;
1051
1052     /*  found=0 => nothing found, use last one
1053      *  found=1 => we just found the best and left the loop
1054      *  found=2 => we restored a good one and have now l3_enc to restore too
1055      */
1056     if (found==2) {
1057         memcpy(l3_enc, bst_l3_enc, sizeof(int)*576);
1058     }
1059     assert(cod_info->part2_3_length <= Max_bits);
1060
1061 }
1062
1063
1064
1065 /************************************************************************
1066  *
1067  *      get_framebits()   
1068  *
1069  *  Robert Hegemann 2000-09-05
1070  *
1071  *  calculates
1072  *  * how many bits are available for analog silent granules
1073  *  * how many bits to use for the lowest allowed bitrate
1074  *  * how many bits each bitrate would provide
1075  *
1076  ************************************************************************/
1077
1078 static void 
1079 get_framebits (
1080     lame_global_flags *gfp,
1081     int     * const analog_mean_bits,
1082     int     * const min_mean_bits,
1083     int             frameBits[15] )
1084 {
1085     lame_internal_flags *gfc=gfp->internal_flags;
1086     int bitsPerFrame, mean_bits, i;
1087     III_side_info_t *l3_side = &gfc->l3_side;
1088     
1089     /*  always use at least this many bits per granule per channel 
1090      *  unless we detect analog silence, see below 
1091      */
1092     gfc->bitrate_index = gfc->VBR_min_bitrate;
1093     getframebits (gfp, &bitsPerFrame, &mean_bits);
1094     *min_mean_bits = mean_bits / gfc->channels_out;
1095
1096     /*  bits for analog silence 
1097      */
1098     gfc->bitrate_index = 1;
1099     getframebits (gfp, &bitsPerFrame, &mean_bits);
1100     *analog_mean_bits = mean_bits / gfc->channels_out;
1101
1102     for (i = 1; i <= gfc->VBR_max_bitrate; i++) {
1103         gfc->bitrate_index = i;
1104         getframebits (gfp, &bitsPerFrame, &mean_bits);
1105         frameBits[i] = ResvFrameBegin (gfp, l3_side, mean_bits, bitsPerFrame);
1106     }
1107 }
1108
1109
1110
1111 /************************************************************************
1112  *
1113  *      calc_min_bits()   
1114  *
1115  *  Robert Hegemann 2000-09-04
1116  *
1117  *  determine minimal bit skeleton
1118  *
1119  ************************************************************************/
1120 inline
1121 static int 
1122 calc_min_bits (
1123     lame_global_flags *gfp,
1124     const gr_info * const cod_info,
1125     const int             pe,
1126     const FLOAT8          ms_ener_ratio, 
1127     const int             bands,    
1128     const int             mch_bits,
1129     const int             analog_mean_bits,
1130     const int             min_mean_bits,
1131     const int             analog_silence,
1132     const int             ch )
1133 {
1134     lame_internal_flags *gfc=gfp->internal_flags;
1135     int min_bits, min_pe_bits;
1136     
1137     if (gfc->nsPsy.use) return 126;
1138                     /*  changed minimum from 1 to 126 bits
1139                      *  the iteration loops require a minimum of bits
1140                      *  for each granule to start with; robert 2001-07-02 */
1141
1142     /*  base amount of minimum bits
1143      */
1144     min_bits = Max (126, min_mean_bits);
1145
1146     if (gfc->mode_ext == MPG_MD_MS_LR && ch == 1)  
1147         min_bits = Max (min_bits, mch_bits/5);
1148
1149     /*  bit skeleton based on PE
1150      */
1151     if (cod_info->block_type == SHORT_TYPE) 
1152         /*  if LAME switches to short blocks then pe is
1153          *  >= 1000 on medium surge
1154          *  >= 3000 on big surge
1155          */
1156         min_pe_bits = (pe-350) * bands/39;
1157     else 
1158         min_pe_bits = (pe-350) * bands/22;
1159     
1160     if (gfc->mode_ext == MPG_MD_MS_LR && ch == 1) {
1161         /*  side channel will use a lower bit skeleton based on PE
1162          */ 
1163         FLOAT8 fac  = .33 * (.5 - ms_ener_ratio) / .5;
1164         min_pe_bits = (int)(min_pe_bits * ((1-fac)/(1+fac)));
1165     }
1166     min_pe_bits = Min (min_pe_bits, (1820 * gfp->out_samplerate / 44100));
1167
1168     /*  determine final minimum bits
1169      */
1170     if (analog_silence && !gfp->VBR_hard_min) 
1171         min_bits = analog_mean_bits;
1172     else 
1173         min_bits = Max (min_bits, min_pe_bits);
1174     
1175     return min_bits;
1176 }
1177
1178
1179
1180 /*********************************************************************
1181  *
1182  *      VBR_prepare()
1183  *
1184  *  2000-09-04 Robert Hegemann
1185  *
1186  *  * converts LR to MS coding when necessary 
1187  *  * calculates allowed/adjusted quantization noise amounts
1188  *  * detects analog silent frames
1189  *
1190  *  some remarks:
1191  *  - lower masking depending on Quality setting
1192  *  - quality control together with adjusted ATH MDCT scaling
1193  *    on lower quality setting allocate more noise from
1194  *    ATH masking, and on higher quality setting allocate
1195  *    less noise from ATH masking.
1196  *  - experiments show that going more than 2dB over GPSYCHO's
1197  *    limits ends up in very annoying artefacts
1198  *
1199  *********************************************************************/
1200
1201 /* RH: this one needs to be overhauled sometime */
1202  
1203 static int 
1204 VBR_prepare (
1205           lame_global_flags *gfp,
1206           FLOAT8          pe            [2][2],
1207           FLOAT8          ms_ener_ratio [2], 
1208           FLOAT8          xr            [2][2][576],
1209           III_psy_ratio   ratio         [2][2], 
1210           III_psy_xmin    l3_xmin       [2][2],
1211           int             frameBits     [16],
1212           int            *analog_mean_bits,
1213           int            *min_mean_bits,
1214           int             min_bits      [2][2],
1215           int             max_bits      [2][2],
1216           int             bands         [2][2] )
1217 {
1218     lame_internal_flags *gfc=gfp->internal_flags;
1219     
1220     
1221     FLOAT8  masking_lower_db, adjust = 0.0;
1222     int     gr, ch;
1223     int     analog_silence = 1;
1224     int     bpf, avg, mxb, bits = 0;
1225   
1226     gfc->bitrate_index = gfc->VBR_max_bitrate;
1227     getframebits (gfp, &bpf, &avg);
1228     bpf = ResvFrameBegin (gfp, &gfc->l3_side, avg, bpf );
1229     avg = (bpf - 8*gfc->sideinfo_len) / gfc->mode_gr;
1230
1231     get_framebits (gfp, analog_mean_bits, min_mean_bits, frameBits);
1232     
1233     for (gr = 0; gr < gfc->mode_gr; gr++) {
1234         mxb = on_pe (gfp, pe, &gfc->l3_side, max_bits[gr], avg, gr);
1235         if (gfc->mode_ext == MPG_MD_MS_LR) {
1236             ms_convert (xr[gr], xr[gr]); 
1237             reduce_side (max_bits[gr], ms_ener_ratio[gr], avg, mxb);
1238         }
1239         for (ch = 0; ch < gfc->channels_out; ++ch) {
1240             gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
1241       
1242             if (gfc->nsPsy.use && gfp->VBR == vbr_rh) {
1243             if (cod_info->block_type == NORM_TYPE) 
1244                 adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05;
1245             else 
1246                 adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14;
1247             }
1248             masking_lower_db   = gfc->VBR->mask_adjust - adjust; 
1249             gfc->masking_lower = pow (10.0, masking_lower_db * 0.1);
1250       
1251             bands[gr][ch] = calc_xmin (gfp, xr[gr][ch], ratio[gr]+ch, 
1252                                        cod_info, l3_xmin[gr]+ch);
1253             if (bands[gr][ch]) 
1254                 analog_silence = 0;
1255
1256             min_bits[gr][ch] = calc_min_bits (gfp, cod_info, (int)pe[gr][ch],
1257                                       ms_ener_ratio[gr], bands[gr][ch],
1258                                       0, *analog_mean_bits, 
1259                                       *min_mean_bits, analog_silence, ch);
1260       
1261             bits += max_bits[gr][ch];
1262         }
1263     }
1264     for (gr = 0; gr < gfc->mode_gr; gr++) {
1265         for (ch = 0; ch < gfc->channels_out; ch++) {            
1266             if (bits > frameBits[gfc->VBR_max_bitrate]) {
1267                 max_bits[gr][ch] *= frameBits[gfc->VBR_max_bitrate];
1268                 max_bits[gr][ch] /= bits;
1269             }
1270             if (min_bits[gr][ch] > max_bits[gr][ch]) 
1271                 min_bits[gr][ch] = max_bits[gr][ch];
1272             
1273         } /* for ch */
1274     }  /* for gr */
1275     
1276     *min_mean_bits = Max(*min_mean_bits, 126);
1277
1278     return analog_silence;
1279 }
1280  
1281  
1282 inline
1283 void bitpressure_strategy1(
1284     lame_internal_flags * gfc,
1285     III_psy_xmin l3_xmin[2][2],
1286     int min_bits[2][2],  
1287     int max_bits[2][2] )  
1288 {
1289     int gr, ch, sfb;
1290     for (gr = 0; gr < gfc->mode_gr; gr++) {
1291         for (ch = 0; ch < gfc->channels_out; ch++) {
1292             if (gfc->l3_side.gr[gr].ch[ch].tt.block_type == SHORT_TYPE) {
1293                 for (sfb = 0; sfb < SBMAX_s; sfb++) {
1294                     l3_xmin[gr][ch].s[sfb][0] *= 1.+.029*sfb*sfb/SBMAX_s/SBMAX_s;
1295                     l3_xmin[gr][ch].s[sfb][1] *= 1.+.029*sfb*sfb/SBMAX_s/SBMAX_s;
1296                     l3_xmin[gr][ch].s[sfb][2] *= 1.+.029*sfb*sfb/SBMAX_s/SBMAX_s;
1297                 }
1298             }
1299             else {
1300                 for (sfb = 0; sfb < SBMAX_l; sfb++) 
1301                     l3_xmin[gr][ch].l[sfb] *= 1.+.029*sfb*sfb/SBMAX_l/SBMAX_l;
1302             }
1303             max_bits[gr][ch] = Max(min_bits[gr][ch], 0.9*max_bits[gr][ch]);
1304         }
1305     }
1306 }
1307
1308 inline
1309 void bitpressure_strategy2( 
1310     lame_internal_flags * gfc,
1311     int bpf, int used, int save_bits[2][2],
1312     int min_bits[2][2], int max_bits[2][2] )  
1313 {
1314     int gr, ch;
1315     for (gr = 0; gr < gfc->mode_gr; gr++) {
1316         for (ch = 0; ch < gfc->channels_out; ch++) {
1317             max_bits[gr][ch]  = save_bits[gr][ch];
1318             max_bits[gr][ch] *= bpf;
1319             max_bits[gr][ch] /= used;
1320             max_bits[gr][ch]  = Max(min_bits[gr][ch],max_bits[gr][ch]);
1321         }
1322     }
1323 }
1324
1325 /************************************************************************
1326  *
1327  *      VBR_iteration_loop()   
1328  *
1329  *  tries to find out how many bits are needed for each granule and channel
1330  *  to get an acceptable quantization. An appropriate bitrate will then be
1331  *  choosed for quantization.  rh 8/99                          
1332  *
1333  *  Robert Hegemann 2000-09-06 rewrite
1334  *
1335  ************************************************************************/
1336
1337 void 
1338 VBR_iteration_loop (
1339     lame_global_flags *gfp,
1340     FLOAT8             pe           [2][2],
1341     FLOAT8             ms_ener_ratio[2], 
1342     FLOAT8             xr           [2][2][576],
1343     III_psy_ratio      ratio        [2][2], 
1344     int                l3_enc       [2][2][576],
1345     III_scalefac_t     scalefac     [2][2] )
1346 {
1347     lame_internal_flags *gfc=gfp->internal_flags;
1348     III_psy_xmin l3_xmin[2][2];
1349   
1350     FLOAT8    xrpow[576];
1351     int       bands[2][2];
1352     int       frameBits[15];
1353     int       bitsPerFrame;
1354     int       save_bits[2][2];
1355     int       used_bits, used_bits2;
1356     int       bits;
1357     int       min_bits[2][2], max_bits[2][2];
1358     int       analog_mean_bits, min_mean_bits;
1359     int       mean_bits;
1360     int       ch, gr, analog_silence;
1361     gr_info             *cod_info;
1362     III_side_info_t     *l3_side  = &gfc->l3_side;
1363
1364     analog_silence = VBR_prepare (gfp, pe, ms_ener_ratio, xr, ratio, 
1365                                   l3_xmin, frameBits, &analog_mean_bits,
1366                                   &min_mean_bits, min_bits, max_bits, bands);
1367
1368     /*---------------------------------*/
1369     for(;;) {  
1370     
1371     /*  quantize granules with lowest possible number of bits
1372      */
1373     
1374     used_bits = 0;
1375     used_bits2 = 0;
1376    
1377     for (gr = 0; gr < gfc->mode_gr; gr++) {
1378         for (ch = 0; ch < gfc->channels_out; ch++) {
1379             int ret; 
1380             cod_info = &l3_side->gr[gr].ch[ch].tt;
1381       
1382             /*  init_outer_loop sets up cod_info, scalefac and xrpow 
1383              */
1384             ret = init_outer_loop(gfc, cod_info, &scalefac[gr][ch],
1385                                   xr[gr][ch], xrpow);
1386             if (ret == 0 || max_bits[gr][ch] == 0) {
1387                 /*  xr contains no energy 
1388                  *  l3_enc, our encoding data, will be quantized to zero
1389                  */
1390                 memset(l3_enc[gr][ch], 0, sizeof(int)*576);
1391                 save_bits[gr][ch] = 0;
1392                 continue; /* with next channel */
1393             }
1394       
1395             if (gfp->VBR == vbr_mtrh) {
1396                 ret = VBR_noise_shaping2 (gfp, xr[gr][ch], xrpow, l3_enc[gr][ch],  
1397                                         min_bits[gr][ch], max_bits[gr][ch], 
1398                                         &scalefac[gr][ch],
1399                                         &l3_xmin[gr][ch], gr, ch );
1400                 if (ret < 0)
1401                     cod_info->part2_3_length = 100000;
1402             } 
1403             else
1404                 VBR_encode_granule (gfp, cod_info, xr[gr][ch], &l3_xmin[gr][ch],
1405                                     &scalefac[gr][ch], xrpow, l3_enc[gr][ch],
1406                                     ch, min_bits[gr][ch], max_bits[gr][ch] );
1407
1408             used_bits += cod_info->part2_3_length;
1409             save_bits[gr][ch] = Min(MAX_BITS, cod_info->part2_3_length);
1410             used_bits2 += Min(MAX_BITS, cod_info->part2_3_length);
1411         } /* for ch */
1412     }    /* for gr */
1413
1414     /*  find lowest bitrate able to hold used bits
1415      */
1416     if (analog_silence && !gfp->VBR_hard_min) 
1417         /*  we detected analog silence and the user did not specify 
1418          *  any hard framesize limit, so start with smallest possible frame
1419          */
1420         gfc->bitrate_index = 1;
1421     else
1422         gfc->bitrate_index = gfc->VBR_min_bitrate;
1423      
1424     for( ; gfc->bitrate_index < gfc->VBR_max_bitrate; gfc->bitrate_index++) {
1425         if (used_bits <= frameBits[gfc->bitrate_index]) break; 
1426     }
1427
1428     getframebits (gfp, &bitsPerFrame, &mean_bits);
1429     bits = ResvFrameBegin (gfp, l3_side, mean_bits, bitsPerFrame);
1430     
1431     if (used_bits <= bits) break;
1432
1433     switch ( gfc -> VBR -> bitpressure ) {
1434     default:
1435     case  1:    bitpressure_strategy1( gfc, l3_xmin, min_bits, max_bits );
1436                 break;
1437     case  2:    bitpressure_strategy2( gfc, frameBits[gfc->bitrate_index], 
1438                                used_bits2, save_bits, min_bits, max_bits );
1439                 break;
1440     }
1441
1442     }   /* breaks adjusted */
1443     /*--------------------------------------*/
1444     
1445     iteration_finish (gfc, xr, l3_enc, scalefac, mean_bits);
1446 }
1447
1448
1449
1450
1451
1452
1453 /********************************************************************
1454  *
1455  *  calc_target_bits()
1456  *
1457  *  calculates target bits for ABR encoding
1458  *
1459  *  mt 2000/05/31
1460  *
1461  ********************************************************************/
1462
1463 static void 
1464 calc_target_bits (
1465     lame_global_flags * gfp,
1466     FLOAT8               pe            [2][2],
1467     FLOAT8               ms_ener_ratio [2],
1468     int                  targ_bits     [2][2],
1469     int                 *analog_silence_bits,
1470     int                 *max_frame_bits )
1471 {
1472     lame_internal_flags *gfc=gfp->internal_flags;
1473     III_side_info_t *l3_side = &gfc->l3_side;
1474     FLOAT8 res_factor;
1475     int gr, ch, totbits, mean_bits, bitsPerFrame;
1476     
1477     gfc->bitrate_index = gfc->VBR_max_bitrate;
1478     getframebits (gfp, &bitsPerFrame, &mean_bits);
1479     *max_frame_bits = ResvFrameBegin (gfp, l3_side, mean_bits, bitsPerFrame);
1480
1481     gfc->bitrate_index = 1;
1482     getframebits (gfp, &bitsPerFrame, &mean_bits);
1483     *analog_silence_bits = mean_bits / gfc->channels_out;
1484
1485     mean_bits  = gfp->VBR_mean_bitrate_kbps * gfp->framesize * 1000;
1486     mean_bits /= gfp->out_samplerate;
1487     mean_bits -= gfc->sideinfo_len*8;
1488     mean_bits /= gfc->mode_gr;
1489
1490     /*
1491         res_factor is the percentage of the target bitrate that should
1492         be used on average.  the remaining bits are added to the
1493         bitreservoir and used for difficult to encode frames.  
1494
1495         Since we are tracking the average bitrate, we should adjust
1496         res_factor "on the fly", increasing it if the average bitrate
1497         is greater than the requested bitrate, and decreasing it
1498         otherwise.  Reasonable ranges are from .9 to 1.0
1499         
1500         Until we get the above suggestion working, we use the following
1501         tuning:
1502         compression ratio    res_factor
1503           5.5  (256kbps)         1.0      no need for bitreservoir 
1504           11   (128kbps)         .93      7% held for reservoir
1505    
1506         with linear interpolation for other values.
1507
1508      */
1509     res_factor = .93 + .07 * (11.0 - gfp->compression_ratio) / (11.0 - 5.5);
1510     if (res_factor <  .90)
1511         res_factor =  .90; 
1512     if (res_factor > 1.00) 
1513         res_factor = 1.00;
1514
1515     for (gr = 0; gr < gfc->mode_gr; gr++) {
1516         for (ch = 0; ch < gfc->channels_out; ch++) {
1517             targ_bits[gr][ch] = res_factor * (mean_bits / gfc->channels_out);
1518             
1519             if (pe[gr][ch] > 700) {
1520                 int add_bits = (pe[gr][ch] - 700) / 1.4;
1521   
1522                 gr_info *cod_info = &l3_side->gr[gr].ch[ch].tt;
1523                 targ_bits[gr][ch] = res_factor * (mean_bits / gfc->channels_out);
1524  
1525                 /* short blocks use a little extra, no matter what the pe */
1526                 if (cod_info->block_type == SHORT_TYPE) {
1527                     if (add_bits < mean_bits/4) 
1528                         add_bits = mean_bits/4; 
1529                 }
1530                 /* at most increase bits by 1.5*average */
1531                 if (add_bits > mean_bits*3/4)
1532                     add_bits = mean_bits*3/4;
1533                 else
1534                 if (add_bits < 0) 
1535                     add_bits = 0;
1536
1537                 targ_bits[gr][ch] += add_bits;
1538             }
1539         }/* for ch */
1540     }   /* for gr */
1541     
1542     if (gfc->mode_ext == MPG_MD_MS_LR) 
1543         for (gr = 0; gr < gfc->mode_gr; gr++) {
1544             reduce_side (targ_bits[gr], ms_ener_ratio[gr], mean_bits,
1545                          MAX_BITS);
1546         }
1547
1548     /*  sum target bits
1549      */
1550     totbits=0;
1551     for (gr = 0; gr < gfc->mode_gr; gr++) {
1552         for (ch = 0; ch < gfc->channels_out; ch++) {
1553             if (targ_bits[gr][ch] > MAX_BITS) 
1554                 targ_bits[gr][ch] = MAX_BITS;
1555             totbits += targ_bits[gr][ch];
1556         }
1557     }
1558
1559     /*  repartion target bits if needed
1560      */
1561     if (totbits > *max_frame_bits) {
1562         for(gr = 0; gr < gfc->mode_gr; gr++) {
1563             for(ch = 0; ch < gfc->channels_out; ch++) {
1564                 targ_bits[gr][ch] *= *max_frame_bits; 
1565                 targ_bits[gr][ch] /= totbits; 
1566             }
1567         }
1568     }
1569 }
1570
1571
1572
1573
1574
1575
1576 /********************************************************************
1577  *
1578  *  ABR_iteration_loop()
1579  *
1580  *  encode a frame with a disired average bitrate
1581  *
1582  *  mt 2000/05/31
1583  *
1584  ********************************************************************/
1585
1586 void 
1587 ABR_iteration_loop(
1588     lame_global_flags *gfp,
1589     FLOAT8             pe           [2][2],
1590     FLOAT8             ms_ener_ratio[2], 
1591     FLOAT8             xr           [2][2][576],
1592     III_psy_ratio      ratio        [2][2], 
1593     int                l3_enc       [2][2][576],
1594     III_scalefac_t     scalefac     [2][2] )
1595 {
1596     lame_internal_flags *gfc=gfp->internal_flags;
1597     III_psy_xmin l3_xmin;
1598     FLOAT8    xrpow[576];
1599     int       targ_bits[2][2];
1600     int       bitsPerFrame, mean_bits, totbits, max_frame_bits;
1601     int       ch, gr, ath_over, ret;
1602     int       analog_silence_bits;
1603     gr_info             *cod_info;
1604     III_side_info_t     *l3_side  = &gfc->l3_side;
1605
1606     calc_target_bits (gfp, pe, ms_ener_ratio, targ_bits, 
1607                       &analog_silence_bits, &max_frame_bits);
1608     
1609     /*  encode granules
1610      */
1611     totbits=0;
1612     for (gr = 0; gr < gfc->mode_gr; gr++) {
1613
1614         if (gfc->mode_ext == MPG_MD_MS_LR) 
1615             ms_convert (xr[gr], xr[gr]);
1616
1617         for (ch = 0; ch < gfc->channels_out; ch++) {
1618             cod_info = &l3_side->gr[gr].ch[ch].tt;
1619
1620             /*  cod_info, scalefac and xrpow get initialized in init_outer_loop
1621              */
1622             ret = init_outer_loop(gfc, cod_info, &scalefac[gr][ch],
1623                                   xr[gr][ch], xrpow);
1624             if (ret == 0) {
1625                 /*  xr contains no energy 
1626                  *  l3_enc, our encoding data, will be quantized to zero
1627                  */
1628                 memset(l3_enc[gr][ch], 0, sizeof(int)*576);
1629             } 
1630             else {
1631                 /*  xr contains energy we will have to encode 
1632                  *  calculate the masking abilities
1633                  *  find some good quantization in outer_loop 
1634                  */
1635                 ath_over = calc_xmin (gfp, xr[gr][ch], &ratio[gr][ch],
1636                                       cod_info, &l3_xmin);
1637                 if (0 == ath_over) /* analog silence */
1638                     targ_bits[gr][ch] = analog_silence_bits;
1639
1640                 outer_loop (gfp, cod_info, xr[gr][ch], &l3_xmin,
1641                             &scalefac[gr][ch], xrpow, l3_enc[gr][ch],
1642                             ch, targ_bits[gr][ch]);
1643             }
1644
1645             totbits += cod_info->part2_3_length;
1646         } /* ch */
1647     }  /* gr */
1648   
1649     /*  find a bitrate which can handle totbits 
1650      */
1651     for (gfc->bitrate_index =  gfc->VBR_min_bitrate ;
1652          gfc->bitrate_index <= gfc->VBR_max_bitrate;
1653          gfc->bitrate_index++    ) {
1654         getframebits (gfp, &bitsPerFrame, &mean_bits);
1655         max_frame_bits = ResvFrameBegin (gfp, l3_side, mean_bits, bitsPerFrame);
1656         if (totbits <= max_frame_bits) break; 
1657     }
1658     assert (gfc->bitrate_index <= gfc->VBR_max_bitrate);
1659
1660     iteration_finish (gfc, xr, l3_enc, scalefac, mean_bits);
1661 }
1662
1663
1664
1665
1666
1667
1668 /************************************************************************
1669  *
1670  *      iteration_loop()                                                    
1671  *
1672  *  author/date??
1673  *
1674  *  encodes one frame of MP3 data with constant bitrate
1675  *
1676  ************************************************************************/
1677
1678 void 
1679 iteration_loop(
1680     lame_global_flags *gfp, 
1681     FLOAT8             pe           [2][2],
1682     FLOAT8             ms_ener_ratio[2],  
1683     FLOAT8             xr           [2][2][576],
1684     III_psy_ratio      ratio        [2][2],  
1685     int                l3_enc       [2][2][576],
1686     III_scalefac_t     scalefac     [2][2] )
1687 {
1688     lame_internal_flags *gfc=gfp->internal_flags;
1689     III_psy_xmin l3_xmin[2];
1690     FLOAT8 xrpow[576];
1691     int    targ_bits[2];
1692     int    bitsPerFrame;
1693     int    mean_bits, max_bits;
1694     int    gr, ch, i;
1695     III_side_info_t     *l3_side = &gfc->l3_side;
1696     gr_info             *cod_info;
1697
1698     getframebits (gfp, &bitsPerFrame, &mean_bits);
1699     ResvFrameBegin (gfp, l3_side, mean_bits, bitsPerFrame );
1700
1701     /* quantize! */
1702     for (gr = 0; gr < gfc->mode_gr; gr++) {
1703
1704         /*  calculate needed bits
1705          */
1706         max_bits = on_pe (gfp, pe, l3_side, targ_bits, mean_bits, gr);
1707         
1708         if (gfc->mode_ext == MPG_MD_MS_LR) {
1709             ms_convert (xr[gr], xr[gr]);
1710             reduce_side (targ_bits, ms_ener_ratio[gr], mean_bits, max_bits);
1711         }
1712         
1713         for (ch=0 ; ch < gfc->channels_out ; ch ++) {
1714             cod_info = &l3_side->gr[gr].ch[ch].tt; 
1715
1716             /*  init_outer_loop sets up cod_info, scalefac and xrpow 
1717              */
1718             i = init_outer_loop(gfc, cod_info, &scalefac[gr][ch],
1719                                 xr[gr][ch], xrpow);
1720             if (i == 0) {
1721                 /*  xr contains no energy, l3_enc will be quantized to zero
1722                  */
1723                 memset(l3_enc[gr][ch], 0, sizeof(int)*576);
1724             }
1725             else {
1726                 /*  xr contains energy we will have to encode 
1727                  *  calculate the masking abilities
1728                  *  find some good quantization in outer_loop 
1729                  */
1730                 calc_xmin (gfp, xr[gr][ch], &ratio[gr][ch], cod_info, 
1731                            &l3_xmin[ch]);
1732                 outer_loop (gfp, cod_info, xr[gr][ch], &l3_xmin[ch], 
1733                             &scalefac[gr][ch], xrpow, l3_enc[gr][ch],
1734                             ch, targ_bits[ch]);
1735             }
1736             assert (cod_info->part2_3_length <= MAX_BITS);
1737
1738             /*  try some better scalefac storage
1739              */
1740             best_scalefac_store (gfc, gr, ch, l3_enc, l3_side, scalefac);
1741             
1742             /*  best huffman_divide may save some bits too
1743              */
1744             if (gfc->use_best_huffman == 1) 
1745                 best_huffman_divide (gfc, cod_info, l3_enc[gr][ch]);
1746             
1747             /*  update reservoir status after FINAL quantization/bitrate
1748              */
1749 #undef  NORES_TEST
1750 #ifndef NORES_TEST
1751             ResvAdjust (gfc, cod_info, l3_side, mean_bits);
1752 #endif      
1753             /*  set the sign of l3_enc from the sign of xr
1754              */
1755             for (i = 0; i < 576; i++) {
1756                 if (xr[gr][ch][i] < 0) l3_enc[gr][ch][i] *= -1; 
1757             }
1758         } /* for ch */
1759     }    /* for gr */
1760     
1761 #ifdef NORES_TEST
1762     /* replace ResvAdjust above with this code if you do not want
1763        the second granule to use bits saved by the first granule.
1764        Requires using the --nores.  This is useful for testing only */
1765     for (gr = 0; gr < gfc->mode_gr; gr++) {
1766         for (ch =  0; ch < gfc->channels_out; ch++) {
1767             cod_info = &l3_side->gr[gr].ch[ch].tt;
1768             ResvAdjust (gfc, cod_info, l3_side, mean_bits);
1769         }
1770     }
1771 #endif
1772
1773     ResvFrameEnd (gfc, l3_side, mean_bits);
1774 }
1775
1776
1777