quantize.c

Go to the documentation of this file.
00001 /*
00002  * MP3 quantization
00003  *
00004  *      Copyright (c) 1999-2000 Mark Taylor
00005  *      Copyright (c) 1999-2003 Takehiro Tominaga
00006  *      Copyright (c) 2000-2007 Robert Hegemann
00007  *      Copyright (c) 2001-2005 Gabriel Bouvigne
00008  *
00009  * This library is free software; you can redistribute it and/or
00010  * modify it under the terms of the GNU Lesser General Public
00011  * License as published by the Free Software Foundation; either
00012  * version 2 of the License, or (at your option) any later version.
00013  *
00014  * This library is distributed in the hope that it will be useful,
00015  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00016  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
00017  * Library General Public License for more details.
00018  *
00019  * You should have received a copy of the GNU Lesser General Public
00020  * License along with this library; if not, write to the
00021  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00022  * Boston, MA 02111-1307, USA.
00023  */
00024 
00025 /* $Id: quantize.c,v 1.191 2007/07/24 17:46:10 bouvigne Exp $ */
00026 
00027 #ifdef HAVE_CONFIG_H
00028 # include <config.h>
00029 #endif
00030 
00031 #include "lame.h"
00032 #include "machine.h"
00033 #include "encoder.h"
00034 #include "util.h"
00035 #include "quantize_pvt.h"
00036 #include "lame_global_flags.h"
00037 #include "reservoir.h"
00038 #include "bitstream.h"
00039 #include "vbrquantize.h"
00040 #include "quantize.h"
00041 #ifdef HAVE_XMMINTRIN_H
00042 #include "vector/lame_intrin.h"
00043 #endif
00044 
00045 
00046 
00047 
00048 /* convert from L/R <-> Mid/Side */
00049 static void
00050 ms_convert(III_side_info_t * l3_side, int gr)
00051 {
00052     int     i;
00053     for (i = 0; i < 576; ++i) {
00054         FLOAT   l, r;
00055         l = l3_side->tt[gr][0].xr[i];
00056         r = l3_side->tt[gr][1].xr[i];
00057         l3_side->tt[gr][0].xr[i] = (l + r) * (FLOAT) (SQRT2 * 0.5);
00058         l3_side->tt[gr][1].xr[i] = (l - r) * (FLOAT) (SQRT2 * 0.5);
00059     }
00060 }
00061 
00062 /************************************************************************
00063  *
00064  *      init_outer_loop()
00065  *  mt 6/99
00066  *
00067  *  initializes cod_info, scalefac and xrpow
00068  *
00069  *  returns 0 if all energies in xr are zero, else 1
00070  *
00071  ************************************************************************/
00072 
00073 static
00074     void
00075 init_xrpow_core_c(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum)
00076 {
00077     int     i;
00078     FLOAT   tmp;
00079     *sum = 0;
00080     for (i = 0; i <= upper; ++i) {
00081         tmp = fabs(cod_info->xr[i]);
00082         *sum += tmp;
00083         xrpow[i] = sqrt(tmp * sqrt(tmp));
00084 
00085         if (xrpow[i] > cod_info->xrpow_max)
00086             cod_info->xrpow_max = xrpow[i];
00087     }
00088 }
00089 
00090 
00091 
00092 
00093 
00094 void
00095 init_xrpow_core_init(lame_internal_flags * const gfc)
00096 {
00097     gfc->init_xrpow_core = init_xrpow_core_c;
00098 
00099 #if defined(HAVE_XMMINTRIN_H)
00100     if (gfc->CPU_features.SSE)
00101         gfc->init_xrpow_core = init_xrpow_core_sse;
00102 #endif
00103 }
00104 
00105 
00106 
00107 static int
00108 init_xrpow(lame_internal_flags * gfc, gr_info * const cod_info, FLOAT xrpow[576])
00109 {
00110     FLOAT   sum = 0;
00111     int     i;
00112     int const upper = cod_info->max_nonzero_coeff;
00113 
00114     assert(xrpow != NULL);
00115     cod_info->xrpow_max = 0;
00116 
00117     /*  check if there is some energy we have to quantize
00118      *  and calculate xrpow matching our fresh scalefactors
00119      */
00120     assert( 0 <= upper && upper <= 575 );
00121     memset(&(xrpow[upper]), 0, (576 - upper) * sizeof(xrpow[0]));
00122 
00123 
00124     gfc->init_xrpow_core(cod_info, xrpow, upper, &sum);
00125 
00126     /*  return 1 if we have something to quantize, else 0
00127      */
00128     if (sum > (FLOAT) 1E-20) {
00129         int     j = 0;
00130         if (gfc->substep_shaping & 2)
00131             j = 1;
00132 
00133         for (i = 0; i < cod_info->psymax; i++)
00134             gfc->pseudohalf[i] = j;
00135 
00136         return 1;
00137     }
00138 
00139     memset(&cod_info->l3_enc[0], 0, sizeof(int) * 576);
00140     return 0;
00141 }
00142 
00143 
00144 
00145 
00146 
00147 extern FLOAT athAdjust(FLOAT a, FLOAT x, FLOAT athFloor);
00148 
00149 
00150 
00151 /*
00152 Gabriel Bouvigne feb/apr 2003
00153 Analog silence detection in partitionned sfb21
00154 or sfb12 for short blocks
00155 
00156 From top to bottom of sfb, changes to 0
00157 coeffs which are below ath. It stops on the first
00158 coeff higher than ath.
00159 */
00160 static void
00161 psfb21_analogsilence(lame_internal_flags const *gfc, gr_info * const cod_info)
00162 {
00163     ATH_t const *const ATH = gfc->ATH;
00164     FLOAT  *const xr = cod_info->xr;
00165 
00166     if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT blocks */
00167         int     gsfb;
00168         int     stop = 0;
00169         for (gsfb = PSFB21 - 1; gsfb >= 0 && !stop; gsfb--) {
00170             int const start = gfc->scalefac_band.psfb21[gsfb];
00171             int const end = gfc->scalefac_band.psfb21[gsfb + 1];
00172             int     j;
00173             FLOAT   ath21;
00174             ath21 = athAdjust(ATH->adjust, ATH->psfb21[gsfb], ATH->floor);
00175 
00176             if (gfc->nsPsy.longfact[21] != 0)
00177                 ath21 *= gfc->nsPsy.longfact[21];
00178 
00179             for (j = end - 1; j >= start; j--) {
00180                 if (fabs(xr[j]) < ath21)
00181                     xr[j] = 0;
00182                 else {
00183                     stop = 1;
00184                     break;
00185                 }
00186             }
00187         }
00188     }
00189     else {
00190         /*note: short blocks coeffs are reordered */
00191         int     block;
00192         for (block = 0; block < 3; block++) {
00193 
00194             int     gsfb;
00195             int     stop = 0;
00196             for (gsfb = PSFB12 - 1; gsfb >= 0 && !stop; gsfb--) {
00197                 int const start = gfc->scalefac_band.s[12] * 3 +
00198                     (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) * block +
00199                     (gfc->scalefac_band.psfb12[gsfb] - gfc->scalefac_band.psfb12[0]);
00200                 int const end =
00201                     start + (gfc->scalefac_band.psfb12[gsfb + 1] - gfc->scalefac_band.psfb12[gsfb]);
00202                 int     j;
00203                 FLOAT   ath12;
00204                 ath12 = athAdjust(ATH->adjust, ATH->psfb12[gsfb], ATH->floor);
00205 
00206                 if (gfc->nsPsy.shortfact[12] != 0)
00207                     ath12 *= gfc->nsPsy.shortfact[12];
00208 
00209                 for (j = end - 1; j >= start; j--) {
00210                     if (fabs(xr[j]) < ath12)
00211                         xr[j] = 0;
00212                     else {
00213                         stop = 1;
00214                         break;
00215                     }
00216                 }
00217             }
00218         }
00219     }
00220 
00221 }
00222 
00223 
00224 
00225 
00226 
00227 static void
00228 init_outer_loop(lame_internal_flags const *gfc, gr_info * const cod_info)
00229 {
00230     int     sfb, j;
00231     /*  initialize fresh cod_info
00232      */
00233     cod_info->part2_3_length = 0;
00234     cod_info->big_values = 0;
00235     cod_info->count1 = 0;
00236     cod_info->global_gain = 210;
00237     cod_info->scalefac_compress = 0;
00238     /* mixed_block_flag, block_type was set in psymodel.c */
00239     cod_info->table_select[0] = 0;
00240     cod_info->table_select[1] = 0;
00241     cod_info->table_select[2] = 0;
00242     cod_info->subblock_gain[0] = 0;
00243     cod_info->subblock_gain[1] = 0;
00244     cod_info->subblock_gain[2] = 0;
00245     cod_info->subblock_gain[3] = 0; /* this one is always 0 */
00246     cod_info->region0_count = 0;
00247     cod_info->region1_count = 0;
00248     cod_info->preflag = 0;
00249     cod_info->scalefac_scale = 0;
00250     cod_info->count1table_select = 0;
00251     cod_info->part2_length = 0;
00252     cod_info->sfb_lmax = SBPSY_l;
00253     cod_info->sfb_smin = SBPSY_s;
00254     cod_info->psy_lmax = gfc->sfb21_extra ? SBMAX_l : SBPSY_l;
00255     cod_info->psymax = cod_info->psy_lmax;
00256     cod_info->sfbmax = cod_info->sfb_lmax;
00257     cod_info->sfbdivide = 11;
00258     for (sfb = 0; sfb < SBMAX_l; sfb++) {
00259         cod_info->width[sfb]
00260             = gfc->scalefac_band.l[sfb + 1] - gfc->scalefac_band.l[sfb];
00261         cod_info->window[sfb] = 3; /* which is always 0. */
00262     }
00263     if (cod_info->block_type == SHORT_TYPE) {
00264         FLOAT   ixwork[576];
00265         FLOAT  *ix;
00266 
00267         cod_info->sfb_smin = 0;
00268         cod_info->sfb_lmax = 0;
00269         if (cod_info->mixed_block_flag) {
00270             /*
00271              *  MPEG-1:      sfbs 0-7 long block, 3-12 short blocks
00272              *  MPEG-2(.5):  sfbs 0-5 long block, 3-12 short blocks
00273              */
00274             cod_info->sfb_smin = 3;
00275             cod_info->sfb_lmax = gfc->mode_gr * 2 + 4;
00276         }
00277         cod_info->psymax
00278             = cod_info->sfb_lmax
00279             + 3 * ((gfc->sfb21_extra ? SBMAX_s : SBPSY_s) - cod_info->sfb_smin);
00280         cod_info->sfbmax = cod_info->sfb_lmax + 3 * (SBPSY_s - cod_info->sfb_smin);
00281         cod_info->sfbdivide = cod_info->sfbmax - 18;
00282         cod_info->psy_lmax = cod_info->sfb_lmax;
00283         /* re-order the short blocks, for more efficient encoding below */
00284         /* By Takehiro TOMINAGA */
00285         /*
00286            Within each scalefactor band, data is given for successive
00287            time windows, beginning with window 0 and ending with window 2.
00288            Within each window, the quantized values are then arranged in
00289            order of increasing frequency...
00290          */
00291         ix = &cod_info->xr[gfc->scalefac_band.l[cod_info->sfb_lmax]];
00292         memcpy(ixwork, cod_info->xr, 576 * sizeof(FLOAT));
00293         for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
00294             int const start = gfc->scalefac_band.s[sfb];
00295             int const end = gfc->scalefac_band.s[sfb + 1];
00296             int     window, l;
00297             for (window = 0; window < 3; window++) {
00298                 for (l = start; l < end; l++) {
00299                     *ix++ = ixwork[3 * l + window];
00300                 }
00301             }
00302         }
00303 
00304         j = cod_info->sfb_lmax;
00305         for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
00306             cod_info->width[j] = cod_info->width[j + 1] = cod_info->width[j + 2]
00307                 = gfc->scalefac_band.s[sfb + 1] - gfc->scalefac_band.s[sfb];
00308             cod_info->window[j] = 0;
00309             cod_info->window[j + 1] = 1;
00310             cod_info->window[j + 2] = 2;
00311             j += 3;
00312         }
00313     }
00314 
00315     cod_info->count1bits = 0;
00316     cod_info->sfb_partition_table = nr_of_sfb_block[0][0];
00317     cod_info->slen[0] = 0;
00318     cod_info->slen[1] = 0;
00319     cod_info->slen[2] = 0;
00320     cod_info->slen[3] = 0;
00321 
00322     cod_info->max_nonzero_coeff = 575;
00323 
00324     /*  fresh scalefactors are all zero
00325      */
00326     memset(cod_info->scalefac, 0, sizeof(cod_info->scalefac));
00327 
00328     psfb21_analogsilence(gfc, cod_info);
00329 }
00330 
00331 
00332 
00333 /************************************************************************
00334  *
00335  *      bin_search_StepSize()
00336  *
00337  *  author/date??
00338  *
00339  *  binary step size search
00340  *  used by outer_loop to get a quantizer step size to start with
00341  *
00342  ************************************************************************/
00343 
00344 typedef enum {
00345     BINSEARCH_NONE,
00346     BINSEARCH_UP,
00347     BINSEARCH_DOWN
00348 } binsearchDirection_t;
00349 
00350 int
00351 bin_search_StepSize(lame_internal_flags * const gfc,
00352                     gr_info * const cod_info,
00353                     int desired_rate, const int ch, const FLOAT xrpow[576])
00354 {
00355     int     nBits;
00356     int     CurrentStep = gfc->CurrentStep[ch];
00357     int     flag_GoneOver = 0;
00358     int const start = gfc->OldValue[ch];
00359     binsearchDirection_t Direction = BINSEARCH_NONE;
00360     cod_info->global_gain = start;
00361     desired_rate -= cod_info->part2_length;
00362 
00363     assert(CurrentStep);
00364     do {
00365         int     step;
00366         nBits = count_bits(gfc, xrpow, cod_info, 0);
00367 
00368         if (CurrentStep == 1 || nBits == desired_rate)
00369             break;      /* nothing to adjust anymore */
00370 
00371         if (nBits > desired_rate) {
00372             /* increase Quantize_StepSize */
00373             if (Direction == BINSEARCH_DOWN)
00374                 flag_GoneOver = 1;
00375 
00376             if (flag_GoneOver)
00377                 CurrentStep /= 2;
00378             Direction = BINSEARCH_UP;
00379             step = CurrentStep;
00380         }
00381         else {
00382             /* decrease Quantize_StepSize */
00383             if (Direction == BINSEARCH_UP)
00384                 flag_GoneOver = 1;
00385 
00386             if (flag_GoneOver)
00387                 CurrentStep /= 2;
00388             Direction = BINSEARCH_DOWN;
00389             step = -CurrentStep;
00390         }
00391         cod_info->global_gain += step;
00392     } while (cod_info->global_gain < 256u);
00393 
00394     if (cod_info->global_gain < 0) {
00395         cod_info->global_gain = 0;
00396         nBits = count_bits(gfc, xrpow, cod_info, 0);
00397     }
00398     else if (cod_info->global_gain > 255) {
00399         cod_info->global_gain = 255;
00400         nBits = count_bits(gfc, xrpow, cod_info, 0);
00401     }
00402     else if (nBits > desired_rate) {
00403         cod_info->global_gain++;
00404         nBits = count_bits(gfc, xrpow, cod_info, 0);
00405     }
00406     gfc->CurrentStep[ch] = (start - cod_info->global_gain >= 4) ? 4 : 2;
00407     gfc->OldValue[ch] = cod_info->global_gain;
00408     cod_info->part2_3_length = nBits;
00409     return nBits;
00410 }
00411 
00412 
00413 
00414 
00415 /************************************************************************
00416  *
00417  *      trancate_smallspectrums()
00418  *
00419  *  Takehiro TOMINAGA 2002-07-21
00420  *
00421  *  trancate smaller nubmers into 0 as long as the noise threshold is allowed.
00422  *
00423  ************************************************************************/
00424 static int
00425 floatcompare(const void *v1, const void *v2)
00426 {
00427     const FLOAT *const a = v1, *const b = v2;
00428     if (*a > *b)
00429         return 1;
00430     if (*a == *b)
00431         return 0;
00432     return -1;
00433 }
00434 
00435 void
00436 trancate_smallspectrums(lame_internal_flags const *gfc,
00437                         gr_info * const gi, const FLOAT * const l3_xmin, FLOAT * const work)
00438 {
00439     int     sfb, j, width;
00440     FLOAT   distort[SFBMAX];
00441     calc_noise_result dummy;
00442 
00443     if ((!(gfc->substep_shaping & 4) && gi->block_type == SHORT_TYPE)
00444         || gfc->substep_shaping & 0x80)
00445         return;
00446     (void) calc_noise(gi, l3_xmin, distort, &dummy, 0);
00447     for (j = 0; j < 576; j++) {
00448         FLOAT   xr = 0.0;
00449         if (gi->l3_enc[j] != 0)
00450             xr = fabs(gi->xr[j]);
00451         work[j] = xr;
00452     }
00453 
00454     j = 0;
00455     sfb = 8;
00456     if (gi->block_type == SHORT_TYPE)
00457         sfb = 6;
00458     do {
00459         FLOAT   allowedNoise, trancateThreshold;
00460         int     nsame, start;
00461 
00462         width = gi->width[sfb];
00463         j += width;
00464         if (distort[sfb] >= 1.0)
00465             continue;
00466 
00467         qsort(&work[j - width], width, sizeof(FLOAT), floatcompare);
00468         if (work[j - 1] == 0.0)
00469             continue;   /* all zero sfb */
00470 
00471         allowedNoise = (1.0 - distort[sfb]) * l3_xmin[sfb];
00472         trancateThreshold = 0.0;
00473         start = 0;
00474         do {
00475             FLOAT   noise;
00476             for (nsame = 1; start + nsame < width; nsame++)
00477                 if (work[start + j - width] != work[start + j + nsame - width])
00478                     break;
00479 
00480             noise = work[start + j - width] * work[start + j - width] * nsame;
00481             if (allowedNoise < noise) {
00482                 if (start != 0)
00483                     trancateThreshold = work[start + j - width - 1];
00484                 break;
00485             }
00486             allowedNoise -= noise;
00487             start += nsame;
00488         } while (start < width);
00489         if (trancateThreshold == 0.0)
00490             continue;
00491 
00492 /*      printf("%e %e %e\n", */
00493 /*             trancateThreshold/l3_xmin[sfb], */
00494 /*             trancateThreshold/(l3_xmin[sfb]*start), */
00495 /*             trancateThreshold/(l3_xmin[sfb]*(start+width)) */
00496 /*          ); */
00497 /*      if (trancateThreshold > 1000*l3_xmin[sfb]*start) */
00498 /*          trancateThreshold = 1000*l3_xmin[sfb]*start; */
00499 
00500         do {
00501             if (fabs(gi->xr[j - width]) <= trancateThreshold)
00502                 gi->l3_enc[j - width] = 0;
00503         } while (--width > 0);
00504     } while (++sfb < gi->psymax);
00505 
00506     gi->part2_3_length = noquant_count_bits(gfc, gi, 0);
00507 }
00508 
00509 
00510 /*************************************************************************
00511  *
00512  *      loop_break()
00513  *
00514  *  author/date??
00515  *
00516  *  Function: Returns zero if there is a scalefac which has not been
00517  *            amplified. Otherwise it returns one.
00518  *
00519  *************************************************************************/
00520 
00521 inline static int
00522 loop_break(const gr_info * const cod_info)
00523 {
00524     int     sfb;
00525 
00526     for (sfb = 0; sfb < cod_info->sfbmax; sfb++)
00527         if (cod_info->scalefac[sfb]
00528             + cod_info->subblock_gain[cod_info->window[sfb]] == 0)
00529             return 0;
00530 
00531     return 1;
00532 }
00533 
00534 
00535 
00536 
00537 /*  mt 5/99:  Function: Improved calc_noise for a single channel   */
00538 
00539 /*************************************************************************
00540  *
00541  *      quant_compare()
00542  *
00543  *  author/date??
00544  *
00545  *  several different codes to decide which quantization is better
00546  *
00547  *************************************************************************/
00548 
00549 static double
00550 penalties(double noise)
00551 {
00552     return FAST_LOG10(0.368 + 0.632 * noise * noise * noise);
00553 }
00554 
00555 static double
00556 get_klemm_noise(const FLOAT * distort, const gr_info * const gi)
00557 {
00558     int     sfb;
00559     double  klemm_noise = 1E-37;
00560     for (sfb = 0; sfb < gi->psymax; sfb++)
00561         klemm_noise += penalties(distort[sfb]);
00562 
00563     return Max(1e-20, klemm_noise);
00564 }
00565 
00566 inline static int
00567 quant_compare(const int quant_comp,
00568               const calc_noise_result * const best,
00569               calc_noise_result * const calc, const gr_info * const gi, const FLOAT * distort)
00570 {
00571     /*
00572        noise is given in decibels (dB) relative to masking thesholds.
00573 
00574        over_noise:  ??? (the previous comment is fully wrong)
00575        tot_noise:   ??? (the previous comment is fully wrong)
00576        max_noise:   max quantization noise
00577 
00578      */
00579     int     better;
00580 
00581     switch (quant_comp) {
00582     default:
00583     case 9:{
00584             if (best->over_count > 0) {
00585                 /* there are distorted sfb */
00586                 better = calc->over_SSD <= best->over_SSD;
00587                 if (calc->over_SSD == best->over_SSD)
00588                     better = calc->bits < best->bits;
00589             }
00590             else {
00591                 /* no distorted sfb */
00592                 better = ((calc->max_noise < 0) &&
00593                           ((calc->max_noise * 10 + calc->bits) <=
00594                            (best->max_noise * 10 + best->bits)));
00595             }
00596             break;
00597         }
00598 
00599     case 0:
00600         better = calc->over_count < best->over_count
00601             || (calc->over_count == best->over_count && calc->over_noise < best->over_noise)
00602             || (calc->over_count == best->over_count &&
00603                 calc->over_noise == best->over_noise && calc->tot_noise < best->tot_noise);
00604         break;
00605 
00606     case 8:
00607         calc->max_noise = get_klemm_noise(distort, gi);
00608         /*lint --fallthrough */
00609     case 1:
00610         better = calc->max_noise < best->max_noise;
00611         break;
00612     case 2:
00613         better = calc->tot_noise < best->tot_noise;
00614         break;
00615     case 3:
00616         better = (calc->tot_noise < best->tot_noise)
00617             && (calc->max_noise < best->max_noise);
00618         break;
00619     case 4:
00620         better = (calc->max_noise <= 0.0 && best->max_noise > 0.2)
00621             || (calc->max_noise <= 0.0 &&
00622                 best->max_noise < 0.0 &&
00623                 best->max_noise > calc->max_noise - 0.2 && calc->tot_noise < best->tot_noise)
00624             || (calc->max_noise <= 0.0 &&
00625                 best->max_noise > 0.0 &&
00626                 best->max_noise > calc->max_noise - 0.2 &&
00627                 calc->tot_noise < best->tot_noise + best->over_noise)
00628             || (calc->max_noise > 0.0 &&
00629                 best->max_noise > -0.05 &&
00630                 best->max_noise > calc->max_noise - 0.1 &&
00631                 calc->tot_noise + calc->over_noise < best->tot_noise + best->over_noise)
00632             || (calc->max_noise > 0.0 &&
00633                 best->max_noise > -0.1 &&
00634                 best->max_noise > calc->max_noise - 0.15 &&
00635                 calc->tot_noise + calc->over_noise + calc->over_noise <
00636                 best->tot_noise + best->over_noise + best->over_noise);
00637         break;
00638     case 5:
00639         better = calc->over_noise < best->over_noise
00640             || (calc->over_noise == best->over_noise && calc->tot_noise < best->tot_noise);
00641         break;
00642     case 6:
00643         better = calc->over_noise < best->over_noise
00644             || (calc->over_noise == best->over_noise &&
00645                 (calc->max_noise < best->max_noise
00646                  || (calc->max_noise == best->max_noise && calc->tot_noise <= best->tot_noise)
00647                 ));
00648         break;
00649     case 7:
00650         better = calc->over_count < best->over_count || calc->over_noise < best->over_noise;
00651         break;
00652     }
00653 
00654 
00655     if (best->over_count == 0) {
00656         /*
00657            If no distorted bands, only use this quantization
00658            if it is better, and if it uses less bits.
00659            Unfortunately, part2_3_length is sometimes a poor
00660            estimator of the final size at low bitrates.
00661          */
00662         better = better && calc->bits < best->bits;
00663     }
00664 
00665 
00666     return better;
00667 }
00668 
00669 
00670 
00671 /*************************************************************************
00672  *
00673  *          amp_scalefac_bands()
00674  *
00675  *  author/date??
00676  *
00677  *  Amplify the scalefactor bands that violate the masking threshold.
00678  *  See ISO 11172-3 Section C.1.5.4.3.5
00679  *
00680  *  distort[] = noise/masking
00681  *  distort[] > 1   ==> noise is not masked
00682  *  distort[] < 1   ==> noise is masked
00683  *  max_dist = maximum value of distort[]
00684  *
00685  *  Three algorithms:
00686  *  noise_shaping_amp
00687  *        0             Amplify all bands with distort[]>1.
00688  *
00689  *        1             Amplify all bands with distort[] >= max_dist^(.5);
00690  *                     ( 50% in the db scale)
00691  *
00692  *        2             Amplify first band with distort[] >= max_dist;
00693  *
00694  *
00695  *  For algorithms 0 and 1, if max_dist < 1, then amplify all bands
00696  *  with distort[] >= .95*max_dist.  This is to make sure we always
00697  *  amplify at least one band.
00698  *
00699  *
00700  *************************************************************************/
00701 static void
00702 amp_scalefac_bands(lame_global_flags const *gfp,
00703                    gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
00704 {
00705     lame_internal_flags *const gfc = gfp->internal_flags;
00706     int     j, sfb;
00707     FLOAT   ifqstep34, trigger;
00708     int     noise_shaping_amp;
00709 
00710     if (cod_info->scalefac_scale == 0) {
00711         ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5) */
00712     }
00713     else {
00714         ifqstep34 = 1.68179283050742922612; /* 2**(.75*1) */
00715     }
00716 
00717     /* compute maximum value of distort[]  */
00718     trigger = 0;
00719     for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
00720         if (trigger < distort[sfb])
00721             trigger = distort[sfb];
00722     }
00723 
00724     noise_shaping_amp = gfc->noise_shaping_amp;
00725     if (noise_shaping_amp == 3) {
00726         if (bRefine == 1)
00727             noise_shaping_amp = 2;
00728         else
00729             noise_shaping_amp = 1;
00730     }
00731     switch (noise_shaping_amp) {
00732     case 2:
00733         /* amplify exactly 1 band */
00734         break;
00735 
00736     case 1:
00737         /* amplify bands within 50% of max (on db scale) */
00738         if (trigger > 1.0)
00739             trigger = pow(trigger, .5);
00740         else
00741             trigger *= .95;
00742         break;
00743 
00744     case 0:
00745     default:
00746         /* ISO algorithm.  amplify all bands with distort>1 */
00747         if (trigger > 1.0)
00748             trigger = 1.0;
00749         else
00750             trigger *= .95;
00751         break;
00752     }
00753 
00754     j = 0;
00755     for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
00756         int const width = cod_info->width[sfb];
00757         int     l;
00758         j += width;
00759         if (distort[sfb] < trigger)
00760             continue;
00761 
00762         if (gfc->substep_shaping & 2) {
00763             gfc->pseudohalf[sfb] = !gfc->pseudohalf[sfb];
00764             if (!gfc->pseudohalf[sfb] && gfc->noise_shaping_amp == 2)
00765                 return;
00766         }
00767         cod_info->scalefac[sfb]++;
00768         for (l = -width; l < 0; l++) {
00769             xrpow[j + l] *= ifqstep34;
00770             if (xrpow[j + l] > cod_info->xrpow_max)
00771                 cod_info->xrpow_max = xrpow[j + l];
00772         }
00773 
00774         if (gfc->noise_shaping_amp == 2)
00775             return;
00776     }
00777 }
00778 
00779 /*************************************************************************
00780  *
00781  *      inc_scalefac_scale()
00782  *
00783  *  Takehiro Tominaga 2000-xx-xx
00784  *
00785  *  turns on scalefac scale and adjusts scalefactors
00786  *
00787  *************************************************************************/
00788 
00789 static void
00790 inc_scalefac_scale(gr_info * const cod_info, FLOAT xrpow[576])
00791 {
00792     int     l, j, sfb;
00793     const FLOAT ifqstep34 = 1.29683955465100964055;
00794 
00795     j = 0;
00796     for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
00797         int const width = cod_info->width[sfb];
00798         int     s = cod_info->scalefac[sfb];
00799         if (cod_info->preflag)
00800             s += pretab[sfb];
00801         j += width;
00802         if (s & 1) {
00803             s++;
00804             for (l = -width; l < 0; l++) {
00805                 xrpow[j + l] *= ifqstep34;
00806                 if (xrpow[j + l] > cod_info->xrpow_max)
00807                     cod_info->xrpow_max = xrpow[j + l];
00808             }
00809         }
00810         cod_info->scalefac[sfb] = s >> 1;
00811     }
00812     cod_info->preflag = 0;
00813     cod_info->scalefac_scale = 1;
00814 }
00815 
00816 
00817 
00818 /*************************************************************************
00819  *
00820  *      inc_subblock_gain()
00821  *
00822  *  Takehiro Tominaga 2000-xx-xx
00823  *
00824  *  increases the subblock gain and adjusts scalefactors
00825  *
00826  *************************************************************************/
00827 
00828 static int
00829 inc_subblock_gain(const lame_internal_flags * const gfc, gr_info * const cod_info, FLOAT xrpow[576])
00830 {
00831     int     sfb, window;
00832     int    *const scalefac = cod_info->scalefac;
00833 
00834     /* subbloc_gain can't do anything in the long block region */
00835     for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {
00836         if (scalefac[sfb] >= 16)
00837             return 1;
00838     }
00839 
00840     for (window = 0; window < 3; window++) {
00841         int     s1, s2, l, j;
00842         s1 = s2 = 0;
00843 
00844         for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbdivide; sfb += 3) {
00845             if (s1 < scalefac[sfb])
00846                 s1 = scalefac[sfb];
00847         }
00848         for (; sfb < cod_info->sfbmax; sfb += 3) {
00849             if (s2 < scalefac[sfb])
00850                 s2 = scalefac[sfb];
00851         }
00852 
00853         if (s1 < 16 && s2 < 8)
00854             continue;
00855 
00856         if (cod_info->subblock_gain[window] >= 7)
00857             return 1;
00858 
00859         /* even though there is no scalefactor for sfb12
00860          * subblock gain affects upper frequencies too, that's why
00861          * we have to go up to SBMAX_s
00862          */
00863         cod_info->subblock_gain[window]++;
00864         j = gfc->scalefac_band.l[cod_info->sfb_lmax];
00865         for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbmax; sfb += 3) {
00866             FLOAT   amp;
00867             int const width = cod_info->width[sfb];
00868             int     s = scalefac[sfb];
00869             assert(s >= 0);
00870             s = s - (4 >> cod_info->scalefac_scale);
00871             if (s >= 0) {
00872                 scalefac[sfb] = s;
00873                 j += width * 3;
00874                 continue;
00875             }
00876 
00877             scalefac[sfb] = 0;
00878             {
00879                 int const gain = 210 + (s << (cod_info->scalefac_scale + 1));
00880                 amp = IPOW20(gain);
00881             }
00882             j += width * (window + 1);
00883             for (l = -width; l < 0; l++) {
00884                 xrpow[j + l] *= amp;
00885                 if (xrpow[j + l] > cod_info->xrpow_max)
00886                     cod_info->xrpow_max = xrpow[j + l];
00887             }
00888             j += width * (3 - window - 1);
00889         }
00890 
00891         {
00892             FLOAT const amp = IPOW20(202);
00893             j += cod_info->width[sfb] * (window + 1);
00894             for (l = -cod_info->width[sfb]; l < 0; l++) {
00895                 xrpow[j + l] *= amp;
00896                 if (xrpow[j + l] > cod_info->xrpow_max)
00897                     cod_info->xrpow_max = xrpow[j + l];
00898             }
00899         }
00900     }
00901     return 0;
00902 }
00903 
00904 
00905 
00906 /********************************************************************
00907  *
00908  *      balance_noise()
00909  *
00910  *  Takehiro Tominaga /date??
00911  *  Robert Hegemann 2000-09-06: made a function of it
00912  *
00913  *  amplifies scalefactor bands,
00914  *   - if all are already amplified returns 0
00915  *   - if some bands are amplified too much:
00916  *      * try to increase scalefac_scale
00917  *      * if already scalefac_scale was set
00918  *          try on short blocks to increase subblock gain
00919  *
00920  ********************************************************************/
00921 inline static int
00922 balance_noise(lame_global_flags const *const gfp,
00923               gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
00924 {
00925     lame_internal_flags *const gfc = gfp->internal_flags;
00926     int     status;
00927 
00928     amp_scalefac_bands(gfp, cod_info, distort, xrpow, bRefine);
00929 
00930     /* check to make sure we have not amplified too much
00931      * loop_break returns 0 if there is an unamplified scalefac
00932      * scale_bitcount returns 0 if no scalefactors are too large
00933      */
00934 
00935     status = loop_break(cod_info);
00936 
00937     if (status)
00938         return 0;       /* all bands amplified */
00939 
00940     /* not all scalefactors have been amplified.  so these
00941      * scalefacs are possibly valid.  encode them:
00942      */
00943     if (gfc->mode_gr == 2)
00944         status = scale_bitcount(cod_info);
00945     else
00946         status = scale_bitcount_lsf(gfc, cod_info);
00947 
00948     if (!status)
00949         return 1;       /* amplified some bands not exceeding limits */
00950 
00951     /*  some scalefactors are too large.
00952      *  lets try setting scalefac_scale=1
00953      */
00954     if (gfc->noise_shaping > 1) {
00955         memset(&gfc->pseudohalf[0], 0, sizeof(gfc->pseudohalf));
00956         if (!cod_info->scalefac_scale) {
00957             inc_scalefac_scale(cod_info, xrpow);
00958             status = 0;
00959         }
00960         else {
00961             if (cod_info->block_type == SHORT_TYPE && gfc->subblock_gain > 0) {
00962                 status = inc_subblock_gain(gfc, cod_info, xrpow)
00963                     || loop_break(cod_info);
00964             }
00965         }
00966     }
00967 
00968     if (!status) {
00969         if (gfc->mode_gr == 2)
00970             status = scale_bitcount(cod_info);
00971         else
00972             status = scale_bitcount_lsf(gfc, cod_info);
00973     }
00974     return !status;
00975 }
00976 
00977 
00978 
00979 /************************************************************************
00980  *
00981  *  outer_loop ()
00982  *
00983  *  Function: The outer iteration loop controls the masking conditions
00984  *  of all scalefactorbands. It computes the best scalefac and
00985  *  global gain. This module calls the inner iteration loop
00986  *
00987  *  mt 5/99 completely rewritten to allow for bit reservoir control,
00988  *  mid/side channels with L/R or mid/side masking thresholds,
00989  *  and chooses best quantization instead of last quantization when
00990  *  no distortion free quantization can be found.
00991  *
00992  *  added VBR support mt 5/99
00993  *
00994  *  some code shuffle rh 9/00
00995  ************************************************************************/
00996 
00997 static int
00998 outer_loop(lame_global_flags const *gfp, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion */
00999            FLOAT xrpow[576], /* coloured magnitudes of spectral */
01000            const int ch, const int targ_bits)
01001 {                       /* maximum allowed bits */
01002     lame_internal_flags *const gfc = gfp->internal_flags;
01003     gr_info cod_info_w;
01004     FLOAT   save_xrpow[576];
01005     FLOAT   distort[SFBMAX];
01006     calc_noise_result best_noise_info;
01007     int     huff_bits;
01008     int     better;
01009     int     age;
01010     calc_noise_data prev_noise;
01011     int     best_part2_3_length = 9999999;
01012     int     bEndOfSearch = 0;
01013     int     bRefine = 0;
01014     int     best_ggain_pass1 = 0;
01015 
01016     (void) bin_search_StepSize(gfc, cod_info, targ_bits, ch, xrpow);
01017 
01018     if (!gfc->noise_shaping)
01019         /* fast mode, no noise shaping, we are ready */
01020         return 100;     /* default noise_info.over_count */
01021 
01022     memset(&prev_noise, 0, sizeof(calc_noise_data));
01023 
01024 
01025     /* compute the distortion in this quantization */
01026     /* coefficients and thresholds both l/r (or both mid/side) */
01027     (void) calc_noise(cod_info, l3_xmin, distort, &best_noise_info, &prev_noise);
01028     best_noise_info.bits = cod_info->part2_3_length;
01029 
01030     cod_info_w = *cod_info;
01031     age = 0;
01032     /* if (gfp->VBR == vbr_rh || gfp->VBR == vbr_mtrh) */
01033     memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
01034 
01035     while (!bEndOfSearch) {
01036         /* BEGIN MAIN LOOP */
01037         do {
01038             calc_noise_result noise_info;
01039             int     search_limit;
01040             int     maxggain = 255;
01041 
01042             /* When quantization with no distorted bands is found,
01043              * allow up to X new unsuccesful tries in serial. This
01044              * gives us more possibilities for different quant_compare modes.
01045              * Much more than 3 makes not a big difference, it is only slower.
01046              */
01047 
01048             if (gfc->substep_shaping & 2) {
01049                 search_limit = 20;
01050             }
01051             else {
01052                 search_limit = 3;
01053             }
01054 
01055 
01056 
01057             /* Check if the last scalefactor band is distorted.
01058              * in VBR mode we can't get rid of the distortion, so quit now
01059              * and VBR mode will try again with more bits.
01060              * (makes a 10% speed increase, the files I tested were
01061              * binary identical, 2000/05/20 Robert Hegemann)
01062              * distort[] > 1 means noise > allowed noise
01063              */
01064             if (gfc->sfb21_extra) {
01065                 if (distort[cod_info_w.sfbmax] > 1.0)
01066                     break;
01067                 if (cod_info_w.block_type == SHORT_TYPE
01068                     && (distort[cod_info_w.sfbmax + 1] > 1.0
01069                         || distort[cod_info_w.sfbmax + 2] > 1.0))
01070                     break;
01071             }
01072 
01073             /* try a new scalefactor conbination on cod_info_w */
01074             if (balance_noise(gfp, &cod_info_w, distort, xrpow, bRefine) == 0)
01075                 break;
01076             if (cod_info_w.scalefac_scale)
01077                 maxggain = 254;
01078 
01079             /* inner_loop starts with the initial quantization step computed above
01080              * and slowly increases until the bits < huff_bits.
01081              * Thus it is important not to start with too large of an inital
01082              * quantization step.  Too small is ok, but inner_loop will take longer
01083              */
01084             huff_bits = targ_bits - cod_info_w.part2_length;
01085             if (huff_bits <= 0)
01086                 break;
01087 
01088             /*  increase quantizer stepsize until needed bits are below maximum
01089              */
01090             while ((cod_info_w.part2_3_length
01091                     = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > huff_bits
01092                    && cod_info_w.global_gain <= maxggain)
01093                 cod_info_w.global_gain++;
01094 
01095             if (cod_info_w.global_gain > maxggain)
01096                 break;
01097 
01098             if (best_noise_info.over_count == 0) {
01099 
01100                 while ((cod_info_w.part2_3_length
01101                         = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > best_part2_3_length
01102                        && cod_info_w.global_gain <= maxggain)
01103                     cod_info_w.global_gain++;
01104 
01105                 if (cod_info_w.global_gain > maxggain)
01106                     break;
01107             }
01108 
01109             /* compute the distortion in this quantization */
01110             (void) calc_noise(&cod_info_w, l3_xmin, distort, &noise_info, &prev_noise);
01111             noise_info.bits = cod_info_w.part2_3_length;
01112 
01113             /* check if this quantization is better
01114              * than our saved quantization */
01115             if (cod_info->block_type != SHORT_TYPE) /* NORM, START or STOP type */
01116                 better = gfp->quant_comp;
01117             else
01118                 better = gfp->quant_comp_short;
01119 
01120 
01121             better = quant_compare(better, &best_noise_info, &noise_info, &cod_info_w, distort);
01122 
01123 
01124             /* save data so we can restore this quantization later */
01125             if (better) {
01126                 best_part2_3_length = cod_info->part2_3_length;
01127                 best_noise_info = noise_info;
01128                 *cod_info = cod_info_w;
01129                 age = 0;
01130                 /* save data so we can restore this quantization later */
01131                 /*if (gfp->VBR == vbr_rh || gfp->VBR == vbr_mtrh) */  {
01132                     /* store for later reuse */
01133                     memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
01134                 }
01135             }
01136             else {
01137                 /* early stop? */
01138                 if (gfc->full_outer_loop == 0) {
01139                     if (++age > search_limit && best_noise_info.over_count == 0)
01140                         break;
01141                     if ((gfc->noise_shaping_amp == 3) && bRefine && age > 30)
01142                         break;
01143                     if ((gfc->noise_shaping_amp == 3) && bRefine &&
01144                         (cod_info_w.global_gain - best_ggain_pass1) > 15)
01145                         break;
01146                 }
01147             }
01148         }
01149         while ((cod_info_w.global_gain + cod_info_w.scalefac_scale) < 255);
01150 
01151         if (gfc->noise_shaping_amp == 3) {
01152             if (!bRefine) {
01153                 /* refine search */
01154                 cod_info_w = *cod_info;
01155                 memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
01156                 age = 0;
01157                 best_ggain_pass1 = cod_info_w.global_gain;
01158 
01159                 bRefine = 1;
01160             }
01161             else {
01162                 /* search already refined, stop */
01163                 bEndOfSearch = 1;
01164             }
01165 
01166         }
01167         else {
01168             bEndOfSearch = 1;
01169         }
01170     }
01171 
01172     assert((cod_info->global_gain + cod_info->scalefac_scale) <= 255);
01173     /*  finish up
01174      */
01175     if (gfp->VBR == vbr_rh || gfp->VBR == vbr_mtrh)
01176         /* restore for reuse on next try */
01177         memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
01178     /*  do the 'substep shaping'
01179      */
01180     else if (gfc->substep_shaping & 1)
01181         trancate_smallspectrums(gfc, cod_info, l3_xmin, xrpow);
01182 
01183     return best_noise_info.over_count;
01184 }
01185 
01186 
01187 
01188 
01189 
01190 /************************************************************************
01191  *
01192  *      iteration_finish_one()
01193  *
01194  *  Robert Hegemann 2000-09-06
01195  *
01196  *  update reservoir status after FINAL quantization/bitrate
01197  *
01198  ************************************************************************/
01199 
01200 static void
01201 iteration_finish_one(lame_internal_flags * gfc, int gr, int ch)
01202 {
01203     III_side_info_t *const l3_side = &gfc->l3_side;
01204     gr_info *const cod_info = &l3_side->tt[gr][ch];
01205 
01206     /*  try some better scalefac storage
01207      */
01208     best_scalefac_store(gfc, gr, ch, l3_side);
01209 
01210     /*  best huffman_divide may save some bits too
01211      */
01212     if (gfc->use_best_huffman == 1)
01213         best_huffman_divide(gfc, cod_info);
01214 
01215     /*  update reservoir status after FINAL quantization/bitrate
01216      */
01217     ResvAdjust(gfc, cod_info);
01218 }
01219 
01220 
01221 
01222 /*********************************************************************
01223  *
01224  *      VBR_encode_granule()
01225  *
01226  *  2000-09-04 Robert Hegemann
01227  *
01228  *********************************************************************/
01229 
01230 static void
01231 VBR_encode_granule(lame_global_flags const *gfp, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion of the scalefactor */
01232                    FLOAT xrpow[576], /* coloured magnitudes of spectral values */
01233                    const int ch, int min_bits, int max_bits)
01234 {
01235     lame_internal_flags *const gfc = gfp->internal_flags;
01236     gr_info bst_cod_info;
01237     FLOAT   bst_xrpow[576];
01238     int const Max_bits = max_bits;
01239     int     real_bits = max_bits + 1;
01240     int     this_bits = (max_bits + min_bits) / 2;
01241     int     dbits, over, found = 0;
01242     int const sfb21_extra = gfc->sfb21_extra;
01243 
01244     assert(Max_bits <= MAX_BITS_PER_CHANNEL);
01245 
01246     /*  search within round about 40 bits of optimal
01247      */
01248     do {
01249         assert(this_bits >= min_bits);
01250         assert(this_bits <= max_bits);
01251         assert(min_bits <= max_bits);
01252 
01253         if (this_bits > Max_bits - 42)
01254             gfc->sfb21_extra = 0;
01255         else
01256             gfc->sfb21_extra = sfb21_extra;
01257 
01258         over = outer_loop(gfp, cod_info, l3_xmin, xrpow, ch, this_bits);
01259 
01260         /*  is quantization as good as we are looking for ?
01261          *  in this case: is no scalefactor band distorted?
01262          */
01263         if (over <= 0) {
01264             found = 1;
01265             /*  now we know it can be done with "real_bits"
01266              *  and maybe we can skip some iterations
01267              */
01268             real_bits = cod_info->part2_3_length;
01269 
01270             /*  store best quantization so far
01271              */
01272             bst_cod_info = *cod_info;
01273             memcpy(bst_xrpow, xrpow, sizeof(FLOAT) * 576);
01274 
01275             /*  try with fewer bits
01276              */
01277             max_bits = real_bits - 32;
01278             dbits = max_bits - min_bits;
01279             this_bits = (max_bits + min_bits) / 2;
01280         }
01281         else {
01282             /*  try with more bits
01283              */
01284             min_bits = this_bits + 32;
01285             dbits = max_bits - min_bits;
01286             this_bits = (max_bits + min_bits) / 2;
01287 
01288             if (found) {
01289                 found = 2;
01290                 /*  start again with best quantization so far
01291                  */
01292                 *cod_info = bst_cod_info;
01293                 memcpy(xrpow, bst_xrpow, sizeof(FLOAT) * 576);
01294             }
01295         }
01296     } while (dbits > 12);
01297 
01298     gfc->sfb21_extra = sfb21_extra;
01299 
01300     /*  found=0 => nothing found, use last one
01301      *  found=1 => we just found the best and left the loop
01302      *  found=2 => we restored a good one and have now l3_enc to restore too
01303      */
01304     if (found == 2) {
01305         memcpy(cod_info->l3_enc, bst_cod_info.l3_enc, sizeof(int) * 576);
01306     }
01307     assert(cod_info->part2_3_length <= Max_bits);
01308 
01309 }
01310 
01311 
01312 
01313 /************************************************************************
01314  *
01315  *      get_framebits()
01316  *
01317  *  Robert Hegemann 2000-09-05
01318  *
01319  *  calculates
01320  *  * how many bits are available for analog silent granules
01321  *  * how many bits to use for the lowest allowed bitrate
01322  *  * how many bits each bitrate would provide
01323  *
01324  ************************************************************************/
01325 
01326 static void
01327 get_framebits(lame_global_flags const *gfp,
01328               int *const analog_mean_bits, int *const min_mean_bits, int frameBits[15])
01329 {
01330     lame_internal_flags *const gfc = gfp->internal_flags;
01331     int     bitsPerFrame, i;
01332 
01333     /*  always use at least this many bits per granule per channel
01334      *  unless we detect analog silence, see below
01335      */
01336     gfc->bitrate_index = gfc->VBR_min_bitrate;
01337     bitsPerFrame = getframebits(gfp);
01338     *min_mean_bits = (bitsPerFrame - gfc->sideinfo_len * 8) / (gfc->mode_gr * gfc->channels_out);
01339 
01340     /*  bits for analog silence
01341      */
01342     gfc->bitrate_index = 1;
01343     bitsPerFrame = getframebits(gfp);
01344     *analog_mean_bits = (bitsPerFrame - gfc->sideinfo_len * 8) / (gfc->mode_gr * gfc->channels_out);
01345 
01346     for (i = 1; i <= gfc->VBR_max_bitrate; i++) {
01347         gfc->bitrate_index = i;
01348         frameBits[i] = ResvFrameBegin(gfp, &bitsPerFrame);
01349     }
01350 }
01351 
01352 
01353 
01354 /************************************************************************
01355  *
01356  *      calc_min_bits()
01357  *
01358  *  Robert Hegemann 2000-09-04
01359  *
01360  *  determine minimal bit skeleton
01361  *
01362  ************************************************************************/
01363 inline static int
01364 calc_min_bits(lame_global_flags const *gfp,
01365               const gr_info * const cod_info,
01366               const int pe,
01367               const FLOAT ms_ener_ratio,
01368               const int bands,
01369               const int mch_bits,
01370               const int analog_mean_bits,
01371               const int min_mean_bits, const int analog_silence, const int ch)
01372 {
01373     lame_internal_flags const *const gfc = gfp->internal_flags;
01374     int     min_bits, min_pe_bits;
01375 
01376     if (gfp->psymodel == PSY_NSPSYTUNE)
01377         return 126;
01378     /*  changed minimum from 1 to 126 bits
01379      *  the iteration loops require a minimum of bits
01380      *  for each granule to start with; robert 2001-07-02 */
01381 
01382     /*  base amount of minimum bits
01383      */
01384     min_bits = Max(126, min_mean_bits);
01385 
01386     if (gfc->mode_ext == MPG_MD_MS_LR && ch == 1)
01387         min_bits = Max(min_bits, mch_bits / 5);
01388 
01389     /*  bit skeleton based on PE
01390      */
01391     if (cod_info->block_type == SHORT_TYPE)
01392         /*  if LAME switches to short blocks then pe is
01393          *  >= 1000 on medium surge
01394          *  >= 3000 on big surge
01395          */
01396         min_pe_bits = (pe - 350) * bands / (cod_info->sfbmax + 3);
01397     else
01398         min_pe_bits = (pe - 350) * bands / (cod_info->sfbmax + 1);
01399 
01400     if (gfc->mode_ext == MPG_MD_MS_LR && ch == 1) {
01401         /*  side channel will use a lower bit skeleton based on PE
01402          */
01403         FLOAT const fac = .33 * (.5 - ms_ener_ratio) / .5;
01404         min_pe_bits = (int) (min_pe_bits * ((1 - fac) / (1 + fac)));
01405     }
01406     min_pe_bits = Min(min_pe_bits, (1820 * gfp->out_samplerate / 44100));
01407 
01408     /*  determine final minimum bits
01409      */
01410     if (analog_silence && !gfp->VBR_hard_min)
01411         min_bits = analog_mean_bits;
01412     else
01413         min_bits = Max(min_bits, min_pe_bits);
01414 
01415     return min_bits;
01416 }
01417 
01418 
01419 
01420 /*********************************************************************
01421  *
01422  *      VBR_prepare()
01423  *
01424  *  2000-09-04 Robert Hegemann
01425  *
01426  *  * converts LR to MS coding when necessary
01427  *  * calculates allowed/adjusted quantization noise amounts
01428  *  * detects analog silent frames
01429  *
01430  *  some remarks:
01431  *  - lower masking depending on Quality setting
01432  *  - quality control together with adjusted ATH MDCT scaling
01433  *    on lower quality setting allocate more noise from
01434  *    ATH masking, and on higher quality setting allocate
01435  *    less noise from ATH masking.
01436  *  - experiments show that going more than 2dB over GPSYCHO's
01437  *    limits ends up in very annoying artefacts
01438  *
01439  *********************************************************************/
01440 
01441 /* RH: this one needs to be overhauled sometime */
01442 
01443 static int
01444 VBR_old_prepare(lame_global_flags const *gfp,
01445                 FLOAT const pe[2][2],
01446                 FLOAT const ms_ener_ratio[2],
01447                 III_psy_ratio const ratio[2][2],
01448                 FLOAT l3_xmin[2][2][SFBMAX],
01449                 int frameBits[16],
01450                 int *analog_mean_bits,
01451                 int *min_mean_bits, int min_bits[2][2], int max_bits[2][2], int bands[2][2])
01452 {
01453     lame_internal_flags *const gfc = gfp->internal_flags;
01454 
01455 
01456     FLOAT   masking_lower_db, adjust = 0.0;
01457     int     gr, ch;
01458     int     analog_silence = 1;
01459     int     avg, mxb, bits = 0;
01460 
01461     gfc->bitrate_index = gfc->VBR_max_bitrate;
01462     avg = ResvFrameBegin(gfp, &avg) / gfc->mode_gr;
01463 
01464     get_framebits(gfp, analog_mean_bits, min_mean_bits, frameBits);
01465 
01466     for (gr = 0; gr < gfc->mode_gr; gr++) {
01467         mxb = on_pe(gfp, pe, &gfc->l3_side, max_bits[gr], avg, gr, 0);
01468         if (gfc->mode_ext == MPG_MD_MS_LR) {
01469             ms_convert(&gfc->l3_side, gr);
01470             reduce_side(max_bits[gr], ms_ener_ratio[gr], avg, mxb);
01471         }
01472         for (ch = 0; ch < gfc->channels_out; ++ch) {
01473             gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
01474 
01475             if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
01476                 adjust = 1.28 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.05;
01477                 masking_lower_db = gfc->PSY->mask_adjust - adjust;
01478             }
01479             else {
01480                 adjust = 2.56 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.14;
01481                 masking_lower_db = gfc->PSY->mask_adjust_short - adjust;
01482             }
01483             gfc->masking_lower = pow(10.0, masking_lower_db * 0.1);
01484 
01485             init_outer_loop(gfc, cod_info);
01486             bands[gr][ch] = calc_xmin(gfp, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]);
01487             if (bands[gr][ch])
01488                 analog_silence = 0;
01489 
01490             min_bits[gr][ch] = calc_min_bits(gfp, cod_info, (int) pe[gr][ch],
01491                                              ms_ener_ratio[gr], bands[gr][ch],
01492                                              0, *analog_mean_bits,
01493                                              *min_mean_bits, analog_silence, ch);
01494 
01495             bits += max_bits[gr][ch];
01496         }
01497     }
01498     for (gr = 0; gr < gfc->mode_gr; gr++) {
01499         for (ch = 0; ch < gfc->channels_out; ch++) {
01500             if (bits > frameBits[gfc->VBR_max_bitrate]) {
01501                 max_bits[gr][ch] *= frameBits[gfc->VBR_max_bitrate];
01502                 max_bits[gr][ch] /= bits;
01503             }
01504             if (min_bits[gr][ch] > max_bits[gr][ch])
01505                 min_bits[gr][ch] = max_bits[gr][ch];
01506 
01507         }               /* for ch */
01508     }                   /* for gr */
01509 
01510     *min_mean_bits = Max(*min_mean_bits, 126);
01511 
01512     return analog_silence;
01513 }
01514 
01515 static void
01516 bitpressure_strategy(lame_internal_flags const *gfc,
01517                      FLOAT l3_xmin[2][2][SFBMAX], int min_bits[2][2], int max_bits[2][2])
01518 {
01519     int     gr, ch, sfb;
01520     for (gr = 0; gr < gfc->mode_gr; gr++) {
01521         for (ch = 0; ch < gfc->channels_out; ch++) {
01522             gr_info const *const gi = &gfc->l3_side.tt[gr][ch];
01523             FLOAT  *pxmin = l3_xmin[gr][ch];
01524             for (sfb = 0; sfb < gi->psy_lmax; sfb++)
01525                 *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_l / SBMAX_l;
01526 
01527             if (gi->block_type == SHORT_TYPE) {
01528                 for (sfb = gi->sfb_smin; sfb < SBMAX_s; sfb++) {
01529                     *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
01530                     *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
01531                     *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
01532                 }
01533             }
01534             max_bits[gr][ch] = Max(min_bits[gr][ch], 0.9 * max_bits[gr][ch]);
01535         }
01536     }
01537 }
01538 
01539 /************************************************************************
01540  *
01541  *      VBR_iteration_loop()
01542  *
01543  *  tries to find out how many bits are needed for each granule and channel
01544  *  to get an acceptable quantization. An appropriate bitrate will then be
01545  *  choosed for quantization.  rh 8/99
01546  *
01547  *  Robert Hegemann 2000-09-06 rewrite
01548  *
01549  ************************************************************************/
01550 
01551 void
01552 VBR_old_iteration_loop(lame_global_flags const *gfp,
01553                        FLOAT const pe[2][2],
01554                        FLOAT const ms_ener_ratio[2], III_psy_ratio const ratio[2][2])
01555 {
01556     lame_internal_flags *const gfc = gfp->internal_flags;
01557     FLOAT   l3_xmin[2][2][SFBMAX];
01558 
01559     FLOAT   xrpow[576];
01560     int     bands[2][2];
01561     int     frameBits[15];
01562     int     used_bits;
01563     int     bits;
01564     int     min_bits[2][2], max_bits[2][2];
01565     int     analog_mean_bits, min_mean_bits;
01566     int     mean_bits;
01567     int     ch, gr, analog_silence;
01568     III_side_info_t *const l3_side = &gfc->l3_side;
01569 
01570     analog_silence = VBR_old_prepare(gfp, pe, ms_ener_ratio, ratio,
01571                                      l3_xmin, frameBits, &analog_mean_bits,
01572                                      &min_mean_bits, min_bits, max_bits, bands);
01573 
01574     /*---------------------------------*/
01575     for (;;) {
01576 
01577         /*  quantize granules with lowest possible number of bits
01578          */
01579 
01580         used_bits = 0;
01581 
01582         for (gr = 0; gr < gfc->mode_gr; gr++) {
01583             for (ch = 0; ch < gfc->channels_out; ch++) {
01584                 int     ret;
01585                 gr_info *const cod_info = &l3_side->tt[gr][ch];
01586 
01587                 /*  init_outer_loop sets up cod_info, scalefac and xrpow
01588                  */
01589                 ret = init_xrpow(gfc, cod_info, xrpow);
01590                 if (ret == 0 || max_bits[gr][ch] == 0) {
01591                     /*  xr contains no energy
01592                      *  l3_enc, our encoding data, will be quantized to zero
01593                      */
01594                     continue; /* with next channel */
01595                 }
01596 
01597                 VBR_encode_granule(gfp, cod_info, l3_xmin[gr][ch], xrpow,
01598                                    ch, min_bits[gr][ch], max_bits[gr][ch]);
01599 
01600                 /*  do the 'substep shaping'
01601                  */
01602                 if (gfc->substep_shaping & 1) {
01603                     trancate_smallspectrums(gfc, &l3_side->tt[gr][ch], l3_xmin[gr][ch], xrpow);
01604                 }
01605 
01606                 ret = cod_info->part2_3_length + cod_info->part2_length;
01607                 used_bits += ret;
01608             }           /* for ch */
01609         }               /* for gr */
01610 
01611         /*  find lowest bitrate able to hold used bits
01612          */
01613         if (analog_silence && !gfp->VBR_hard_min)
01614             /*  we detected analog silence and the user did not specify
01615              *  any hard framesize limit, so start with smallest possible frame
01616              */
01617             gfc->bitrate_index = 1;
01618         else
01619             gfc->bitrate_index = gfc->VBR_min_bitrate;
01620 
01621         for (; gfc->bitrate_index < gfc->VBR_max_bitrate; gfc->bitrate_index++) {
01622             if (used_bits <= frameBits[gfc->bitrate_index])
01623                 break;
01624         }
01625         bits = ResvFrameBegin(gfp, &mean_bits);
01626 
01627         if (used_bits <= bits)
01628             break;
01629 
01630         bitpressure_strategy(gfc, l3_xmin, min_bits, max_bits);
01631 
01632     }                   /* breaks adjusted */
01633     /*--------------------------------------*/
01634 
01635     for (gr = 0; gr < gfc->mode_gr; gr++) {
01636         for (ch = 0; ch < gfc->channels_out; ch++) {
01637             iteration_finish_one(gfc, gr, ch);
01638         }               /* for ch */
01639     }                   /* for gr */
01640     ResvFrameEnd(gfc, mean_bits);
01641 }
01642 
01643 
01644 
01645 static int
01646 VBR_new_prepare(lame_global_flags const *gfp,
01647                 FLOAT const pe[2][2],
01648                 FLOAT const ms_ener_ratio[2],
01649                 III_psy_ratio const ratio[2][2],
01650                 FLOAT l3_xmin[2][2][SFBMAX], int frameBits[16], int max_bits[2][2])
01651 {
01652     lame_internal_flags *const gfc = gfp->internal_flags;
01653 
01654 
01655     FLOAT   masking_lower_db, adjust = 0.0;
01656     int     gr, ch;
01657     int     analog_silence = 1;
01658     int     avg, mxb, bits = 0;
01659     int     dummy_not_used_anymore;
01660 
01661     gfc->bitrate_index = gfc->VBR_max_bitrate;
01662     (void) ResvFrameBegin(gfp, &avg);
01663 
01664     get_framebits(gfp, &dummy_not_used_anymore, &dummy_not_used_anymore, frameBits);
01665 
01666     for (gr = 0; gr < gfc->mode_gr; gr++) {
01667         mxb = on_pe(gfp, pe, &gfc->l3_side, max_bits[gr], avg, gr, 0);
01668         if (gfc->mode_ext == MPG_MD_MS_LR) {
01669             ms_convert(&gfc->l3_side, gr);
01670         }
01671         for (ch = 0; ch < gfc->channels_out; ++ch) {
01672             gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
01673 
01674             if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
01675                 /*
01676                 //adjust = 1.28 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.05;
01677                 */
01678                 adjust = 0.4;
01679                 masking_lower_db = gfc->PSY->mask_adjust - adjust;
01680             }
01681             else {
01682                 /*
01683                 //adjust = 2.56 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.14;
01684                 */
01685                 adjust = 0.7;
01686                 masking_lower_db = gfc->PSY->mask_adjust_short - adjust;
01687             }
01688             gfc->masking_lower = pow(10.0, masking_lower_db * 0.1);
01689 
01690             init_outer_loop(gfc, cod_info);
01691             if (0 != calc_xmin(gfp, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]))
01692                 analog_silence = 0;
01693 
01694             bits += max_bits[gr][ch];
01695         }
01696     }
01697     for (gr = 0; gr < gfc->mode_gr; gr++) {
01698         for (ch = 0; ch < gfc->channels_out; ch++) {
01699             if (bits > frameBits[gfc->VBR_max_bitrate]) {
01700                 max_bits[gr][ch] *= frameBits[gfc->VBR_max_bitrate];
01701                 max_bits[gr][ch] /= bits;
01702             }
01703 
01704         }               /* for ch */
01705     }                   /* for gr */
01706 
01707     return analog_silence;
01708 }
01709 
01710 
01711 void
01712 VBR_new_iteration_loop(lame_global_flags const *gfp,
01713                        FLOAT const pe[2][2],
01714                        FLOAT const ms_ener_ratio[2], III_psy_ratio const ratio[2][2])
01715 {
01716     lame_internal_flags *const gfc = gfp->internal_flags;
01717     FLOAT   l3_xmin[2][2][SFBMAX];
01718 
01719     FLOAT   xrpow[2][2][576];
01720     int     frameBits[15];
01721     int     used_bits;
01722     int     max_bits[2][2];
01723     int     ch, gr, analog_silence;
01724     III_side_info_t *const l3_side = &gfc->l3_side;
01725 
01726     analog_silence = VBR_new_prepare(gfp, pe, ms_ener_ratio, ratio, l3_xmin, frameBits, max_bits);
01727 
01728     for (gr = 0; gr < gfc->mode_gr; gr++) {
01729         for (ch = 0; ch < gfc->channels_out; ch++) {
01730             gr_info *const cod_info = &l3_side->tt[gr][ch];
01731 
01732             /*  init_outer_loop sets up cod_info, scalefac and xrpow
01733              */
01734             if (0 == init_xrpow(gfc, cod_info, xrpow[gr][ch])) {
01735                 max_bits[gr][ch] = 0; /* silent granule needs no bits */
01736             }
01737         }               /* for ch */
01738     }                   /* for gr */
01739 
01740     /*  quantize granules with lowest possible number of bits
01741      */
01742 
01743     used_bits = VBR_encode_frame(gfc, xrpow, l3_xmin, max_bits);
01744 
01745     /*  find lowest bitrate able to hold used bits
01746      */
01747     if (analog_silence && !gfp->VBR_hard_min)
01748         /*  we detected analog silence and the user did not specify
01749          *  any hard framesize limit, so start with smallest possible frame
01750          */
01751         gfc->bitrate_index = 1;
01752     else
01753         gfc->bitrate_index = gfc->VBR_min_bitrate;
01754 
01755     for (; gfc->bitrate_index < gfc->VBR_max_bitrate; gfc->bitrate_index++) {
01756         if (used_bits <= frameBits[gfc->bitrate_index])
01757             break;
01758     }
01759     if (used_bits <= frameBits[gfc->VBR_max_bitrate]) {
01760         /* update Reservoire status */
01761         int     mean_bits, fullframebits;
01762         fullframebits = ResvFrameBegin(gfp, &mean_bits);
01763         assert( used_bits <= fullframebits );
01764         for (gr = 0; gr < gfc->mode_gr; gr++) {
01765             for (ch = 0; ch < gfc->channels_out; ch++) {
01766                 gr_info const *const cod_info = &l3_side->tt[gr][ch];
01767                 ResvAdjust(gfc, cod_info);
01768             }
01769         }
01770         ResvFrameEnd(gfc, mean_bits);
01771     }
01772     else {
01773         /* SHOULD NOT HAPPEN INTERNAL ERROR
01774          */
01775         ERRORF(gfc, "INTERNAL ERROR IN VBR NEW CODE, please send bug report\n");
01776         exit(-1);
01777     }
01778 }
01779 
01780 
01781 
01782 
01783 
01784 /********************************************************************
01785  *
01786  *  calc_target_bits()
01787  *
01788  *  calculates target bits for ABR encoding
01789  *
01790  *  mt 2000/05/31
01791  *
01792  ********************************************************************/
01793 
01794 static void
01795 calc_target_bits(lame_global_flags const *gfp,
01796                  FLOAT const pe[2][2],
01797                  FLOAT const ms_ener_ratio[2],
01798                  int targ_bits[2][2], int *analog_silence_bits, int *max_frame_bits)
01799 {
01800     lame_internal_flags *const gfc = gfp->internal_flags;
01801     III_side_info_t const *const l3_side = &gfc->l3_side;
01802     FLOAT   res_factor;
01803     int     gr, ch, totbits, mean_bits;
01804 
01805     gfc->bitrate_index = gfc->VBR_max_bitrate;
01806     *max_frame_bits = ResvFrameBegin(gfp, &mean_bits);
01807 
01808     gfc->bitrate_index = 1;
01809     mean_bits = getframebits(gfp) - gfc->sideinfo_len * 8;
01810     *analog_silence_bits = mean_bits / (gfc->mode_gr * gfc->channels_out);
01811 
01812     mean_bits = gfp->VBR_mean_bitrate_kbps * gfp->framesize * 1000;
01813     if (gfc->substep_shaping & 1)
01814         mean_bits *= 1.09;
01815     mean_bits /= gfp->out_samplerate;
01816     mean_bits -= gfc->sideinfo_len * 8;
01817     mean_bits /= (gfc->mode_gr * gfc->channels_out);
01818 
01819     /*
01820        res_factor is the percentage of the target bitrate that should
01821        be used on average.  the remaining bits are added to the
01822        bitreservoir and used for difficult to encode frames.
01823 
01824        Since we are tracking the average bitrate, we should adjust
01825        res_factor "on the fly", increasing it if the average bitrate
01826        is greater than the requested bitrate, and decreasing it
01827        otherwise.  Reasonable ranges are from .9 to 1.0
01828 
01829        Until we get the above suggestion working, we use the following
01830        tuning:
01831        compression ratio    res_factor
01832        5.5  (256kbps)         1.0      no need for bitreservoir
01833        11   (128kbps)         .93      7% held for reservoir
01834 
01835        with linear interpolation for other values.
01836 
01837      */
01838     res_factor = .93 + .07 * (11.0 - gfp->compression_ratio) / (11.0 - 5.5);
01839     if (res_factor < .90)
01840         res_factor = .90;
01841     if (res_factor > 1.00)
01842         res_factor = 1.00;
01843 
01844     for (gr = 0; gr < gfc->mode_gr; gr++) {
01845         int sum = 0;
01846         for (ch = 0; ch < gfc->channels_out; ch++) {
01847             targ_bits[gr][ch] = res_factor * mean_bits;
01848 
01849             if (pe[gr][ch] > 700) {
01850                 int     add_bits = (pe[gr][ch] - 700) / 1.4;
01851 
01852                 gr_info const *const cod_info = &l3_side->tt[gr][ch];
01853                 targ_bits[gr][ch] = res_factor * mean_bits;
01854 
01855                 /* short blocks use a little extra, no matter what the pe */
01856                 if (cod_info->block_type == SHORT_TYPE) {
01857                     if (add_bits < mean_bits / 2)
01858                         add_bits = mean_bits / 2;
01859                 }
01860                 /* at most increase bits by 1.5*average */
01861                 if (add_bits > mean_bits * 3 / 2)
01862                     add_bits = mean_bits * 3 / 2;
01863                 else if (add_bits < 0)
01864                     add_bits = 0;
01865 
01866                 targ_bits[gr][ch] += add_bits;
01867             }
01868             if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL) {
01869                 targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
01870             }
01871             sum += targ_bits[gr][ch];
01872         }               /* for ch */
01873         if (sum > MAX_BITS_PER_GRANULE) {
01874             for (ch = 0; ch < gfc->channels_out; ++ch) {
01875               targ_bits[gr][ch] *= MAX_BITS_PER_GRANULE;
01876               targ_bits[gr][ch] /= sum;
01877             } 
01878         }
01879     }                   /* for gr */
01880 
01881     if (gfc->mode_ext == MPG_MD_MS_LR)
01882         for (gr = 0; gr < gfc->mode_gr; gr++) {
01883             reduce_side(targ_bits[gr], ms_ener_ratio[gr], mean_bits * gfc->channels_out, MAX_BITS_PER_GRANULE);
01884         }
01885 
01886     /*  sum target bits
01887      */
01888     totbits = 0;
01889     for (gr = 0; gr < gfc->mode_gr; gr++) {
01890         for (ch = 0; ch < gfc->channels_out; ch++) {
01891             if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL)
01892                 targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
01893             totbits += targ_bits[gr][ch];
01894         }
01895     }
01896 
01897     /*  repartion target bits if needed
01898      */
01899     if (totbits > *max_frame_bits) {
01900         for (gr = 0; gr < gfc->mode_gr; gr++) {
01901             for (ch = 0; ch < gfc->channels_out; ch++) {
01902                 targ_bits[gr][ch] *= *max_frame_bits;
01903                 targ_bits[gr][ch] /= totbits;
01904             }
01905         }
01906     }
01907 }
01908 
01909 
01910 
01911 
01912 
01913 
01914 /********************************************************************
01915  *
01916  *  ABR_iteration_loop()
01917  *
01918  *  encode a frame with a disired average bitrate
01919  *
01920  *  mt 2000/05/31
01921  *
01922  ********************************************************************/
01923 
01924 void
01925 ABR_iteration_loop(lame_global_flags const *gfp,
01926                    FLOAT const pe[2][2],
01927                    FLOAT const ms_ener_ratio[2], III_psy_ratio const ratio[2][2])
01928 {
01929     lame_internal_flags *const gfc = gfp->internal_flags;
01930     FLOAT   l3_xmin[SFBMAX];
01931     FLOAT   xrpow[576];
01932     int     targ_bits[2][2];
01933     int     mean_bits, max_frame_bits;
01934     int     ch, gr, ath_over;
01935     int     analog_silence_bits;
01936     gr_info *cod_info;
01937     III_side_info_t *const l3_side = &gfc->l3_side;
01938 
01939     calc_target_bits(gfp, pe, ms_ener_ratio, targ_bits, &analog_silence_bits, &max_frame_bits);
01940 
01941     /*  encode granules
01942      */
01943     for (gr = 0; gr < gfc->mode_gr; gr++) {
01944 
01945         if (gfc->mode_ext == MPG_MD_MS_LR) {
01946             ms_convert(&gfc->l3_side, gr);
01947         }
01948         for (ch = 0; ch < gfc->channels_out; ch++) {
01949             FLOAT   adjust, masking_lower_db;
01950             cod_info = &l3_side->tt[gr][ch];
01951 
01952             if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
01953                 /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
01954                 adjust = 0;
01955                 masking_lower_db = gfc->PSY->mask_adjust - adjust;
01956             }
01957             else {
01958                 /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
01959                 adjust = 0;
01960                 masking_lower_db = gfc->PSY->mask_adjust_short - adjust;
01961             }
01962             gfc->masking_lower = pow(10.0, masking_lower_db * 0.1);
01963 
01964 
01965             /*  cod_info, scalefac and xrpow get initialized in init_outer_loop
01966              */
01967             init_outer_loop(gfc, cod_info);
01968             if (init_xrpow(gfc, cod_info, xrpow)) {
01969                 /*  xr contains energy we will have to encode
01970                  *  calculate the masking abilities
01971                  *  find some good quantization in outer_loop
01972                  */
01973                 ath_over = calc_xmin(gfp, &ratio[gr][ch], cod_info, l3_xmin);
01974                 if (0 == ath_over) /* analog silence */
01975                     targ_bits[gr][ch] = analog_silence_bits;
01976 
01977                 (void) outer_loop(gfp, cod_info, l3_xmin, xrpow, ch, targ_bits[gr][ch]);
01978             }
01979             iteration_finish_one(gfc, gr, ch);
01980         }               /* ch */
01981     }                   /* gr */
01982 
01983     /*  find a bitrate which can refill the resevoir to positive size.
01984      */
01985     for (gfc->bitrate_index = gfc->VBR_min_bitrate;
01986          gfc->bitrate_index <= gfc->VBR_max_bitrate; gfc->bitrate_index++) {
01987         if (ResvFrameBegin(gfp, &mean_bits) >= 0)
01988             break;
01989     }
01990     assert(gfc->bitrate_index <= gfc->VBR_max_bitrate);
01991 
01992     ResvFrameEnd(gfc, mean_bits);
01993 }
01994 
01995 
01996 
01997 
01998 
01999 
02000 /************************************************************************
02001  *
02002  *      CBR_iteration_loop()
02003  *
02004  *  author/date??
02005  *
02006  *  encodes one frame of MP3 data with constant bitrate
02007  *
02008  ************************************************************************/
02009 
02010 void
02011 CBR_iteration_loop(lame_global_flags const *gfp,
02012                    FLOAT const pe[2][2],
02013                    FLOAT const ms_ener_ratio[2], III_psy_ratio const ratio[2][2])
02014 {
02015     lame_internal_flags *const gfc = gfp->internal_flags;
02016     FLOAT   l3_xmin[SFBMAX];
02017     FLOAT   xrpow[576];
02018     int     targ_bits[2];
02019     int     mean_bits, max_bits;
02020     int     gr, ch;
02021     III_side_info_t *const l3_side = &gfc->l3_side;
02022     gr_info *cod_info;
02023 
02024     (void) ResvFrameBegin(gfp, &mean_bits);
02025 
02026     /* quantize! */
02027     for (gr = 0; gr < gfc->mode_gr; gr++) {
02028 
02029         /*  calculate needed bits
02030          */
02031         max_bits = on_pe(gfp, pe, l3_side, targ_bits, mean_bits, gr, gr);
02032 
02033         if (gfc->mode_ext == MPG_MD_MS_LR) {
02034             ms_convert(&gfc->l3_side, gr);
02035             reduce_side(targ_bits, ms_ener_ratio[gr], mean_bits, max_bits);
02036         }
02037 
02038         for (ch = 0; ch < gfc->channels_out; ch++) {
02039             FLOAT   adjust, masking_lower_db;
02040             cod_info = &l3_side->tt[gr][ch];
02041 
02042             if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
02043                 /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
02044                 adjust = 0;
02045                 masking_lower_db = gfc->PSY->mask_adjust - adjust;
02046             }
02047             else {
02048                 /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
02049                 adjust = 0;
02050                 masking_lower_db = gfc->PSY->mask_adjust_short - adjust;
02051             }
02052             gfc->masking_lower = pow(10.0, masking_lower_db * 0.1);
02053 
02054             /*  init_outer_loop sets up cod_info, scalefac and xrpow
02055              */
02056             init_outer_loop(gfc, cod_info);
02057             if (init_xrpow(gfc, cod_info, xrpow)) {
02058                 /*  xr contains energy we will have to encode
02059                  *  calculate the masking abilities
02060                  *  find some good quantization in outer_loop
02061                  */
02062                 (void) calc_xmin(gfp, &ratio[gr][ch], cod_info, l3_xmin);
02063                 (void) outer_loop(gfp, cod_info, l3_xmin, xrpow, ch, targ_bits[ch]);
02064             }
02065 
02066             iteration_finish_one(gfc, gr, ch);
02067             assert(cod_info->part2_3_length <= MAX_BITS_PER_CHANNEL);
02068             assert(cod_info->part2_3_length <= targ_bits[ch]);
02069         }               /* for ch */
02070     }                   /* for gr */
02071 
02072     ResvFrameEnd(gfc, mean_bits);
02073 }
02074 

Generated on Sun Dec 2 11:34:20 2007 for LAME by  doxygen 1.5.2