1 /*
2  * MP3 quantization
3  *
4  *      Copyright (c) 1999-2000 Mark Taylor
5  *      Copyright (c) 1999-2003 Takehiro Tominaga
6  *      Copyright (c) 2000-2011 Robert Hegemann
7  *      Copyright (c) 2001-2005 Gabriel Bouvigne
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24 
25 /* $Id: quantize.c,v 1.216.2.1 2012/01/08 23:49:58 robert Exp $ */
26 
27 #ifdef HAVE_CONFIG_H
28 # include <config.h>
29 #endif
30 
31 #include "lame.h"
32 #include "lame-machine.h"
33 #include "encoder.h"
34 #include "util.h"
35 #include "quantize_pvt.h"
36 #include "reservoir.h"
37 #include "bitstream.h"
38 #include "vbrquantize.h"
39 #include "quantize.h"
40 #ifdef HAVE_XMMINTRIN_H
41 #include "vector/lame_intrin.h"
42 #endif
43 
44 
45 
46 
47 /* convert from L/R <-> Mid/Side */
48 static void
ms_convert(III_side_info_t * l3_side,int gr)49 ms_convert(III_side_info_t * l3_side, int gr)
50 {
51     int     i;
52     for (i = 0; i < 576; ++i) {
53         FLOAT   l, r;
54         l = l3_side->tt[gr][0].xr[i];
55         r = l3_side->tt[gr][1].xr[i];
56         l3_side->tt[gr][0].xr[i] = (l + r) * (FLOAT) (SQRT2 * 0.5);
57         l3_side->tt[gr][1].xr[i] = (l - r) * (FLOAT) (SQRT2 * 0.5);
58     }
59 }
60 
61 /************************************************************************
62  *
63  *      init_outer_loop()
64  *  mt 6/99
65  *
66  *  initializes cod_info, scalefac and xrpow
67  *
68  *  returns 0 if all energies in xr are zero, else 1
69  *
70  ************************************************************************/
71 
72 static void
init_xrpow_core_c(gr_info * const cod_info,FLOAT xrpow[576],int upper,FLOAT * sum)73 init_xrpow_core_c(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum)
74 {
75     int     i;
76     FLOAT   tmp;
77     *sum = 0;
78     for (i = 0; i <= upper; ++i) {
79         tmp = fabs(cod_info->xr[i]);
80         *sum += tmp;
81         xrpow[i] = sqrt(tmp * sqrt(tmp));
82 
83         if (xrpow[i] > cod_info->xrpow_max)
84             cod_info->xrpow_max = xrpow[i];
85     }
86 }
87 
88 #if defined(__GNUC__) && defined(__GNUC_MINOR__)
89 #  if (__GNUC__ == 4) && (__GNUC_MINOR__ == 9)
90 #    define DONT_USE_SSE
91 #  endif
92 #endif
93 
94 void
init_xrpow_core_init(lame_internal_flags * const gfc)95 init_xrpow_core_init(lame_internal_flags * const gfc)
96 {
97     gfc->init_xrpow_core = init_xrpow_core_c;
98 
99 #if defined(HAVE_XMMINTRIN_H) && !defined(DONT_USE_SSE)
100     if (gfc->CPU_features.SSE)
101         gfc->init_xrpow_core = init_xrpow_core_sse;
102 #endif
103 #ifndef HAVE_NASM
104 #if defined(MIN_ARCH_SSE) && !defined(DONT_USE_SSE)
105     gfc->init_xrpow_core = init_xrpow_core_sse;
106 #endif
107 #endif
108 }
109 
110 
111 
112 static int
init_xrpow(lame_internal_flags * gfc,gr_info * const cod_info,FLOAT xrpow[576])113 init_xrpow(lame_internal_flags * gfc, gr_info * const cod_info, FLOAT xrpow[576])
114 {
115     FLOAT   sum = 0;
116     int     i;
117     int const upper = cod_info->max_nonzero_coeff;
118 
119     assert(xrpow != NULL);
120     cod_info->xrpow_max = 0;
121 
122     /*  check if there is some energy we have to quantize
123      *  and calculate xrpow matching our fresh scalefactors
124      */
125     assert(0 <= upper && upper <= 575);
126     memset(&(xrpow[upper]), 0, (576 - upper) * sizeof(xrpow[0]));
127 
128 
129     gfc->init_xrpow_core(cod_info, xrpow, upper, &sum);
130 
131     /*  return 1 if we have something to quantize, else 0
132      */
133     if (sum > (FLOAT) 1E-20) {
134         int     j = 0;
135         if (gfc->sv_qnt.substep_shaping & 2)
136             j = 1;
137 
138         for (i = 0; i < cod_info->psymax; i++)
139             gfc->sv_qnt.pseudohalf[i] = j;
140 
141         return 1;
142     }
143 
144     memset(&cod_info->l3_enc[0], 0, sizeof(int) * 576);
145     return 0;
146 }
147 
148 
149 
150 
151 
152 /*
153 Gabriel Bouvigne feb/apr 2003
154 Analog silence detection in partitionned sfb21
155 or sfb12 for short blocks
156 
157 From top to bottom of sfb, changes to 0
158 coeffs which are below ath. It stops on the first
159 coeff higher than ath.
160 */
161 static void
psfb21_analogsilence(lame_internal_flags const * gfc,gr_info * const cod_info)162 psfb21_analogsilence(lame_internal_flags const *gfc, gr_info * const cod_info)
163 {
164     ATH_t const *const ATH = gfc->ATH;
165     FLOAT  *const xr = cod_info->xr;
166 
167     if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT blocks */
168         int     gsfb;
169         int     stop = 0;
170         for (gsfb = PSFB21 - 1; gsfb >= 0 && !stop; gsfb--) {
171             int const start = gfc->scalefac_band.psfb21[gsfb];
172             int const end = gfc->scalefac_band.psfb21[gsfb + 1];
173             int     j;
174             FLOAT   ath21;
175             ath21 = athAdjust(ATH->adjust_factor, ATH->psfb21[gsfb], ATH->floor, 0);
176 
177             if (gfc->sv_qnt.longfact[21] > 1e-12f)
178                 ath21 *= gfc->sv_qnt.longfact[21];
179 
180             for (j = end - 1; j >= start; j--) {
181                 if (fabs(xr[j]) < ath21)
182                     xr[j] = 0;
183                 else {
184                     stop = 1;
185                     break;
186                 }
187             }
188         }
189     }
190     else {
191         /*note: short blocks coeffs are reordered */
192         int     block;
193         for (block = 0; block < 3; block++) {
194 
195             int     gsfb;
196             int     stop = 0;
197             for (gsfb = PSFB12 - 1; gsfb >= 0 && !stop; gsfb--) {
198                 int const start = gfc->scalefac_band.s[12] * 3 +
199                     (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) * block +
200                     (gfc->scalefac_band.psfb12[gsfb] - gfc->scalefac_band.psfb12[0]);
201                 int const end =
202                     start + (gfc->scalefac_band.psfb12[gsfb + 1] - gfc->scalefac_band.psfb12[gsfb]);
203                 int     j;
204                 FLOAT   ath12;
205                 ath12 = athAdjust(ATH->adjust_factor, ATH->psfb12[gsfb], ATH->floor, 0);
206 
207                 if (gfc->sv_qnt.shortfact[12] > 1e-12f)
208                     ath12 *= gfc->sv_qnt.shortfact[12];
209 
210                 for (j = end - 1; j >= start; j--) {
211                     if (fabs(xr[j]) < ath12)
212                         xr[j] = 0;
213                     else {
214                         stop = 1;
215                         break;
216                     }
217                 }
218             }
219         }
220     }
221 
222 }
223 
224 
225 
226 
227 
228 static void
init_outer_loop(lame_internal_flags const * gfc,gr_info * const cod_info)229 init_outer_loop(lame_internal_flags const *gfc, gr_info * const cod_info)
230 {
231     SessionConfig_t const *const cfg = &gfc->cfg;
232     int     sfb, j;
233     /*  initialize fresh cod_info
234      */
235     cod_info->part2_3_length = 0;
236     cod_info->big_values = 0;
237     cod_info->count1 = 0;
238     cod_info->global_gain = 210;
239     cod_info->scalefac_compress = 0;
240     /* mixed_block_flag, block_type was set in psymodel.c */
241     cod_info->table_select[0] = 0;
242     cod_info->table_select[1] = 0;
243     cod_info->table_select[2] = 0;
244     cod_info->subblock_gain[0] = 0;
245     cod_info->subblock_gain[1] = 0;
246     cod_info->subblock_gain[2] = 0;
247     cod_info->subblock_gain[3] = 0; /* this one is always 0 */
248     cod_info->region0_count = 0;
249     cod_info->region1_count = 0;
250     cod_info->preflag = 0;
251     cod_info->scalefac_scale = 0;
252     cod_info->count1table_select = 0;
253     cod_info->part2_length = 0;
254     if (cfg->samplerate_out <= 8000) {
255       cod_info->sfb_lmax = 17;
256       cod_info->sfb_smin = 9;
257       cod_info->psy_lmax = 17;
258     }
259     else {
260       cod_info->sfb_lmax = SBPSY_l;
261       cod_info->sfb_smin = SBPSY_s;
262       cod_info->psy_lmax = gfc->sv_qnt.sfb21_extra ? SBMAX_l : SBPSY_l;
263     }
264     cod_info->psymax = cod_info->psy_lmax;
265     cod_info->sfbmax = cod_info->sfb_lmax;
266     cod_info->sfbdivide = 11;
267     for (sfb = 0; sfb < SBMAX_l; sfb++) {
268         cod_info->width[sfb]
269             = gfc->scalefac_band.l[sfb + 1] - gfc->scalefac_band.l[sfb];
270         cod_info->window[sfb] = 3; /* which is always 0. */
271     }
272     if (cod_info->block_type == SHORT_TYPE) {
273         FLOAT   ixwork[576];
274         FLOAT  *ix;
275 
276         cod_info->sfb_smin = 0;
277         cod_info->sfb_lmax = 0;
278         if (cod_info->mixed_block_flag) {
279             /*
280              *  MPEG-1:      sfbs 0-7 long block, 3-12 short blocks
281              *  MPEG-2(.5):  sfbs 0-5 long block, 3-12 short blocks
282              */
283             cod_info->sfb_smin = 3;
284             cod_info->sfb_lmax = cfg->mode_gr * 2 + 4;
285         }
286         if (cfg->samplerate_out <= 8000) {
287             cod_info->psymax
288                 = cod_info->sfb_lmax
289                 + 3 * (9 - cod_info->sfb_smin);
290             cod_info->sfbmax = cod_info->sfb_lmax + 3 * (9 - cod_info->sfb_smin);
291         }
292         else {
293             cod_info->psymax
294                 = cod_info->sfb_lmax
295                 + 3 * ((gfc->sv_qnt.sfb21_extra ? SBMAX_s : SBPSY_s) - cod_info->sfb_smin);
296             cod_info->sfbmax = cod_info->sfb_lmax + 3 * (SBPSY_s - cod_info->sfb_smin);
297         }
298         cod_info->sfbdivide = cod_info->sfbmax - 18;
299         cod_info->psy_lmax = cod_info->sfb_lmax;
300         /* re-order the short blocks, for more efficient encoding below */
301         /* By Takehiro TOMINAGA */
302         /*
303            Within each scalefactor band, data is given for successive
304            time windows, beginning with window 0 and ending with window 2.
305            Within each window, the quantized values are then arranged in
306            order of increasing frequency...
307          */
308         ix = &cod_info->xr[gfc->scalefac_band.l[cod_info->sfb_lmax]];
309         memcpy(ixwork, cod_info->xr, 576 * sizeof(FLOAT));
310         for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
311             int const start = gfc->scalefac_band.s[sfb];
312             int const end = gfc->scalefac_band.s[sfb + 1];
313             int     window, l;
314             for (window = 0; window < 3; window++) {
315                 for (l = start; l < end; l++) {
316                     *ix++ = ixwork[3 * l + window];
317                 }
318             }
319         }
320 
321         j = cod_info->sfb_lmax;
322         for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
323             cod_info->width[j] = cod_info->width[j + 1] = cod_info->width[j + 2]
324                 = gfc->scalefac_band.s[sfb + 1] - gfc->scalefac_band.s[sfb];
325             cod_info->window[j] = 0;
326             cod_info->window[j + 1] = 1;
327             cod_info->window[j + 2] = 2;
328             j += 3;
329         }
330     }
331 
332     cod_info->count1bits = 0;
333     cod_info->sfb_partition_table = nr_of_sfb_block[0][0];
334     cod_info->slen[0] = 0;
335     cod_info->slen[1] = 0;
336     cod_info->slen[2] = 0;
337     cod_info->slen[3] = 0;
338 
339     cod_info->max_nonzero_coeff = 575;
340 
341     /*  fresh scalefactors are all zero
342      */
343     memset(cod_info->scalefac, 0, sizeof(cod_info->scalefac));
344 
345     if (cfg->vbr != vbr_mt && cfg->vbr != vbr_mtrh && cfg->vbr != vbr_abr && cfg->vbr != vbr_off) {
346         psfb21_analogsilence(gfc, cod_info);
347     }
348 }
349 
350 
351 
352 /************************************************************************
353  *
354  *      bin_search_StepSize()
355  *
356  *  author/date??
357  *
358  *  binary step size search
359  *  used by outer_loop to get a quantizer step size to start with
360  *
361  ************************************************************************/
362 
363 typedef enum {
364     BINSEARCH_NONE,
365     BINSEARCH_UP,
366     BINSEARCH_DOWN
367 } binsearchDirection_t;
368 
369 static int
bin_search_StepSize(lame_internal_flags * const gfc,gr_info * const cod_info,int desired_rate,const int ch,const FLOAT xrpow[576])370 bin_search_StepSize(lame_internal_flags * const gfc, gr_info * const cod_info,
371                     int desired_rate, const int ch, const FLOAT xrpow[576])
372 {
373     int     nBits;
374     int     CurrentStep = gfc->sv_qnt.CurrentStep[ch];
375     int     flag_GoneOver = 0;
376     int const start = gfc->sv_qnt.OldValue[ch];
377     binsearchDirection_t Direction = BINSEARCH_NONE;
378     cod_info->global_gain = start;
379     desired_rate -= cod_info->part2_length;
380 
381     assert(CurrentStep);
382     for (;;) {
383         int     step;
384         nBits = count_bits(gfc, xrpow, cod_info, 0);
385 
386         if (CurrentStep == 1 || nBits == desired_rate)
387             break;      /* nothing to adjust anymore */
388 
389         if (nBits > desired_rate) {
390             /* increase Quantize_StepSize */
391             if (Direction == BINSEARCH_DOWN)
392                 flag_GoneOver = 1;
393 
394             if (flag_GoneOver)
395                 CurrentStep /= 2;
396             Direction = BINSEARCH_UP;
397             step = CurrentStep;
398         }
399         else {
400             /* decrease Quantize_StepSize */
401             if (Direction == BINSEARCH_UP)
402                 flag_GoneOver = 1;
403 
404             if (flag_GoneOver)
405                 CurrentStep /= 2;
406             Direction = BINSEARCH_DOWN;
407             step = -CurrentStep;
408         }
409         cod_info->global_gain += step;
410         if (cod_info->global_gain < 0) {
411             cod_info->global_gain = 0;
412             flag_GoneOver = 1;
413         }
414         if (cod_info->global_gain > 255) {
415             cod_info->global_gain = 255;
416             flag_GoneOver = 1;
417         }
418     }
419 
420     assert(cod_info->global_gain >= 0);
421     assert(cod_info->global_gain < 256);
422 
423     while (nBits > desired_rate && cod_info->global_gain < 255) {
424         cod_info->global_gain++;
425         nBits = count_bits(gfc, xrpow, cod_info, 0);
426     }
427     gfc->sv_qnt.CurrentStep[ch] = (start - cod_info->global_gain >= 4) ? 4 : 2;
428     gfc->sv_qnt.OldValue[ch] = cod_info->global_gain;
429     cod_info->part2_3_length = nBits;
430     return nBits;
431 }
432 
433 
434 
435 
436 /************************************************************************
437  *
438  *      trancate_smallspectrums()
439  *
440  *  Takehiro TOMINAGA 2002-07-21
441  *
442  *  trancate smaller nubmers into 0 as long as the noise threshold is allowed.
443  *
444  ************************************************************************/
445 static int
floatcompare(const void * v1,const void * v2)446 floatcompare(const void *v1, const void *v2)
447 {
448     const FLOAT *const a = v1, *const b = v2;
449     if (*a > *b)
450         return 1;
451     if (*a < *b)
452         return -1;
453     return 0;
454 }
455 
456 static void
trancate_smallspectrums(lame_internal_flags const * gfc,gr_info * const gi,const FLOAT * const l3_xmin,FLOAT * const work)457 trancate_smallspectrums(lame_internal_flags const *gfc,
458                         gr_info * const gi, const FLOAT * const l3_xmin, FLOAT * const work)
459 {
460     int     sfb, j, width;
461     FLOAT   distort[SFBMAX];
462     calc_noise_result dummy;
463 
464     if ((!(gfc->sv_qnt.substep_shaping & 4) && gi->block_type == SHORT_TYPE)
465         || gfc->sv_qnt.substep_shaping & 0x80)
466         return;
467     (void) calc_noise(gi, l3_xmin, distort, &dummy, 0);
468     for (j = 0; j < 576; j++) {
469         FLOAT   xr = 0.0;
470         if (gi->l3_enc[j] != 0)
471             xr = fabs(gi->xr[j]);
472         work[j] = xr;
473     }
474 
475     j = 0;
476     sfb = 8;
477     if (gi->block_type == SHORT_TYPE)
478         sfb = 6;
479     do {
480         FLOAT   allowedNoise, trancateThreshold;
481         int     nsame, start;
482 
483         width = gi->width[sfb];
484         j += width;
485         if (distort[sfb] >= 1.0)
486             continue;
487 
488         qsort(&work[j - width], width, sizeof(FLOAT), floatcompare);
489         if (EQ(work[j - 1], 0.0))
490             continue;   /* all zero sfb */
491 
492         allowedNoise = (1.0 - distort[sfb]) * l3_xmin[sfb];
493         trancateThreshold = 0.0;
494         start = 0;
495         do {
496             FLOAT   noise;
497             for (nsame = 1; start + nsame < width; nsame++)
498                 if (NEQ(work[start + j - width], work[start + j + nsame - width]))
499                     break;
500 
501             noise = work[start + j - width] * work[start + j - width] * nsame;
502             if (allowedNoise < noise) {
503                 if (start != 0)
504                     trancateThreshold = work[start + j - width - 1];
505                 break;
506             }
507             allowedNoise -= noise;
508             start += nsame;
509         } while (start < width);
510         if (EQ(trancateThreshold, 0.0))
511             continue;
512 
513 /*      printf("%e %e %e\n", */
514 /*             trancateThreshold/l3_xmin[sfb], */
515 /*             trancateThreshold/(l3_xmin[sfb]*start), */
516 /*             trancateThreshold/(l3_xmin[sfb]*(start+width)) */
517 /*          ); */
518 /*      if (trancateThreshold > 1000*l3_xmin[sfb]*start) */
519 /*          trancateThreshold = 1000*l3_xmin[sfb]*start; */
520 
521         do {
522             if (fabs(gi->xr[j - width]) <= trancateThreshold)
523                 gi->l3_enc[j - width] = 0;
524         } while (--width > 0);
525     } while (++sfb < gi->psymax);
526 
527     gi->part2_3_length = noquant_count_bits(gfc, gi, 0);
528 }
529 
530 
531 /*************************************************************************
532  *
533  *      loop_break()
534  *
535  *  author/date??
536  *
537  *  Function: Returns zero if there is a scalefac which has not been
538  *            amplified. Otherwise it returns one.
539  *
540  *************************************************************************/
541 
542 inline static int
loop_break(const gr_info * const cod_info)543 loop_break(const gr_info * const cod_info)
544 {
545     int     sfb;
546 
547     for (sfb = 0; sfb < cod_info->sfbmax; sfb++)
548         if (cod_info->scalefac[sfb]
549             + cod_info->subblock_gain[cod_info->window[sfb]] == 0)
550             return 0;
551 
552     return 1;
553 }
554 
555 
556 
557 
558 /*  mt 5/99:  Function: Improved calc_noise for a single channel   */
559 
560 /*************************************************************************
561  *
562  *      quant_compare()
563  *
564  *  author/date??
565  *
566  *  several different codes to decide which quantization is better
567  *
568  *************************************************************************/
569 
570 static double
penalties(double noise)571 penalties(double noise)
572 {
573     return FAST_LOG10(0.368 + 0.632 * noise * noise * noise);
574 }
575 
576 static double
get_klemm_noise(const FLOAT * distort,const gr_info * const gi)577 get_klemm_noise(const FLOAT * distort, const gr_info * const gi)
578 {
579     int     sfb;
580     double  klemm_noise = 1E-37;
581     for (sfb = 0; sfb < gi->psymax; sfb++)
582         klemm_noise += penalties(distort[sfb]);
583 
584     return Max(1e-20, klemm_noise);
585 }
586 
587 inline static int
quant_compare(const int quant_comp,const calc_noise_result * const best,calc_noise_result * const calc,const gr_info * const gi,const FLOAT * distort)588 quant_compare(const int quant_comp,
589               const calc_noise_result * const best,
590               calc_noise_result * const calc, const gr_info * const gi, const FLOAT * distort)
591 {
592     /*
593        noise is given in decibels (dB) relative to masking thesholds.
594 
595        over_noise:  ??? (the previous comment is fully wrong)
596        tot_noise:   ??? (the previous comment is fully wrong)
597        max_noise:   max quantization noise
598 
599      */
600     int     better;
601 
602     switch (quant_comp) {
603     default:
604     case 9:{
605             if (best->over_count > 0) {
606                 /* there are distorted sfb */
607                 better = calc->over_SSD <= best->over_SSD;
608                 if (calc->over_SSD == best->over_SSD)
609                     better = calc->bits < best->bits;
610             }
611             else {
612                 /* no distorted sfb */
613                 better = ((calc->max_noise < 0) &&
614                           ((calc->max_noise * 10 + calc->bits) <=
615                            (best->max_noise * 10 + best->bits)));
616             }
617             break;
618         }
619 
620     case 0:
621         better = calc->over_count < best->over_count
622             || (calc->over_count == best->over_count && calc->over_noise < best->over_noise)
623             || (calc->over_count == best->over_count &&
624                 EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);
625         break;
626 
627     case 8:
628         calc->max_noise = get_klemm_noise(distort, gi);
629         /*lint --fallthrough */
630     case 1:
631         better = calc->max_noise < best->max_noise;
632         break;
633     case 2:
634         better = calc->tot_noise < best->tot_noise;
635         break;
636     case 3:
637         better = (calc->tot_noise < best->tot_noise)
638             && (calc->max_noise < best->max_noise);
639         break;
640     case 4:
641         better = (calc->max_noise <= 0.0 && best->max_noise > 0.2)
642             || (calc->max_noise <= 0.0 &&
643                 best->max_noise < 0.0 &&
644                 best->max_noise > calc->max_noise - 0.2 && calc->tot_noise < best->tot_noise)
645             || (calc->max_noise <= 0.0 &&
646                 best->max_noise > 0.0 &&
647                 best->max_noise > calc->max_noise - 0.2 &&
648                 calc->tot_noise < best->tot_noise + best->over_noise)
649             || (calc->max_noise > 0.0 &&
650                 best->max_noise > -0.05 &&
651                 best->max_noise > calc->max_noise - 0.1 &&
652                 calc->tot_noise + calc->over_noise < best->tot_noise + best->over_noise)
653             || (calc->max_noise > 0.0 &&
654                 best->max_noise > -0.1 &&
655                 best->max_noise > calc->max_noise - 0.15 &&
656                 calc->tot_noise + calc->over_noise + calc->over_noise <
657                 best->tot_noise + best->over_noise + best->over_noise);
658         break;
659     case 5:
660         better = calc->over_noise < best->over_noise
661             || (EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);
662         break;
663     case 6:
664         better = calc->over_noise < best->over_noise
665             || (EQ(calc->over_noise, best->over_noise) &&
666                 (calc->max_noise < best->max_noise
667                  || (EQ(calc->max_noise, best->max_noise) && calc->tot_noise <= best->tot_noise)
668                 ));
669         break;
670     case 7:
671         better = calc->over_count < best->over_count || calc->over_noise < best->over_noise;
672         break;
673     }
674 
675 
676     if (best->over_count == 0) {
677         /*
678            If no distorted bands, only use this quantization
679            if it is better, and if it uses less bits.
680            Unfortunately, part2_3_length is sometimes a poor
681            estimator of the final size at low bitrates.
682          */
683         better = better && calc->bits < best->bits;
684     }
685 
686 
687     return better;
688 }
689 
690 
691 
692 /*************************************************************************
693  *
694  *          amp_scalefac_bands()
695  *
696  *  author/date??
697  *
698  *  Amplify the scalefactor bands that violate the masking threshold.
699  *  See ISO 11172-3 Section C.1.5.4.3.5
700  *
701  *  distort[] = noise/masking
702  *  distort[] > 1   ==> noise is not masked
703  *  distort[] < 1   ==> noise is masked
704  *  max_dist = maximum value of distort[]
705  *
706  *  Three algorithms:
707  *  noise_shaping_amp
708  *        0             Amplify all bands with distort[]>1.
709  *
710  *        1             Amplify all bands with distort[] >= max_dist^(.5);
711  *                     ( 50% in the db scale)
712  *
713  *        2             Amplify first band with distort[] >= max_dist;
714  *
715  *
716  *  For algorithms 0 and 1, if max_dist < 1, then amplify all bands
717  *  with distort[] >= .95*max_dist.  This is to make sure we always
718  *  amplify at least one band.
719  *
720  *
721  *************************************************************************/
722 static void
amp_scalefac_bands(lame_internal_flags * gfc,gr_info * const cod_info,FLOAT const * distort,FLOAT xrpow[576],int bRefine)723 amp_scalefac_bands(lame_internal_flags * gfc,
724                    gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
725 {
726     SessionConfig_t const *const cfg = &gfc->cfg;
727     int     j, sfb;
728     FLOAT   ifqstep34, trigger;
729     int     noise_shaping_amp;
730 
731     if (cod_info->scalefac_scale == 0) {
732         ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5) */
733     }
734     else {
735         ifqstep34 = 1.68179283050742922612; /* 2**(.75*1) */
736     }
737 
738     /* compute maximum value of distort[]  */
739     trigger = 0;
740     for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
741         if (trigger < distort[sfb])
742             trigger = distort[sfb];
743     }
744 
745     noise_shaping_amp = cfg->noise_shaping_amp;
746     if (noise_shaping_amp == 3) {
747         if (bRefine == 1)
748             noise_shaping_amp = 2;
749         else
750             noise_shaping_amp = 1;
751     }
752     switch (noise_shaping_amp) {
753     case 2:
754         /* amplify exactly 1 band */
755         break;
756 
757     case 1:
758         /* amplify bands within 50% of max (on db scale) */
759         if (trigger > 1.0)
760             trigger = pow(trigger, .5);
761         else
762             trigger *= .95;
763         break;
764 
765     case 0:
766     default:
767         /* ISO algorithm.  amplify all bands with distort>1 */
768         if (trigger > 1.0)
769             trigger = 1.0;
770         else
771             trigger *= .95;
772         break;
773     }
774 
775     j = 0;
776     for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
777         int const width = cod_info->width[sfb];
778         int     l;
779         j += width;
780         if (distort[sfb] < trigger)
781             continue;
782 
783         if (gfc->sv_qnt.substep_shaping & 2) {
784             gfc->sv_qnt.pseudohalf[sfb] = !gfc->sv_qnt.pseudohalf[sfb];
785             if (!gfc->sv_qnt.pseudohalf[sfb] && cfg->noise_shaping_amp == 2)
786                 return;
787         }
788         cod_info->scalefac[sfb]++;
789         for (l = -width; l < 0; l++) {
790             xrpow[j + l] *= ifqstep34;
791             if (xrpow[j + l] > cod_info->xrpow_max)
792                 cod_info->xrpow_max = xrpow[j + l];
793         }
794 
795         if (cfg->noise_shaping_amp == 2)
796             return;
797     }
798 }
799 
800 /*************************************************************************
801  *
802  *      inc_scalefac_scale()
803  *
804  *  Takehiro Tominaga 2000-xx-xx
805  *
806  *  turns on scalefac scale and adjusts scalefactors
807  *
808  *************************************************************************/
809 
810 static void
inc_scalefac_scale(gr_info * const cod_info,FLOAT xrpow[576])811 inc_scalefac_scale(gr_info * const cod_info, FLOAT xrpow[576])
812 {
813     int     l, j, sfb;
814     const FLOAT ifqstep34 = 1.29683955465100964055;
815 
816     j = 0;
817     for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
818         int const width = cod_info->width[sfb];
819         int     s = cod_info->scalefac[sfb];
820         if (cod_info->preflag)
821             s += pretab[sfb];
822         j += width;
823         if (s & 1) {
824             s++;
825             for (l = -width; l < 0; l++) {
826                 xrpow[j + l] *= ifqstep34;
827                 if (xrpow[j + l] > cod_info->xrpow_max)
828                     cod_info->xrpow_max = xrpow[j + l];
829             }
830         }
831         cod_info->scalefac[sfb] = s >> 1;
832     }
833     cod_info->preflag = 0;
834     cod_info->scalefac_scale = 1;
835 }
836 
837 
838 
839 /*************************************************************************
840  *
841  *      inc_subblock_gain()
842  *
843  *  Takehiro Tominaga 2000-xx-xx
844  *
845  *  increases the subblock gain and adjusts scalefactors
846  *
847  *************************************************************************/
848 
849 static int
inc_subblock_gain(const lame_internal_flags * const gfc,gr_info * const cod_info,FLOAT xrpow[576])850 inc_subblock_gain(const lame_internal_flags * const gfc, gr_info * const cod_info, FLOAT xrpow[576])
851 {
852     int     sfb, window;
853     int    *const scalefac = cod_info->scalefac;
854 
855     /* subbloc_gain can't do anything in the long block region */
856     for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {
857         if (scalefac[sfb] >= 16)
858             return 1;
859     }
860 
861     for (window = 0; window < 3; window++) {
862         int     s1, s2, l, j;
863         s1 = s2 = 0;
864 
865         for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbdivide; sfb += 3) {
866             if (s1 < scalefac[sfb])
867                 s1 = scalefac[sfb];
868         }
869         for (; sfb < cod_info->sfbmax; sfb += 3) {
870             if (s2 < scalefac[sfb])
871                 s2 = scalefac[sfb];
872         }
873 
874         if (s1 < 16 && s2 < 8)
875             continue;
876 
877         if (cod_info->subblock_gain[window] >= 7)
878             return 1;
879 
880         /* even though there is no scalefactor for sfb12
881          * subblock gain affects upper frequencies too, that's why
882          * we have to go up to SBMAX_s
883          */
884         cod_info->subblock_gain[window]++;
885         j = gfc->scalefac_band.l[cod_info->sfb_lmax];
886         for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbmax; sfb += 3) {
887             FLOAT   amp;
888             int const width = cod_info->width[sfb];
889             int     s = scalefac[sfb];
890             assert(s >= 0);
891             s = s - (4 >> cod_info->scalefac_scale);
892             if (s >= 0) {
893                 scalefac[sfb] = s;
894                 j += width * 3;
895                 continue;
896             }
897 
898             scalefac[sfb] = 0;
899             {
900                 int const gain = 210 + (s << (cod_info->scalefac_scale + 1));
901                 amp = IPOW20(gain);
902             }
903             j += width * (window + 1);
904             for (l = -width; l < 0; l++) {
905                 xrpow[j + l] *= amp;
906                 if (xrpow[j + l] > cod_info->xrpow_max)
907                     cod_info->xrpow_max = xrpow[j + l];
908             }
909             j += width * (3 - window - 1);
910         }
911 
912         {
913             FLOAT const amp = IPOW20(202);
914             j += cod_info->width[sfb] * (window + 1);
915             for (l = -cod_info->width[sfb]; l < 0; l++) {
916                 xrpow[j + l] *= amp;
917                 if (xrpow[j + l] > cod_info->xrpow_max)
918                     cod_info->xrpow_max = xrpow[j + l];
919             }
920         }
921     }
922     return 0;
923 }
924 
925 
926 
927 /********************************************************************
928  *
929  *      balance_noise()
930  *
931  *  Takehiro Tominaga /date??
932  *  Robert Hegemann 2000-09-06: made a function of it
933  *
934  *  amplifies scalefactor bands,
935  *   - if all are already amplified returns 0
936  *   - if some bands are amplified too much:
937  *      * try to increase scalefac_scale
938  *      * if already scalefac_scale was set
939  *          try on short blocks to increase subblock gain
940  *
941  ********************************************************************/
942 inline static int
balance_noise(lame_internal_flags * gfc,gr_info * const cod_info,FLOAT const * distort,FLOAT xrpow[576],int bRefine)943 balance_noise(lame_internal_flags * gfc,
944               gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
945 {
946     SessionConfig_t const *const cfg = &gfc->cfg;
947     int     status;
948 
949     amp_scalefac_bands(gfc, cod_info, distort, xrpow, bRefine);
950 
951     /* check to make sure we have not amplified too much
952      * loop_break returns 0 if there is an unamplified scalefac
953      * scale_bitcount returns 0 if no scalefactors are too large
954      */
955 
956     status = loop_break(cod_info);
957 
958     if (status)
959         return 0;       /* all bands amplified */
960 
961     /* not all scalefactors have been amplified.  so these
962      * scalefacs are possibly valid.  encode them:
963      */
964     status = scale_bitcount(gfc, cod_info);
965 
966     if (!status)
967         return 1;       /* amplified some bands not exceeding limits */
968 
969     /*  some scalefactors are too large.
970      *  lets try setting scalefac_scale=1
971      */
972     if (cfg->noise_shaping > 1) {
973         memset(&gfc->sv_qnt.pseudohalf[0], 0, sizeof(gfc->sv_qnt.pseudohalf));
974         if (!cod_info->scalefac_scale) {
975             inc_scalefac_scale(cod_info, xrpow);
976             status = 0;
977         }
978         else {
979             if (cod_info->block_type == SHORT_TYPE && cfg->subblock_gain > 0) {
980                 status = inc_subblock_gain(gfc, cod_info, xrpow)
981                     || loop_break(cod_info);
982             }
983         }
984     }
985 
986     if (!status) {
987         status = scale_bitcount(gfc, cod_info);
988     }
989     return !status;
990 }
991 
992 
993 
994 /************************************************************************
995  *
996  *  outer_loop ()
997  *
998  *  Function: The outer iteration loop controls the masking conditions
999  *  of all scalefactorbands. It computes the best scalefac and
1000  *  global gain. This module calls the inner iteration loop
1001  *
1002  *  mt 5/99 completely rewritten to allow for bit reservoir control,
1003  *  mid/side channels with L/R or mid/side masking thresholds,
1004  *  and chooses best quantization instead of last quantization when
1005  *  no distortion free quantization can be found.
1006  *
1007  *  added VBR support mt 5/99
1008  *
1009  *  some code shuffle rh 9/00
1010  ************************************************************************/
1011 
1012 static int
outer_loop(lame_internal_flags * gfc,gr_info * const cod_info,const FLOAT * const l3_xmin,FLOAT xrpow[576],const int ch,const int targ_bits)1013 outer_loop(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion */
1014            FLOAT xrpow[576], /* coloured magnitudes of spectral */
1015            const int ch, const int targ_bits)
1016 {                       /* maximum allowed bits */
1017     SessionConfig_t const *const cfg = &gfc->cfg;
1018     gr_info cod_info_w;
1019     FLOAT   save_xrpow[576];
1020     FLOAT   distort[SFBMAX];
1021     calc_noise_result best_noise_info;
1022     int     huff_bits;
1023     int     better;
1024     int     age;
1025     calc_noise_data prev_noise;
1026     int     best_part2_3_length = 9999999;
1027     int     bEndOfSearch = 0;
1028     int     bRefine = 0;
1029     int     best_ggain_pass1 = 0;
1030 
1031     (void) bin_search_StepSize(gfc, cod_info, targ_bits, ch, xrpow);
1032 
1033     if (!cfg->noise_shaping)
1034         /* fast mode, no noise shaping, we are ready */
1035         return 100;     /* default noise_info.over_count */
1036 
1037     memset(&prev_noise, 0, sizeof(calc_noise_data));
1038 
1039 
1040     /* compute the distortion in this quantization */
1041     /* coefficients and thresholds both l/r (or both mid/side) */
1042     (void) calc_noise(cod_info, l3_xmin, distort, &best_noise_info, &prev_noise);
1043     best_noise_info.bits = cod_info->part2_3_length;
1044 
1045     cod_info_w = *cod_info;
1046     age = 0;
1047     /* if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */
1048     memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
1049 
1050     while (!bEndOfSearch) {
1051         /* BEGIN MAIN LOOP */
1052         do {
1053             calc_noise_result noise_info;
1054             int     search_limit;
1055             int     maxggain = 255;
1056 
1057             /* When quantization with no distorted bands is found,
1058              * allow up to X new unsuccesful tries in serial. This
1059              * gives us more possibilities for different quant_compare modes.
1060              * Much more than 3 makes not a big difference, it is only slower.
1061              */
1062 
1063             if (gfc->sv_qnt.substep_shaping & 2) {
1064                 search_limit = 20;
1065             }
1066             else {
1067                 search_limit = 3;
1068             }
1069 
1070 
1071 
1072             /* Check if the last scalefactor band is distorted.
1073              * in VBR mode we can't get rid of the distortion, so quit now
1074              * and VBR mode will try again with more bits.
1075              * (makes a 10% speed increase, the files I tested were
1076              * binary identical, 2000/05/20 Robert Hegemann)
1077              * distort[] > 1 means noise > allowed noise
1078              */
1079             if (gfc->sv_qnt.sfb21_extra) {
1080                 if (distort[cod_info_w.sfbmax] > 1.0)
1081                     break;
1082                 if (cod_info_w.block_type == SHORT_TYPE
1083                     && (distort[cod_info_w.sfbmax + 1] > 1.0
1084                         || distort[cod_info_w.sfbmax + 2] > 1.0))
1085                     break;
1086             }
1087 
1088             /* try a new scalefactor conbination on cod_info_w */
1089             if (balance_noise(gfc, &cod_info_w, distort, xrpow, bRefine) == 0)
1090                 break;
1091             if (cod_info_w.scalefac_scale)
1092                 maxggain = 254;
1093 
1094             /* inner_loop starts with the initial quantization step computed above
1095              * and slowly increases until the bits < huff_bits.
1096              * Thus it is important not to start with too large of an inital
1097              * quantization step.  Too small is ok, but inner_loop will take longer
1098              */
1099             huff_bits = targ_bits - cod_info_w.part2_length;
1100             if (huff_bits <= 0)
1101                 break;
1102 
1103             /*  increase quantizer stepsize until needed bits are below maximum
1104              */
1105             while ((cod_info_w.part2_3_length
1106                     = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > huff_bits
1107                    && cod_info_w.global_gain <= maxggain)
1108                 cod_info_w.global_gain++;
1109 
1110             if (cod_info_w.global_gain > maxggain)
1111                 break;
1112 
1113             if (best_noise_info.over_count == 0) {
1114 
1115                 while ((cod_info_w.part2_3_length
1116                         = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > best_part2_3_length
1117                        && cod_info_w.global_gain <= maxggain)
1118                     cod_info_w.global_gain++;
1119 
1120                 if (cod_info_w.global_gain > maxggain)
1121                     break;
1122             }
1123 
1124             /* compute the distortion in this quantization */
1125             (void) calc_noise(&cod_info_w, l3_xmin, distort, &noise_info, &prev_noise);
1126             noise_info.bits = cod_info_w.part2_3_length;
1127 
1128             /* check if this quantization is better
1129              * than our saved quantization */
1130             if (cod_info->block_type != SHORT_TYPE) /* NORM, START or STOP type */
1131                 better = cfg->quant_comp;
1132             else
1133                 better = cfg->quant_comp_short;
1134 
1135 
1136             better = quant_compare(better, &best_noise_info, &noise_info, &cod_info_w, distort);
1137 
1138 
1139             /* save data so we can restore this quantization later */
1140             if (better) {
1141                 best_part2_3_length = cod_info->part2_3_length;
1142                 best_noise_info = noise_info;
1143                 *cod_info = cod_info_w;
1144                 age = 0;
1145                 /* save data so we can restore this quantization later */
1146                 /*if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */  {
1147                     /* store for later reuse */
1148                     memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
1149                 }
1150             }
1151             else {
1152                 /* early stop? */
1153                 if (cfg->full_outer_loop == 0) {
1154                     if (++age > search_limit && best_noise_info.over_count == 0)
1155                         break;
1156                     if ((cfg->noise_shaping_amp == 3) && bRefine && age > 30)
1157                         break;
1158                     if ((cfg->noise_shaping_amp == 3) && bRefine &&
1159                         (cod_info_w.global_gain - best_ggain_pass1) > 15)
1160                         break;
1161                 }
1162             }
1163         }
1164         while ((cod_info_w.global_gain + cod_info_w.scalefac_scale) < 255);
1165 
1166         if (cfg->noise_shaping_amp == 3) {
1167             if (!bRefine) {
1168                 /* refine search */
1169                 cod_info_w = *cod_info;
1170                 memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
1171                 age = 0;
1172                 best_ggain_pass1 = cod_info_w.global_gain;
1173 
1174                 bRefine = 1;
1175             }
1176             else {
1177                 /* search already refined, stop */
1178                 bEndOfSearch = 1;
1179             }
1180 
1181         }
1182         else {
1183             bEndOfSearch = 1;
1184         }
1185     }
1186 
1187     assert((cod_info->global_gain + cod_info->scalefac_scale) <= 255);
1188     /*  finish up
1189      */
1190     if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh || cfg->vbr == vbr_mt)
1191         /* restore for reuse on next try */
1192         memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
1193     /*  do the 'substep shaping'
1194      */
1195     else if (gfc->sv_qnt.substep_shaping & 1)
1196         trancate_smallspectrums(gfc, cod_info, l3_xmin, xrpow);
1197 
1198     return best_noise_info.over_count;
1199 }
1200 
1201 
1202 
1203 
1204 
1205 /************************************************************************
1206  *
1207  *      iteration_finish_one()
1208  *
1209  *  Robert Hegemann 2000-09-06
1210  *
1211  *  update reservoir status after FINAL quantization/bitrate
1212  *
1213  ************************************************************************/
1214 
1215 static void
iteration_finish_one(lame_internal_flags * gfc,int gr,int ch)1216 iteration_finish_one(lame_internal_flags * gfc, int gr, int ch)
1217 {
1218     SessionConfig_t const *const cfg = &gfc->cfg;
1219     III_side_info_t *const l3_side = &gfc->l3_side;
1220     gr_info *const cod_info = &l3_side->tt[gr][ch];
1221 
1222     /*  try some better scalefac storage
1223      */
1224     best_scalefac_store(gfc, gr, ch, l3_side);
1225 
1226     /*  best huffman_divide may save some bits too
1227      */
1228     if (cfg->use_best_huffman == 1)
1229         best_huffman_divide(gfc, cod_info);
1230 
1231     /*  update reservoir status after FINAL quantization/bitrate
1232      */
1233     ResvAdjust(gfc, cod_info);
1234 }
1235 
1236 
1237 
1238 /*********************************************************************
1239  *
1240  *      VBR_encode_granule()
1241  *
1242  *  2000-09-04 Robert Hegemann
1243  *
1244  *********************************************************************/
1245 
1246 static void
VBR_encode_granule(lame_internal_flags * gfc,gr_info * const cod_info,const FLOAT * const l3_xmin,FLOAT xrpow[576],const int ch,int min_bits,int max_bits)1247 VBR_encode_granule(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion of the scalefactor */
1248                    FLOAT xrpow[576], /* coloured magnitudes of spectral values */
1249                    const int ch, int min_bits, int max_bits)
1250 {
1251     gr_info bst_cod_info;
1252     FLOAT   bst_xrpow[576];
1253     int const Max_bits = max_bits;
1254     int     real_bits = max_bits + 1;
1255     int     this_bits = (max_bits + min_bits) / 2;
1256     int     dbits, over, found = 0;
1257     int const sfb21_extra = gfc->sv_qnt.sfb21_extra;
1258 
1259     assert(Max_bits <= MAX_BITS_PER_CHANNEL);
1260     memset(bst_cod_info.l3_enc, 0, sizeof(bst_cod_info.l3_enc));
1261 
1262     /*  search within round about 40 bits of optimal
1263      */
1264     do {
1265         assert(this_bits >= min_bits);
1266         assert(this_bits <= max_bits);
1267         assert(min_bits <= max_bits);
1268 
1269         if (this_bits > Max_bits - 42)
1270             gfc->sv_qnt.sfb21_extra = 0;
1271         else
1272             gfc->sv_qnt.sfb21_extra = sfb21_extra;
1273 
1274         over = outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, this_bits);
1275 
1276         /*  is quantization as good as we are looking for ?
1277          *  in this case: is no scalefactor band distorted?
1278          */
1279         if (over <= 0) {
1280             found = 1;
1281             /*  now we know it can be done with "real_bits"
1282              *  and maybe we can skip some iterations
1283              */
1284             real_bits = cod_info->part2_3_length;
1285 
1286             /*  store best quantization so far
1287              */
1288             bst_cod_info = *cod_info;
1289             memcpy(bst_xrpow, xrpow, sizeof(FLOAT) * 576);
1290 
1291             /*  try with fewer bits
1292              */
1293             max_bits = real_bits - 32;
1294             dbits = max_bits - min_bits;
1295             this_bits = (max_bits + min_bits) / 2;
1296         }
1297         else {
1298             /*  try with more bits
1299              */
1300             min_bits = this_bits + 32;
1301             dbits = max_bits - min_bits;
1302             this_bits = (max_bits + min_bits) / 2;
1303 
1304             if (found) {
1305                 found = 2;
1306                 /*  start again with best quantization so far
1307                  */
1308                 *cod_info = bst_cod_info;
1309                 memcpy(xrpow, bst_xrpow, sizeof(FLOAT) * 576);
1310             }
1311         }
1312     } while (dbits > 12);
1313 
1314     gfc->sv_qnt.sfb21_extra = sfb21_extra;
1315 
1316     /*  found=0 => nothing found, use last one
1317      *  found=1 => we just found the best and left the loop
1318      *  found=2 => we restored a good one and have now l3_enc to restore too
1319      */
1320     if (found == 2) {
1321         memcpy(cod_info->l3_enc, bst_cod_info.l3_enc, sizeof(int) * 576);
1322     }
1323     assert(cod_info->part2_3_length <= Max_bits);
1324 
1325 }
1326 
1327 
1328 
1329 /************************************************************************
1330  *
1331  *      get_framebits()
1332  *
1333  *  Robert Hegemann 2000-09-05
1334  *
1335  *  calculates
1336  *  * how many bits are available for analog silent granules
1337  *  * how many bits to use for the lowest allowed bitrate
1338  *  * how many bits each bitrate would provide
1339  *
1340  ************************************************************************/
1341 
1342 static void
get_framebits(lame_internal_flags * gfc,int frameBits[15])1343 get_framebits(lame_internal_flags * gfc, int frameBits[15])
1344 {
1345     SessionConfig_t const *const cfg = &gfc->cfg;
1346     EncResult_t *const eov = &gfc->ov_enc;
1347     int     bitsPerFrame, i;
1348 
1349     /*  always use at least this many bits per granule per channel
1350      *  unless we detect analog silence, see below
1351      */
1352     eov->bitrate_index = cfg->vbr_min_bitrate_index;
1353     bitsPerFrame = getframebits(gfc);
1354 
1355     /*  bits for analog silence
1356      */
1357     eov->bitrate_index = 1;
1358     bitsPerFrame = getframebits(gfc);
1359 
1360     for (i = 1; i <= cfg->vbr_max_bitrate_index; i++) {
1361         eov->bitrate_index = i;
1362         frameBits[i] = ResvFrameBegin(gfc, &bitsPerFrame);
1363     }
1364 }
1365 
1366 
1367 
1368 /*********************************************************************
1369  *
1370  *      VBR_prepare()
1371  *
1372  *  2000-09-04 Robert Hegemann
1373  *
1374  *  * converts LR to MS coding when necessary
1375  *  * calculates allowed/adjusted quantization noise amounts
1376  *  * detects analog silent frames
1377  *
1378  *  some remarks:
1379  *  - lower masking depending on Quality setting
1380  *  - quality control together with adjusted ATH MDCT scaling
1381  *    on lower quality setting allocate more noise from
1382  *    ATH masking, and on higher quality setting allocate
1383  *    less noise from ATH masking.
1384  *  - experiments show that going more than 2dB over GPSYCHO's
1385  *    limits ends up in very annoying artefacts
1386  *
1387  *********************************************************************/
1388 
1389 /* RH: this one needs to be overhauled sometime */
1390 
1391 static int
VBR_old_prepare(lame_internal_flags * gfc,const FLOAT pe[2][2],FLOAT const ms_ener_ratio[2],const III_psy_ratio ratio[2][2],FLOAT l3_xmin[2][2][SFBMAX],int frameBits[16],int min_bits[2][2],int max_bits[2][2],int bands[2][2])1392 VBR_old_prepare(lame_internal_flags * gfc,
1393                 const FLOAT pe[2][2], FLOAT const ms_ener_ratio[2],
1394                 const III_psy_ratio ratio[2][2],
1395                 FLOAT l3_xmin[2][2][SFBMAX],
1396                 int frameBits[16], int min_bits[2][2], int max_bits[2][2], int bands[2][2])
1397 {
1398     SessionConfig_t const *const cfg = &gfc->cfg;
1399     EncResult_t *const eov = &gfc->ov_enc;
1400 
1401     FLOAT   masking_lower_db, adjust = 0.0;
1402     int     gr, ch;
1403     int     analog_silence = 1;
1404     int     avg, mxb, bits = 0;
1405 
1406     eov->bitrate_index = cfg->vbr_max_bitrate_index;
1407     avg = ResvFrameBegin(gfc, &avg) / cfg->mode_gr;
1408 
1409     get_framebits(gfc, frameBits);
1410 
1411     for (gr = 0; gr < cfg->mode_gr; gr++) {
1412         mxb = on_pe(gfc, pe, max_bits[gr], avg, gr, 0);
1413         if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
1414             ms_convert(&gfc->l3_side, gr);
1415             reduce_side(max_bits[gr], ms_ener_ratio[gr], avg, mxb);
1416         }
1417         for (ch = 0; ch < cfg->channels_out; ++ch) {
1418             gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
1419 
1420             if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
1421                 adjust = 1.28 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.05;
1422                 masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
1423             }
1424             else {
1425                 adjust = 2.56 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.14;
1426                 masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
1427             }
1428             gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
1429 
1430             init_outer_loop(gfc, cod_info);
1431             bands[gr][ch] = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]);
1432             if (bands[gr][ch])
1433                 analog_silence = 0;
1434 
1435             min_bits[gr][ch] = 126;
1436 
1437             bits += max_bits[gr][ch];
1438         }
1439     }
1440     for (gr = 0; gr < cfg->mode_gr; gr++) {
1441         for (ch = 0; ch < cfg->channels_out; ch++) {
1442             if (bits > frameBits[cfg->vbr_max_bitrate_index] && bits > 0) {
1443                 max_bits[gr][ch] *= frameBits[cfg->vbr_max_bitrate_index];
1444                 max_bits[gr][ch] /= bits;
1445             }
1446             if (min_bits[gr][ch] > max_bits[gr][ch])
1447                 min_bits[gr][ch] = max_bits[gr][ch];
1448 
1449         }               /* for ch */
1450     }                   /* for gr */
1451 
1452     return analog_silence;
1453 }
1454 
1455 static void
bitpressure_strategy(lame_internal_flags const * gfc,FLOAT l3_xmin[2][2][SFBMAX],const int min_bits[2][2],int max_bits[2][2])1456 bitpressure_strategy(lame_internal_flags const *gfc,
1457                      FLOAT l3_xmin[2][2][SFBMAX], const int min_bits[2][2], int max_bits[2][2])
1458 {
1459     SessionConfig_t const *const cfg = &gfc->cfg;
1460     int     gr, ch, sfb;
1461     for (gr = 0; gr < cfg->mode_gr; gr++) {
1462         for (ch = 0; ch < cfg->channels_out; ch++) {
1463             gr_info const *const gi = &gfc->l3_side.tt[gr][ch];
1464             FLOAT  *pxmin = l3_xmin[gr][ch];
1465             for (sfb = 0; sfb < gi->psy_lmax; sfb++)
1466                 *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_l / SBMAX_l;
1467 
1468             if (gi->block_type == SHORT_TYPE) {
1469                 for (sfb = gi->sfb_smin; sfb < SBMAX_s; sfb++) {
1470                     *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
1471                     *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
1472                     *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
1473                 }
1474             }
1475             max_bits[gr][ch] = Max(min_bits[gr][ch], 0.9 * max_bits[gr][ch]);
1476         }
1477     }
1478 }
1479 
1480 /************************************************************************
1481  *
1482  *      VBR_iteration_loop()
1483  *
1484  *  tries to find out how many bits are needed for each granule and channel
1485  *  to get an acceptable quantization. An appropriate bitrate will then be
1486  *  choosed for quantization.  rh 8/99
1487  *
1488  *  Robert Hegemann 2000-09-06 rewrite
1489  *
1490  ************************************************************************/
1491 
1492 void
VBR_old_iteration_loop(lame_internal_flags * gfc,const FLOAT pe[2][2],const FLOAT ms_ener_ratio[2],const III_psy_ratio ratio[2][2])1493 VBR_old_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
1494                        const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
1495 {
1496     SessionConfig_t const *const cfg = &gfc->cfg;
1497     EncResult_t *const eov = &gfc->ov_enc;
1498     FLOAT   l3_xmin[2][2][SFBMAX];
1499 
1500     FLOAT   xrpow[576];
1501     int     bands[2][2];
1502     int     frameBits[15];
1503     int     used_bits;
1504     int     bits;
1505     int     min_bits[2][2], max_bits[2][2];
1506     int     mean_bits;
1507     int     ch, gr, analog_silence;
1508     III_side_info_t *const l3_side = &gfc->l3_side;
1509 
1510     analog_silence = VBR_old_prepare(gfc, pe, ms_ener_ratio, ratio,
1511                                      l3_xmin, frameBits, min_bits, max_bits, bands);
1512 
1513     /*---------------------------------*/
1514     for (;;) {
1515 
1516         /*  quantize granules with lowest possible number of bits
1517          */
1518 
1519         used_bits = 0;
1520 
1521         for (gr = 0; gr < cfg->mode_gr; gr++) {
1522             for (ch = 0; ch < cfg->channels_out; ch++) {
1523                 int     ret;
1524                 gr_info *const cod_info = &l3_side->tt[gr][ch];
1525 
1526                 /*  init_outer_loop sets up cod_info, scalefac and xrpow
1527                  */
1528                 ret = init_xrpow(gfc, cod_info, xrpow);
1529                 if (ret == 0 || max_bits[gr][ch] == 0) {
1530                     /*  xr contains no energy
1531                      *  l3_enc, our encoding data, will be quantized to zero
1532                      */
1533                     continue; /* with next channel */
1534                 }
1535 
1536                 VBR_encode_granule(gfc, cod_info, l3_xmin[gr][ch], xrpow,
1537                                    ch, min_bits[gr][ch], max_bits[gr][ch]);
1538 
1539                 /*  do the 'substep shaping'
1540                  */
1541                 if (gfc->sv_qnt.substep_shaping & 1) {
1542                     trancate_smallspectrums(gfc, &l3_side->tt[gr][ch], l3_xmin[gr][ch], xrpow);
1543                 }
1544 
1545                 ret = cod_info->part2_3_length + cod_info->part2_length;
1546                 used_bits += ret;
1547             }           /* for ch */
1548         }               /* for gr */
1549 
1550         /*  find lowest bitrate able to hold used bits
1551          */
1552         if (analog_silence && !cfg->enforce_min_bitrate)
1553             /*  we detected analog silence and the user did not specify
1554              *  any hard framesize limit, so start with smallest possible frame
1555              */
1556             eov->bitrate_index = 1;
1557         else
1558             eov->bitrate_index = cfg->vbr_min_bitrate_index;
1559 
1560         for (; eov->bitrate_index < cfg->vbr_max_bitrate_index; eov->bitrate_index++) {
1561             if (used_bits <= frameBits[eov->bitrate_index])
1562                 break;
1563         }
1564         bits = ResvFrameBegin(gfc, &mean_bits);
1565 
1566         if (used_bits <= bits)
1567             break;
1568 
1569         bitpressure_strategy(gfc, l3_xmin, (const int (*)[2])min_bits, max_bits);
1570 
1571     }                   /* breaks adjusted */
1572     /*--------------------------------------*/
1573 
1574     for (gr = 0; gr < cfg->mode_gr; gr++) {
1575         for (ch = 0; ch < cfg->channels_out; ch++) {
1576             iteration_finish_one(gfc, gr, ch);
1577         }               /* for ch */
1578     }                   /* for gr */
1579     ResvFrameEnd(gfc, mean_bits);
1580 }
1581 
1582 
1583 
1584 static int
VBR_new_prepare(lame_internal_flags * gfc,const FLOAT pe[2][2],const III_psy_ratio ratio[2][2],FLOAT l3_xmin[2][2][SFBMAX],int frameBits[16],int max_bits[2][2],int * max_resv)1585 VBR_new_prepare(lame_internal_flags * gfc,
1586                 const FLOAT pe[2][2], const III_psy_ratio ratio[2][2],
1587                 FLOAT l3_xmin[2][2][SFBMAX], int frameBits[16], int max_bits[2][2],
1588                 int* max_resv)
1589 {
1590     SessionConfig_t const *const cfg = &gfc->cfg;
1591     EncResult_t *const eov = &gfc->ov_enc;
1592 
1593     int     gr, ch;
1594     int     analog_silence = 1;
1595     int     avg, bits = 0;
1596     int     maximum_framebits;
1597 
1598     if (!cfg->free_format) {
1599         eov->bitrate_index = cfg->vbr_max_bitrate_index;
1600         (void) ResvFrameBegin(gfc, &avg);
1601         *max_resv = gfc->sv_enc.ResvMax;
1602 
1603         get_framebits(gfc, frameBits);
1604         maximum_framebits = frameBits[cfg->vbr_max_bitrate_index];
1605     }
1606     else {
1607         eov->bitrate_index = 0;
1608         maximum_framebits = ResvFrameBegin(gfc, &avg);
1609         frameBits[0] = maximum_framebits;
1610         *max_resv = gfc->sv_enc.ResvMax;
1611     }
1612 
1613     for (gr = 0; gr < cfg->mode_gr; gr++) {
1614         (void) on_pe(gfc, pe, max_bits[gr], avg, gr, 0);
1615         if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
1616             ms_convert(&gfc->l3_side, gr);
1617         }
1618         for (ch = 0; ch < cfg->channels_out; ++ch) {
1619             gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
1620 
1621             gfc->sv_qnt.masking_lower = pow(10.0, gfc->sv_qnt.mask_adjust * 0.1);
1622 
1623             init_outer_loop(gfc, cod_info);
1624             if (0 != calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]))
1625                 analog_silence = 0;
1626 
1627             bits += max_bits[gr][ch];
1628         }
1629     }
1630     for (gr = 0; gr < cfg->mode_gr; gr++) {
1631         for (ch = 0; ch < cfg->channels_out; ch++) {
1632             if (bits > maximum_framebits && bits > 0) {
1633                 max_bits[gr][ch] *= maximum_framebits;
1634                 max_bits[gr][ch] /= bits;
1635             }
1636 
1637         }               /* for ch */
1638     }                   /* for gr */
1639     if (analog_silence) {
1640         *max_resv = 0;
1641     }
1642     return analog_silence;
1643 }
1644 
1645 
1646 
1647 void
VBR_new_iteration_loop(lame_internal_flags * gfc,const FLOAT pe[2][2],const FLOAT ms_ener_ratio[2],const III_psy_ratio ratio[2][2])1648 VBR_new_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
1649                        const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
1650 {
1651     SessionConfig_t const *const cfg = &gfc->cfg;
1652     EncResult_t *const eov = &gfc->ov_enc;
1653     FLOAT   l3_xmin[2][2][SFBMAX];
1654 
1655     FLOAT   xrpow[2][2][576];
1656     int     frameBits[15];
1657     int     used_bits;
1658     int     max_bits[2][2];
1659     int     ch, gr, analog_silence, pad;
1660     III_side_info_t *const l3_side = &gfc->l3_side;
1661 
1662     const FLOAT (*const_l3_xmin)[2][SFBMAX] = (const FLOAT (*)[2][SFBMAX])l3_xmin;
1663     const FLOAT (*const_xrpow)[2][576] = (const FLOAT (*)[2][576])xrpow;
1664     const int (*const_max_bits)[2] = (const int (*)[2])max_bits;
1665 
1666     (void) ms_ener_ratio; /* not used */
1667 
1668     memset(xrpow, 0, sizeof(xrpow));
1669 
1670     analog_silence = VBR_new_prepare(gfc, pe, ratio, l3_xmin, frameBits, max_bits, &pad);
1671 
1672     for (gr = 0; gr < cfg->mode_gr; gr++) {
1673         for (ch = 0; ch < cfg->channels_out; ch++) {
1674             gr_info *const cod_info = &l3_side->tt[gr][ch];
1675 
1676             /*  init_outer_loop sets up cod_info, scalefac and xrpow
1677              */
1678             if (0 == init_xrpow(gfc, cod_info, xrpow[gr][ch])) {
1679                 max_bits[gr][ch] = 0; /* silent granule needs no bits */
1680             }
1681         }               /* for ch */
1682     }                   /* for gr */
1683 
1684     /*  quantize granules with lowest possible number of bits
1685      */
1686 
1687     used_bits = VBR_encode_frame(gfc, const_xrpow, const_l3_xmin, const_max_bits);
1688 
1689     if (!cfg->free_format) {
1690         int     i, j;
1691 
1692         /*  find lowest bitrate able to hold used bits
1693          */
1694         if (analog_silence && !cfg->enforce_min_bitrate) {
1695             /*  we detected analog silence and the user did not specify
1696              *  any hard framesize limit, so start with smallest possible frame
1697              */
1698             i = 1;
1699         }
1700         else {
1701             i = cfg->vbr_min_bitrate_index;
1702         }
1703 
1704         for (; i < cfg->vbr_max_bitrate_index; i++) {
1705             if (used_bits <= frameBits[i])
1706                 break;
1707         }
1708         if (i > cfg->vbr_max_bitrate_index) {
1709             i = cfg->vbr_max_bitrate_index;
1710         }
1711         if (pad > 0) {
1712             for (j = cfg->vbr_max_bitrate_index; j > i; --j) {
1713                 int const unused = frameBits[j] - used_bits;
1714                 if (unused <= pad)
1715                     break;
1716             }
1717             eov->bitrate_index = j;
1718         }
1719         else {
1720             eov->bitrate_index = i;
1721         }
1722     }
1723     else {
1724 #if 0
1725         static int mmm = 0;
1726         int     fff = getFramesize_kbps(gfc, used_bits);
1727         int     hhh = getFramesize_kbps(gfc, MAX_BITS_PER_GRANULE * cfg->mode_gr);
1728         if (mmm < fff)
1729             mmm = fff;
1730         printf("demand=%3d kbps  max=%3d kbps   limit=%3d kbps\n", fff, mmm, hhh);
1731 #endif
1732         eov->bitrate_index = 0;
1733     }
1734     if (used_bits <= frameBits[eov->bitrate_index]) {
1735         /* update Reservoire status */
1736         int     mean_bits, fullframebits;
1737         fullframebits = ResvFrameBegin(gfc, &mean_bits);
1738         if (used_bits > fullframebits) {
1739             assert(used_bits <= fullframebits);
1740         }
1741         for (gr = 0; gr < cfg->mode_gr; gr++) {
1742             for (ch = 0; ch < cfg->channels_out; ch++) {
1743                 gr_info const *const cod_info = &l3_side->tt[gr][ch];
1744                 ResvAdjust(gfc, cod_info);
1745             }
1746         }
1747         ResvFrameEnd(gfc, mean_bits);
1748     }
1749     else {
1750         /* SHOULD NOT HAPPEN INTERNAL ERROR
1751          */
1752         ERRORF(gfc, "INTERNAL ERROR IN VBR NEW CODE, please send bug report\n");
1753         exit(-1);
1754     }
1755 }
1756 
1757 
1758 
1759 
1760 
1761 /********************************************************************
1762  *
1763  *  calc_target_bits()
1764  *
1765  *  calculates target bits for ABR encoding
1766  *
1767  *  mt 2000/05/31
1768  *
1769  ********************************************************************/
1770 
1771 static void
calc_target_bits(lame_internal_flags * gfc,const FLOAT pe[2][2],FLOAT const ms_ener_ratio[2],int targ_bits[2][2],int * analog_silence_bits,int * max_frame_bits)1772 calc_target_bits(lame_internal_flags * gfc,
1773                  const FLOAT pe[2][2],
1774                  FLOAT const ms_ener_ratio[2],
1775                  int targ_bits[2][2], int *analog_silence_bits, int *max_frame_bits)
1776 {
1777     SessionConfig_t const *const cfg = &gfc->cfg;
1778     EncResult_t *const eov = &gfc->ov_enc;
1779     III_side_info_t const *const l3_side = &gfc->l3_side;
1780     FLOAT   res_factor;
1781     int     gr, ch, totbits, mean_bits;
1782     int     framesize = 576 * cfg->mode_gr;
1783 
1784     eov->bitrate_index = cfg->vbr_max_bitrate_index;
1785     *max_frame_bits = ResvFrameBegin(gfc, &mean_bits);
1786 
1787     eov->bitrate_index = 1;
1788     mean_bits = getframebits(gfc) - cfg->sideinfo_len * 8;
1789     *analog_silence_bits = mean_bits / (cfg->mode_gr * cfg->channels_out);
1790 
1791     mean_bits = cfg->vbr_avg_bitrate_kbps * framesize * 1000;
1792     if (gfc->sv_qnt.substep_shaping & 1)
1793         mean_bits *= 1.09;
1794     mean_bits /= cfg->samplerate_out;
1795     mean_bits -= cfg->sideinfo_len * 8;
1796     mean_bits /= (cfg->mode_gr * cfg->channels_out);
1797 
1798     /*
1799        res_factor is the percentage of the target bitrate that should
1800        be used on average.  the remaining bits are added to the
1801        bitreservoir and used for difficult to encode frames.
1802 
1803        Since we are tracking the average bitrate, we should adjust
1804        res_factor "on the fly", increasing it if the average bitrate
1805        is greater than the requested bitrate, and decreasing it
1806        otherwise.  Reasonable ranges are from .9 to 1.0
1807 
1808        Until we get the above suggestion working, we use the following
1809        tuning:
1810        compression ratio    res_factor
1811        5.5  (256kbps)         1.0      no need for bitreservoir
1812        11   (128kbps)         .93      7% held for reservoir
1813 
1814        with linear interpolation for other values.
1815 
1816      */
1817     res_factor = .93 + .07 * (11.0 - cfg->compression_ratio) / (11.0 - 5.5);
1818     if (res_factor < .90)
1819         res_factor = .90;
1820     if (res_factor > 1.00)
1821         res_factor = 1.00;
1822 
1823     for (gr = 0; gr < cfg->mode_gr; gr++) {
1824         int     sum = 0;
1825         for (ch = 0; ch < cfg->channels_out; ch++) {
1826             targ_bits[gr][ch] = res_factor * mean_bits;
1827 
1828             if (pe[gr][ch] > 700) {
1829                 int     add_bits = (pe[gr][ch] - 700) / 1.4;
1830 
1831                 gr_info const *const cod_info = &l3_side->tt[gr][ch];
1832                 targ_bits[gr][ch] = res_factor * mean_bits;
1833 
1834                 /* short blocks use a little extra, no matter what the pe */
1835                 if (cod_info->block_type == SHORT_TYPE) {
1836                     if (add_bits < mean_bits / 2)
1837                         add_bits = mean_bits / 2;
1838                 }
1839                 /* at most increase bits by 1.5*average */
1840                 if (add_bits > mean_bits * 3 / 2)
1841                     add_bits = mean_bits * 3 / 2;
1842                 else if (add_bits < 0)
1843                     add_bits = 0;
1844 
1845                 targ_bits[gr][ch] += add_bits;
1846             }
1847             if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL) {
1848                 targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
1849             }
1850             sum += targ_bits[gr][ch];
1851         }               /* for ch */
1852         if (sum > MAX_BITS_PER_GRANULE) {
1853             for (ch = 0; ch < cfg->channels_out; ++ch) {
1854                 targ_bits[gr][ch] *= MAX_BITS_PER_GRANULE;
1855                 targ_bits[gr][ch] /= sum;
1856             }
1857         }
1858     }                   /* for gr */
1859 
1860     if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR)
1861         for (gr = 0; gr < cfg->mode_gr; gr++) {
1862             reduce_side(targ_bits[gr], ms_ener_ratio[gr], mean_bits * cfg->channels_out,
1863                         MAX_BITS_PER_GRANULE);
1864         }
1865 
1866     /*  sum target bits
1867      */
1868     totbits = 0;
1869     for (gr = 0; gr < cfg->mode_gr; gr++) {
1870         for (ch = 0; ch < cfg->channels_out; ch++) {
1871             if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL)
1872                 targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
1873             totbits += targ_bits[gr][ch];
1874         }
1875     }
1876 
1877     /*  repartion target bits if needed
1878      */
1879     if (totbits > *max_frame_bits && totbits > 0) {
1880         for (gr = 0; gr < cfg->mode_gr; gr++) {
1881             for (ch = 0; ch < cfg->channels_out; ch++) {
1882                 targ_bits[gr][ch] *= *max_frame_bits;
1883                 targ_bits[gr][ch] /= totbits;
1884             }
1885         }
1886     }
1887 }
1888 
1889 
1890 
1891 
1892 
1893 
1894 /********************************************************************
1895  *
1896  *  ABR_iteration_loop()
1897  *
1898  *  encode a frame with a disired average bitrate
1899  *
1900  *  mt 2000/05/31
1901  *
1902  ********************************************************************/
1903 
1904 void
ABR_iteration_loop(lame_internal_flags * gfc,const FLOAT pe[2][2],const FLOAT ms_ener_ratio[2],const III_psy_ratio ratio[2][2])1905 ABR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
1906                    const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
1907 {
1908     SessionConfig_t const *const cfg = &gfc->cfg;
1909     EncResult_t *const eov = &gfc->ov_enc;
1910     FLOAT   l3_xmin[SFBMAX];
1911     FLOAT   xrpow[576];
1912     int     targ_bits[2][2];
1913     int     mean_bits, max_frame_bits;
1914     int     ch, gr, ath_over;
1915     int     analog_silence_bits;
1916     gr_info *cod_info;
1917     III_side_info_t *const l3_side = &gfc->l3_side;
1918 
1919     mean_bits = 0;
1920 
1921     calc_target_bits(gfc, pe, ms_ener_ratio, targ_bits, &analog_silence_bits, &max_frame_bits);
1922 
1923     /*  encode granules
1924      */
1925     for (gr = 0; gr < cfg->mode_gr; gr++) {
1926 
1927         if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
1928             ms_convert(&gfc->l3_side, gr);
1929         }
1930         for (ch = 0; ch < cfg->channels_out; ch++) {
1931             FLOAT   adjust, masking_lower_db;
1932             cod_info = &l3_side->tt[gr][ch];
1933 
1934             if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
1935                 /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
1936                 adjust = 0;
1937                 masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
1938             }
1939             else {
1940                 /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
1941                 adjust = 0;
1942                 masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
1943             }
1944             gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
1945 
1946 
1947             /*  cod_info, scalefac and xrpow get initialized in init_outer_loop
1948              */
1949             init_outer_loop(gfc, cod_info);
1950             if (init_xrpow(gfc, cod_info, xrpow)) {
1951                 /*  xr contains energy we will have to encode
1952                  *  calculate the masking abilities
1953                  *  find some good quantization in outer_loop
1954                  */
1955                 ath_over = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);
1956                 if (0 == ath_over) /* analog silence */
1957                     targ_bits[gr][ch] = analog_silence_bits;
1958 
1959                 (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[gr][ch]);
1960             }
1961             iteration_finish_one(gfc, gr, ch);
1962         }               /* ch */
1963     }                   /* gr */
1964 
1965     /*  find a bitrate which can refill the resevoir to positive size.
1966      */
1967     for (eov->bitrate_index = cfg->vbr_min_bitrate_index;
1968          eov->bitrate_index <= cfg->vbr_max_bitrate_index; eov->bitrate_index++) {
1969         if (ResvFrameBegin(gfc, &mean_bits) >= 0)
1970             break;
1971     }
1972     assert(eov->bitrate_index <= cfg->vbr_max_bitrate_index);
1973 
1974     ResvFrameEnd(gfc, mean_bits);
1975 }
1976 
1977 
1978 
1979 
1980 
1981 
1982 /************************************************************************
1983  *
1984  *      CBR_iteration_loop()
1985  *
1986  *  author/date??
1987  *
1988  *  encodes one frame of MP3 data with constant bitrate
1989  *
1990  ************************************************************************/
1991 
1992 void
CBR_iteration_loop(lame_internal_flags * gfc,const FLOAT pe[2][2],const FLOAT ms_ener_ratio[2],const III_psy_ratio ratio[2][2])1993 CBR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
1994                    const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
1995 {
1996     SessionConfig_t const *const cfg = &gfc->cfg;
1997     FLOAT   l3_xmin[SFBMAX];
1998     FLOAT   xrpow[576];
1999     int     targ_bits[2];
2000     int     mean_bits, max_bits;
2001     int     gr, ch;
2002     III_side_info_t *const l3_side = &gfc->l3_side;
2003     gr_info *cod_info;
2004 
2005     (void) ResvFrameBegin(gfc, &mean_bits);
2006 
2007     /* quantize! */
2008     for (gr = 0; gr < cfg->mode_gr; gr++) {
2009 
2010         /*  calculate needed bits
2011          */
2012         max_bits = on_pe(gfc, pe, targ_bits, mean_bits, gr, gr);
2013 
2014         if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
2015             ms_convert(&gfc->l3_side, gr);
2016             reduce_side(targ_bits, ms_ener_ratio[gr], mean_bits, max_bits);
2017         }
2018 
2019         for (ch = 0; ch < cfg->channels_out; ch++) {
2020             FLOAT   adjust, masking_lower_db;
2021             cod_info = &l3_side->tt[gr][ch];
2022 
2023             if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
2024                 /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
2025                 adjust = 0;
2026                 masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
2027             }
2028             else {
2029                 /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
2030                 adjust = 0;
2031                 masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
2032             }
2033             gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
2034 
2035             /*  init_outer_loop sets up cod_info, scalefac and xrpow
2036              */
2037             init_outer_loop(gfc, cod_info);
2038             if (init_xrpow(gfc, cod_info, xrpow)) {
2039                 /*  xr contains energy we will have to encode
2040                  *  calculate the masking abilities
2041                  *  find some good quantization in outer_loop
2042                  */
2043                 (void) calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);
2044                 (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[ch]);
2045             }
2046 
2047             iteration_finish_one(gfc, gr, ch);
2048             assert(cod_info->part2_3_length <= MAX_BITS_PER_CHANNEL);
2049             assert(cod_info->part2_3_length <= targ_bits[ch]);
2050         }               /* for ch */
2051     }                   /* for gr */
2052 
2053     ResvFrameEnd(gfc, mean_bits);
2054 }
2055