home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 13 / AACD13.ISO / AACD / Sound / LAME / src / quantize.c < prev    next >
C/C++ Source or Header  |  2000-08-03  |  44KB  |  1,335 lines

  1. /*
  2.  * MP3 quantization
  3.  *
  4.  * Copyright (c) 1999 Mark Taylor
  5.  *
  6.  * This program is free software; you can redistribute it and/or modify
  7.  * it under the terms of the GNU General Public License as published by
  8.  * the Free Software Foundation; either version 2, or (at your option)
  9.  * any later version.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program; see the file COPYING.  If not, write to
  18.  * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  */
  20.  
  21.  
  22.  
  23. #include <assert.h>
  24. #include "util.h"
  25. #include "l3side.h"
  26. #include "quantize.h"
  27. #include "reservoir.h"
  28. #include "quantize-pvt.h"
  29. #include "gtkanal.h"
  30.  
  31.  
  32.  
  33.  
  34. /************************************************************************/
  35. /*  iteration_loop()                                                    */
  36. /************************************************************************/
  37. void
  38. iteration_loop( lame_global_flags *gfp, FLOAT8 pe[2][2],
  39.                 FLOAT8 ms_ener_ratio[2],  FLOAT8 xr[2][2][576],
  40.                 III_psy_ratio ratio[2][2],  int l3_enc[2][2][576],
  41.                 III_scalefac_t scalefac[2][2])
  42. {
  43.   III_psy_xmin l3_xmin[2];
  44.   FLOAT8 xrpow[576];
  45.   FLOAT8 xfsf[4][SBMAX_l];
  46.   FLOAT8 noise[4]; /* over,max_noise,over_noise,tot_noise; */
  47.   int targ_bits[2];
  48.   int bitsPerFrame;
  49.   int mean_bits,max_bits;
  50.   int ch, gr, i, bit_rate;
  51.   gr_info *cod_info;
  52.   lame_internal_flags *gfc=gfp->internal_flags;
  53.   III_side_info_t *l3_side = &gfc->l3_side;
  54.  
  55.   iteration_init(gfp,l3_side,l3_enc);
  56.   bit_rate = bitrate_table[gfp->version][gfc->bitrate_index];
  57.   getframebits(gfp,&bitsPerFrame, &mean_bits);
  58.   ResvFrameBegin(gfp, l3_side, mean_bits, bitsPerFrame );
  59.  
  60.   /* quantize! */
  61.   for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
  62.  
  63.     max_bits=on_pe(gfp,pe,l3_side,targ_bits,mean_bits, gr);
  64.     if (gfc->mode_ext==MPG_MD_MS_LR) {
  65.       ms_convert(xr[gr], xr[gr]);
  66.       reduce_side(targ_bits,ms_ener_ratio[gr],mean_bits,max_bits);
  67.     }
  68.     for (ch=0 ; ch < gfc->stereo ; ch ++) {
  69.       cod_info = &l3_side->gr[gr].ch[ch].tt; 
  70.  
  71.       if (!init_outer_loop(gfp,xr[gr][ch],xrpow, cod_info))
  72.         {
  73.           /* xr contains no energy 
  74.            * cod_info-> was initialized in init_outer_loop
  75.            */
  76.           memset(&scalefac[gr][ch],0,sizeof(III_scalefac_t));
  77.           memset(l3_enc[gr][ch],0,576*sizeof(int));
  78.           memset(xfsf,0,sizeof(xfsf));
  79.           memset(noise,0,sizeof(noise));
  80.         }
  81.       else
  82.         {
  83.           calc_xmin(gfp,xr[gr][ch], &ratio[gr][ch], cod_info, &l3_xmin[ch]);
  84.           outer_loop( gfp,xr[gr][ch], targ_bits[ch], noise, &l3_xmin[ch],
  85.                       l3_enc[gr][ch], &scalefac[gr][ch], cod_info, xfsf, ch,
  86.                       xrpow);
  87.         }
  88.  
  89.       best_scalefac_store(gfp,gr, ch, l3_enc, l3_side, scalefac);
  90.       if (gfc->use_best_huffman==1) {
  91.     best_huffman_divide(gfc, gr, ch, cod_info, l3_enc[gr][ch]);
  92.       }
  93.       assert((int)cod_info->part2_3_length < 4096);
  94.  
  95.       if (gfp->gtkflag) {
  96.         set_pinfo (gfp, cod_info, &ratio[gr][ch], &scalefac[gr][ch], 
  97.                    xr[gr][ch], xfsf, noise, gr, ch);
  98.       }
  99.  
  100. /*#define NORES_TEST */
  101. #ifndef NORES_TEST
  102.       ResvAdjust(gfp,cod_info, l3_side, mean_bits );
  103. #endif
  104.       /* set the sign of l3_enc */
  105.       for ( i = 0; i < 576; i++) {
  106.         if (xr[gr][ch][i] < 0) {
  107.           l3_enc[gr][ch][i] *= -1;
  108.         }
  109.       }
  110.  
  111.  
  112.     } /* loop over ch */
  113.   } /* loop over gr */
  114.  
  115. #ifdef NORES_TEST
  116.   /* replace ResvAdjust above with this code if you do not want
  117.      the second granule to use bits saved by the first granule.
  118.      when combined with --nores, this is usefull for testing only */
  119.   for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
  120.     for ( ch =  0; ch < gfc->stereo; ch++ ) {
  121.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  122.       ResvAdjust(gfp, cod_info, l3_side, mean_bits );
  123.     }
  124.   }
  125. #endif
  126.   ResvFrameEnd(gfp,l3_side, mean_bits );
  127. }
  128.  
  129.  
  130.  
  131.  
  132. /*
  133.  *  ABR_iteration_loop()
  134.  *
  135.  *  encode a frame with a disired average bitrate
  136.  *
  137.  *  mt 2000/05/31
  138.  */
  139. void
  140. ABR_iteration_loop (lame_global_flags *gfp, FLOAT8 pe[2][2],
  141.                     FLOAT8 ms_ener_ratio[2], FLOAT8 xr[2][2][576],
  142.                     III_psy_ratio ratio[2][2], int l3_enc[2][2][576],
  143.                     III_scalefac_t scalefac[2][2])
  144. {
  145.   III_psy_xmin l3_xmin;
  146.   FLOAT8    xrpow[576];
  147.   FLOAT8    xfsf[4][SBMAX_l];
  148.   FLOAT8    noise[4];
  149.   int       targ_bits[2][2];
  150.   int       bit_rate,bitsPerFrame, mean_bits,totbits,max_frame_bits;
  151.   int       i,ch, gr, ath_over;
  152.   int       analog_silence_bits;
  153.   FLOAT8    res_factor;
  154.   gr_info  *cod_info = NULL;
  155.   lame_internal_flags *gfc=gfp->internal_flags;
  156.   III_side_info_t *l3_side = &gfc->l3_side;
  157.  
  158.   iteration_init(gfp,l3_side,l3_enc);
  159.  
  160.   gfc->bitrate_index = gfc->VBR_max_bitrate;
  161.   getframebits (gfp,&bitsPerFrame, &mean_bits);
  162.   max_frame_bits=ResvFrameBegin (gfp,l3_side, mean_bits, bitsPerFrame);
  163.  
  164.   gfc->bitrate_index = 1;
  165.   getframebits (gfp,&bitsPerFrame, &mean_bits);
  166.   analog_silence_bits = mean_bits/gfc->stereo;
  167.  
  168.   /* compute a target  mean_bits based on compression ratio 
  169.    * which was set based on VBR_q  
  170.    */
  171.   bit_rate = gfp->VBR_mean_bitrate_kbps;
  172.   bitsPerFrame = (bit_rate*gfp->framesize*1000)/gfp->out_samplerate;
  173.   mean_bits = (bitsPerFrame - 8*gfc->sideinfo_len) / gfc->mode_gr;
  174.  
  175.  
  176.   res_factor = .90 + .10*(11.0- gfp->compression_ratio)/(11.0-5.5);
  177.   if (res_factor <  .90) { res_factor =  .90; }
  178.   if (res_factor > 1.00) { res_factor = 1.00; }
  179.  
  180.  
  181.  
  182.   for(gr = 0; gr < gfc->mode_gr; gr++) {
  183.     for(ch = 0; ch < gfc->stereo; ch++) {
  184.       targ_bits[gr][ch]=res_factor*(mean_bits/gfc->stereo);
  185.       if (pe[gr][ch]>700) {
  186.         int add_bits=(pe[gr][ch]-700)/1.4;
  187.  
  188.         cod_info = &l3_side->gr[gr].ch[ch].tt;
  189.         targ_bits[gr][ch]=res_factor*(mean_bits/gfc->stereo);
  190.  
  191.         /* short blocks use a little extra, no matter what the pe */
  192.         if (cod_info->block_type==SHORT_TYPE) {
  193.           if (add_bits<mean_bits/4) { add_bits=mean_bits/4; }
  194.         }
  195.         /* at most increase bits by 1.5*average */
  196.         if (add_bits > .75*mean_bits) { add_bits=mean_bits*.75; }
  197.         if (add_bits < 0) { add_bits=0; }
  198.  
  199.         targ_bits[gr][ch] += add_bits;
  200.       }
  201.     }
  202.   }
  203.   if (gfc->mode_ext==MPG_MD_MS_LR) {
  204.     for(gr = 0; gr < gfc->mode_gr; gr++) {
  205.       reduce_side(targ_bits[gr],ms_ener_ratio[gr],mean_bits,4095);
  206.     }
  207.   }
  208.  
  209.   totbits=0;
  210.   for(gr = 0; gr < gfc->mode_gr; gr++) {
  211.     for(ch = 0; ch < gfc->stereo; ch++) {
  212.       if (targ_bits[gr][ch] > 4095) { targ_bits[gr][ch]=4095; }
  213.       totbits += targ_bits[gr][ch];
  214.     }
  215.   }
  216.  
  217.   if (totbits > max_frame_bits) {
  218.     for(gr = 0; gr < gfc->mode_gr; gr++) {
  219.       for(ch = 0; ch < gfc->stereo; ch++) {
  220.         targ_bits[gr][ch] *= ((float)max_frame_bits/(float)totbits); 
  221.       }
  222.     }
  223.   }
  224.  
  225.   totbits=0;
  226.   for(gr = 0; gr < gfc->mode_gr; gr++) {
  227.  
  228.     if (gfc->mode_ext==MPG_MD_MS_LR) { ms_convert(xr[gr], xr[gr]); }
  229.  
  230.     for(ch = 0; ch < gfc->stereo; ch++) {
  231.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  232.  
  233.       if (!init_outer_loop(gfp,xr[gr][ch],xrpow, cod_info)) {
  234.         /* xr contains no energy 
  235.          * cod_info was set in init_outer_loop above
  236.          */
  237.         memset(&scalefac[gr][ch],0,sizeof(III_scalefac_t));
  238.         memset(l3_enc[gr][ch],0,576*sizeof(int));
  239.         memset(noise,0,sizeof(noise));
  240.       } else {
  241.         ath_over = calc_xmin(gfp,xr[gr][ch],&ratio[gr][ch],cod_info,&l3_xmin);
  242.         if (0==ath_over) {
  243.           /* analog silence */
  244.           targ_bits[gr][ch]=analog_silence_bits;
  245.         }
  246.  
  247.         outer_loop( gfp,xr[gr][ch], targ_bits[gr][ch], noise, &l3_xmin,
  248.                     l3_enc[gr][ch], &scalefac[gr][ch], cod_info, xfsf, ch,
  249.                     xrpow);
  250.       }
  251.  
  252.       totbits += cod_info->part2_3_length;
  253.       if (gfp->gtkflag) {
  254.         set_pinfo(gfp, cod_info, &ratio[gr][ch], &scalefac[gr][ch],
  255.                   xr[gr][ch], xfsf, noise, gr, ch);
  256.       }
  257.     } /* ch */
  258.   }  /* gr */
  259.   
  260.   /*******************************************************************
  261.    * find a bitrate which can handle totbits 
  262.    *******************************************************************/
  263.   for( gfc->bitrate_index =  gfc->VBR_min_bitrate ;
  264.        gfc->bitrate_index <= gfc->VBR_max_bitrate;
  265.        gfc->bitrate_index++    ) {
  266.     getframebits (gfp,&bitsPerFrame, &mean_bits);
  267.     max_frame_bits=ResvFrameBegin (gfp,l3_side, mean_bits, bitsPerFrame);
  268.     if( totbits <= max_frame_bits) { break; }
  269.   }
  270.   assert (gfc->bitrate_index <= gfc->VBR_max_bitrate);
  271.  
  272.  
  273.  
  274.   /*******************************************************************
  275.    * update reservoir status after FINAL quantization/bitrate 
  276.    *******************************************************************/
  277.   for (gr = 0; gr < gfc->mode_gr; gr++)
  278.     for (ch = 0; ch < gfc->stereo; ch++) {
  279.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  280.  
  281.       best_scalefac_store(gfp,gr, ch, l3_enc, l3_side, scalefac);
  282.       if (gfc->use_best_huffman==1 ) {
  283.         best_huffman_divide(gfc, gr, ch, cod_info, l3_enc[gr][ch]);
  284.       }
  285.       if (gfp->gtkflag) {
  286.         gfc->pinfo->LAMEmainbits[gr][ch]=cod_info->part2_3_length;
  287.       }
  288.       ResvAdjust (gfp,cod_info, l3_side, mean_bits);
  289.       /* set the sign of l3_enc from the sign of xr */
  290.       for ( i = 0; i < 576; i++) {
  291.         if (xr[gr][ch][i] < 0) { l3_enc[gr][ch][i] *= -1; }
  292.       }
  293.  
  294.     }
  295.   ResvFrameEnd (gfp,l3_side, mean_bits);
  296. }
  297.  
  298.  
  299.  
  300.  
  301. /************************************************************************
  302.  *
  303.  * VBR_iteration_loop()   
  304.  *
  305.  * tries to find out how many bits are needed for each granule and channel
  306.  * to get an acceptable quantization. An appropriate bitrate will then be
  307.  * choosed for quantization.  rh 8/99                          
  308.  *
  309.  ************************************************************************/
  310. void
  311. VBR_iteration_loop (lame_global_flags *gfp, FLOAT8 pe[2][2], 
  312.                     FLOAT8 ms_ener_ratio[2], FLOAT8 xr[2][2][576],
  313.                     III_psy_ratio ratio[2][2], int l3_enc[2][2][576],
  314.                     III_scalefac_t scalefac[2][2])
  315. {
  316.   /* PLL 16/07/2000 */
  317. #ifdef macintosh
  318.   static plotting_data bst_pinfo;
  319. #else
  320.   plotting_data bst_pinfo;
  321. #endif
  322.  
  323.   gr_info         bst_cod_info, clean_cod_info;
  324.   III_scalefac_t  bst_scalefac;
  325.   int             bst_l3_enc[576]; 
  326.   
  327.   III_psy_xmin l3_xmin[2][2];
  328.   FLOAT8    xrpow[2][576];
  329.   FLOAT8    noise[4];          /* over,max_noise,over_noise,tot_noise; */
  330.   FLOAT8    xfsf[4][SBMAX_l];
  331.   int       save_bits[2][2];
  332.   int       bands[2][2];
  333.   int       this_bits, dbits;
  334.   int       used_bits=0;
  335.   int       min_bits,max_bits,min_mean_bits=0,analog_mean_bits,Max_bits;
  336.   int       frameBits[15];
  337.   int       bitsPerFrame;
  338.   int       bits;
  339.   int       mean_bits;
  340.   int       i,ch, gr, analog_silence;
  341.   int       reduce_s_ch=0;
  342.   gr_info  *cod_info = NULL;
  343.   lame_internal_flags *gfc=gfp->internal_flags;
  344.   III_side_info_t *l3_side = &gfc->l3_side;
  345.  
  346.   iteration_init(gfp,l3_side,l3_enc);
  347.  
  348.   /* my experiences are, that side channel reduction  
  349.    * does more harm than good when VBR encoding
  350.    * (Robert.Hegemann@gmx.de 2000-02-18)
  351.    */
  352.   if (gfc->mode_ext==MPG_MD_MS_LR && gfp->quality >= 5) { 
  353.     reduce_s_ch=1;
  354.   }
  355.  
  356.   /* bits for analog silence */
  357.   gfc->bitrate_index = 1;
  358.   getframebits (gfp,&bitsPerFrame, &mean_bits);
  359.   analog_mean_bits = mean_bits/gfc->stereo;
  360.   
  361.   analog_silence=1;
  362.   for (gr = 0; gr < gfc->mode_gr; gr++) {
  363.     /* copy data to be quantized into xr */
  364.     if (gfc->mode_ext==MPG_MD_MS_LR) { ms_convert(xr[gr],xr[gr]); }
  365.     for (ch = 0; ch < gfc->stereo; ch++) {
  366.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  367.       /* - lower masking depending on Quality setting
  368.        * - quality control together with adjusted ATH MDCT scaling
  369.        *   on lower quality setting allocate more noise from
  370.        *   ATH masking, and on higher quality setting allocate
  371.        *   less noise from ATH masking.
  372.        * - experiments show that going more than 2dB over GPSYCHO's
  373.        *   limits ends up in very annoying artefacts
  374.        */
  375.       {
  376.         static const FLOAT8 dbQ[10]={-4.,-3.,-2.,-1.,0,.5,1.,1.5,2.,2.5};
  377.         FLOAT8 masking_lower_db, adjust;
  378.         assert( gfp->VBR_q <= 9 );
  379.         assert( gfp->VBR_q >= 0 );
  380.         
  381.         if (cod_info->block_type==SHORT_TYPE) {
  382.           adjust = 5/(1+exp(3.5-pe[gr][ch]/300.))-0.14;
  383.         } else {
  384.           adjust = 2/(1+exp(3.5-pe[gr][ch]/300.))-0.05;
  385.         }
  386.         if (gfc->noise_shaping==2) {
  387.           adjust = Max(1.25,adjust);
  388.         }
  389.         masking_lower_db = dbQ[gfp->VBR_q]-adjust; 
  390.         gfc->masking_lower = pow(10.0,masking_lower_db/10);
  391.       }
  392.       bands[gr][ch] = calc_xmin(gfp,xr[gr][ch], &ratio[gr][ch], 
  393.                                 cod_info, &l3_xmin[gr][ch]);
  394.       if (bands[gr][ch]) {
  395.         analog_silence = 0;
  396.       }
  397.     }
  398.   }
  399.   
  400.   /*******************************************************************
  401.    * how many bits are available for each bitrate?
  402.    *******************************************************************/
  403.   for( gfc->bitrate_index = 1;
  404.        gfc->bitrate_index <= gfc->VBR_max_bitrate;
  405.        gfc->bitrate_index++    ) {
  406.     getframebits (gfp,&bitsPerFrame, &mean_bits);
  407.     if (gfc->bitrate_index == gfc->VBR_min_bitrate) {
  408.       /* always use at least this many bits per granule per channel */
  409.       /* unless we detect analog silence, see below */
  410.       min_mean_bits=mean_bits/gfc->stereo;
  411.     }
  412.     frameBits[gfc->bitrate_index]
  413.      = ResvFrameBegin (gfp,l3_side, mean_bits, bitsPerFrame);
  414.   }
  415.  
  416.  
  417.   gfc->bitrate_index=gfc->VBR_max_bitrate;
  418.   
  419.   /*******************************************************************
  420.    * how many bits would we use of it?
  421.    *******************************************************************/
  422.   for (gr = 0; gr < gfc->mode_gr; gr++) {
  423.     int num_chan=gfc->stereo;
  424.     
  425.     /* determine quality based on mid channel only */
  426.     if (reduce_s_ch) { num_chan=1; }  
  427.  
  428.     for (ch = 0; ch < num_chan; ch++) { 
  429.       int real_bits, min_pe_bits, mdct_lines=0;
  430.       
  431.       /******************************************************************
  432.        * find smallest number of bits for an allowable quantization
  433.        ******************************************************************/
  434.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  435.       min_bits = Max(125,min_mean_bits);
  436.  
  437.       if (gfc->mode_ext==MPG_MD_MS_LR && ch==1) { 
  438.         min_bits = Max(min_bits,0.2*save_bits[gr][0]);
  439.       }
  440.       mdct_lines = init_outer_loop(gfp,xr[gr][ch],xrpow[0], cod_info);
  441.       if (mdct_lines == 0)
  442.       {
  443.         /* xr contains no energy 
  444.          * cod_info was set in init_outer_loop above
  445.          */
  446.         memset(&scalefac[gr][ch],0,sizeof(III_scalefac_t));
  447.         memset(l3_enc[gr][ch],0,576*sizeof(int));
  448.         save_bits[gr][ch] = 0;
  449.         if (gfp->gtkflag) {
  450.           memset(xfsf,0,sizeof(xfsf));
  451.           set_pinfo(gfp, cod_info, &ratio[gr][ch], &scalefac[gr][ch],
  452.                     xr[gr][ch], xfsf, noise, gr, ch);
  453.         }
  454.         continue; /* with next channel */
  455.       }
  456.       
  457.       memcpy( &clean_cod_info, cod_info, sizeof(gr_info) );
  458.       
  459.       if (cod_info->block_type==SHORT_TYPE) {
  460.         /* if LAME switches to short blocks then pe is
  461.          * >= 1000 on medium surge
  462.          * >= 3000 on big surge
  463.          */
  464.         min_pe_bits = (pe[gr][ch]-350) * bands[gr][ch]/39.;
  465.       } else {
  466.         min_pe_bits = (pe[gr][ch]-350) * bands[gr][ch]/22.;
  467.       }
  468.       min_pe_bits=Min(min_pe_bits,1820);
  469.  
  470.       if (analog_silence && !gfp->VBR_hard_min) {
  471.         min_bits = analog_mean_bits;
  472.       } else {
  473.         min_bits = Max(min_bits,min_pe_bits);
  474.       }
  475.       max_bits = 1200
  476.                + frameBits[gfc->VBR_max_bitrate]/(gfc->stereo*gfc->mode_gr);
  477.       max_bits = Min(max_bits,4095-195*(gfc->stereo-1));
  478.       max_bits = Max(max_bits,min_bits);
  479.       Max_bits = max_bits;
  480.  
  481.       this_bits = min_bits+(max_bits-min_bits)/2;
  482.       real_bits = max_bits+1;
  483.  
  484.       /* bin search to within +40 bits of optimal */
  485.       do {
  486.         assert(this_bits>=min_bits);
  487.         assert(this_bits<=max_bits);
  488.  
  489.         /*
  490.          *  OK, start with a fresh setting
  491.          *  - scalefac  will be set up by outer_loop
  492.          *  - l3_enc    will be set up by outer_loop
  493.          *  + cod_info  we will restore our initialized one, see below
  494.          */
  495.         memcpy( cod_info, &clean_cod_info, sizeof(gr_info) );
  496.         memcpy(xrpow[1], xrpow[0], sizeof(xrpow[0]));
  497.         outer_loop( gfp,xr[gr][ch], this_bits, noise, &l3_xmin[gr][ch],
  498.                     l3_enc[gr][ch],&scalefac[gr][ch], cod_info,
  499.                     xfsf, ch, xrpow[1]);
  500.  
  501.         /* is quantization as good as we are looking for ?
  502.          */
  503.         if (noise[0] <= 0) {
  504.           /* we now know it can be done with "real_bits"
  505.            * and maybe we can skip some iterations
  506.            */
  507.           real_bits = cod_info->part2_3_length;
  508.           /*
  509.            * save best quantization so far
  510.            */
  511.           memcpy( &bst_scalefac, &scalefac[gr][ch], sizeof(III_scalefac_t)  );
  512.           memcpy(  bst_l3_enc,    l3_enc  [gr][ch], sizeof(int)*576         );
  513.           memcpy( &bst_cod_info,  cod_info,         sizeof(gr_info)         );
  514.           if (gfp->gtkflag) {
  515.             set_pinfo(gfp, cod_info, &ratio[gr][ch], &scalefac[gr][ch],
  516.                       xr[gr][ch], xfsf, noise, gr, ch);
  517.             memcpy( &bst_pinfo, gfc->pinfo, sizeof(plotting_data) );
  518.           }
  519.           /* try with fewer bits
  520.            */
  521.           max_bits = real_bits-32;
  522.         } else {
  523.           /* try with more bits
  524.            */
  525.           min_bits = this_bits+32;
  526.         }
  527.         dbits = max_bits-min_bits;
  528.         this_bits = min_bits+dbits/2;
  529.       } while (dbits>8) ;
  530.  
  531.       if (real_bits <= Max_bits) {
  532.         /* restore best quantization found */
  533.         memcpy(  cod_info,         &bst_cod_info, sizeof(gr_info)        );
  534.         memcpy( &scalefac[gr][ch], &bst_scalefac, sizeof(III_scalefac_t) );
  535.         memcpy(  l3_enc  [gr][ch],  bst_l3_enc,   sizeof(int)*576        );
  536.         if (gfp->gtkflag) {
  537.           memcpy( gfc->pinfo, &bst_pinfo, sizeof(plotting_data) );
  538.         }
  539.       } else {
  540.         /* we didn't find any satisfying quantization above
  541.          * the only thing we still need to set is the gtk info field
  542.          */
  543.         if (gfp->gtkflag) {
  544.           set_pinfo(gfp, cod_info, &ratio[gr][ch], &scalefac[gr][ch],
  545.                     xr[gr][ch], xfsf, noise, gr, ch);
  546.         }
  547.       }
  548.  
  549.       assert((int)cod_info->part2_3_length <= Max_bits);
  550.       assert((int)cod_info->part2_3_length < 4096);
  551.       save_bits[gr][ch] = cod_info->part2_3_length;
  552.       used_bits += save_bits[gr][ch];
  553.       
  554.     } /* for ch */
  555.   }  /* for gr */
  556.  
  557.   if (reduce_s_ch) {
  558.     /* number of bits needed was found for MID channel above.  Use formula
  559.      * (fixed bitrate code) to set the side channel bits */
  560.     for (gr = 0; gr < gfc->mode_gr; gr++) {
  561.       FLOAT8 fac = .33*(.5-ms_ener_ratio[gr])/.5;
  562.       save_bits[gr][1]=((1-fac)/(1+fac))*save_bits[gr][0];
  563.       save_bits[gr][1]=Max(analog_mean_bits,save_bits[gr][1]);
  564.       used_bits += save_bits[gr][1];
  565.     }
  566.   }
  567.  
  568.   /******************************************************************
  569.    * find lowest bitrate able to hold used bits
  570.    ******************************************************************/
  571.   if (analog_silence && !gfp->VBR_hard_min) {
  572.     gfc->bitrate_index = 1;
  573.   } else {
  574.     gfc->bitrate_index = gfc->VBR_min_bitrate;
  575.   }
  576.   for( ; gfc->bitrate_index < gfc->VBR_max_bitrate; gfc->bitrate_index++ ) {
  577.     if( used_bits <= frameBits[gfc->bitrate_index] ) { break; }
  578.   }
  579.  
  580.   /*******************************************************************
  581.    * calculate quantization for this bitrate
  582.    *******************************************************************/  
  583.   getframebits (gfp,&bitsPerFrame, &mean_bits);
  584.   bits=ResvFrameBegin (gfp,l3_side, mean_bits, bitsPerFrame);
  585.  
  586.   for(gr = 0; gr < gfc->mode_gr; gr++) {
  587.     for(ch = 0; ch < gfc->stereo; ch++) {
  588.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  589.       
  590.       if (used_bits > bits) {
  591.         /* repartion available bits in same proportion
  592.          */
  593.         save_bits[gr][ch] = (save_bits[gr][ch]*frameBits[gfc->bitrate_index])
  594.                           / used_bits;
  595.       }
  596.       if (used_bits > bits || (reduce_s_ch && ch == 1)) {        
  597.         if (!init_outer_loop(gfp,xr[gr][ch], xrpow[0], cod_info)) {
  598.           /* xr contains no energy 
  599.            * cod_info was set in init_outer_loop above
  600.            */
  601.           memset(&scalefac[gr][ch],0,sizeof(III_scalefac_t));
  602.           memset(l3_enc[gr][ch],0,576*sizeof(int));
  603.           memset(noise,0,sizeof(noise));
  604.         } else {
  605.           outer_loop( gfp,xr[gr][ch], save_bits[gr][ch], noise,
  606.                       &l3_xmin[gr][ch], l3_enc[gr][ch], &scalefac[gr][ch],
  607.                       cod_info, xfsf, ch, xrpow[0]);
  608.         }
  609.         if (gfp->gtkflag) {
  610.           set_pinfo(gfp, cod_info, &ratio[gr][ch], &scalefac[gr][ch],
  611.                     xr[gr][ch], xfsf, noise, gr, ch);
  612.         }
  613.       }
  614.       /* update reservoir status after FINAL quantization/bitrate
  615.        */
  616.       best_scalefac_store(gfp,gr, ch, l3_enc, l3_side, scalefac);
  617.       if (gfc->use_best_huffman==1) {
  618.         best_huffman_divide(gfc, gr, ch, cod_info, l3_enc[gr][ch]);
  619.       }
  620.       if (gfp->gtkflag) {
  621.         gfc->pinfo->LAMEmainbits[gr][ch]=cod_info->part2_3_length;
  622.       }
  623.       ResvAdjust (gfp,cod_info, l3_side, mean_bits);
  624.       
  625.       /* set the sign of l3_enc from the sign of xr 
  626.        */
  627.       for ( i = 0; i < 576; i++) {
  628.         if (xr[gr][ch][i] < 0) { l3_enc[gr][ch][i] *= -1; }
  629.       }
  630.     } /* ch */
  631.   }  /* gr */
  632.  
  633.   ResvFrameEnd (gfp,l3_side, mean_bits);
  634. }
  635.  
  636.  
  637.  
  638.  
  639. #ifndef RH_NOISE_CALC
  640. INLINE 
  641. int quant_compare(int experimentalX,
  642.                   calc_noise_result *best,
  643.                   calc_noise_result *calc)
  644. {
  645.   /*
  646.     noise is given in decibals (db) relative to masking thesholds.
  647.  
  648.     over_noise:  sum of quantization noise > masking
  649.     tot_noise:   sum of all quantization noise
  650.     max_noise:   max quantization noise 
  651.  
  652.    */
  653.   int better=0;
  654.  
  655.   switch (experimentalX) {
  656.   default:
  657.   case 0: better =   calc->over_count  < best->over_count
  658.                  ||  ( calc->over_count == best->over_count
  659.                        && calc->over_noise < best->over_noise )
  660.                  ||  ( calc->over_count == best->over_count 
  661.                        && calc->over_noise==best->over_noise
  662.                && calc->tot_noise < best->tot_noise)
  663.         ; break;
  664.  
  665.  
  666.   case 1: better = calc->max_noise < best->max_noise; break;
  667.  
  668.   case 2: better = calc->tot_noise < best->tot_noise; break;
  669.   
  670.   case 3: better =  calc->tot_noise < best->tot_noise
  671.                  && calc->max_noise < best->max_noise + 2; break;
  672.   
  673.   case 4: better =  (
  674.                       (0>=calc->max_noise)
  675.                     &&(best->max_noise>2)
  676.                     )
  677.                  || (
  678.                       (0>=calc->max_noise)
  679.                     &&(best->max_noise<0)
  680.                     &&((best->max_noise+2)>calc->max_noise)
  681.                     &&(calc->tot_noise<best->tot_noise)
  682.                     )
  683.                  || (
  684.                       (0>=calc->max_noise)
  685.                     &&(best->max_noise>0)
  686.                     &&((best->max_noise+2)>calc->max_noise)
  687.                     &&(calc->tot_noise<(best->tot_noise+best->over_noise))
  688.                     )
  689.                  || (
  690.                       (0<calc->max_noise)
  691.                     &&(best->max_noise>-0.5)
  692.                     &&((best->max_noise+1)>calc->max_noise)
  693.                     &&((  calc->tot_noise+calc->over_noise)
  694.                         <(best->tot_noise+best->over_noise))
  695.                     )
  696.                  || (
  697.                       (0<calc->max_noise)
  698.                     &&(best->max_noise>-1)
  699.                     &&((best->max_noise+1.5)>calc->max_noise)
  700.                     &&((  calc->tot_noise+calc->over_noise+calc->over_noise)
  701.                         <(best->tot_noise+best->over_noise+best->over_noise))
  702.                     )
  703.                   ; break;
  704.      
  705.   case 5: better =   calc->over_noise  < best->over_noise
  706.                  ||( calc->over_noise == best->over_noise
  707.                   && calc->tot_noise   < best->tot_noise ); break;
  708.   
  709.   case 6: better =     calc->over_noise  < best->over_noise
  710.                  ||(   calc->over_noise == best->over_noise
  711.                   &&(  calc->max_noise   < best->max_noise
  712.                    ||( calc->max_noise  == best->max_noise
  713.                     && calc->tot_noise  <= best->tot_noise ))); break;
  714.   
  715.   case 7: better =  calc->over_count < best->over_count
  716.                  || calc->over_noise < best->over_noise; break;
  717.   }
  718.  
  719.   return better;
  720. }
  721.  
  722. #else
  723.  
  724. INLINE 
  725. int quant_compare(int experimentalX,
  726.                   calc_noise_result *best,
  727.                   calc_noise_result *calc)
  728. {
  729.   /*
  730.     noise relative to masking thesholds.
  731.  
  732.     over_noise:  sum of quantization noise > masking
  733.     tot_noise:   sum of all quantization noise
  734.     max_noise:   max quantization noise 
  735.  
  736.    */
  737.   int better=0;
  738.   const FLOAT8 nrg_1p0dB = 0.794328234; /* -1.0 dB */
  739.   const FLOAT8 nrg_0p5dB = 0.891250938; /* -0.5 dB */
  740.   const FLOAT8 nrg1p0dB  = 1.258925412; /*  1.0 dB */
  741.   const FLOAT8 nrg1p5dB  = 1.412537545; /*  1.5 dB */
  742.   const FLOAT8 nrg2p0dB  = 1.584893192; /*  2.0 dB */
  743.  
  744.   switch (experimentalX) {
  745.   default:
  746.   case 0: better =   calc->over_count  < best->over_count
  747.                  ||( calc->over_count == best->over_count
  748.                   && calc->over_noise <  best->over_noise )
  749.                  ||( calc->over_count == best->over_count 
  750.                   && calc->over_noise == best->over_noise
  751.           && calc->tot_noise   < best->tot_noise  )
  752.         ; break;
  753.  
  754.  
  755.   case 1: better = calc->max_noise < best->max_noise; break;
  756.  
  757.   case 2: better = calc->tot_noise < best->tot_noise; break;
  758.   
  759.   case 3: better =  calc->tot_noise < best->tot_noise
  760.                  && calc->max_noise < best->max_noise*nrg2p0dB; break;
  761.   
  762.   case 4: better =  (
  763.                       (              1 >= calc->max_noise)
  764.                     &&(best->max_noise  > nrg2p0dB       )
  765.                     )
  766.                  || (
  767.                       (                        1 >= calc->max_noise)
  768.                     &&( best->max_noise           < 1              )
  769.                     &&((best->max_noise*nrg2p0dB) > calc->max_noise)
  770.                     &&( calc->tot_noise           < best->tot_noise)
  771.                     )
  772.                  || (
  773.                       (                        1 >= calc->max_noise)
  774.                     &&( best->max_noise           > 1              )
  775.                     &&((best->max_noise*nrg2p0dB) > calc->max_noise)
  776.                     &&( calc->tot_noise < (best->tot_noise*best->over_noise))
  777.                     )
  778.                  || (
  779.                       (                        1  < calc->max_noise)
  780.                     &&( best->max_noise           > nrg_0p5dB      )
  781.                     &&((best->max_noise*nrg1p0dB) > calc->max_noise)
  782.                     &&(  (calc->tot_noise*calc->over_noise)
  783.                         <(best->tot_noise*best->over_noise)        )
  784.                     )
  785.                  || (
  786.                       (                         1 < calc->max_noise)
  787.                     &&( best->max_noise           > nrg_1p0dB      )
  788.                     &&((best->max_noise*nrg1p5dB) > calc->max_noise)
  789.                     &&(  (calc->tot_noise*calc->over_noise*calc->over_noise)
  790.                         <(best->tot_noise*best->over_noise*best->over_noise))
  791.                     )
  792.                   ; break;
  793.      
  794.   case 5: better =   calc->over_noise  < best->over_noise
  795.                  ||( calc->over_noise == best->over_noise
  796.                   && calc->tot_noise   < best->tot_noise ); break;
  797.   
  798.   case 6: better =     calc->over_noise  < best->over_noise
  799.                  ||(   calc->over_noise == best->over_noise
  800.                   &&(  calc->max_noise   < best->max_noise
  801.                    ||( calc->max_noise  == best->max_noise
  802.                     && calc->tot_noise  <= best->tot_noise ))); break;
  803.   
  804.   case 7: better =  calc->over_count < best->over_count
  805.                  || calc->over_noise < best->over_noise; break;
  806.   }
  807.  
  808.   return better;
  809. }
  810. #endif
  811.  
  812.  
  813. /************************************************************************/
  814. /*  init_outer_loop  mt 6/99                                            */
  815. /*  returns 0 if all energies in xr are zero, else 1                    */
  816. /************************************************************************/
  817. int init_outer_loop(lame_global_flags *gfp, 
  818.     FLOAT8 xr[576], FLOAT8 xrpow[576],     /*  could be L/R OR MID/SIDE */
  819.     gr_info *cod_info)
  820. {
  821.   int i, o=0;
  822.  
  823.   cod_info->part2_3_length    = 0;
  824.   cod_info->big_values        = 0;
  825.   cod_info->count1            = 0;
  826.   cod_info->global_gain       = 210;
  827.   cod_info->scalefac_compress = 0;
  828.   /* window_switching_flag */
  829.   /* block_type            */
  830.   /* mixed_block_flag      */
  831.   cod_info->table_select[0]   = 0;
  832.   cod_info->table_select[1]   = 0;
  833.   cod_info->table_select[2]   = 0;
  834.   cod_info->subblock_gain[0]  = 0;
  835.   cod_info->subblock_gain[1]  = 0;
  836.   cod_info->subblock_gain[2]  = 0;
  837.   cod_info->region0_count     = 0;
  838.   cod_info->region1_count     = 0;
  839.   cod_info->preflag           = 0;
  840.   cod_info->scalefac_scale    = 0;
  841.   cod_info->count1table_select= 0;
  842.   cod_info->part2_length      = 0;
  843.   /* sfb_lmax              */
  844.   /* sfb_smax              */
  845.   cod_info->count1bits        = 0;  
  846.   cod_info->sfb_partition_table = &nr_of_sfb_block[0][0][0];
  847.   cod_info->slen[0] = 0;
  848.   cod_info->slen[1] = 0;
  849.   cod_info->slen[2] = 0;
  850.   cod_info->slen[3] = 0;
  851.  
  852.   /*
  853.    *  check if there is some energy we have to quantize
  854.    *  if so, then return 1 else 0
  855.    */
  856.   for (i=0; i<576; i++) {
  857.     FLOAT8 temp=fabs(xr[i]);
  858.     xrpow[i]=sqrt(sqrt(temp)*temp);
  859.     o += temp>1E-20;
  860.   }
  861.   
  862.   return o>0;
  863. }
  864.  
  865.  
  866.  
  867.  
  868. /************************************************************************/
  869. /*  outer_loop                                                         */
  870. /************************************************************************/
  871. /*  Function: The outer iteration loop controls the masking conditions  */
  872. /*  of all scalefactorbands. It computes the best scalefac and          */
  873. /*  global gain. This module calls the inner iteration loop             
  874.  * 
  875.  *  mt 5/99 completely rewritten to allow for bit reservoir control,   
  876.  *  mid/side channels with L/R or mid/side masking thresholds, 
  877.  *  and chooses best quantization instead of last quantization when 
  878.  *  no distortion free quantization can be found.  
  879.  *  
  880.  *  added VBR support mt 5/99
  881.  ************************************************************************/
  882. void outer_loop(
  883.     lame_global_flags *gfp,
  884.     FLOAT8 xr[576],        
  885.     int targ_bits,
  886.     FLOAT8 best_noise[4],
  887.     III_psy_xmin *l3_xmin,   /* the allowed distortion of the scalefactor */
  888.     int l3_enc[576],         /* vector of quantized values ix(0..575) */
  889.     III_scalefac_t *scalefac, /* scalefactors */
  890.     gr_info *cod_info,
  891.     FLOAT8 xfsf[4][SBMAX_l],
  892.     int ch, 
  893.     FLOAT8 xrpow[576])
  894. {
  895.   III_scalefac_t scalefac_w;
  896.   gr_info save_cod_info;
  897.   FLOAT8 xfsf_w[4][SBMAX_l];
  898.   FLOAT8 distort[4][SBMAX_l];
  899.   calc_noise_result noise_info;
  900.   calc_noise_result best_noise_info;
  901.   int l3_enc_w[576]; 
  902.   int iteration;
  903.   int status,bits_found=0;
  904.   int huff_bits;
  905.   int better;
  906.   int over=0;
  907.   lame_internal_flags *gfc=gfp->internal_flags;
  908.  
  909.   int notdone=1;
  910.  
  911.   noise_info.over_count = 100;
  912.   noise_info.tot_count = 100;
  913.   noise_info.max_noise = 0;
  914.   noise_info.tot_noise = 0;
  915.   noise_info.over_noise = 0;
  916.   best_noise_info = noise_info;
  917.  
  918.  
  919.  
  920.   /* reset of iteration variables */
  921.   memset(&scalefac_w, 0, sizeof(III_scalefac_t));
  922.   
  923.   bits_found=bin_search_StepSize2(gfp,targ_bits,gfc->OldValue[ch],
  924.                                   l3_enc_w,xrpow,cod_info);
  925.   gfc->OldValue[ch] = cod_info->global_gain;
  926.  
  927.  
  928.   /* BEGIN MAIN LOOP */
  929.   iteration = 0;
  930.   while ( notdone  ) {
  931.     iteration += 1;
  932.  
  933.  
  934.     /* inner_loop starts with the initial quantization step computed above
  935.      * and slowly increases until the bits < huff_bits.
  936.      * Thus it is important not to start with too large of an inital
  937.      * quantization step.  Too small is ok, but inner_loop will take longer 
  938.      */
  939.     huff_bits = targ_bits - cod_info->part2_length;
  940.     if (huff_bits < 0) {
  941.       assert(iteration != 1);
  942.       /* scale factors too large, not enough bits. use previous quantizaton */
  943.       notdone=0;
  944.     } else {
  945.       /* if this is the first iteration, see if we can reuse the quantization
  946.        * computed in bin_search_StepSize above */
  947.       int real_bits;
  948.  
  949.       if (iteration==1) {
  950.         if(bits_found>huff_bits) {
  951.           cod_info->global_gain++;
  952.           real_bits = inner_loop(gfp,xrpow, l3_enc_w, huff_bits, cod_info);
  953.         } else {
  954.           real_bits=bits_found;
  955.         }
  956.       } else {
  957.         real_bits=inner_loop(gfp,xrpow, l3_enc_w, huff_bits, cod_info);
  958.       }
  959.  
  960.  
  961.       cod_info->part2_3_length = real_bits;
  962.  
  963.       /* compute the distortion in this quantization */
  964.       if (gfc->noise_shaping==0) {
  965.         over=0;
  966.       } else {
  967.         /* coefficients and thresholds both l/r (or both mid/side) */
  968.         over = calc_noise( gfp,xr, l3_enc_w, cod_info, xfsf_w,distort,
  969.                            l3_xmin, &scalefac_w, &noise_info);
  970.       }
  971.  
  972.  
  973.       /* check if this quantization is better the our saved quantization */
  974.       if (iteration == 1) {
  975.         better=1;
  976.       } else { 
  977.         better=quant_compare(gfp->experimentalX, &best_noise_info, &noise_info);
  978.       }
  979.       /* save data so we can restore this quantization later */    
  980.       if (better) {
  981.         best_noise_info = noise_info;
  982.  
  983.         memcpy(scalefac, &scalefac_w, sizeof(III_scalefac_t));
  984.         memcpy(l3_enc,l3_enc_w,sizeof(int)*576);
  985.         memcpy(&save_cod_info,cod_info,sizeof(save_cod_info));
  986.  
  987.         if (gfp->gtkflag) {
  988.           memcpy(xfsf, xfsf_w, sizeof(xfsf_w));
  989.         }
  990.       }
  991.     }
  992.  
  993.  
  994.  
  995.  
  996.  
  997.  
  998.  
  999.  
  1000.     /* if no bands with distortion and -X0, we are done */
  1001.     if (0==gfp->experimentalX && 0==over) {
  1002.       notdone=0;
  1003.     }
  1004.     /* do at least 7 tries and stop 
  1005.      * if our best quantization so far had no distorted bands
  1006.      * this gives us more possibilities for our different quant_compare modes
  1007.      */
  1008.     if (iteration>7 && best_noise_info.over_count==0) {
  1009.       notdone=0;
  1010.     }
  1011.     if (notdone) {
  1012.       amp_scalefac_bands( gfp, xrpow, cod_info, &scalefac_w, distort);
  1013.  
  1014.       /* check to make sure we have not amplified too much */
  1015.       /* loop_break returns 0 if there is an unamplified scalefac */
  1016.       /* scale_bitcount returns 0 if no scalefactors are too large */
  1017.       status = loop_break(&scalefac_w, cod_info);
  1018.       if ( status == 0 ) {
  1019.         /* not all scalefactors have been amplified.  so these 
  1020.          * scalefacs are possibly valid.  encode them: */
  1021.         if ( gfp->version == 1 ) {
  1022.           status = scale_bitcount(&scalefac_w, cod_info);
  1023.         } else {
  1024.           status = scale_bitcount_lsf(&scalefac_w, cod_info);
  1025.         }
  1026.         if (status) {
  1027.           /*  some scalefactors are too large.  lets try setting
  1028.            * scalefac_scale=1 */
  1029.           if (gfc->noise_shaping > 1 && !cod_info->scalefac_scale) {
  1030.             inc_scalefac_scale(gfp, &scalefac_w, cod_info, xrpow);
  1031.             status = 0;
  1032.           } else {
  1033.             if (cod_info->block_type == SHORT_TYPE
  1034.                && gfp->experimentalZ && gfc->noise_shaping > 1) {
  1035.                 inc_subblock_gain(gfp, &scalefac_w, cod_info, xrpow);
  1036.                 status = loop_break(&scalefac_w, cod_info);
  1037.             }
  1038.           }
  1039.           if (!status) {
  1040.             if ( gfp->version == 1 ) {
  1041.               status = scale_bitcount(&scalefac_w, cod_info);
  1042.             } else {
  1043.               status = scale_bitcount_lsf(&scalefac_w, cod_info);
  1044.             }
  1045.           }
  1046.         } /* status != 0 */
  1047.       } /* status == 0 */
  1048.       notdone = !status;
  1049.     }
  1050.  
  1051.     /* Check if the last scalefactor band is distorted.
  1052.      * in VBR mode we can't get rid of the distortion, so quit now
  1053.      * and VBR mode will try again with more bits.  
  1054.      * (makes a 10% speed increase, the files I tested were
  1055.      * binary identical, 2000/05/20 Robert.Hegemann@gmx.de)
  1056.      * NOTE: distort[] = changed to:  noise/allowed noise
  1057.      * so distort[] > 1 means noise > allowed noise
  1058.      */
  1059.     if (gfp->VBR==vbr_rh || iteration>100) {
  1060.       if (cod_info->block_type == SHORT_TYPE) {
  1061.         if ((distort[1][SBMAX_s-1] > 1)
  1062.           ||(distort[2][SBMAX_s-1] > 1)
  1063.           ||(distort[3][SBMAX_s-1] > 1)) { notdone=0; }
  1064.       } else {
  1065.         if (distort[0][SBMAX_l-1] > 1) { notdone=0; }
  1066.       }
  1067.     }
  1068.  
  1069.   }    /* done with main iteration */
  1070.  
  1071.   memcpy(cod_info,&save_cod_info,sizeof(save_cod_info));
  1072.   cod_info->part2_3_length += cod_info->part2_length;
  1073.  
  1074.  
  1075.   /* finish up */
  1076.   assert( cod_info->global_gain < 256 );
  1077.  
  1078.   best_noise[0]=best_noise_info.over_count;
  1079.   best_noise[1]=best_noise_info.max_noise;
  1080.   best_noise[2]=best_noise_info.over_noise;
  1081.   best_noise[3]=best_noise_info.tot_noise;
  1082. }
  1083.  
  1084.  
  1085.  
  1086.  
  1087.  
  1088.   
  1089.  
  1090.  
  1091.  
  1092.  
  1093.  
  1094.  
  1095.  
  1096.  
  1097.  
  1098.  
  1099.  
  1100.  
  1101.  
  1102.  
  1103. /*************************************************************************/
  1104. /*            amp_scalefac_bands                                         */
  1105. /*************************************************************************/
  1106.  
  1107. /* 
  1108.   Amplify the scalefactor bands that violate the masking threshold.
  1109.   See ISO 11172-3 Section C.1.5.4.3.5
  1110. */
  1111. #ifndef RH_NOISE_CALC
  1112. void amp_scalefac_bands(lame_global_flags *gfp, FLOAT8 xrpow[576], 
  1113.                         gr_info *cod_info, III_scalefac_t *scalefac,
  1114.                         FLOAT8 distort[4][SBMAX_l])
  1115. {
  1116.   int start, end, l,i,j;
  1117.   u_int sfb;
  1118.   FLOAT8 ifqstep34,distort_thresh;
  1119.   lame_internal_flags *gfc=gfp->internal_flags;
  1120.  
  1121.   if ( cod_info->scalefac_scale == 0 ) {
  1122.     ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5)*/
  1123.   } else {
  1124.     ifqstep34 = 1.68179283050742922612;  /* 2**(.75*1) */
  1125.   }
  1126.   /* distort[] = noise/masking.  Comput distort_thresh so that:
  1127.    * distort_thresh = 1, unless all bands have distort < 1
  1128.    * In that case, just amplify bands with distortion
  1129.    * within 95% of largest distortion/masking ratio */
  1130.   distort_thresh = -900;
  1131.   for ( sfb = 0; sfb < cod_info->sfb_lmax; sfb++ ) {
  1132.     distort_thresh = Max(distort[0][sfb],distort_thresh);
  1133.   }
  1134.  
  1135.   for ( sfb = cod_info->sfb_smax; sfb < 12; sfb++ ) {
  1136.     for ( i = 0; i < 3; i++ ) {
  1137.       distort_thresh = Max(distort[i+1][sfb],distort_thresh);
  1138.     }
  1139.   }
  1140.   if (distort_thresh>1.0)
  1141.     distort_thresh=1.0;
  1142.   else
  1143.     distort_thresh *= .95;
  1144.  
  1145.  
  1146.   for ( sfb = 0; sfb < cod_info->sfb_lmax; sfb++ ) {
  1147.     if ( distort[0][sfb]>distort_thresh  ) {
  1148.       scalefac->l[sfb]++;
  1149.       start = gfc->scalefac_band.l[sfb];
  1150.       end   = gfc->scalefac_band.l[sfb+1];
  1151.       for ( l = start; l < end; l++ ) {
  1152.         xrpow[l] *= ifqstep34;
  1153.       }
  1154.     }
  1155.   }
  1156.     
  1157.  
  1158.   for ( j=0,sfb = cod_info->sfb_smax; sfb < 12; sfb++ ) {
  1159.     start = gfc->scalefac_band.s[sfb];
  1160.     end   = gfc->scalefac_band.s[sfb+1];
  1161.     for ( i = 0; i < 3; i++ ) {
  1162.       int j2 = j;
  1163.       if ( distort[i+1][sfb]>distort_thresh) {
  1164.         scalefac->s[sfb][i]++;
  1165.         for (l = start; l < end; l++) {
  1166.           xrpow[j2++] *= ifqstep34;
  1167.         }
  1168.       }
  1169.       j += end-start;
  1170.     }
  1171.   }
  1172. }
  1173. #else
  1174. void amp_scalefac_bands(lame_global_flags *gfp, FLOAT8 xrpow[576], 
  1175.                         gr_info *cod_info, III_scalefac_t *scalefac,
  1176.                         FLOAT8 distort[4][SBMAX_l])
  1177. {
  1178.   int start, end, l,i,j, max_ind[4]={0,0,0,0};
  1179.   u_int sfb;
  1180.   FLOAT8 ifqstep34,distort_thresh[4]={1E-20,1E-20,1E-20,1E-20};
  1181.   lame_internal_flags *gfc=gfp->internal_flags;
  1182.  
  1183.   if ( cod_info->scalefac_scale == 0 ) {
  1184.     ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5)*/
  1185.   } else {
  1186.     ifqstep34 = 1.68179283050742922612;  /* 2**(.75*1) */
  1187.   }
  1188.   /* distort[] = noise/masking.  Comput distort_thresh so that:
  1189.    * distort_thresh = 1, unless all bands have distort < 1
  1190.    * In that case, just amplify bands with distortion
  1191.    * within 95% of largest distortion/masking ratio */
  1192.   for ( sfb = 0; sfb < cod_info->sfb_lmax; sfb++ ) {
  1193.     if (distort[0][sfb] > distort_thresh[0]) {
  1194.       distort_thresh[0] = distort[0][sfb];
  1195.       max_ind[0] = sfb;
  1196.     }
  1197.   }
  1198.  
  1199.   for ( i = 1; i < 4; i++ ) {
  1200.     for ( sfb = cod_info->sfb_smax; sfb < 12; sfb++ ) {
  1201.       if (distort[i][sfb] > distort_thresh[i]) {
  1202.         distort_thresh[i] = distort[i][sfb];
  1203.         max_ind[i] = sfb;
  1204.       }
  1205.     }
  1206.   }
  1207.   
  1208.   for ( i = 0; i < 4; i++ ) {
  1209.     if (distort_thresh[i]>1.0)
  1210.       distort_thresh[i] = 1.0;
  1211.     else
  1212.       distort_thresh[i] = pow(distort_thresh[i], 1.05);
  1213.   }
  1214.  
  1215.   for ( sfb = 0; sfb < cod_info->sfb_lmax; sfb++ ) {
  1216.     if ( distort[0][sfb]>distort_thresh[0]
  1217.      && (sfb==max_ind[0] || !gfp->experimentalY)) {
  1218.       scalefac->l[sfb]++;
  1219.       start = gfc->scalefac_band.l[sfb];
  1220.       end   = gfc->scalefac_band.l[sfb+1];
  1221.       for ( l = start; l < end; l++ ) {
  1222.         xrpow[l] *= ifqstep34;
  1223.       }
  1224.     }
  1225.   }
  1226.     
  1227.  
  1228.   for ( j=0,sfb = cod_info->sfb_smax; sfb < 12; sfb++ ) {
  1229.     start = gfc->scalefac_band.s[sfb];
  1230.     end   = gfc->scalefac_band.s[sfb+1];
  1231.     for ( i = 0; i < 3; i++ ) {
  1232.       int j2 = j;
  1233.       if ( distort[i+1][sfb]>distort_thresh[i+1]
  1234.        && (sfb==max_ind[i+1] || !gfp->experimentalY)) {
  1235.         scalefac->s[sfb][i]++;
  1236.         for (l = start; l < end; l++) {
  1237.           xrpow[j2++] *= ifqstep34;
  1238.         }
  1239.       }
  1240.       j += end-start;
  1241.     }
  1242.   }
  1243. }
  1244. #endif
  1245.  
  1246. void inc_scalefac_scale(lame_global_flags *gfp, III_scalefac_t *scalefac,
  1247.                         gr_info *cod_info, FLOAT8 xrpow[576])
  1248. {
  1249.   int start, end, l,i,j;
  1250.   int sfb;
  1251.   lame_internal_flags *gfc=gfp->internal_flags;
  1252.   const FLOAT8 ifqstep34 = 1.29683955465100964055;
  1253.  
  1254.   for ( sfb = 0; sfb < cod_info->sfb_lmax; sfb++ ) {
  1255.     int s = scalefac->l[sfb];
  1256.     if (cod_info->preflag) {
  1257.        s += pretab[sfb];
  1258.     }
  1259.     if (s & 1) {
  1260.       s++;
  1261.       start = gfc->scalefac_band.l[sfb];
  1262.       end   = gfc->scalefac_band.l[sfb+1];
  1263.       for ( l = start; l < end; l++ ) {
  1264.         xrpow[l] *= ifqstep34;
  1265.       }
  1266.     }
  1267.     scalefac->l[sfb] = s >> 1;
  1268.     cod_info->preflag = 0;
  1269.   }
  1270.  
  1271.   for ( j=0,sfb = cod_info->sfb_smax; sfb < 12; sfb++ ) {
  1272.     start = gfc->scalefac_band.s[sfb];
  1273.     end   = gfc->scalefac_band.s[sfb+1];
  1274.     for ( i = 0; i < 3; i++ ) {
  1275.       int j2=j;
  1276.       if (scalefac->s[sfb][i] & 1) {
  1277.         scalefac->s[sfb][i]++;
  1278.         for (l = start; l < end; l++) {
  1279.           xrpow[j2++] *= ifqstep34;
  1280.         }
  1281.       }
  1282.       scalefac->s[sfb][i] >>= 1;
  1283.       j += end-start;
  1284.     }
  1285.   }
  1286.   cod_info->scalefac_scale = 1;
  1287. }
  1288.  
  1289. void inc_subblock_gain(lame_global_flags *gfp, III_scalefac_t *scalefac,
  1290.                        gr_info *cod_info, FLOAT8 xrpow[576])
  1291. {
  1292.   int start, end, l,i;
  1293.   int sfb;
  1294.   lame_internal_flags *gfc=gfp->internal_flags;
  1295.  
  1296.   fun_reorder(gfc->scalefac_band.s,xrpow);
  1297.  
  1298.   for ( i = 0; i < 3; i++ ) {
  1299.     if (cod_info->subblock_gain[i] >= 7) {
  1300.       continue;
  1301.     }
  1302.     for ( sfb = cod_info->sfb_smax; sfb < 12; sfb++ ) {
  1303.       if (scalefac->s[sfb][i] >= 8) {
  1304.         break;
  1305.       }
  1306.     }
  1307.     if (sfb == 12) {
  1308.       continue;
  1309.     }
  1310.     for ( sfb = cod_info->sfb_smax; sfb < 12; sfb++ ) {
  1311.       if (scalefac->s[sfb][i] >= 2) {
  1312.         scalefac->s[sfb][i] -= 2;
  1313.       } else {
  1314.         FLOAT8 amp = pow(2.0, 0.75*(2 - scalefac->s[sfb][i]));
  1315.         scalefac->s[sfb][i] = 0;
  1316.         start = gfc->scalefac_band.s[sfb];
  1317.         end   = gfc->scalefac_band.s[sfb+1];
  1318.         for (l = start; l < end; l++) {
  1319.           xrpow[l * 3 + i] *= amp;
  1320.         }
  1321.       }
  1322.     }
  1323.     {
  1324.       FLOAT8 amp = pow(2.0, 0.75*2);
  1325.       start = gfc->scalefac_band.s[sfb];
  1326.       for (l = start; l < 192; l++) {
  1327.         xrpow[l * 3 + i] *= amp;
  1328.       }
  1329.     }
  1330.     cod_info->subblock_gain[i]++;
  1331.   }
  1332.  
  1333.   freorder(gfc->scalefac_band.s,xrpow);
  1334. }
  1335.