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