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

  1. /*
  2.  *    LAME MP3 encoding engine
  3.  *
  4.  *    Copyright (c) 1999 Mark Taylor
  5.  *
  6.  * This library is free software; you can redistribute it and/or
  7.  * modify it under the terms of the GNU Library General Public
  8.  * License as published by the Free Software Foundation; either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * This library is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
  14.  * Library General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU Library General Public
  17.  * License along with this library; if not, write to the
  18.  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19.  * Boston, MA 02111-1307, USA.
  20.  */
  21.  
  22.  
  23. #include <assert.h>
  24.  
  25.  
  26. #include "gtkanal.h"
  27. #include "lame.h"
  28. #include "util.h"
  29. #include "timestatus.h"
  30. #include "psymodel.h"
  31. #include "newmdct.h"
  32. #include "quantize.h"
  33. #include "quantize-pvt.h"
  34. #include "bitstream.h"
  35. #include "version.h"
  36. #include "VbrTag.h"
  37. #include "id3tag.h"
  38. #include "tables.h"
  39. #include "brhist.h"
  40. #include "get_audio.h"
  41.  
  42. #ifdef __riscos__
  43. #include "asmstuff.h"
  44. #endif
  45.  
  46. /* lame_init_params_ppflt_lowpass */
  47.  
  48. static void
  49. lame_init_params_ppflt_lowpass(FLOAT8 amp_lowpass[32], float lowpass1,
  50.                    float lowpass2, int *lowpass_band,
  51.                    int *minband, int *maxband)
  52. {
  53.     int band;
  54.     FLOAT8 freq;
  55.  
  56.     for (band = 0; band <= 31; band++) {
  57.         freq = band / 31.0;
  58.         amp_lowpass[band] = 1;
  59.         /* this band and above will be zeroed: */
  60.         if (freq >= lowpass2) {
  61.             *lowpass_band = Min(*lowpass_band, band);
  62.             amp_lowpass[band]=0;
  63.         }
  64.         if (lowpass1 < freq && freq < lowpass2) {
  65.             *minband = Min(*minband, band);
  66.             *maxband = Max(*maxband, band);
  67.             amp_lowpass[band] = cos((PI / 2) *
  68.                         (lowpass1 - freq) /
  69.                         (lowpass2 - lowpass1));
  70.         }
  71.         /*
  72.         DEBUGF("lowpass band=%i  amp=%f \n",
  73.                band, gfc->amp_lowpass[band]);
  74.         */
  75.     }
  76. }
  77.  
  78. /* lame_init_params_ppflt */
  79.  
  80. static void
  81. lame_init_params_ppflt(lame_internal_flags *gfc)
  82. {
  83.   /***************************************************************/
  84.   /* compute info needed for polyphase filter (filter type==0, default) */
  85.   /***************************************************************/
  86.  
  87.     int band, maxband, minband;
  88.     FLOAT8 freq;
  89.  
  90.     if (gfc->lowpass1 > 0) {
  91.         minband = 999;
  92.         maxband = -1;
  93.         lame_init_params_ppflt_lowpass(gfc->amp_lowpass,
  94.                            gfc->lowpass1, gfc->lowpass2,
  95.                            &gfc->lowpass_band, &minband,
  96.                            &maxband);
  97.         /* compute the *actual* transition band implemented by
  98.          * the polyphase filter */
  99.         if (minband == 999) {
  100.             gfc->lowpass1 = (gfc->lowpass_band - .75) / 31.0;
  101.         } else {
  102.             gfc->lowpass1 = (minband - .75) / 31.0;
  103.         }
  104.         gfc->lowpass2 = gfc->lowpass_band / 31.0;
  105.  
  106.         gfc->lowpass_start_band = minband;
  107.         gfc->lowpass_end_band = maxband;
  108.  
  109.         /* as the lowpass may have changed above
  110.          * calculate the amplification here again
  111.          */
  112.         for (band = minband; band <= maxband; band++) {
  113.             freq = band / 31.0;
  114.             gfc->amp_lowpass[band] =
  115.                 cos((PI / 2) * (gfc->lowpass1 - freq) /
  116.                     (gfc->lowpass2 - gfc->lowpass1));
  117.         }
  118.     } else {
  119.         gfc->lowpass_start_band = 0;
  120.         gfc->lowpass_end_band = -1;/* do not to run into for-loops */
  121.     }
  122.  
  123.     /* make sure highpass filter is within 90% of what the effective
  124.      * highpass frequency will be */
  125.     if (gfc->highpass2 > 0) {
  126.         if (gfc->highpass2 < .9 * (.75 / 31.0) ) {
  127.             gfc->highpass1 = 0;
  128.             gfc->highpass2 = 0;
  129.             MSGF("Warning: highpass filter disabled.  "
  130.                  "highpass frequency to small\n");
  131.         }
  132.     }
  133.  
  134.     if (gfc->highpass2 > 0) {
  135.         minband = 999;
  136.         maxband = -1;
  137.         for (band = 0; band <= 31; band++) {
  138.             freq = band / 31.0;
  139.             gfc->amp_highpass[band] = 1;
  140.             /* this band and below will be zereod */
  141.             if (freq <= gfc->highpass1) {
  142.                 gfc->highpass_band = Max(gfc->highpass_band,
  143.                              band);
  144.                 gfc->amp_highpass[band] = 0;
  145.             }
  146.             if (gfc->highpass1 < freq && freq < gfc->highpass2) {
  147.                 minband = Min(minband, band);
  148.                 maxband = Max(maxband, band);
  149.                 gfc->amp_highpass[band] =
  150.                     cos((PI / 2) *
  151.                         (gfc->highpass2 - freq) / 
  152.                         (gfc->highpass2 - gfc->highpass1));
  153.             }
  154.             /*
  155.             DEBUGF("highpass band=%i  amp=%f \n",
  156.                    band, gfc->amp_highpass[band]);
  157.             */
  158.         }
  159.         /* compute the *actual* transition band implemented by
  160.          * the polyphase filter */
  161.         gfc->highpass1 = gfc->highpass_band / 31.0;
  162.         if (maxband == -1) {
  163.             gfc->highpass2 = (gfc->highpass_band + .75) / 31.0;
  164.         } else {
  165.             gfc->highpass2 = (maxband + .75) / 31.0;
  166.         }
  167.  
  168.         gfc->highpass_start_band = minband;
  169.         gfc->highpass_end_band = maxband;
  170.  
  171.         /* as the highpass may have changed above
  172.          * calculate the amplification here again
  173.          */
  174.         for (band = minband; band <= maxband; band++) {
  175.             freq = band / 31.0;
  176.             gfc->amp_highpass[band] =
  177.                 cos((PI / 2) * (gfc->highpass2 - freq) /
  178.                     (gfc->highpass2 - gfc->highpass1));
  179.         }
  180.     } else {
  181.         gfc->highpass_start_band = 0;
  182.         gfc->highpass_end_band = -1;/* do not to run into for-loops */
  183.     }
  184.     /*
  185.     DEBUGF("lowpass band with amp=0:  %i \n",gfc->lowpass_band);
  186.     DEBUGF("highpass band with amp=0:  %i \n",gfc->highpass_band);
  187.     DEBUGF("lowpass band start:  %i \n",gfc->lowpass_start_band);
  188.     DEBUGF("lowpass band end:    %i \n",gfc->lowpass_end_band);
  189.     DEBUGF("highpass band start:  %i \n",gfc->highpass_start_band);
  190.     DEBUGF("highpass band end:    %i \n",gfc->highpass_end_band);
  191.     */
  192. }
  193.  
  194. /********************************************************************
  195.  *   initialize internal params based on data in gf
  196.  *   (globalflags struct filled in by calling program)
  197.  *
  198.  ********************************************************************/
  199. int lame_init_params(lame_global_flags *gfp)
  200. {
  201.   int i;
  202.   lame_internal_flags *gfc=gfp->internal_flags;
  203.   gfc->lame_init_params_init=1;
  204.  
  205.   gfp->frameNum=0;
  206.   if (gfp->num_channels==1) {
  207.     gfp->mode = MPG_MD_MONO;
  208.   }
  209.   gfc->stereo=2;
  210.   if (gfp->mode == MPG_MD_MONO) gfc->stereo=1;
  211.  
  212.   if (gfp->silent) {
  213.    gfp->brhist_disp=0;  /* turn of VBR historgram */
  214.   }
  215.   if (gfp->VBR==vbr_off) {
  216.     gfp->brhist_disp=0;  /* turn of VBR historgram */
  217.   }
  218.   if (gfp->VBR!=vbr_off) {
  219.     gfp->free_format=0;  /* VBR cant mix with free format */
  220.   }
  221.  
  222.   if (gfp->VBR==vbr_off && gfp->brate==0) {
  223.     /* no bitrate or compression ratio specified, use 11 */
  224.     if (gfp->compression_ratio==0) gfp->compression_ratio=11;
  225.   }
  226.  
  227.  
  228.   /* find bitrate if user specify a compression ratio */
  229.   if (gfp->VBR==vbr_off && gfp->compression_ratio > 0) {
  230.     
  231.     if (gfp->out_samplerate==0) 
  232.       gfp->out_samplerate=validSamplerate(gfp->in_samplerate);   
  233.     
  234.     /* choose a bitrate for the output samplerate which achieves
  235.      * specifed compression ratio 
  236.      */
  237.     gfp->brate = 
  238.       gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->compression_ratio);
  239.  
  240.     /* we need the version for the bitrate table look up */
  241.     gfc->samplerate_index = SmpFrqIndex((long)gfp->out_samplerate, &gfp->version);
  242.     /* find the nearest allowed bitrate */
  243.     if (!gfp->free_format)
  244.       gfp->brate = FindNearestBitrate(gfp->brate,gfp->version,gfp->out_samplerate);
  245.   }
  246.   if (gfp->brate >= 320) gfp->VBR=vbr_off;  /* dont bother with VBR at 320kbs */
  247.  
  248.  
  249.  
  250.   /* set the output sampling rate, and resample options if necessary
  251.      samplerate = input sample rate
  252.      resamplerate = ouput sample rate
  253.   */
  254.   if (gfp->out_samplerate==0) {
  255.     /* user did not specify output sample rate */
  256.     gfp->out_samplerate=gfp->in_samplerate;   /* default */
  257.  
  258.  
  259.     /* if resamplerate is not valid, find a valid value */
  260.     gfp->out_samplerate = validSamplerate(gfp->out_samplerate);
  261.  
  262.     if (gfp->VBR==vbr_off && gfp->brate>0) {
  263.       /* check if user specified bitrate requires downsampling */
  264.       gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->brate);
  265.       if (gfp->compression_ratio > 13 ) {
  266.     /* automatic downsample, if possible */
  267.     gfp->out_samplerate = validSamplerate((10*1000L*gfp->brate)/(16*gfc->stereo));
  268.       }
  269.     }
  270.     if (gfp->VBR==vbr_abr) {
  271.       /* check if user specified bitrate requires downsampling */
  272.       gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->VBR_mean_bitrate_kbps);
  273.       if (gfp->compression_ratio > 13 ) {
  274.     /* automatic downsample, if possible */
  275.     gfp->out_samplerate = validSamplerate((10*1000L*gfp->VBR_mean_bitrate_kbps)/(16*gfc->stereo));
  276.       }
  277.     }
  278.   }
  279.  
  280.   gfc->mode_gr = (gfp->out_samplerate <= 24000) ? 1 : 2;  /* mode_gr = 2 */
  281.   gfp->encoder_delay = ENCDELAY;
  282.   gfp->framesize = gfc->mode_gr*576;
  283.   if (gfp->ogg) gfp->framesize = 1024;
  284.  
  285.  
  286.   gfc->resample_ratio=1;
  287.   if (gfp->out_samplerate != gfp->in_samplerate) 
  288.         gfc->resample_ratio = (FLOAT)gfp->in_samplerate/(FLOAT)gfp->out_samplerate;
  289.  
  290.   /* estimate total frames.  must be done after setting sampling rate so
  291.    * we know the framesize.  */
  292.   gfp->totalframes=0;
  293.   gfp->totalframes = 2+ gfp->num_samples/(gfc->resample_ratio*gfp->framesize);
  294.  
  295.  
  296.  
  297.   /* 44.1kHz at 56kbs/channel: compression factor of 12.6
  298.      44.1kHz at 64kbs/channel: compression factor of 11.025
  299.      44.1kHz at 80kbs/channel: compression factor of 8.82
  300.      22.05kHz at 24kbs:  14.7
  301.      22.05kHz at 32kbs:  11.025
  302.      22.05kHz at 40kbs:  8.82
  303.      16kHz at 16kbs:  16.0
  304.      16kHz at 24kbs:  10.7
  305.  
  306.      compression_ratio
  307.         11                                .70?
  308.         12                   sox resample .66
  309.         14.7                 sox resample .45
  310.  
  311.   */
  312.  
  313.   /* for VBR, take a guess at the compression_ratio. for example: */
  314.   /* VBR_q           compression       like
  315.                       4.4             320kbs/41khz
  316.      0-1              5.5             256kbs/41khz
  317.      2                7.3             192kbs/41khz
  318.      4                8.8             160kbs/41khz
  319.      6                11              128kbs/41khz
  320.      9                14.7             96kbs
  321.      for lower bitrates, downsample with --resample
  322.   */
  323.   if (gfp->VBR==vbr_mt || gfp->VBR==vbr_rh) {
  324.     gfp->compression_ratio = 5.0 + gfp->VBR_q;
  325.   }else
  326.   if (gfp->VBR==vbr_abr) {
  327.     gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->VBR_mean_bitrate_kbps);
  328.   }else{
  329.     gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->brate);
  330.   }
  331.  
  332.  
  333.  
  334.   /* At higher quality (lower compression) use STEREO instead of JSTEREO.
  335.    * (unless the user explicitly specified a mode ) */
  336.   if ( (!gfp->mode_fixed) && (gfp->mode !=MPG_MD_MONO)) {
  337.     if (gfp->compression_ratio < 9 ) {
  338.       gfp->mode = MPG_MD_STEREO;
  339.     }
  340.   }
  341.  
  342.  
  343.   /****************************************************************/
  344.   /* if a filter has not been enabled, see if we should add one: */
  345.   /****************************************************************/
  346.   if (gfp->lowpassfreq == 0) {
  347.     /* If the user has not selected their own filter, add a lowpass
  348.      * filter based on the compression ratio.  Formula based on
  349.           44.1   /160    4.4x
  350.           44.1   /128    5.5x      keep all bands
  351.           44.1   /96kbs  7.3x      keep band 28
  352.           44.1   /80kbs  8.8x      keep band 25
  353.           44.1khz/64kbs  11x       keep band 21  22?
  354.  
  355.       16khz/24kbs  10.7x       keep band 21
  356.       22kHz/32kbs  11x         keep band ?
  357.       22kHz/24kbs  14.7x       keep band 16
  358.           16    16     16x         keep band 14
  359.     */
  360.  
  361.  
  362.     /* Should we use some lowpass filters? */
  363.     int band = 1+floor(.5 + 14-18*log(gfp->compression_ratio/16.0));
  364.     if (gfc->resample_ratio != 1) {
  365.       /* resampling.  if we are resampling, add lowpass at least 90% */
  366.       band = Min(band,29);
  367.     }
  368.  
  369.     if (band < 31) {
  370.       gfc->lowpass1 = band/31.0;
  371.       gfc->lowpass2 = band/31.0;
  372.     }
  373.   }
  374.  
  375.   /****************************************************************/
  376.   /* apply user driven filters*/
  377.   /****************************************************************/
  378.   if ( gfp->highpassfreq > 0 ) {
  379.     gfc->highpass1 = 2.0*gfp->highpassfreq/gfp->out_samplerate; /* will always be >=0 */
  380.     if ( gfp->highpasswidth >= 0 ) {
  381.       gfc->highpass2 = 2.0*(gfp->highpassfreq+gfp->highpasswidth)/gfp->out_samplerate;
  382.     } else {
  383.       /* 15% above on default */
  384.       /* gfc->highpass2 = 1.15*2.0*gfp->highpassfreq/gfp->out_samplerate;  */
  385.       gfc->highpass2 = 1.00*2.0*gfp->highpassfreq/gfp->out_samplerate; 
  386.     }
  387.   }
  388.  
  389.   if ( gfp->lowpassfreq > 0 ) {
  390.     gfc->lowpass2 = 2.0*gfp->lowpassfreq/gfp->out_samplerate; /* will always be >=0 */
  391.     if ( gfp->lowpasswidth >= 0 ) {
  392.       gfc->lowpass1 = 2.0*(gfp->lowpassfreq-gfp->lowpasswidth)/gfp->out_samplerate;
  393.       if ( gfc->lowpass1 < 0 ) { /* has to be >= 0 */
  394.     gfc->lowpass1 = 0;
  395.       }
  396.     } else {
  397.       /* 15% below on default */
  398.       /* gfc->lowpass1 = 0.85*2.0*gfp->lowpassfreq/gfp->out_samplerate;  */
  399.       gfc->lowpass1 = 1.00*2.0*gfp->lowpassfreq/gfp->out_samplerate;
  400.     }
  401.   }
  402.  
  403.  
  404.   /***************************************************************/
  405.   /* compute info needed for polyphase filter (filter type==0, default)   */
  406.   /***************************************************************/
  407.   lame_init_params_ppflt(gfc);
  408.  
  409.  
  410.   /***************************************************************/
  411.   /* compute info needed for FIR filter (filter_type==1) */
  412.   /***************************************************************/
  413.   /* not yet coded */
  414.  
  415.   gfc->mode_ext=MPG_MD_LR_LR;
  416.   gfc->stereo = (gfp->mode == MPG_MD_MONO) ? 1 : 2;
  417.  
  418.   gfc->samplerate_index = SmpFrqIndex((long)gfp->out_samplerate, &gfp->version);
  419.   if( gfc->samplerate_index < 0) {
  420.     display_bitrates(stderr);
  421.     return -1;
  422.   }
  423.   if (gfp->free_format) {
  424.     gfc->bitrate_index=0;
  425.   }else{
  426.     if( (gfc->bitrate_index = BitrateIndex(gfp->brate, gfp->version,gfp->out_samplerate)) < 0) {
  427.       display_bitrates(stderr);
  428.       return -1;
  429.     }
  430.   }
  431.  
  432.  
  433.   /* choose a min/max bitrate for VBR */
  434.   if (gfp->VBR!=vbr_off) {
  435.     /* if the user didn't specify VBR_max_bitrate: */
  436.     if (0==gfp->VBR_max_bitrate_kbps) {
  437.       gfc->VBR_max_bitrate=14;   /* default: allow 320kbs */
  438.     }else{
  439.       if( (gfc->VBR_max_bitrate  = BitrateIndex(gfp->VBR_max_bitrate_kbps, gfp->version,gfp->out_samplerate)) < 0) {
  440.     display_bitrates(stderr);
  441.     return -1;
  442.       }
  443.     }
  444.     if (0==gfp->VBR_min_bitrate_kbps) {
  445.       gfc->VBR_min_bitrate=1;  /* 32 kbps */
  446.     }else{
  447.       if( (gfc->VBR_min_bitrate  = BitrateIndex(gfp->VBR_min_bitrate_kbps, gfp->version,gfp->out_samplerate)) < 0) {
  448.     display_bitrates(stderr);
  449.     return -1;
  450.       }
  451.     }
  452.     gfp->VBR_mean_bitrate_kbps = Min(bitrate_table[gfp->version][gfc->VBR_max_bitrate]*.95,gfp->VBR_mean_bitrate_kbps);
  453.     gfp->VBR_mean_bitrate_kbps = Max(bitrate_table[gfp->version][gfc->VBR_min_bitrate]*.95,gfp->VBR_mean_bitrate_kbps);
  454.     
  455.     /* Note: ABR mode should normally be used without a -V n setting,
  456.      * (or with the default value of 4)
  457.      * but the code below allows us to test how adjusting the maskings
  458.      * effects CBR encodings.  Lowering the maskings will make LAME
  459.      * work harder to get over=0 and may give better noise shaping?
  460.      */
  461.     if (gfp->VBR == vbr_abr)
  462.     {
  463.       static const FLOAT8 dbQ[10]={-5.0,-3.75,-2.5,-1.25,0,0.4,0.8,1.2,1.6,2.0};
  464.       FLOAT8 masking_lower_db;
  465.       assert( gfp->VBR_q <= 9 );
  466.       assert( gfp->VBR_q >= 0 );
  467.       masking_lower_db = dbQ[gfp->VBR_q];
  468.       gfc->masking_lower = pow(10.0,masking_lower_db/10);
  469.       gfc->ATH_vbrlower = (4-gfp->VBR_q)*4.0; 
  470.     }
  471.     
  472.     if (gfp->VBR == vbr_rh)
  473.     {
  474.       gfc->ATH_vbrlower = (4-gfp->VBR_q)*4.0;     
  475.     }
  476.  
  477.  
  478.  
  479.   }
  480.  
  481.   /* VBR needs at least the output of GPSYCHO,
  482.    * so we have to garantee that by setting a minimum 
  483.    * quality level, actually level 5 does it.
  484.    * the -v and -V x settings switch the quality to level 2
  485.    * you would have to add a -q 5 to reduce the quality
  486.    * down to level 5
  487.    */
  488.   if (gfp->VBR!=vbr_off) gfp->quality=Min(gfp->quality,5);
  489.   /* dont allow forced mid/side stereo for mono output */
  490.   if (gfp->mode == MPG_MD_MONO) gfp->force_ms=0;
  491.  
  492.  
  493.   /* Do not write VBR tag if VBR flag is not specified */
  494.   if (gfp->VBR==vbr_off) gfp->bWriteVbrTag=0;
  495.   if (gfp->ogg) gfp->bWriteVbrTag=0;
  496.   if (gfp->gtkflag) gfp->bWriteVbrTag=0;
  497.  
  498.   /* some file options not allowed if output is: not specified or stdout */
  499.  
  500.   if (gfp->outPath!=NULL && gfp->outPath[0]=='-' ) {
  501.     gfp->bWriteVbrTag=0; /* turn off VBR tag */
  502.   }
  503.  
  504.   if (gfp->outPath==NULL || gfp->outPath[0]=='-' ) {
  505.     gfp->id3v1_enabled=0;       /* turn off ID3 version 1 tagging */
  506.   }
  507.  
  508.  
  509.  
  510.   if (gfc->pinfo != NULL) {
  511.     gfp->bWriteVbrTag=0;  /* disable Xing VBR tag */
  512.   }
  513.  
  514.   init_bit_stream_w(gfc);
  515.  
  516.  
  517.   /* set internal feature flags.  USER should not access these since
  518.    * some combinations will produce strange results */
  519.  
  520.   /* no psymodel, no noise shaping */
  521.   if (gfp->quality==9) {
  522.     gfc->filter_type=0;
  523.     gfc->psymodel=0;
  524.     gfc->quantization=0;
  525.     gfc->noise_shaping=0;
  526.     gfc->noise_shaping_stop=0;
  527.     gfc->use_best_huffman=0;
  528.   }
  529.  
  530.   if (gfp->quality==8) gfp->quality=7;
  531.  
  532.   /* use psymodel (for short block and m/s switching), but no noise shapping */
  533.   if (gfp->quality==7) {
  534.     gfc->filter_type=0;
  535.     gfc->psymodel=1;
  536.     gfc->quantization=0;
  537.     gfc->noise_shaping=0;
  538.     gfc->noise_shaping_stop=0;
  539.     gfc->use_best_huffman=0;
  540.   }
  541.  
  542.   if (gfp->quality==6) gfp->quality=5;
  543.  
  544.   if (gfp->quality==5) {
  545.     /* the default */
  546.     gfc->filter_type=0;
  547.     gfc->psymodel=1;
  548.     gfc->quantization=0;
  549.     gfc->noise_shaping=1;
  550.     gfc->noise_shaping_stop=0;
  551.     gfc->use_best_huffman=0;
  552.   }
  553.  
  554.   if (gfp->quality==4) gfp->quality=3;
  555.  
  556.   if (gfp->quality==3) {
  557.     gfc->filter_type=0;
  558.     gfc->psymodel=1;
  559.     gfc->quantization=1;
  560.     gfc->noise_shaping=1;
  561.     gfc->noise_shaping_stop=0;
  562.     gfc->use_best_huffman=1;
  563.   }
  564.  
  565.   if (gfp->quality==2) {
  566.     gfc->filter_type=0;
  567.     gfc->psymodel=1;
  568.     gfc->quantization=1;
  569.     gfc->noise_shaping=1;
  570.     gfc->noise_shaping_stop=0;
  571.     gfc->use_best_huffman=1;
  572.   }
  573.  
  574.   if (gfp->quality==1) {
  575.     gfc->filter_type=0;
  576.     gfc->psymodel=1;
  577.     gfc->quantization=1;
  578.     gfc->noise_shaping=2;
  579.     gfc->noise_shaping_stop=0;
  580.     gfc->use_best_huffman=1;
  581.   }
  582.  
  583.   if (gfp->quality==0) {
  584.     /* 0..1 quality */
  585.     gfc->filter_type=1;         /* not yet coded */
  586.     gfc->psymodel=1;
  587.     gfc->quantization=1;
  588.     gfc->noise_shaping=3;       /* not yet coded */
  589.     gfc->noise_shaping_stop=2;  /* not yet coded */
  590.     gfc->use_best_huffman=2;   /* not yet coded */
  591.     return -1;
  592.   }
  593.  
  594.  
  595.   for (i = 0; i < SBMAX_l + 1; i++) {
  596.     gfc->scalefac_band.l[i] =
  597.       sfBandIndex[gfc->samplerate_index + (gfp->version * 3) + 
  598.              6*(gfp->out_samplerate<16000)].l[i];
  599.   }
  600.   for (i = 0; i < SBMAX_s + 1; i++) {
  601.     gfc->scalefac_band.s[i] =
  602.       sfBandIndex[gfc->samplerate_index + (gfp->version * 3) + 
  603.              6*(gfp->out_samplerate<16000)].s[i];
  604.   }
  605.  
  606.  
  607.   /* determine the mean bitrate for main data */
  608.   gfc->sideinfo_len = 4;
  609.   if ( gfp->version == 1 )
  610.     {   /* MPEG 1 */
  611.       if ( gfc->stereo == 1 )
  612.     gfc->sideinfo_len += 17;
  613.       else
  614.     gfc->sideinfo_len += 32;
  615.     }
  616.   else
  617.     {   /* MPEG 2 */
  618.       if ( gfc->stereo == 1 )
  619.     gfc->sideinfo_len += 9;
  620.       else
  621.     gfc->sideinfo_len += 17;
  622.     }
  623.   
  624.   if (gfp->error_protection) gfc->sideinfo_len += 2;
  625.   
  626.  
  627.   if (gfp->bWriteVbrTag)
  628.     {
  629.       /* Write initial VBR Header to bitstream */
  630.       InitVbrTag(gfp);
  631.     }
  632.  
  633.   if (gfp->brhist_disp)
  634.     brhist_init(gfp,1,14);
  635.  
  636. #ifdef HAVEVORBIS
  637.   if (gfp->ogg) {
  638.     lame_encode_ogg_init(gfp);
  639.     gfc->filter_type = -1;   /* vorbis claims not to need filters */
  640.     gfp->VBR=vbr_off;            /* ignore lame's various VBR modes */
  641.   }
  642. #endif
  643.  
  644.   return 0;
  645. }
  646.  
  647.  
  648.  
  649.  
  650.  
  651.  
  652.  
  653.  
  654.  
  655. /************************************************************************
  656.  *
  657.  * print_config
  658.  *
  659.  * PURPOSE:  Prints the encoding parameters used
  660.  *
  661.  ************************************************************************/
  662. void lame_print_config(lame_global_flags *gfp)
  663. {
  664.   lame_internal_flags *gfc=gfp->internal_flags;
  665.  
  666.   static const char *mode_names[4] = { "stereo", "j-stereo", "dual-ch", "single-ch" };
  667.   FLOAT out_samplerate=gfp->out_samplerate/1000.0;
  668.   FLOAT in_samplerate = gfc->resample_ratio*out_samplerate;
  669.  
  670.   lame_print_version(stderr);
  671.   if (gfp->num_channels==2 && gfc->stereo==1) {
  672.     MSGF("Autoconverting from stereo to mono. Setting encoding to mono mode.\n");
  673.   }
  674.   if (gfc->resample_ratio!=1) {
  675.     MSGF("Resampling:  input=%.1fkHz  output=%.1fkHz\n",
  676.         in_samplerate,out_samplerate);
  677.   }
  678.   if (gfc->filter_type==0) {
  679.   if (gfc->highpass2>0.0)
  680.     MSGF("Using polyphase highpass filter, transition band: %.0f Hz -  %.0f Hz\n",
  681.         gfc->highpass1*out_samplerate*500,
  682.         gfc->highpass2*out_samplerate*500);
  683.   if (gfc->lowpass1>0.0)
  684.     MSGF("Using polyphase lowpass filter,  transition band:  %.0f Hz - %.0f Hz\n",
  685.         gfc->lowpass1*out_samplerate*500,
  686.         gfc->lowpass2*out_samplerate*500);
  687.   }
  688. #ifdef RH_NOISE_CALC
  689.   if (gfp->experimentalY) {
  690.     MSGF("careful noise shaping, only maximum distorted band at once\n");
  691.   }
  692. #endif
  693.  
  694.   if (gfp->gtkflag) {
  695.     MSGF("Analyzing %s \n",gfp->inPath);
  696.   }
  697.   else {
  698.     MSGF("Encoding %s to %s\n",
  699.         (strcmp(gfp->inPath, "-")? gfp->inPath : "stdin"),
  700.         (strcmp(gfp->outPath, "-")? gfp->outPath : "stdout"));
  701.     if (gfp->ogg) {
  702.       MSGF("Encoding as %.1f kHz VBR Ogg Vorbis \n",
  703.           gfp->out_samplerate/1000.0);
  704.     }else
  705.     if (gfp->VBR==vbr_mt || gfp->VBR==vbr_rh)
  706.       MSGF("Encoding as %.1f kHz VBR(q=%i) %s MPEG%i LayerIII (%4.1fx estimated) qval=%i\n",
  707.           gfp->out_samplerate/1000.0,
  708.           gfp->VBR_q,mode_names[gfp->mode],2-gfp->version,gfp->compression_ratio,gfp->quality);
  709.     else
  710.     if (gfp->VBR==vbr_abr)
  711.       MSGF("Encoding as %.1f kHz average %d kbps %s MPEG%i LayerIII (%4.1fx) qval=%i\n",
  712.           gfp->out_samplerate/1000.0,
  713.           gfp->VBR_mean_bitrate_kbps,mode_names[gfp->mode],2-gfp->version,gfp->compression_ratio,gfp->quality);
  714.     else {
  715.       MSGF("Encoding as %.1f kHz %d kbps %s MPEG%i LayerIII (%4.1fx)  qval=%i\n",
  716.           gfp->out_samplerate/1000.0,gfp->brate,
  717.           mode_names[gfp->mode],2-gfp->version,gfp->compression_ratio,gfp->quality);
  718.     }
  719.   }
  720.   if (gfp->free_format) {
  721.     MSGF("Warning: many decoders cannot handle free format bitstreams\n");
  722.     if (gfp->brate>320) {
  723.       MSGF("Warning: many decoders cannot handle free format bitrates > 320kbs\n");
  724.     }
  725.   }
  726.  
  727.   fflush(stderr);
  728. }
  729.  
  730.  
  731.  
  732. /*****************************************************************/
  733. /* write ID3 version 2 tag to output file, if asked for          */
  734. /*****************************************************************/
  735. void lame_id3v2_tag(lame_global_flags *gfp,FILE *outf)
  736. {
  737.   /*
  738.    * NOTE: "lame_id3v2_tag" is obviously just a wrapper to call the function
  739.    * below and have a nice "lame_"-prefixed function name in "lame.h".
  740.    * -- gramps
  741.    */
  742. #ifdef HAVEVORBIS
  743.   /* no ID3 version 2 tags in Ogg Vorbis output */
  744.   if (!gfp->ogg) {
  745. #endif
  746.     id3tag_write_v2(&gfp->tag_spec,outf);
  747. #ifdef HAVEVORBIS
  748.   }
  749. #endif
  750. }
  751.  
  752.  
  753.  
  754.  
  755.  
  756.  
  757.  
  758.  
  759.  
  760.  
  761.  
  762.  
  763. /************************************************************************
  764. *
  765. * encodeframe()           Layer 3
  766. *
  767. * encode a single frame
  768. *
  769. ************************************************************************
  770. lame_encode_frame()
  771.  
  772.  
  773.                        gr 0            gr 1
  774. inbuf:           |--------------|---------------|-------------|
  775. MDCT output:  |--------------|---------------|-------------|
  776.  
  777. FFT's                    <---------1024---------->
  778.                                          <---------1024-------->
  779.  
  780.  
  781.  
  782.     inbuf = buffer of PCM data size=MP3 framesize
  783.     encoder acts on inbuf[ch][0], but output is delayed by MDCTDELAY
  784.     so the MDCT coefficints are from inbuf[ch][-MDCTDELAY]
  785.  
  786.     psy-model FFT has a 1 granule day, so we feed it data for the next granule.
  787.     FFT is centered over granule:  224+576+224
  788.     So FFT starts at:   576-224-MDCTDELAY
  789.  
  790.     MPEG2:  FFT ends at:  BLKSIZE+576-224-MDCTDELAY
  791.     MPEG1:  FFT ends at:  BLKSIZE+2*576-224-MDCTDELAY    (1904)
  792.  
  793.     FFT starts at 576-224-MDCTDELAY (304)  = 576-FFTOFFSET
  794.  
  795. */
  796.  
  797. int lame_encode_mp3_frame(lame_global_flags *gfp,
  798. short int inbuf_l[],short int inbuf_r[],
  799. char *mp3buf, int mp3buf_size)
  800. {
  801. #ifdef macintosh /* PLL 14/04/2000 */
  802.   static FLOAT8 xr[2][2][576];
  803.   static int l3_enc[2][2][576];
  804. #else
  805.   FLOAT8 xr[2][2][576];
  806.   int l3_enc[2][2][576];
  807. #endif
  808.   int mp3count;
  809.   III_psy_ratio masking_ratio[2][2];    /*LR ratios */
  810.   III_psy_ratio masking_MS_ratio[2][2]; /*MS ratios */
  811.   III_psy_ratio (*masking)[2][2];  /*LR ratios and MS ratios*/
  812.   III_scalefac_t scalefac[2][2];
  813.   short int *inbuf[2];
  814.   lame_internal_flags *gfc=gfp->internal_flags;
  815.  
  816.  
  817.   typedef FLOAT8 pedata[2][2];
  818.   pedata pe,pe_MS;
  819.   pedata *pe_use;
  820.  
  821.   int ch,gr,mean_bits;
  822.   int bitsPerFrame;
  823.  
  824.   int check_ms_stereo;
  825.   FLOAT8 ms_ratio_next=0;
  826.   FLOAT8 ms_ratio_prev=0;
  827.  
  828.   memset((char *) masking_ratio, 0, sizeof(masking_ratio));
  829.   memset((char *) masking_MS_ratio, 0, sizeof(masking_MS_ratio));
  830.   memset((char *) scalefac, 0, sizeof(scalefac));
  831.   inbuf[0]=inbuf_l;
  832.   inbuf[1]=inbuf_r;
  833.     
  834.   gfc->mode_ext = MPG_MD_LR_LR;
  835.  
  836.   if (gfc->lame_encode_frame_init==0 )  {
  837. #if 0
  838.     /* Figure average number of 'slots' per frame. */
  839.     FLOAT8 avg_slots_per_frame;
  840.     FLOAT8 sampfreq =   gfp->out_samplerate/1000.0;
  841.     int bit_rate = gfp->brate;
  842.  
  843.     avg_slots_per_frame = (bit_rate*gfp->framesize) /
  844.       (sampfreq* 8);
  845.     /* -f fast-math option causes some strange rounding here, be carefull: */
  846.     gfc->frac_SpF  = avg_slots_per_frame - floor(avg_slots_per_frame + 1e-9);
  847.     if (fabs(gfc->frac_SpF) < 1e-9) gfc->frac_SpF = 0;
  848.     gfc->slot_lag  = -gfc->frac_SpF;
  849.     gfc->padding = 1;
  850.     if (gfc->frac_SpF==0) gfc->padding = 0;
  851. #else
  852.     /* padding method as described in 
  853.      * "MPEG-Layer3 / Bitstream Syntax and Decoding"
  854.      * by Martin Sieler, Ralph Sperschneider
  855.      *
  856.      * note: there is no padding for the very first frame
  857.      *
  858.      * Robert.Hegemann@gmx.de 2000-06-22
  859.      */
  860.         
  861.     gfc->difference = ((gfp->version+1)*72000L*gfp->brate) % gfp->out_samplerate;
  862.     gfc->remainder  = gfc->difference;
  863. #endif    
  864.     
  865.     gfc->lame_encode_frame_init=1;
  866.     
  867.     /* check FFT will not use a negative starting offset */
  868.     assert(576>=FFTOFFSET);
  869.     /* check if we have enough data for FFT */
  870.     assert(gfc->mf_size>=(BLKSIZE+gfp->framesize-FFTOFFSET));
  871.     /* check if we have enough data for polyphase filterbank */
  872.     /* it needs 1152 samples + 286 samples ignored for one granule */
  873.     /*          1152+576+286 samples for two granules */
  874.     assert(gfc->mf_size>=(286+576*(1+gfc->mode_gr)));
  875.  
  876.     /* prime the MDCT/polyphase filterbank with a short block */
  877.     { 
  878.       int i,j;
  879.       short primebuff0[286+1152+576];
  880.       short primebuff1[286+1152+576];
  881.       for (i=0, j=0; i<286+576*(1+gfc->mode_gr); ++i) {
  882.     if (i<576*gfc->mode_gr) {
  883.       primebuff0[i]=0;
  884.       if (gfc->stereo) 
  885.         primebuff1[i]=0;
  886.     }else{
  887.       primebuff0[i]=inbuf[0][j];
  888.       if (gfc->stereo) 
  889.         primebuff1[i]=inbuf[1][j];
  890.       ++j;
  891.     }
  892.       }
  893.       /* polyphase filtering / mdct */
  894.       for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
  895.     for ( ch = 0; ch < gfc->stereo; ch++ ) {
  896.       gfc->l3_side.gr[gr].ch[ch].tt.block_type=SHORT_TYPE;
  897.     }
  898.       }
  899.       mdct_sub48(gfp,primebuff0, primebuff1, xr, &gfc->l3_side);
  900.     }
  901.   }
  902.  
  903.  
  904.   /********************** padding *****************************/
  905.   switch (gfp->padding_type) {
  906.   case 0:
  907.     gfc->padding=0;
  908.     break;
  909.   case 1:
  910.     gfc->padding=1;
  911.     break;
  912.   case 2:
  913.   default:
  914.     if (gfp->VBR!=vbr_off) {
  915.       gfc->padding=0;
  916.     } else {
  917.       if (gfp->disable_reservoir) {
  918.     gfc->padding = 0;
  919.     /* if the user specified --nores, dont very gfc->padding either */
  920.     /* tiny changes in frac_SpF rounding will cause file differences */
  921.       }else{
  922. #if 0
  923.     if (gfc->frac_SpF != 0) {
  924.       if (gfc->slot_lag > (gfc->frac_SpF-1.0) ) {
  925.         gfc->slot_lag -= gfc->frac_SpF;
  926.         gfc->padding = 0;
  927.         DEBUGF("%i padding = 0 \n",gfp->frameNum);
  928.  
  929.       }
  930.       else {
  931.         gfc->padding = 1;
  932.         gfc->slot_lag += (1-gfc->frac_SpF);
  933.       }
  934.     }
  935. #else
  936.         /* padding method as described in 
  937.          * "MPEG-Layer3 / Bitstream Syntax and Decoding"
  938.          * by Martin Sieler, Ralph Sperschneider
  939.          *
  940.          * note: there is no padding for the very first frame
  941.          *
  942.          * Robert.Hegemann@gmx.de 2000-06-22
  943.          */
  944.  
  945.         gfc->remainder -= gfc->difference;
  946.         if (gfc->remainder < 0)
  947.           {
  948.             gfc->remainder += gfp->out_samplerate;
  949.             gfc->padding = 1;
  950.           }
  951.         else
  952.           {
  953.             gfc->padding = 0;
  954.           }
  955. #endif
  956.       } /* reservoir enabled */
  957.     }
  958.   }
  959.  
  960.  
  961.   /********************** status display  *****************************/
  962.   if (!gfp->gtkflag && !gfp->silent) {
  963.     int mod = gfp->version == 0 ? 100 : 50;
  964.     if (gfp->frameNum%mod==0) {
  965.       timestatus(gfp->out_samplerate,gfp->frameNum,gfp->totalframes,gfp->framesize);
  966.  
  967.       if (gfp->brhist_disp)
  968.       brhist_disp(gfp->totalframes);
  969.  
  970.     }
  971.   }
  972.  
  973.   if (gfc->psymodel) {
  974.     /* psychoacoustic model
  975.      * psy model has a 1 granule (576) delay that we must compensate for
  976.      * (mt 6/99).
  977.      */
  978.     int ret;
  979.     short int *bufp[2];  /* address of beginning of left & right granule */
  980.     int blocktype[2];
  981.  
  982.     ms_ratio_prev=gfc->ms_ratio[gfc->mode_gr-1];
  983.     for (gr=0; gr < gfc->mode_gr ; gr++) {
  984.  
  985.       for ( ch = 0; ch < gfc->stereo; ch++ )
  986.     bufp[ch] = &inbuf[ch][576 + gr*576-FFTOFFSET];
  987.  
  988.       ret=L3psycho_anal( gfp,bufp, gr, 
  989.              &gfc->ms_ratio[gr],&ms_ratio_next,&gfc->ms_ener_ratio[gr],
  990.              masking_ratio, masking_MS_ratio,
  991.              pe[gr],pe_MS[gr],blocktype);
  992.       if (ret!=0) return -4;
  993.  
  994.       for ( ch = 0; ch < gfc->stereo; ch++ )
  995.     gfc->l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
  996.  
  997.     }
  998.   }else{
  999.     for (gr=0; gr < gfc->mode_gr ; gr++)
  1000.       for ( ch = 0; ch < gfc->stereo; ch++ ) {
  1001.     gfc->l3_side.gr[gr].ch[ch].tt.block_type=NORM_TYPE;
  1002.     pe[gr][ch]=700;
  1003.       }
  1004.   }
  1005.  
  1006.  
  1007.   /* block type flags */
  1008.   for( gr = 0; gr < gfc->mode_gr; gr++ ) {
  1009.     for ( ch = 0; ch < gfc->stereo; ch++ ) {
  1010.       gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
  1011.       cod_info->mixed_block_flag = 0;     /* never used by this model */
  1012.       if (cod_info->block_type == NORM_TYPE )
  1013.     cod_info->window_switching_flag = 0;
  1014.       else
  1015.     cod_info->window_switching_flag = 1;
  1016.     }
  1017.   }
  1018.  
  1019.  
  1020.   /* polyphase filtering / mdct */
  1021.   mdct_sub48(gfp,inbuf[0], inbuf[1], xr, &gfc->l3_side);
  1022.   /* re-order the short blocks, for more efficient encoding below */
  1023.   for (gr = 0; gr < gfc->mode_gr; gr++) {
  1024.     for (ch = 0; ch < gfc->stereo; ch++) {
  1025.       gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
  1026.       if (cod_info->block_type==SHORT_TYPE) {
  1027.     freorder(gfc->scalefac_band.s,xr[gr][ch]);
  1028.       }
  1029.     }
  1030.   }
  1031.   
  1032.  
  1033.  
  1034.  
  1035.  
  1036.   /* use m/s gfc->stereo? */
  1037.   check_ms_stereo =  (gfp->mode == MPG_MD_JOINT_STEREO);
  1038.   if (check_ms_stereo) {
  1039.     /* make sure block type is the same in each channel */
  1040.     check_ms_stereo =
  1041.       (gfc->l3_side.gr[0].ch[0].tt.block_type==gfc->l3_side.gr[0].ch[1].tt.block_type) &&
  1042.       (gfc->l3_side.gr[1].ch[0].tt.block_type==gfc->l3_side.gr[1].ch[1].tt.block_type);
  1043.   }
  1044.   if (check_ms_stereo) {
  1045.     /* ms_ratio = is like the ratio of side_energy/total_energy */
  1046.     FLOAT8 ms_ratio_ave;
  1047.     /*     ms_ratio_ave = .5*(ms_ratio[0] + ms_ratio[1]);*/
  1048.     ms_ratio_ave = .25*(gfc->ms_ratio[0] + gfc->ms_ratio[1]+
  1049.              ms_ratio_prev + ms_ratio_next);
  1050.     if ( (ms_ratio_ave <.35) && (.5*(gfc->ms_ratio[0]+gfc->ms_ratio[1])<.45) )
  1051.          gfc->mode_ext = MPG_MD_MS_LR;
  1052.   }
  1053.   if (gfp->force_ms) gfc->mode_ext = MPG_MD_MS_LR;
  1054.  
  1055.  
  1056.  
  1057.   if (gfp->gtkflag && gfc->pinfo != NULL) {
  1058.     for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
  1059.       for ( ch = 0; ch < gfc->stereo; ch++ ) {
  1060.     gfc->pinfo->ms_ratio[gr]=gfc->ms_ratio[gr];
  1061.     gfc->pinfo->ms_ener_ratio[gr]=gfc->ms_ener_ratio[gr];
  1062.     gfc->pinfo->blocktype[gr][ch]=
  1063.       gfc->l3_side.gr[gr].ch[ch].tt.block_type;
  1064.     memcpy(gfc->pinfo->xr[gr][ch],xr[gr][ch],sizeof(xr[gr][ch]));
  1065.     /* if MS stereo, switch to MS psy data */
  1066.     if (gfc->mode_ext==MPG_MD_MS_LR) {
  1067.       gfc->pinfo->pe[gr][ch]=gfc->pinfo->pe[gr][ch+2];
  1068.       gfc->pinfo->ers[gr][ch]=gfc->pinfo->ers[gr][ch+2];
  1069.       memcpy(gfc->pinfo->energy[gr][ch],gfc->pinfo->energy[gr][ch+2],
  1070.          sizeof(gfc->pinfo->energy[gr][ch]));
  1071.     }
  1072.       }
  1073.     }
  1074.   }
  1075.  
  1076.  
  1077.  
  1078.  
  1079.   /* bit and noise allocation */
  1080.   if (MPG_MD_MS_LR == gfc->mode_ext) {
  1081.     masking = &masking_MS_ratio;    /* use MS masking */
  1082.     pe_use = &pe_MS;
  1083.   } else {
  1084.     masking = &masking_ratio;    /* use LR masking */
  1085.     pe_use = &pe;
  1086.   }
  1087.  
  1088.  
  1089.   switch (gfp->VBR){ 
  1090.   default:
  1091.   case vbr_off:
  1092.     iteration_loop( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1093.     break;
  1094.   case vbr_mt:
  1095.     VBR_quantize( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1096.     break;
  1097.   case vbr_rh:
  1098.     VBR_iteration_loop( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1099.     break;
  1100.   case vbr_abr:
  1101.     ABR_iteration_loop( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1102.     break;
  1103.   }
  1104.  
  1105.   /* update VBR histogram data */
  1106.   brhist_add_count(gfc->bitrate_index);
  1107.  
  1108.   /*  write the frame to the bitstream  */
  1109.   getframebits(gfp,&bitsPerFrame,&mean_bits);
  1110.  
  1111.   format_bitstream( gfp, bitsPerFrame, l3_enc, scalefac);
  1112.  
  1113.   /* copy mp3 bit buffer into array */
  1114.   mp3count = copy_buffer(mp3buf,mp3buf_size,&gfc->bs);
  1115.  
  1116.   if (gfp->bWriteVbrTag) AddVbrFrame(gfp);
  1117.  
  1118.  
  1119.   if (gfp->gtkflag && gfc->pinfo != NULL) {
  1120.     int j;
  1121.     for ( ch = 0; ch < gfc->stereo; ch++ ) {
  1122.       for ( j = 0; j < FFTOFFSET; j++ )
  1123.     gfc->pinfo->pcmdata[ch][j] = gfc->pinfo->pcmdata[ch][j+gfp->framesize];
  1124.       for ( j = FFTOFFSET; j < 1600; j++ ) {
  1125.     gfc->pinfo->pcmdata[ch][j] = inbuf[ch][j-FFTOFFSET];
  1126.       }
  1127.     }
  1128.   }
  1129.  
  1130.   gfp->frameNum++;
  1131.   return mp3count;
  1132. }
  1133.  
  1134.  
  1135. /* routine to feed exactly one frame (gfp->framesize) worth of data to the 
  1136. encoding engine.  All buffering, resampling, etc, handled by calling
  1137. program.  
  1138. */
  1139. int lame_encode_frame(lame_global_flags *gfp,
  1140. short int inbuf_l[],short int inbuf_r[],
  1141. char *mp3buf, int mp3buf_size)
  1142. {
  1143.   if (gfp->ogg) {
  1144. #ifdef HAVEVORBIS
  1145.     return lame_encode_ogg_frame(gfp,inbuf_l,inbuf_r,mp3buf,mp3buf_size);
  1146. #else
  1147.     return -5; /* wanna encode ogg without vorbis */
  1148. #endif
  1149.   } else {
  1150.     return lame_encode_mp3_frame(gfp,inbuf_l,inbuf_r,mp3buf,mp3buf_size);
  1151.   }
  1152. }
  1153.  
  1154.  
  1155.  
  1156.  
  1157.  
  1158.  
  1159.  
  1160.  
  1161.  
  1162.  
  1163.  
  1164.  
  1165. /*
  1166.  * THE MAIN LAME ENCODING INTERFACE
  1167.  * mt 3/00
  1168.  *
  1169.  * input pcm data, output (maybe) mp3 frames.
  1170.  * This routine handles all buffering, resampling and filtering for you.
  1171.  * The required mp3buffer_size can be computed from num_samples,
  1172.  * samplerate and encoding rate, but here is a worst case estimate:
  1173.  *
  1174.  * mp3buffer_size in bytes = 1.25*num_samples + 7200
  1175.  *
  1176.  * return code = number of bytes output in mp3buffer.  can be 0
  1177. */
  1178. int lame_encode_buffer(lame_global_flags *gfp,
  1179.    short int buffer_l[], short int buffer_r[],int nsamples,
  1180.    char *mp3buf, int mp3buf_size)
  1181. {
  1182.   int mp3size = 0, ret, i, ch, mf_needed;
  1183.   lame_internal_flags *gfc=gfp->internal_flags;
  1184.   short int *mfbuf[2];
  1185.   short int *in_buffer[2];
  1186.   in_buffer[0] = buffer_l;
  1187.   in_buffer[1] = buffer_r;
  1188.  
  1189.   if (!gfc->lame_init_params_init) return -3;
  1190.  
  1191.   /* some sanity checks */
  1192.   assert(ENCDELAY>=MDCTDELAY);
  1193.   assert(BLKSIZE-FFTOFFSET >= 0);
  1194.   mf_needed = BLKSIZE+gfp->framesize-FFTOFFSET;  /* ammount needed for FFT */
  1195.   mf_needed = Max(mf_needed,286+576*(1+gfc->mode_gr)); /* ammount needed for MDCT/filterbank */
  1196.   assert(MFSIZE>=mf_needed);
  1197.  
  1198.   mfbuf[0]=gfc->mfbuf[0];
  1199.   mfbuf[1]=gfc->mfbuf[1];
  1200.  
  1201.   if (gfp->num_channels==2  && gfc->stereo==1) {
  1202.     /* downsample to mono */
  1203.     for (i=0; i<nsamples; ++i) {
  1204.       in_buffer[0][i]=((int)in_buffer[0][i]+(int)in_buffer[1][i])/2;
  1205.       in_buffer[1][i]=0;
  1206.     }
  1207.   }
  1208.  
  1209.  
  1210.   while (nsamples > 0) {
  1211.     int n_in=0;
  1212.     int n_out=0;
  1213.     /* copy in new samples into mfbuf, with filtering */
  1214.  
  1215.     for (ch=0; ch<gfc->stereo; ch++) {
  1216.       if (gfc->resample_ratio>1)  {
  1217.     n_out=fill_buffer_downsample(gfp,&mfbuf[ch][gfc->mf_size],gfp->framesize,
  1218.                       in_buffer[ch],nsamples,&n_in,ch);
  1219.       } else if (gfc->resample_ratio<1) {
  1220.     n_out=fill_buffer_upsample(gfp,&mfbuf[ch][gfc->mf_size],gfp->framesize,
  1221.                       in_buffer[ch],nsamples,&n_in,ch);
  1222.       } else {
  1223.     n_out=Min(gfp->framesize,nsamples);
  1224.     n_in = n_out;
  1225.     memcpy( (char *) &mfbuf[ch][gfc->mf_size],(char *)in_buffer[ch],sizeof(short int)*n_out);
  1226.       }
  1227.       in_buffer[ch] += n_in;
  1228.     }
  1229.  
  1230.     nsamples -= n_in;
  1231.     gfc->mf_size += n_out;
  1232.     assert(gfc->mf_size<=MFSIZE);
  1233.     gfc->mf_samples_to_encode += n_out;
  1234.  
  1235.  
  1236.     if (gfc->mf_size >= mf_needed) {
  1237.       /* encode the frame.  */
  1238.       ret = lame_encode_frame(gfp,mfbuf[0],mfbuf[1],mp3buf,mp3buf_size);
  1239.  
  1240.       if (ret < 0) return ret;
  1241.       mp3buf += ret;
  1242.       mp3size += ret;
  1243.  
  1244.       /* shift out old samples */
  1245.       gfc->mf_size -= gfp->framesize;
  1246.       gfc->mf_samples_to_encode -= gfp->framesize;
  1247.       for (ch=0; ch<gfc->stereo; ch++)
  1248.     for (i=0; i<gfc->mf_size; i++)
  1249.       mfbuf[ch][i]=mfbuf[ch][i+gfp->framesize];
  1250.     }
  1251.   }
  1252.   assert(nsamples==0);
  1253.  
  1254.   return mp3size;
  1255. }
  1256.  
  1257.  
  1258.  
  1259.  
  1260. int lame_encode_buffer_interleaved(lame_global_flags *gfp,
  1261.    short int buffer[], int nsamples, char *mp3buf, int mp3buf_size)
  1262. {
  1263.   int mp3size = 0, ret, i, ch, mf_needed;
  1264.   lame_internal_flags *gfc=gfp->internal_flags;
  1265.   short int *mfbuf[2];
  1266.  
  1267.   if (!gfc->lame_init_params_init) return -3;
  1268.  
  1269.   mfbuf[0]=gfc->mfbuf[0];
  1270.   mfbuf[1]=gfc->mfbuf[1];
  1271.  
  1272.   /* some sanity checks */
  1273.   assert(ENCDELAY>=MDCTDELAY);
  1274.   assert(BLKSIZE-FFTOFFSET >= 0);
  1275.   mf_needed = BLKSIZE+gfp->framesize-FFTOFFSET;
  1276.   assert(MFSIZE>=mf_needed);
  1277.  
  1278.   if (gfp->num_channels == 1) {
  1279.     return lame_encode_buffer(gfp,buffer, NULL ,nsamples,mp3buf,mp3buf_size);
  1280.   }
  1281.  
  1282.   if (gfc->resample_ratio!=1)  {
  1283.     short int *buffer_l;
  1284.     short int *buffer_r;
  1285.     buffer_l=malloc(sizeof(short int)*nsamples);
  1286.     buffer_r=malloc(sizeof(short int)*nsamples);
  1287.     if (buffer_l == NULL || buffer_r == NULL) {
  1288.       return -2;
  1289.     }
  1290.     for (i=0; i<nsamples; i++) {
  1291.       buffer_l[i]=buffer[2*i];
  1292.       buffer_r[i]=buffer[2*i+1];
  1293.     }
  1294.     ret = lame_encode_buffer(gfp,buffer_l,buffer_r,nsamples,mp3buf,mp3buf_size);
  1295.     free(buffer_l);
  1296.     free(buffer_r);
  1297.     return ret;
  1298.   }
  1299.  
  1300.  
  1301.   if (gfp->num_channels==2  && gfc->stereo==1) {
  1302.     /* downsample to mono */
  1303.     for (i=0; i<nsamples; ++i) {
  1304.       buffer[2*i]=((int)buffer[2*i]+(int)buffer[2*i+1])/2;
  1305.       buffer[2*i+1]=0;
  1306.     }
  1307.   }
  1308.  
  1309.  
  1310.   while (nsamples > 0) {
  1311.     int n_out;
  1312.     /* copy in new samples */
  1313.     n_out = Min(gfp->framesize,nsamples);
  1314.     for (i=0; i<n_out; ++i) {
  1315.       mfbuf[0][gfc->mf_size+i]=buffer[2*i];
  1316.       mfbuf[1][gfc->mf_size+i]=buffer[2*i+1];
  1317.     }
  1318.     buffer += 2*n_out;
  1319.  
  1320.     nsamples -= n_out;
  1321.     gfc->mf_size += n_out;
  1322.     assert(gfc->mf_size<=MFSIZE);
  1323.     gfc->mf_samples_to_encode += n_out;
  1324.  
  1325.     if (gfc->mf_size >= mf_needed) {
  1326.       /* encode the frame */
  1327.       ret = lame_encode_frame(gfp,mfbuf[0],mfbuf[1],mp3buf,mp3buf_size);
  1328.       if (ret < 0) {
  1329.     /* fatel error: mp3buffer was too small */
  1330.     return ret;
  1331.       }
  1332.       mp3buf += ret;
  1333.       mp3size += ret;
  1334.  
  1335.       /* shift out old samples */
  1336.       gfc->mf_size -= gfp->framesize;
  1337.       gfc->mf_samples_to_encode -= gfp->framesize;
  1338.       for (ch=0; ch<gfc->stereo; ch++)
  1339.     for (i=0; i<gfc->mf_size; i++)
  1340.       mfbuf[ch][i]=mfbuf[ch][i+gfp->framesize];
  1341.     }
  1342.   }
  1343.   assert(nsamples==0);
  1344.   return mp3size;
  1345. }
  1346.  
  1347.  
  1348.  
  1349.  
  1350. /* old LAME interface.  use lame_encode_buffer instead */
  1351. int lame_encode(lame_global_flags *gfp, short int in_buffer[2][1152],char *mp3buf,int size){
  1352.   int imp3;
  1353.   lame_internal_flags *gfc=gfp->internal_flags;
  1354.   if (!gfc->lame_init_params_init) return -3;
  1355.   imp3= lame_encode_buffer(gfp,in_buffer[0],in_buffer[1],gfp->framesize,mp3buf,size);
  1356.   return imp3;
  1357. }
  1358.  
  1359.  
  1360. /*****************************************************************/
  1361. /* flush internal mp3 buffers,                                   */
  1362. /*****************************************************************/
  1363. int lame_encode_finish(lame_global_flags *gfp,char *mp3buffer, int mp3buffer_size)
  1364. {
  1365.   int imp3=0,mp3count,mp3buffer_size_remaining;
  1366.   short int buffer[2][1152];
  1367.   lame_internal_flags *gfc=gfp->internal_flags;
  1368.  
  1369.   memset((char *)buffer,0,sizeof(buffer));
  1370.   mp3count = 0;
  1371.  
  1372.   while (gfc->mf_samples_to_encode > 0) {
  1373.  
  1374.     mp3buffer_size_remaining = mp3buffer_size - mp3count;
  1375.  
  1376.     /* if user specifed buffer size = 0, dont check size */
  1377.     if (mp3buffer_size == 0) mp3buffer_size_remaining=0;  
  1378.  
  1379.     /* send in a frame of 0 padding until all internal sample buffers flushed */
  1380.     imp3=lame_encode_buffer(gfp,buffer[0],buffer[1],gfp->framesize,mp3buffer,mp3buffer_size_remaining);
  1381.     /* dont count the above padding: */
  1382.     gfc->mf_samples_to_encode -= gfp->framesize;
  1383.  
  1384.     if (imp3 < 0) {
  1385.       /* some type of fatel error */
  1386.       freegfc(gfc);    
  1387.       return imp3;
  1388.     }
  1389.     mp3buffer += imp3;
  1390.     mp3count += imp3;
  1391.   }
  1392.  
  1393.  
  1394.   gfp->frameNum--;
  1395.   if (!gfp->gtkflag && !gfp->silent) {
  1396.       timestatus(gfp->out_samplerate,gfp->frameNum,gfp->totalframes,gfp->framesize);
  1397.  
  1398.       if (gfp->brhist_disp)
  1399.     {
  1400.       brhist_disp(gfp->totalframes);
  1401.       brhist_disp_total(gfp);
  1402.     }
  1403.  
  1404.       timestatus_finish();
  1405.   }
  1406.  
  1407.   mp3buffer_size_remaining = mp3buffer_size - mp3count;
  1408.   /* if user specifed buffer size = 0, dont check size */
  1409.   if (mp3buffer_size == 0) mp3buffer_size_remaining=0;  
  1410.  
  1411.   if (gfp->ogg) {
  1412. #ifdef HAVEVORBIS    
  1413.     /* ogg related stuff */
  1414.     imp3 = lame_encode_ogg_finish(gfp,mp3buffer,mp3buffer_size_remaining);
  1415. #endif
  1416.   }else{
  1417.     /* mp3 related stuff.  bit buffer might still contain some data */
  1418.     flush_bitstream(gfp);
  1419.     imp3= copy_buffer(mp3buffer,mp3buffer_size_remaining,&gfc->bs);
  1420.   }
  1421.   if (imp3 < 0) {
  1422.     freegfc(gfc);    
  1423.     return imp3;
  1424.   }
  1425.   mp3count += imp3;
  1426.  
  1427.   freegfc(gfc);    
  1428.   return mp3count;
  1429. }
  1430.  
  1431.  
  1432. /*****************************************************************/
  1433. /* write VBR Xing header, and ID3 version 1 tag, if asked for    */
  1434. /*****************************************************************/
  1435. void lame_mp3_tags(lame_global_flags *gfp)
  1436. {
  1437.   if (gfp->bWriteVbrTag)
  1438.     {
  1439.       /* Calculate relative quality of VBR stream
  1440.        * 0=best, 100=worst */
  1441.       int nQuality=gfp->VBR_q*100/9;
  1442.       /* Write Xing header again */
  1443.       PutVbrTag(gfp,gfp->outPath,nQuality);
  1444.     }
  1445.  
  1446.  
  1447.   /* write an ID3 version 1 tag  */
  1448.   if(gfp->id3v1_enabled
  1449. #ifdef HAVEVORBIS
  1450.     /* no ID3 version 1 tags in Ogg Vorbis output */
  1451.     && !gfp->ogg
  1452. #endif
  1453.     ) {
  1454.     /*
  1455.      * NOTE: The new tagging API only knows about streams and always writes at
  1456.      * the current position, so we have to open the file and seek to the end of
  1457.      * it here.  Perhaps we should just NOT close the file when the bitstream is
  1458.      * completed, nor when the final VBR tag is written.
  1459.      * -- gramps
  1460.      */
  1461.     FILE *stream = fopen(gfp->outPath, "rb+");
  1462.     if (stream && !fseek(stream, 0, SEEK_END)) {
  1463.       id3tag_write_v1(&gfp->tag_spec, stream);
  1464.       fclose(stream);
  1465.     }
  1466.   }
  1467. }
  1468.  
  1469.  
  1470. void lame_version(lame_global_flags *gfp,char *ostring) {
  1471.   strncpy(ostring,get_lame_version(),20);
  1472. }
  1473.  
  1474.  
  1475.  
  1476.  
  1477.  
  1478.  
  1479.  
  1480. /* initialize mp3 encoder */
  1481. int lame_init(lame_global_flags *gfp)
  1482. {
  1483.   lame_internal_flags *gfc;
  1484.  
  1485.   /*
  1486.    *  Disable floating point exepctions
  1487.    */
  1488. #ifdef __FreeBSD__
  1489. # include <floatingpoint.h>
  1490.   {
  1491.   /* seet floating point mask to the Linux default */
  1492.   fp_except_t mask;
  1493.   mask=fpgetmask();
  1494.   /* if bit is set, we get SIGFPE on that error! */
  1495.   fpsetmask(mask & ~(FP_X_INV|FP_X_DZ));
  1496.   /*  DEBUGF("FreeBSD mask is 0x%x\n",mask); */
  1497.   }
  1498. #endif
  1499. #if defined(__riscos__) && !defined(ABORTFP)
  1500.   /* Disable FPE's under RISC OS */
  1501.   /* if bit is set, we disable trapping that error! */
  1502.   /*   _FPE_IVO : invalid operation */
  1503.   /*   _FPE_DVZ : divide by zero */
  1504.   /*   _FPE_OFL : overflow */
  1505.   /*   _FPE_UFL : underflow */
  1506.   /*   _FPE_INX : inexact */
  1507.   DisableFPETraps( _FPE_IVO | _FPE_DVZ | _FPE_OFL );
  1508. #endif
  1509.  
  1510.  
  1511.   /*
  1512.    *  Debugging stuff
  1513.    *  The default is to ignore FPE's, unless compiled with -DABORTFP
  1514.    *  so add code below to ENABLE FPE's.
  1515.    */
  1516.  
  1517. #if defined(ABORTFP) 
  1518. #if defined(_MSC_VER)
  1519.   {
  1520.     #include <float.h>
  1521.     unsigned int mask;
  1522.     mask=_controlfp( 0, 0 );
  1523.     mask&=~(_EM_OVERFLOW|_EM_UNDERFLOW|_EM_ZERODIVIDE|_EM_INVALID);
  1524.     mask=_controlfp( mask, _MCW_EM );
  1525.     }
  1526. #elif defined(__CYGWIN__)
  1527. #  define _FPU_GETCW(cw) __asm__ ("fnstcw %0" : "=m" (*&cw))
  1528. #  define _FPU_SETCW(cw) __asm__ ("fldcw %0" : : "m" (*&cw))
  1529.  
  1530. #  define _EM_INEXACT     0x00000001 /* inexact (precision) */
  1531. #  define _EM_UNDERFLOW   0x00000002 /* underflow */
  1532. #  define _EM_OVERFLOW    0x00000004 /* overflow */
  1533. #  define _EM_ZERODIVIDE  0x00000008 /* zero divide */
  1534. #  define _EM_INVALID     0x00000010 /* invalid */
  1535.   {
  1536.     unsigned int mask;
  1537.     _FPU_GETCW(mask);
  1538.     /* Set the FPU control word to abort on most FPEs */
  1539.     mask &= ~(_EM_UNDERFLOW | _EM_OVERFLOW | _EM_ZERODIVIDE | _EM_INVALID);
  1540.     _FPU_SETCW(mask);
  1541.   }
  1542. # elif (defined(__linux__) || defined(__FreeBSD__))
  1543.   {
  1544. #  include <fpu_control.h>
  1545. #  ifndef _FPU_GETCW
  1546. #  define _FPU_GETCW(cw) __asm__ ("fnstcw %0" : "=m" (*&cw))
  1547. #  endif
  1548. #  ifndef _FPU_SETCW
  1549. #  define _FPU_SETCW(cw) __asm__ ("fldcw %0" : : "m" (*&cw))
  1550. #  endif
  1551.     unsigned int mask;
  1552.     _FPU_GETCW(mask);
  1553.     /* Set the Linux mask to abort on most FPE's */
  1554.     /* if bit is set, we _mask_ SIGFPE on that error! */
  1555.     /*  mask &= ~( _FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM | _FPU_MASK_UM );*/
  1556.     mask &= ~( _FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM );
  1557.     _FPU_SETCW(mask);
  1558.   }
  1559. #endif
  1560. #endif /* ABORTFP */
  1561.  
  1562.  
  1563.  
  1564.   memset(gfp,0,sizeof(lame_global_flags));
  1565.   if (NULL==(gfp->internal_flags = malloc(sizeof(lame_internal_flags))))
  1566.     return -1;
  1567.   gfc=(lame_internal_flags *) gfp->internal_flags;
  1568.   memset(gfc,0,sizeof(lame_internal_flags));
  1569.  
  1570.   /* Global flags.  set defaults here */
  1571.   gfp->mode = MPG_MD_JOINT_STEREO;
  1572.   gfp->mode_fixed=0;
  1573.   gfp->force_ms=0;
  1574.   gfp->brate=0;
  1575.   gfp->copyright=0;
  1576.   gfp->original=1;
  1577.   gfp->extension=0;
  1578.   gfp->error_protection=0;
  1579.   gfp->emphasis=0;
  1580.   gfp->in_samplerate=1000*44.1;
  1581.   gfp->out_samplerate=0;
  1582.   gfp->num_channels=2;
  1583.   gfp->num_samples=MAX_U_32_NUM;
  1584.  
  1585.   gfp->allow_diff_short=0;
  1586.   gfp->ATHonly=0;
  1587.   gfp->noATH=0;
  1588.   gfp->bWriteVbrTag=1;
  1589.   gfp->cwlimit=0;
  1590.   gfp->disable_reservoir=0;
  1591.   gfp->experimentalX = 0;
  1592.   gfp->experimentalY = 0;
  1593.   gfp->experimentalZ = 0;
  1594.   gfp->exp_nspsytune = 0;
  1595.   gfp->gtkflag=0;
  1596.   gfp->quality=5;
  1597.   gfp->input_format=sf_unknown;
  1598.  
  1599.   gfp->lowpassfreq=0;
  1600.   gfp->highpassfreq=0;
  1601.   gfp->lowpasswidth = -1;
  1602.   gfp->highpasswidth = -1;
  1603.  
  1604.   gfp->no_short_blocks=0;
  1605.   gfp->padding_type=2;
  1606.   gfp->swapbytes=0;
  1607.   gfp->silent=1;
  1608.   gfp->VBR=vbr_off;
  1609.   gfp->VBR_q=4;
  1610.   gfp->VBR_mean_bitrate_kbps=128;
  1611.   gfp->VBR_min_bitrate_kbps=0;
  1612.   gfp->VBR_max_bitrate_kbps=0;
  1613.   gfp->VBR_hard_min=0;
  1614.  
  1615.   gfc->pcmbitwidth = 16;
  1616.   gfc->resample_ratio=1;
  1617.   gfc->lowpass_band=32;
  1618.   gfc->highpass_band = -1;
  1619.   gfc->VBR_min_bitrate=1;
  1620.   gfc->VBR_max_bitrate=13;
  1621.  
  1622.   gfc->OldValue[0]=180;
  1623.   gfc->OldValue[1]=180;
  1624.   gfc->CurrentStep=4;
  1625.   gfc->masking_lower=1;
  1626.  
  1627.  
  1628.   memset(&gfc->bs, 0, sizeof(Bit_stream_struc));
  1629.   memset(&gfc->l3_side,0x00,sizeof(III_side_info_t));
  1630.  
  1631.   memset((char *) gfc->mfbuf, 0, sizeof(short)*2*MFSIZE);
  1632.  
  1633.   /* The reason for
  1634.    *       int mf_samples_to_encode = ENCDELAY + 288;
  1635.    * ENCDELAY = internal encoder delay.  And then we have to add 288
  1636.    * because of the 50% MDCT overlap.  A 576 MDCT granule decodes to
  1637.    * 1152 samples.  To synthesize the 576 samples centered under this granule
  1638.    * we need the previous granule for the first 288 samples (no problem), and
  1639.    * the next granule for the next 288 samples (not possible if this is last
  1640.    * granule).  So we need to pad with 288 samples to make sure we can
  1641.    * encode the 576 samples we are interested in.
  1642.    */
  1643.   gfc->mf_samples_to_encode = ENCDELAY+288;
  1644.   gfc->mf_size=ENCDELAY-MDCTDELAY;  /* we pad input with this many 0's */
  1645.  
  1646.   return 0;
  1647. }
  1648.  
  1649.  
  1650.