home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 13 / AACD13.ISO / AACD / Sound / LAME / src / vbrquantize.c < prev    next >
C/C++ Source or Header  |  2000-08-06  |  28KB  |  1,024 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. #include <assert.h>
  21. #include "util.h"
  22. #include "l3side.h"
  23. #include "quantize.h"
  24. #include "reservoir.h"
  25. #include "quantize-pvt.h"
  26. #include "gtkanal.h"
  27.  
  28.  
  29. #if (defined(__GNUC__) && defined(__i386__))
  30. #define USE_GNUC_ASM
  31. #endif
  32. #ifdef _MSC_VER
  33. #define USE_MSC_ASM
  34. #endif
  35.  
  36.  
  37.  
  38. /*********************************************************************
  39.  * XRPOW_FTOI is a macro to convert floats to ints.  
  40.  * if XRPOW_FTOI(x) = nearest_int(x), then QUANTFAC(x)=adj43asm[x]
  41.  *                                         ROUNDFAC= -0.0946
  42.  *
  43.  * if XRPOW_FTOI(x) = floor(x), then QUANTFAC(x)=asj43[x]   
  44.  *                                   ROUNDFAC=0.4054
  45.  *********************************************************************/
  46. #ifdef USE_GNUC_ASM
  47. #  define QUANTFAC(rx)  adj43asm[rx]
  48. #  define ROUNDFAC -0.0946
  49. #  define XRPOW_FTOI(src, dest) \
  50.      asm ("fistpl %0 " : "=m"(dest) : "t"(src) : "st")
  51. #elif defined (USE_MSC_ASM)
  52. #  define QUANTFAC(rx)  adj43asm[rx]
  53. #  define ROUNDFAC -0.0946
  54. #  define XRPOW_FTOI(src, dest) do { \
  55.      FLOAT8 src_ = (src); \
  56.      int dest_; \
  57.      { \
  58.        __asm fld src_ \
  59.        __asm fistp dest_ \
  60.      } \
  61.      (dest) = dest_; \
  62.    } while (0)
  63. #else
  64. #  define QUANTFAC(rx)  adj43[rx]
  65. #  define ROUNDFAC 0.4054
  66. #  define XRPOW_FTOI(src,dest) ((dest) = (int)(src))
  67. #endif
  68.  
  69.  
  70.  
  71. #undef MAXQUANTERROR
  72.  
  73.  
  74. FLOAT8 calc_sfb_noise(FLOAT8 *xr, FLOAT8 *xr34, int bw, int sf)
  75. {
  76.   int j;
  77.   FLOAT8 xfsf=0;
  78.   FLOAT8 sfpow,sfpow34;
  79.  
  80.   sfpow = POW20(sf+210); /*pow(2.0,sf/4.0); */
  81.   sfpow34  = IPOW20(sf+210); /*pow(sfpow,-3.0/4.0);*/
  82.  
  83.   for ( j=0; j < bw ; ++j) {
  84.     int ix;
  85.     FLOAT8 temp;
  86.  
  87. #if 0
  88.     if (xr34[j]*sfpow34 > IXMAX_VAL) return -1;
  89.     ix=floor( xr34[j]*sfpow34);
  90.     temp = fabs(xr[j])- pow43[ix]*sfpow;
  91.     temp *= temp;
  92.  
  93.     if (ix < IXMAX_VAL) {
  94.       temp2 = fabs(xr[j])- pow43[ix+1]*sfpow;
  95.       temp2 *=temp2;
  96.       if (temp2<temp) {
  97.     temp=temp2;
  98.     ++ix;
  99.       }
  100.     }
  101. #else
  102.     if (xr34[j]*sfpow34 > IXMAX_VAL) return -1;
  103.  
  104.     temp = xr34[j]*sfpow34;
  105.     XRPOW_FTOI(temp, ix);
  106.     XRPOW_FTOI(temp + QUANTFAC(ix), ix);
  107.     temp = fabs(xr[j])- pow43[ix]*sfpow;
  108.     temp *= temp;
  109.     
  110. #endif
  111.     
  112. #ifdef MAXQUANTERROR
  113.     xfsf = Max(xfsf,temp);
  114. #else
  115.     xfsf += temp;
  116. #endif
  117.   }
  118. #ifdef MAXQUANTERROR
  119.   return xfsf;
  120. #else
  121.   return xfsf/bw;
  122. #endif
  123. }
  124.  
  125.  
  126.  
  127.  
  128.  
  129. FLOAT8 calc_sfb_noise_ave(FLOAT8 *xr, FLOAT8 *xr34, int bw,int sf)
  130. {
  131.   int j;
  132.   FLOAT8 xfsf=0, xfsf_p1=0, xfsf_m1=0;
  133.   FLOAT8 sfpow34,sfpow34_p1,sfpow34_m1;
  134.   FLOAT8 sfpow,sfpow_p1,sfpow_m1;
  135.  
  136.   sfpow = POW20(sf+210); /*pow(2.0,sf/4.0); */
  137.   sfpow34  = IPOW20(sf+210); /*pow(sfpow,-3.0/4.0);*/
  138.  
  139.   sfpow_m1 = sfpow*.8408964153;  /* pow(2,(sf-1)/4.0) */
  140.   sfpow34_m1 = sfpow34*1.13878863476;       /* .84089 ^ -3/4 */
  141.  
  142.   sfpow_p1 = sfpow*1.189207115;  
  143.   sfpow34_p1 = sfpow34*0.878126080187;
  144.  
  145.   for ( j=0; j < bw ; ++j) {
  146.     int ix;
  147.     FLOAT8 temp,temp_p1,temp_m1;
  148.  
  149.     if (xr34[j]*sfpow34_m1 > IXMAX_VAL) return -1;
  150.  
  151.     temp = xr34[j]*sfpow34;
  152.     XRPOW_FTOI(temp, ix);
  153.     XRPOW_FTOI(temp + QUANTFAC(ix), ix);
  154.     temp = fabs(xr[j])- pow43[ix]*sfpow;
  155.     temp *= temp;
  156.  
  157.     temp_p1 = xr34[j]*sfpow34_p1;
  158.     XRPOW_FTOI(temp_p1, ix);
  159.     XRPOW_FTOI(temp_p1 + QUANTFAC(ix), ix);
  160.     temp_p1 = fabs(xr[j])- pow43[ix]*sfpow_p1;
  161.     temp_p1 *= temp_p1;
  162.     
  163.     temp_m1 = xr34[j]*sfpow34_m1;
  164.     XRPOW_FTOI(temp_m1, ix);
  165.     XRPOW_FTOI(temp_m1 + QUANTFAC(ix), ix);
  166.     temp_m1 = fabs(xr[j])- pow43[ix]*sfpow_m1;
  167.     temp_m1 *= temp_m1;
  168.  
  169. #ifdef MAXQUANTERROR
  170.     xfsf = Max(xfsf,temp);
  171.     xfsf_p1 = Max(xfsf_p1,temp_p1);
  172.     xfsf_m1 = Max(xfsf_m1,temp_m1);
  173. #else
  174.     xfsf += temp;
  175.     xfsf_p1 += temp_p1;
  176.     xfsf_m1 += temp_m1;
  177. #endif
  178.   }
  179.   if (xfsf_p1>xfsf) xfsf = xfsf_p1;
  180.   if (xfsf_m1>xfsf) xfsf = xfsf_m1;
  181. #ifdef MAXQUANTERROR
  182.   return xfsf;
  183. #else
  184.   return xfsf/bw;
  185. #endif
  186. }
  187.  
  188.  
  189.  
  190. int find_scalefac(FLOAT8 *xr,FLOAT8 *xr34,int sfb,
  191.              FLOAT8 l3_xmin,int bw)
  192. {
  193.   FLOAT8 xfsf;
  194.   int i,sf,sf_ok,delsf;
  195.  
  196.   /* search will range from sf:  -209 -> 45  */
  197.   sf = -82;
  198.   delsf = 128;
  199.  
  200.   sf_ok=10000;
  201.   for (i=0; i<7; i++) {
  202.     delsf /= 2;
  203.     //      xfsf = calc_sfb_noise(xr,xr34,bw,sf);
  204.     xfsf = calc_sfb_noise_ave(xr,xr34,bw,sf);
  205.  
  206.     if (xfsf < 0) {
  207.       /* scalefactors too small */
  208.       sf += delsf;
  209.     }else{
  210.       if (sf_ok==10000) sf_ok=sf;  
  211.       if (xfsf > l3_xmin)  {
  212.     /* distortion.  try a smaller scalefactor */
  213.     sf -= delsf;
  214.       }else{
  215.     sf_ok = sf;
  216.     sf += delsf;
  217.       }
  218.     }
  219.   } 
  220.   assert(sf_ok!=10000);
  221.   //  assert(delsf==1);  /* when for loop goes up to 7 */
  222.  
  223.   return sf;
  224. }
  225.  
  226.  
  227.  
  228. /*
  229.     sfb=0..5  scalefac < 16 
  230.     sfb>5     scalefac < 8
  231.  
  232.     ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
  233.     ol_sf =  (cod_info->global_gain-210.0);
  234.     ol_sf -= 8*cod_info->subblock_gain[i];
  235.     ol_sf -= ifqstep*scalefac[gr][ch].s[sfb][i];
  236.  
  237. */
  238. int compute_scalefacs_short(int sf[SBPSY_s][3],gr_info *cod_info,
  239. int scalefac[SBPSY_s][3],unsigned int sbg[3])
  240. {
  241.   int maxrange,maxrange1,maxrange2,maxover;
  242.   int sfb,i;
  243.   int ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
  244.  
  245.   maxover=0;
  246.   maxrange1 = 15;
  247.   maxrange2 = 7;
  248.  
  249.  
  250.   for (i=0; i<3; ++i) {
  251.     int maxsf1=0,maxsf2=0,minsf=1000;
  252.     /* see if we should use subblock gain */
  253.     for ( sfb = 0; sfb < SBPSY_s; sfb++ ) {
  254.       if (sfb < 6) {
  255.     if (-sf[sfb][i]>maxsf1) maxsf1 = -sf[sfb][i];
  256.       } else {
  257.     if (-sf[sfb][i]>maxsf2) maxsf2 = -sf[sfb][i];
  258.       }
  259.       if (-sf[sfb][i]<minsf) minsf = -sf[sfb][i];
  260.     }
  261.  
  262.     /* boost subblock gain as little as possible so we can
  263.      * reach maxsf1 with scalefactors 
  264.      * 8*sbg >= maxsf1   
  265.      */
  266.     maxsf1 = Max(maxsf1-maxrange1*ifqstep,maxsf2-maxrange2*ifqstep);
  267.     sbg[i]=0;
  268.     if (minsf >0 ) sbg[i] = floor(.125*minsf + .001);
  269.     if (maxsf1 > 0)  sbg[i]  = Max(sbg[i],maxsf1/8 + (maxsf1 % 8 != 0));
  270.     if (sbg[i] > 7) sbg[i]=7;
  271.  
  272.  
  273.     for ( sfb = 0; sfb < SBPSY_s; sfb++ ) {
  274.       sf[sfb][i] += 8*sbg[i];
  275.  
  276.       if (sf[sfb][i] < 0) {
  277.     maxrange = sfb < 6 ? maxrange1 : maxrange2;
  278.     scalefac[sfb][i]=-sf[sfb][i]/ifqstep + (-sf[sfb][i]%ifqstep != 0);
  279.     if (scalefac[sfb][i]>maxrange) scalefac[sfb][i]=maxrange;
  280.     
  281.     if (-(sf[sfb][i] + scalefac[sfb][i]*ifqstep) >maxover)  {
  282.       maxover=-(sf[sfb][i] + scalefac[sfb][i]*ifqstep);
  283.     }
  284.       }
  285.     }
  286.   }
  287.  
  288.   return maxover;
  289. }
  290.  
  291.  
  292.  
  293.  
  294.  
  295. int max_range_short[SBPSY_s]=
  296. {15, 15, 15, 15, 15, 15 ,  7,    7,    7,    7,   7,     7 };
  297. int max_range_long[SBPSY_l]=
  298. {15,   15,  15,  15,  15,  15,  15,  15,  15,  15,  15,   7,   7,   7,   7,   7,   7,   7,    7,    7,    7};
  299.  
  300.  
  301. /*
  302.       ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
  303.       ol_sf =  (cod_info->global_gain-210.0);
  304.       ol_sf -= ifqstep*scalefac[gr][ch].l[sfb];
  305.       if (cod_info->preflag && sfb>=11) 
  306.       ol_sf -= ifqstep*pretab[sfb];
  307. */
  308. int compute_scalefacs_long(int sf[SBPSY_l],gr_info *cod_info,int scalefac[SBPSY_l])
  309. {
  310.   int sfb;
  311.   int maxover;
  312.   int ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
  313.   
  314.  
  315.   if (cod_info->preflag)
  316.     for ( sfb = 11; sfb < SBPSY_l; sfb++ ) 
  317.       sf[sfb] += pretab[sfb]*ifqstep;
  318.  
  319.  
  320.   maxover=0;
  321.   for ( sfb = 0; sfb < SBPSY_l; sfb++ ) {
  322.  
  323.     if (sf[sfb]<0) {
  324.       /* ifqstep*scalefac >= -sf[sfb], so round UP */
  325.       scalefac[sfb]=-sf[sfb]/ifqstep  + (-sf[sfb] % ifqstep != 0);
  326.       if (scalefac[sfb] > max_range_long[sfb]) scalefac[sfb]=max_range_long[sfb];
  327.       
  328.       /* sf[sfb] should now be positive: */
  329.       if (  -(sf[sfb] + scalefac[sfb]*ifqstep)  > maxover) {
  330.     maxover = -(sf[sfb] + scalefac[sfb]*ifqstep);
  331.       }
  332.     }
  333.   }
  334.  
  335.   return maxover;
  336. }
  337.   
  338.   
  339.  
  340.  
  341.  
  342.  
  343.  
  344.  
  345. /************************************************************************
  346.  *
  347.  * quantize and encode with the given scalefacs and global gain
  348.  *
  349.  * compute scalefactors, l3_enc, and return number of bits needed to encode
  350.  *
  351.  *
  352.  ************************************************************************/
  353. void
  354. VBR_quantize_granule(lame_global_flags *gfp,
  355.                 FLOAT8 xr34[576], int l3_enc[576],
  356.              III_psy_ratio *ratio,  
  357.                 III_scalefac_t *scalefac, int gr, int ch)
  358. {
  359.   lame_internal_flags *gfc=gfp->internal_flags;
  360.   int status;
  361.   gr_info *cod_info;  
  362.   III_side_info_t * l3_side;
  363.   l3_side = &gfc->l3_side;
  364.   cod_info = &l3_side->gr[gr].ch[ch].tt;
  365.  
  366.  
  367.   /* encode scalefacs */
  368.   if ( gfp->version == 1 ) 
  369.     status=scale_bitcount(scalefac, cod_info);
  370.   else
  371.     status=scale_bitcount_lsf(scalefac, cod_info);
  372.  
  373.   if (status!=0) {
  374.     return;
  375.   }
  376.   
  377.   /* quantize xr34 */
  378.   cod_info->part2_3_length = count_bits(gfp,l3_enc,xr34,cod_info);
  379.   if (cod_info->part2_3_length >= LARGE_BITS) return;
  380.   cod_info->part2_3_length += cod_info->part2_length;
  381.  
  382.  
  383.   if (gfc->use_best_huffman==1) {
  384.     best_huffman_divide(gfc, gr, ch, cod_info, l3_enc);
  385.   }
  386.   return;
  387. }
  388.   
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.  
  401.  
  402.  
  403.  
  404.  
  405.  
  406. /************************************************************************
  407.  *
  408.  * VBR_noise_shaping()
  409.  *
  410.  * compute scalefactors, l3_enc, and return number of bits needed to encode
  411.  *
  412.  * return code:    0   scalefactors were found with all noise < masking
  413.  *
  414.  *               n>0   scalefactors required too many bits.  global gain
  415.  *                     was decreased by n
  416.  *                     If n is large, we should probably recompute scalefacs
  417.  *                     with a lower quality.
  418.  *
  419.  *               n<0   scalefactors used less than minbits.
  420.  *                     global gain was increased by n.  
  421.  *                     If n is large, might want to recompute scalefacs
  422.  *                     with a higher quality setting?
  423.  *
  424.  ************************************************************************/
  425. int
  426. VBR_noise_shaping
  427. (
  428.  lame_global_flags *gfp,
  429.  FLOAT8 xr[576], FLOAT8 xr34orig[576], III_psy_ratio *ratio,
  430.  int l3_enc[576], int digital_silence, int minbits, int maxbits,
  431.  III_scalefac_t *scalefac, III_psy_xmin *l3_xmin,
  432.  int gr,int ch)
  433. {
  434.   lame_internal_flags *gfc=gfp->internal_flags;
  435.   int       start,end,bw,sfb,l, i,j, vbrmax;
  436.   III_scalefac_t vbrsf;
  437.   III_scalefac_t save_sf;
  438.   int maxover0,maxover1,maxover0p,maxover1p,maxover,mover;
  439.   int ifqstep;
  440.   III_side_info_t * l3_side;
  441.   gr_info *cod_info;  
  442.   FLOAT8 xr34[576];
  443.   int shortblock;
  444.   int global_gain_adjust=0;
  445.  
  446.   l3_side = &gfc->l3_side;
  447.   cod_info = &l3_side->gr[gr].ch[ch].tt;
  448.   shortblock = (cod_info->block_type == SHORT_TYPE);
  449.   
  450.   memcpy(xr34, xr34orig, sizeof(xr34));
  451.  
  452.   
  453. #define MAX_SF_DELTA 4  
  454.   vbrmax=-10000;
  455.   if (shortblock) {
  456.     for ( j=0, sfb = 0; sfb < SBMAX_s; sfb++ )  {
  457.       for ( i = 0; i < 3; i++ ) {
  458.     start = gfc->scalefac_band.s[ sfb ];
  459.     end   = gfc->scalefac_band.s[ sfb+1 ];
  460.     bw = end - start;
  461.     vbrsf.s[sfb][i] = find_scalefac(&xr[j],&xr34[j],sfb,
  462.                     l3_xmin->s[sfb][i],bw);
  463.     j += bw;
  464.       }
  465.     }
  466.  
  467.     for ( sfb = 0; sfb < SBMAX_s; sfb++ )  {
  468.       for ( i = 0; i < 3; i++ ) {
  469.     if (sfb>0) 
  470.       vbrsf.s[sfb][i] = Min(vbrsf.s[sfb-1][i]+MAX_SF_DELTA,vbrsf.s[sfb][i]);
  471.     if (sfb< SBMAX_s-1) 
  472.       vbrsf.s[sfb][i] = Min(vbrsf.s[sfb+1][i]+MAX_SF_DELTA,vbrsf.s[sfb][i]);
  473.       }
  474.     }
  475.  
  476.     for ( j=0, sfb = 0; sfb < SBMAX_s; sfb++ )  {
  477.       for ( i = 0; i < 3; i++ ) {
  478.     if (vbrsf.s[sfb][i]>vbrmax) vbrmax=vbrsf.s[sfb][i];
  479.       }
  480.     }
  481.  
  482.   }else{
  483.     for ( sfb = 0; sfb < SBMAX_l; sfb++ )   {
  484.       start = gfc->scalefac_band.l[ sfb ];
  485.       end   = gfc->scalefac_band.l[ sfb+1 ];
  486.       bw = end - start;
  487.       vbrsf.l[sfb] = find_scalefac(&xr[start],&xr34[start],sfb,
  488.                    l3_xmin->l[sfb],bw);
  489.  
  490.     }
  491.  
  492.     for ( sfb = 0; sfb < SBMAX_l; sfb++ )   {
  493.       if (sfb>0) 
  494.     vbrsf.l[sfb] = Min(vbrsf.l[sfb-1]+MAX_SF_DELTA,vbrsf.l[sfb]);
  495.       if (sfb< SBMAX_l-1) 
  496.     vbrsf.l[sfb] = Min(vbrsf.l[sfb+1]+MAX_SF_DELTA,vbrsf.l[sfb]);
  497.  
  498.     }
  499.  
  500.     for ( sfb = 0; sfb < SBMAX_l; sfb++ )   
  501.       if (vbrsf.l[sfb]>vbrmax) vbrmax = vbrsf.l[sfb];
  502.  
  503.  
  504.   } /* compute needed scalefactors */
  505.  
  506.  
  507.  
  508.   /* save a copy of vbrsf, incase we have to recomptue scalefacs */
  509.   memcpy(&save_sf,&vbrsf,sizeof(III_scalefac_t));
  510.  
  511.  
  512.   do { 
  513.  
  514.   memset(scalefac,0,sizeof(III_scalefac_t));
  515.     
  516.   if (shortblock) {
  517.     /******************************************************************
  518.      *
  519.      *  short block scalefacs
  520.      *
  521.      ******************************************************************/
  522.     maxover0=0;
  523.     maxover1=0;
  524.     for ( sfb = 0; sfb < SBPSY_s; sfb++ ) {
  525.       for ( i = 0; i < 3; i++ ) {
  526.     maxover0 = Max(maxover0,(vbrmax - vbrsf.s[sfb][i]) - (4*14 + 2*max_range_short[sfb]) );
  527.     maxover1 = Max(maxover1,(vbrmax - vbrsf.s[sfb][i]) - (4*14 + 4*max_range_short[sfb]) );
  528.       }
  529.     }
  530.     if (gfc->noise_shaping==2)
  531.       /* allow scalefac_scale=1 */
  532.       mover = Min(maxover0,maxover1);
  533.     else
  534.       mover = maxover0; 
  535.  
  536.  
  537.     vbrmax -= mover;
  538.     maxover0 -= mover;
  539.     maxover1 -= mover;
  540.  
  541.     if (maxover0==0) 
  542.       cod_info->scalefac_scale = 0;
  543.     else if (maxover1==0)
  544.       cod_info->scalefac_scale = 1;
  545.  
  546.  
  547.     /* sf =  (cod_info->global_gain-210.0) */
  548.     cod_info->global_gain = vbrmax +210;
  549.     assert(cod_info->global_gain < 256);
  550.     if (cod_info->global_gain>255) cod_info->global_gain=255;
  551.     
  552.     for ( sfb = 0; sfb < SBPSY_s; sfb++ ) {
  553.       for ( i = 0; i < 3; i++ ) {
  554.     vbrsf.s[sfb][i]-=vbrmax;
  555.       }
  556.     }
  557.     maxover=compute_scalefacs_short(vbrsf.s,cod_info,scalefac->s,cod_info->subblock_gain);
  558.     assert(maxover <=0);
  559.     {
  560.       /* adjust global_gain so at least 1 subblock gain = 0 */
  561.       int minsfb=999;
  562.       for (i=0; i<3; i++) minsfb = Min(minsfb,cod_info->subblock_gain[i]);
  563.       minsfb = Min(cod_info->global_gain/8,minsfb);
  564.       vbrmax -= 8*minsfb; 
  565.       cod_info->global_gain -= 8*minsfb;
  566.       for (i=0; i<3; i++) cod_info->subblock_gain[i] -= minsfb;
  567.     }
  568.     
  569.     
  570.     
  571.     /* quantize xr34[] based on computed scalefactors */
  572.     ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
  573.     for ( j=0, sfb = 0; sfb < SBPSY_s; sfb++ ) {
  574.       start = gfc->scalefac_band.s[ sfb ];
  575.       end   = gfc->scalefac_band.s[ sfb+1 ];
  576.       for (i=0; i<3; i++) {
  577.     int ifac;
  578.     FLOAT8 fac;
  579.     ifac = (8*cod_info->subblock_gain[i]+ifqstep*scalefac->s[sfb][i]);
  580.     if (ifac+210<Q_MAX) 
  581.       fac = 1/IPOW20(ifac+210);
  582.     else
  583.       fac = pow(2.0,.75*ifac/4.0);
  584.     for ( l = start; l < end; l++ ) 
  585.       xr34[j++]*=fac;
  586.       }
  587.     }
  588.     
  589.     
  590.     
  591.   }else{
  592.     /******************************************************************
  593.      *
  594.      *  long block scalefacs
  595.      *
  596.      ******************************************************************/
  597.     maxover0=0;
  598.     maxover1=0;
  599.     maxover0p=0;
  600.     maxover1p=0;
  601.     
  602.     
  603.     for ( sfb = 0; sfb < SBPSY_l; sfb++ ) {
  604.       maxover0 = Max(maxover0,(vbrmax - vbrsf.l[sfb]) - 2*max_range_long[sfb] );
  605.       maxover0p = Max(maxover0,(vbrmax - vbrsf.l[sfb]) - 2*(max_range_long[sfb]+pretab[sfb]) );
  606.       maxover1 = Max(maxover1,(vbrmax - vbrsf.l[sfb]) - 4*max_range_long[sfb] );
  607.       maxover1p = Max(maxover1,(vbrmax - vbrsf.l[sfb]) - 4*(max_range_long[sfb]+pretab[sfb]));
  608.     }
  609.     mover = Min(maxover0,maxover0p);
  610.     if (gfc->noise_shaping==2) {
  611.       /* allow scalefac_scale=1 */
  612.       mover = Min(mover,maxover1);
  613.       mover = Min(mover,maxover1p);
  614.     }
  615.  
  616.  
  617.     vbrmax -= mover;
  618.     maxover0 -= mover;
  619.     maxover0p -= mover;
  620.     maxover1 -= mover;
  621.     maxover1p -= mover;
  622.  
  623.  
  624.     if (maxover0<=0) {
  625.       cod_info->scalefac_scale = 0;
  626.       cod_info->preflag=0;
  627.       vbrmax -= maxover0;
  628.     } else if (maxover0p<=0) {
  629.       cod_info->scalefac_scale = 0;
  630.       cod_info->preflag=1;
  631.       vbrmax -= maxover0p;
  632.     } else if (maxover1==0) {
  633.       cod_info->scalefac_scale = 1;
  634.       cod_info->preflag=0;
  635.     } else if (maxover1p==0) {
  636.       cod_info->scalefac_scale = 1;
  637.       cod_info->preflag=1;
  638.     } else {
  639.       ERRORF("error vbrquantize.c...\n");
  640.       LAME_ERROR_EXIT();
  641.     }
  642.  
  643.     
  644.     /* sf =  (cod_info->global_gain-210.0) */
  645.     cod_info->global_gain = vbrmax +210;
  646.     assert(cod_info->global_gain < 256);
  647.     if (cod_info->global_gain>255) cod_info->global_gain=255;
  648.  
  649.     
  650.     for ( sfb = 0; sfb < SBPSY_l; sfb++ )   
  651.       vbrsf.l[sfb] -= vbrmax;
  652.     
  653.     
  654.     maxover=compute_scalefacs_long(vbrsf.l,cod_info,scalefac->l);
  655.     assert(maxover <=0);
  656.     
  657.     
  658.     /* quantize xr34[] based on computed scalefactors */
  659.     ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
  660.     for ( sfb = 0; sfb < SBPSY_l; sfb++ ) {
  661.       int ifac;
  662.       FLOAT8 fac;
  663.       ifac = ifqstep*scalefac->l[sfb];
  664.       if (cod_info->preflag)
  665.     ifac += ifqstep*pretab[sfb];
  666.  
  667.       if (ifac+210<Q_MAX) 
  668.     fac = 1/IPOW20(ifac+210);
  669.       else
  670.     fac = pow(2.0,.75*ifac/4.0);
  671.  
  672.       start = gfc->scalefac_band.l[ sfb ];
  673.       end   = gfc->scalefac_band.l[ sfb+1 ];
  674.       for ( l = start; l < end; l++ ) {
  675.         xr34[l]*=fac;
  676.       }
  677.     }
  678.   } 
  679.  
  680.   VBR_quantize_granule(gfp,xr34,l3_enc,ratio,scalefac,gr,ch);
  681.  
  682.  
  683.  
  684.  
  685.   if (cod_info->part2_3_length < minbits) {
  686.     /* decrease global gain, recompute scale factors */
  687.     if (digital_silence) break;  
  688.     //    if (cod_info->part2_3_length-cod_info->part2_length== 0) break;
  689.     if (vbrmax+210 ==0 ) break;
  690.     
  691.  
  692.  
  693.     --vbrmax;
  694.     --global_gain_adjust;
  695.     memcpy(&vbrsf,&save_sf,sizeof(III_scalefac_t));
  696.     memcpy(xr34, xr34orig, sizeof(xr34));
  697.   }
  698.  
  699.   } while ((cod_info->part2_3_length < minbits));
  700.  
  701.  
  702.  
  703.   while (cod_info->part2_3_length > Min(maxbits,4095)) {
  704.     /* increase global gain, keep exisiting scale factors */
  705.     ++cod_info->global_gain;
  706.     if (cod_info->global_gain > 255) 
  707.       ERRORF("%ld impossible to encode this frame! bits=%d\n",
  708.           gfp->frameNum,cod_info->part2_3_length);
  709.     VBR_quantize_granule(gfp,xr34,l3_enc,ratio,scalefac,gr,ch);
  710.  
  711.     ++global_gain_adjust;
  712.   }
  713.  
  714.  
  715.   return global_gain_adjust;
  716. }
  717.  
  718.  
  719.  
  720.  
  721. void
  722. VBR_quantize(lame_global_flags *gfp,
  723.                 FLOAT8 pe[2][2], FLOAT8 ms_ener_ratio[2],
  724.                 FLOAT8 xr[2][2][576], III_psy_ratio ratio[2][2],
  725.                 int l3_enc[2][2][576],
  726.                 III_scalefac_t scalefac[2][2])
  727. {
  728.   III_psy_xmin l3_xmin[2][2];
  729.   lame_internal_flags *gfc=gfp->internal_flags;
  730.   int minbits,maxbits,max_frame_bits,totbits,gr,ch,i,bits_ok;
  731.   int bitsPerFrame,mean_bits;
  732.   int analog_silence;
  733.   FLOAT8 qadjust;
  734.   III_side_info_t * l3_side;
  735.   gr_info *cod_info;  
  736.   int digital_silence[2][2];
  737.   FLOAT8 masking_lower_db=0;
  738.   FLOAT8 xr34[2][2][576];
  739.   // static const FLOAT8 dbQ[10]={-6.0,-5.0,-4.0,-3.0, -2.0, -1.0, -.25, .5, 1.25, 2.0};
  740.   /* from quantize.c VBR algorithm */
  741.   /*static const FLOAT8 dbQ[10]=
  742.    {-5.5,-4.25,-3.0,-2.50, -1.75, -.75, -.5, -.25, .25, .75};*/
  743.   static const FLOAT8 dbQ[10]=
  744.   {-6.06,-4.4,-2.9,-1.57, -0.4, 0.61, 1.45, 2.13, 2.65, 3.0};
  745.   
  746.   qadjust=0;   /* start with -1 db quality improvement over quantize.c VBR */
  747.  
  748.   l3_side = &gfc->l3_side;
  749.   gfc->ATH_vbrlower = (4-gfp->VBR_q)*4.0; 
  750.   if (gfc->ATH_vbrlower < 0) gfc->ATH_vbrlower=0;
  751.   iteration_init(gfp,l3_side,l3_enc);
  752.  
  753.  
  754.   /* now find out: if the frame can be considered analog silent
  755.    *               if each granule can be considered digital silent
  756.    * and calculate l3_xmin and the fresh xr34 array
  757.    */
  758.  
  759.   assert( gfp->VBR_q <= 9 );
  760.   assert( gfp->VBR_q >= 0 );
  761.   analog_silence=1;
  762.   for (gr = 0; gr < gfc->mode_gr; gr++) {
  763.     /* copy data to be quantized into xr */
  764.     if (gfc->mode_ext==MPG_MD_MS_LR) {
  765.       ms_convert(xr[gr],xr[gr]);
  766.     }
  767.     for (ch = 0; ch < gfc->stereo; ch++) {
  768.       /* if in the following sections the quality would not be adjusted
  769.        * then we would only have to call calc_xmin once here and
  770.        * could drop subsequently calls (rh 2000/07/17)
  771.        */
  772.       int over_ath;
  773.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  774.       cod_info->part2_3_length=LARGE_BITS;
  775.       
  776.       /* quality setting */
  777.       masking_lower_db = dbQ[gfp->VBR_q];
  778.       if (pe[gr][ch]>750) {
  779.         masking_lower_db -= Min(10,4*(pe[gr][ch]-750.)/750.);
  780.       }
  781.       gfc->masking_lower = pow(10.0,masking_lower_db/10);
  782.       
  783.       /* masking thresholds */
  784.       over_ath = calc_xmin(gfp,xr[gr][ch],ratio[gr]+ch,cod_info,l3_xmin[gr]+ch);
  785.       
  786.       /* if there are bands with more energy than the ATH 
  787.        * then we say the frame is not analog silent */
  788.       if (over_ath) {
  789.         analog_silence = 0;
  790.       }
  791.       
  792.       /* if there is no line with more energy than 1e-20
  793.        * then this granule is considered to be digital silent
  794.        * plus calculation of xr34 */
  795.       digital_silence[gr][ch] = 1;
  796.       for(i=0;i<576;i++) {
  797.         FLOAT8 temp=fabs(xr[gr][ch][i]);
  798.         xr34[gr][ch][i]=sqrt(sqrt(temp)*temp);
  799.         digital_silence[gr][ch] &= temp < 1E-20;
  800.       }
  801.     } /* ch */
  802.   }  /* gr */
  803.  
  804.   
  805.   /* compute minimum allowed bits from minimum allowed bitrate */
  806.   if (analog_silence) {
  807.     gfc->bitrate_index=1;
  808.   } else {
  809.     gfc->bitrate_index=gfc->VBR_min_bitrate;
  810.   }
  811.   getframebits(gfp,&bitsPerFrame, &mean_bits);
  812.   minbits = (mean_bits/gfc->stereo);
  813.  
  814.   /* compute maximum allowed bits from max allowed bitrate */
  815.   gfc->bitrate_index=gfc->VBR_max_bitrate;
  816.   getframebits(gfp,&bitsPerFrame, &mean_bits);
  817.   max_frame_bits = ResvFrameBegin(gfp,l3_side, mean_bits, bitsPerFrame);
  818.   maxbits=2.5*(mean_bits/gfc->stereo);
  819.  
  820.   {
  821.   /* compute a target  mean_bits based on compression ratio 
  822.    * which was set based on VBR_q  
  823.    */
  824.   int bit_rate = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->compression_ratio);
  825.   bitsPerFrame = (bit_rate*gfp->framesize*1000)/gfp->out_samplerate;
  826.   mean_bits = (bitsPerFrame - 8*gfc->sideinfo_len) / gfc->mode_gr;
  827.   }
  828.  
  829.  
  830.   minbits = Max(minbits,125);
  831.   minbits=Max(minbits,.40*(mean_bits/gfc->stereo));
  832.   maxbits=Min(maxbits,2.5*(mean_bits/gfc->stereo));
  833.  
  834.  
  835.  
  836.  
  837.  
  838.  
  839.  
  840.   /* 
  841.    * loop over all ch,gr, encoding anything with bits > .5*(max_frame_bits/4)
  842.    *
  843.    * If a particular granule uses way too many bits, it will be re-encoded
  844.    * on the next iteration of the loop (with a lower quality setting).  
  845.    * But granules which dont use
  846.    * use too many bits will not be re-encoded.
  847.    *
  848.    * minbits:  minimum allowed bits for 1 granule 1 channel
  849.    * maxbits:  maximum allowwed bits for 1 granule 1 channel
  850.    * max_frame_bits:  maximum allowed bits for entire frame
  851.    * (max_frame_bits/4)   estimate of average bits per granule per channel
  852.    * 
  853.    */
  854.  
  855.   do {
  856.   
  857.     totbits=0;
  858.     for (gr = 0; gr < gfc->mode_gr; gr++) {
  859.       int minbits_lr[2];
  860.       minbits_lr[0]=minbits;
  861.       minbits_lr[1]=minbits;
  862.  
  863. #if 0
  864.       if (gfc->mode_ext==MPG_MD_MS_LR) {
  865.         FLOAT8 fac;
  866.         fac = .33*(.5-ms_ener_ratio[gr])/.5;
  867.         if (fac<0) fac=0;
  868.         if (fac>.5) fac=.5;
  869.         minbits_lr[0] = (1+fac)*minbits;
  870.         minbits_lr[1] = Max(125,(1-fac)*minbits);
  871.       }
  872. #endif
  873.  
  874.  
  875.       for (ch = 0; ch < gfc->stereo; ch++) { 
  876.         int adjusted,shortblock;
  877.         cod_info = &l3_side->gr[gr].ch[ch].tt;
  878.         
  879.         /* ENCODE this data first pass, and on future passes unless it uses
  880.          * a very small percentage of the max_frame_bits  */
  881.         if (cod_info->part2_3_length > (max_frame_bits/(2*gfc->stereo*gfc->mode_gr))) {
  882.   
  883.           shortblock = (cod_info->block_type == SHORT_TYPE);
  884.   
  885.           /* Adjust allowed masking based on quality setting */
  886.           if (qadjust!=0 /*|| shortblock*/) {
  887.             masking_lower_db = dbQ[gfp->VBR_q] + qadjust;
  888.  
  889.             /*
  890.             if (shortblock) masking_lower_db -= 4;
  891.             */
  892.      
  893.             if (pe[gr][ch]>750)
  894.               masking_lower_db -= Min(10,4*(pe[gr][ch]-750.)/750.);
  895.             gfc->masking_lower = pow(10.0,masking_lower_db/10);
  896.             calc_xmin( gfp,xr[gr][ch], ratio[gr]+ch, cod_info, l3_xmin[gr]+ch);
  897.           }
  898.           
  899.           /* digital silent granules do not need the full round trip,
  900.            * but this can be optimized later on
  901.            */
  902.           adjusted = VBR_noise_shaping (gfp,xr[gr][ch],xr34[gr][ch],
  903.                                         ratio[gr]+ch,l3_enc[gr][ch],
  904.                                         digital_silence[gr][ch],
  905.                                         minbits_lr[ch],
  906.                                         maxbits,scalefac[gr]+ch,
  907.                                         l3_xmin[gr]+ch,gr,ch);
  908.           if (adjusted>10) {
  909.             /* global_gain was changed by a large amount to get bits < maxbits */
  910.             /* quality is set to high.  we could set bits = LARGE_BITS
  911.              * to force re-encoding.  But most likely the other channels/granules
  912.              * will also use too many bits, and the entire frame will
  913.              * be > max_frame_bits, forcing re-encoding below.
  914.              */
  915.             // cod_info->part2_3_bits = LARGE_BITS;
  916.           }
  917.         }
  918.         totbits += cod_info->part2_3_length;
  919.       }
  920.     }
  921.     bits_ok=1;
  922.     if (totbits>max_frame_bits) {
  923.       /* lower quality */
  924.       qadjust += Max(.125,Min(1,(totbits-max_frame_bits)/300.0));
  925.       /* adjusting minbits and maxbits is necessary too
  926.        * cos lowering quality is not enough in rare cases
  927.        * when each granule still needs almost maxbits, it wont fit */ 
  928.       minbits = Max(125,minbits*0.975);
  929.       maxbits = Max(minbits,maxbits*0.975);
  930.       //      DEBUGF("%i totbits>max_frame_bits   totbits=%i  maxbits=%i \n",gfp->frameNum,totbits,max_frame_bits);
  931.       //      DEBUGF("next masking_lower_db = %f \n",masking_lower_db + qadjust);
  932.       bits_ok=0;
  933.     }
  934.     
  935.   } while (!bits_ok);
  936.   
  937.  
  938.   /* find optimal scalefac storage.  Cant be done above because
  939.    * might enable scfsi which breaks the interation loops */
  940.   totbits=0;
  941.   for (gr = 0; gr < gfc->mode_gr; gr++) {
  942.     for (ch = 0; ch < gfc->stereo; ch++) {
  943.       best_scalefac_store(gfp,gr, ch, l3_enc, l3_side, scalefac);
  944.       totbits += l3_side->gr[gr].ch[ch].tt.part2_3_length;
  945.     }
  946.   }
  947.  
  948.  
  949.  
  950.   
  951.   if (gfp->gtkflag) {
  952.     for (gr = 0; gr < gfc->mode_gr; gr++) {
  953.       for (ch = 0; ch < gfc->stereo; ch++) {
  954.         III_psy_xmin l3_xmin;
  955.         calc_noise_result noise_info;
  956.         FLOAT8 noise[4];
  957.         FLOAT8 xfsf[4][SBMAX_l];
  958.         FLOAT8 distort[4][SBMAX_l];
  959.  
  960.         cod_info = &l3_side->gr[gr].ch[ch].tt;
  961.  
  962.         /* recompute allowed noise with no 'masking_lower' for
  963.          * frame analyzer */
  964.         gfc->masking_lower=1.0;
  965.         cod_info = &l3_side->gr[gr].ch[ch].tt;
  966.         calc_xmin( gfp,xr[gr][ch], &ratio[gr][ch], cod_info, &l3_xmin);
  967.  
  968.         calc_noise( gfp, xr[gr][ch], l3_enc[gr][ch], cod_info, 
  969.                     xfsf,distort, &l3_xmin, &scalefac[gr][ch], &noise_info);
  970.         noise[0] = noise_info.over_count;
  971.         noise[1] = noise_info.max_noise;
  972.         noise[2] = noise_info.over_noise;
  973.         noise[3] = noise_info.tot_noise;
  974.  
  975.         set_pinfo (gfp, cod_info, &ratio[gr][ch], &scalefac[gr][ch], xr[gr][ch], xfsf, noise, gr, ch);
  976.       }
  977.     }
  978.   }
  979.  
  980.  
  981.   
  982.  
  983.   if (analog_silence && !gfp->VBR_hard_min) {
  984.     gfc->bitrate_index = 1;
  985.   } else {
  986.     gfc->bitrate_index = gfc->VBR_min_bitrate;
  987.   }
  988.   for( ; gfc->bitrate_index < gfc->VBR_max_bitrate; gfc->bitrate_index++ ) {
  989.  
  990.     getframebits (gfp,&bitsPerFrame, &mean_bits);
  991.     maxbits = ResvFrameBegin(gfp,l3_side, mean_bits, bitsPerFrame);
  992.     if (totbits <= maxbits) break;
  993.   }
  994.   if (gfc->bitrate_index == gfc->VBR_max_bitrate) {
  995.     getframebits (gfp,&bitsPerFrame, &mean_bits);
  996.     maxbits = ResvFrameBegin(gfp,l3_side, mean_bits, bitsPerFrame);
  997.   }
  998.  
  999.   //  DEBUGF("%i total_bits=%i max_frame_bits=%i index=%i  \n",gfp->frameNum,totbits,max_frame_bits,gfc->bitrate_index);
  1000.  
  1001.   for (gr = 0; gr < gfc->mode_gr; gr++) {
  1002.     for (ch = 0; ch < gfc->stereo; ch++) {
  1003.       cod_info = &l3_side->gr[gr].ch[ch].tt;
  1004.  
  1005.  
  1006.       ResvAdjust (gfp,cod_info, l3_side, mean_bits);
  1007.       
  1008.       /*******************************************************************
  1009.        * set the sign of l3_enc from the sign of xr
  1010.        *******************************************************************/
  1011.       for ( i = 0; i < 576; i++) {
  1012.         if (xr[gr][ch][i] < 0) l3_enc[gr][ch][i] *= -1;
  1013.       }
  1014.     }
  1015.   }
  1016.   ResvFrameEnd (gfp,l3_side, mean_bits);
  1017.  
  1018.  
  1019.  
  1020. }
  1021.  
  1022.  
  1023.  
  1024.