home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / dctm.lzh / DCTM / source.lzh / source / PCM2MP.Cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2003-02-08  |  102.3 KB  |  3,220 lines

  1. /*************************************************************************
  2.     PCM2MP.cpp
  3.  
  4.     03/02/08    Xiaohong
  5. *************************************************************************/
  6. //#include <dos.h>
  7. //#include <ctype.h>
  8. #include "tompeg.h"
  9. #include "alloc_0.h"
  10. #include "alloc_1.h"
  11. #include "alloc_2.h"
  12. #include "alloc_3.h"
  13. #include "absthr_0.h"
  14. #include "absthr_1.h"
  15. #include "absthr_2.h"
  16. #include "fft.h"
  17. #include "BitStreamStruct.h"
  18. #include <math.h>
  19. #include <windows.h>
  20. #include <vfw.h>
  21. #include "macros.h"
  22.  
  23. /***********************************************************************
  24. *
  25. *  Global Definitions
  26. *
  27. ***********************************************************************/
  28.  
  29. /* General Definitions */
  30.  
  31. #define         MAX_U_32_NUM            0xFFFFFFFF
  32. #define         PI                      3.14159265358979
  33. #define         PI4                     (PI/4)
  34. #define         PI64                    (PI/64)
  35. #define         LN_TO_LOG10             0.2302585093
  36.  
  37. #define         MPEG_AUDIO_ID           1
  38.  
  39. #define         SBLIMIT                 32
  40. #define         HAN_SIZE                512
  41. #define         SCALE_BLOCK             12
  42. #define         SCALE_RANGE             64
  43. #define         SCALE                   32768
  44. #define         CRC16_POLYNOMIAL        0x8005
  45.  
  46. /* MPEG Header Definitions - Mode Values */
  47.  
  48. #define         MPG_MD_STEREO           0
  49. #define         MPG_MD_JOINT_STEREO     1
  50. #define         MPG_MD_DUAL_CHANNEL     2
  51. #define         MPG_MD_MONO             3
  52.  
  53. /***********************************************************************
  54. *
  55. *  Global Type Definitions
  56. *
  57. ***********************************************************************/
  58.  
  59. /* Structure for Reading Layer II Allocation Tables from File */
  60.  
  61. typedef struct {
  62.     unsigned int    steps;
  63.     unsigned int    bits;
  64.     unsigned int    group;
  65.     unsigned int    quant;
  66. } sb_alloc, *alloc_ptr;
  67.  
  68. typedef sb_alloc al_table[SBLIMIT][16];
  69.  
  70. /* Header Information Structure */
  71.  
  72. typedef struct
  73. {
  74.     int version;
  75.     int lay;
  76.     bool error_protection;
  77.     int bitrate_index;
  78.     int sampling_frequency;
  79.     int padding;
  80.     int extension;
  81.     int mode;
  82.     int mode_ext;
  83.     int copyright;
  84.     int original;
  85.     int emphasis;
  86. } layer, *the_layer;
  87.  
  88. /* Parent Structure Interpreting some Frame Parameters in Header */
  89.  
  90. class frame_params
  91. {
  92. public:
  93.     frame_params(layer*);
  94.     ~frame_params();
  95.  
  96.     void free_table(void);
  97.     bool alloc_table(void);
  98.  
  99.     layer       *header;        /* raw header information */
  100.     int         actual_mode;    /* when writing IS, may forget if 0 chs */
  101.     al_table    *alloc;         /* bit allocation table read in */
  102.     int         tab_num;        /* number of table as loaded */
  103.     int         stereo;         /* 1 for mono, 2 for stereo */
  104.     int         jsbound;        /* first band of joint stereo coding */
  105.     int         sblimit;        /* total number of sub bands */
  106. };
  107. frame_params::frame_params(layer* pl)
  108. {
  109.     header = pl;
  110.     alloc = NULL;
  111.     tab_num = -1;
  112. }
  113. frame_params::~frame_params()
  114. {
  115.     free_table();
  116. }
  117. void frame_params::free_table(void)
  118. {
  119.     if(alloc!=NULL)
  120.     {
  121.         _free(alloc);
  122.     }
  123. }
  124. bool frame_params::alloc_table(void)
  125. {
  126.     free_table();
  127.  
  128.     if((alloc = (al_table *)_malloc(sizeof(al_table)))==NULL)
  129.     {
  130.         return false;
  131.     }
  132.     ZeroMemory(alloc,sizeof(al_table));
  133.     return true;
  134. }
  135.  
  136. #define DFLT_SFQ        44.1   /* default input sampling rate is 44.1 kHz */
  137. #define DFLT_EMP        'n'    /* default de-emphasis is none */
  138.  
  139. /* This is the smallest MNR a subband can have before it is counted
  140.    as 'noisy' by the logic which chooses the number of JS subbands */
  141.  
  142. #define NOISY_MIN_MNR   0.0
  143.  
  144. /* Psychoacoustic Model 2 Definitions */
  145.  
  146. #define HBLKSIZE        513
  147. #define CBANDS          63
  148. #define LXMIN           32.0
  149.  
  150. /* additonal def's for avi handling */
  151.  
  152. #define PCM_BUFFER        2304
  153.  
  154.  
  155. /* Psychoacoustic Model 2 Type Definitions */
  156.  
  157.  
  158. /***********************************************************************
  159. *
  160. *  Encoder Function Prototype Declarations
  161. *
  162. ***********************************************************************/
  163. /* The following functions are in the file "encode.c" */
  164.  
  165. static unsigned long read_samples(short[PCM_BUFFER],const long,const long,bool*);
  166. static inline unsigned char get_audio(short[2][1152], unsigned long,int, int);
  167. static void window_subband(short**, double[], int);
  168. static inline void create_ana_filter(double[SBLIMIT][64]);
  169. static void filter_subband(double[HAN_SIZE], double[SBLIMIT]);
  170. static void encode_info(frame_params*, BitStreamStruct*);
  171. static inline void I_combine_LR(double[2][3][SCALE_BLOCK][SBLIMIT],
  172.                            double[3][SCALE_BLOCK][SBLIMIT]);
  173. static inline void II_combine_LR(double[2][3][SCALE_BLOCK][SBLIMIT],
  174.                            double[3][SCALE_BLOCK][SBLIMIT], int);
  175. static void I_scale_factor_calc(double[][3][SCALE_BLOCK][SBLIMIT],
  176.                            unsigned int[][3][SBLIMIT], int);
  177. static void II_scale_factor_calc(double[][3][SCALE_BLOCK][SBLIMIT],
  178.                            unsigned int[][3][SBLIMIT], int, int);
  179. static inline void pick_scale(unsigned int[2][3][SBLIMIT], frame_params*,
  180.                            double[2][SBLIMIT]);
  181. static inline void put_scale(unsigned int[][3][SBLIMIT],const frame_params*,
  182.                            double[2][SBLIMIT]);
  183. static inline void II_transmission_pattern(unsigned int[2][3][SBLIMIT],
  184.                            unsigned int[2][SBLIMIT], frame_params*);
  185. static inline void II_encode_scale(unsigned int[2][SBLIMIT],
  186.                            unsigned int[2][SBLIMIT],
  187.                            unsigned int[2][3][SBLIMIT], frame_params*,
  188.                            BitStreamStruct*);
  189. static inline void I_encode_scale(unsigned int[2][3][SBLIMIT],
  190.                                   const unsigned int[2][SBLIMIT],
  191.                                   const frame_params*,
  192.                                   BitStreamStruct*);
  193. static int II_bits_for_nonoise(const double[2][SBLIMIT],const unsigned int[2][SBLIMIT],
  194.                            const frame_params*);
  195. static inline bool II_main_bit_allocation(const double[2][SBLIMIT],
  196.                            const unsigned int[2][SBLIMIT], unsigned int[2][SBLIMIT],
  197.                            int*,frame_params*);
  198. static inline int II_a_bit_allocation(const double[][SBLIMIT],const unsigned int[][SBLIMIT],
  199.                            unsigned int[][SBLIMIT], int*,const frame_params*);
  200. static int I_bits_for_nonoise(const double[2][SBLIMIT],const frame_params*);
  201. static inline bool I_main_bit_allocation(const double[2][SBLIMIT],
  202.                            unsigned int[2][SBLIMIT], int*,frame_params*);
  203. static inline int I_a_bit_allocation(const double[2][SBLIMIT], unsigned int[2][SBLIMIT],
  204.                            int*,const frame_params*);
  205. static inline void I_subband_quantization(unsigned int[2][3][SBLIMIT],
  206.                            double[2][3][SCALE_BLOCK][SBLIMIT], unsigned int[3][SBLIMIT],
  207.                            double[3][SCALE_BLOCK][SBLIMIT], unsigned int[2][SBLIMIT],
  208.                            unsigned int[2][3][SCALE_BLOCK][SBLIMIT], frame_params*);
  209. static inline void II_subband_quantization(unsigned int[2][3][SBLIMIT],
  210.                            double[2][3][SCALE_BLOCK][SBLIMIT], unsigned int[3][SBLIMIT],
  211.                            double[3][SCALE_BLOCK][SBLIMIT], unsigned int[2][SBLIMIT],
  212.                            unsigned int[2][3][SCALE_BLOCK][SBLIMIT], frame_params*);
  213. static inline void II_encode_bit_alloc(const unsigned int[][SBLIMIT],const frame_params*,
  214.                            BitStreamStruct*);
  215. static inline void I_encode_bit_alloc(const unsigned int[][SBLIMIT],const frame_params*,
  216.                            BitStreamStruct*);
  217. static inline void I_sample_encoding(unsigned int[2][3][SCALE_BLOCK][SBLIMIT],
  218.                            unsigned int[2][SBLIMIT], frame_params*,
  219.                            BitStreamStruct*);
  220. static inline void II_sample_encoding(unsigned int[2][3][SCALE_BLOCK][SBLIMIT],
  221.                            unsigned int[2][SBLIMIT], frame_params*,
  222.                            BitStreamStruct*);
  223. static inline void encode_CRC(unsigned int, BitStreamStruct*);
  224. /* The following functions are in the file "common.c" */
  225.  
  226. static inline int read_bit_alloc(int, al_table*);
  227. static inline int pick_table(frame_params*,bool*);
  228. static int js_bound(const int,const int);
  229. static inline bool hdr_to_frps(frame_params*);
  230. static inline int BitrateIndex(const int,const unsigned int);
  231. static inline int SmpFrqIndex(long);
  232. static inline void I_CRC_calc(frame_params*, unsigned int[2][SBLIMIT],
  233.                         unsigned int*);
  234. static inline void II_CRC_calc(frame_params*, unsigned int[2][SBLIMIT],
  235.                         unsigned int[2][SBLIMIT], unsigned int*);
  236. static void update_CRC(unsigned int, unsigned int, unsigned int*);
  237.  
  238. /* The following functions are in the file "psy.c" */
  239.  
  240. static TOMPGRET psycho_anal(
  241.                  const short* buffer,short int savebuf[1056],
  242.                  const int chn,const int lay,
  243.                  double snr32[],const double sfreq);
  244.  
  245. static void filter(short *work_buffer, unsigned int length, unsigned int stereo, unsigned int mult);
  246.  
  247.  
  248. /* Global variable definitions for "avi2mp2.c" */
  249.  
  250. static const double  g_fSamplingFrequency[4] = {44.1, 48.0, 32.0, 0.0};
  251.  
  252. static const unsigned int  g_uBitRateArray[2][15] = 
  253. {
  254.     {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448},
  255.     {0,32,48,56,64,80,96,112,128,160,192,224,256,320,384}
  256. };
  257.  
  258. static const double g_fMultiple[64] = 
  259. {
  260.     2.00000000000000, 1.58740105196820, 1.25992104989487,
  261.     1.00000000000000, 0.79370052598410, 0.62996052494744, 0.50000000000000,
  262.     0.39685026299205, 0.31498026247372, 0.25000000000000, 0.19842513149602,
  263.     0.15749013123686, 0.12500000000000, 0.09921256574801, 0.07874506561843,
  264.     0.06250000000000, 0.04960628287401, 0.03937253280921, 0.03125000000000,
  265.     0.02480314143700, 0.01968626640461, 0.01562500000000, 0.01240157071850,
  266.     0.00984313320230, 0.00781250000000, 0.00620078535925, 0.00492156660115,
  267.     0.00390625000000, 0.00310039267963, 0.00246078330058, 0.00195312500000,
  268.     0.00155019633981, 0.00123039165029, 0.00097656250000, 0.00077509816991,
  269.     0.00061519582514, 0.00048828125000, 0.00038754908495, 0.00030759791257,
  270.     0.00024414062500, 0.00019377454248, 0.00015379895629, 0.00012207031250,
  271.     0.00009688727124, 0.00007689947814, 0.00006103515625, 0.00004844363562,
  272.     0.00003844973907, 0.00003051757813, 0.00002422181781, 0.00001922486954,
  273.     0.00001525878906, 0.00001211090890, 0.00000961243477, 0.00000762939453,
  274.     0.00000605545445, 0.00000480621738, 0.00000381469727, 0.00000302772723,
  275.     0.00000240310869, 0.00000190734863, 0.00000151386361, 0.00000120155435,
  276.     1E-20
  277. };
  278.  
  279.  
  280. //char             programName[] = "avi2mpg1";
  281. //static int    channels;
  282.  
  283. static unsigned long g_nLastSample = 0;
  284. static long g_nBytesProcessed = 0;
  285.  
  286. static WAVEFORMATEX g_stWavFormat;
  287. static PAVISTREAM g_pAudioStream = NULL;
  288. static AVISTREAMINFO g_stAudioStreamInfo;
  289.  
  290. /* Implementations */
  291.  
  292. /*---------------------------------------------------------
  293.     âpâëâüü[â^é╠É▌ÆΦ
  294. ---------------------------------------------------------*/
  295. static TOMPGRET set_parms(frame_params  *fr_ps,
  296.                           BitStreamStruct *bs,
  297.                       unsigned long *num_samples,
  298.                       const char *tempfile,
  299.                       const int audio_layer_param,
  300.                       const bool joint_stereo_param,
  301.                       const unsigned int bitrate)
  302. {
  303.     layer *info = fr_ps->header;
  304.     int   err = 0, i = 0;
  305.  
  306.     /* preset defaults */
  307.     info->lay = audio_layer_param;
  308.  
  309.     if(g_stWavFormat.nChannels == 1)
  310.     {
  311.         info->mode = MPG_MD_MONO;
  312.         info->mode_ext = 0;
  313.     }
  314.     else
  315.     {
  316.         if(joint_stereo_param)
  317.         {
  318.             info->mode = MPG_MD_JOINT_STEREO;
  319.         }
  320.         else
  321.         {
  322.             info->mode = MPG_MD_STEREO;
  323.             info->mode_ext = 0;
  324.         }
  325.     }
  326.  
  327.     if((info->sampling_frequency = SmpFrqIndex((long)(1000*DFLT_SFQ))) < 0)
  328.     {
  329.         return TR_SAMPLING_FREQUENCY_ERR;
  330.     }
  331.     if((info->bitrate_index = BitrateIndex(info->lay, bitrate)) < 0)
  332.     {
  333.         return TR_AUDIO_BITRATE_ERR;
  334.     }
  335.  
  336.     switch(DFLT_EMP)
  337.     {
  338.         case 'n': info->emphasis = 0; break;
  339.         case '5': info->emphasis = 1; break;
  340.         case 'c': info->emphasis = 3; break;
  341.         default: 
  342.             return TR_ERR;
  343.     }
  344.  
  345.     info->copyright = 0;
  346.     info->original = 0;
  347.     info->error_protection = false;
  348.  
  349.     //length = sizeof(pWavFormat);
  350.  
  351.     //channels = g_stWavFormat.nChannels; // store for later
  352.  
  353.     if(g_stWavFormat.wFormatTag != WAVE_FORMAT_PCM)
  354.     {
  355.         return TR_NOT_PCM;
  356.     }
  357.  
  358.     if ((g_stWavFormat.nSamplesPerSec != 11025) 
  359.         && (g_stWavFormat.nSamplesPerSec != 22050)
  360.         && (g_stWavFormat.nSamplesPerSec != 44100))
  361.     {
  362.         return TR_SAMPLE_PER_SEC_ERR;
  363.     }
  364.     if ((g_stWavFormat.wBitsPerSample != 16) 
  365.         && (g_stWavFormat.wBitsPerSample != 8))
  366.     {
  367.         return TR_BITS_PER_SAMPLE_ERR;
  368.     }
  369.  
  370.     switch(bs->OpenBitStreamW(tempfile,BUFFER_SIZE))
  371.     {
  372.         case BSSR_OK:
  373.             break;
  374.         case BSSR_OPEN_FILE_ERR:
  375.             return TR_OPEN_TMP_AUDIO_FILE_ERR;
  376.         case BSSR_ALLOC_BUFFER_ERR:
  377.             return TR_ALLOC_BIT_STREAM_BUFFER_ERR;
  378.         default:
  379.             return TR_ERR;
  380.     }
  381.  
  382.     *num_samples=0;
  383.     if(g_stWavFormat.nChannels == 2)
  384.         *num_samples += g_stAudioStreamInfo.dwLength * 2;
  385.     else
  386.         *num_samples += g_stAudioStreamInfo.dwLength;
  387.  
  388.     if(g_stWavFormat.nSamplesPerSec == 22050)
  389.         *num_samples = *num_samples * 2;
  390.  
  391.     if(g_stWavFormat.nSamplesPerSec == 11025)
  392.         *num_samples = *num_samples * 4;
  393.  
  394.     return TR_OK;
  395.  
  396. }
  397.  
  398.  
  399. /************************************************************************
  400. /*
  401. /* avi2mp2
  402. /*
  403. /* PURPOSE:  MPEG I Encoder supporting layers 1 and 2, and
  404. /* psychoacoustic model 2 (AT&T)
  405. /*
  406. /* SEMANTICS:  One overlapping frame of audio of up to 2 channels are
  407. /* processed at a time in the following order:
  408. /* (associated routines are in parentheses)
  409. /*
  410. /* 1.  Filter sliding window of data to get 32 subband
  411. /* samples per channel.
  412. /* (window_subband,filter_subband)
  413. /*
  414. /* 2.  If joint stereo mode, combine left and right channels
  415. /* for subbands above #jsbound#.
  416. /* (*_combine_LR)
  417. /*
  418. /* 3.  Calculate scalefactors for the frame, and if layer 2,
  419. /* also calculate scalefactor select information.
  420. /* (*_scale_factor_calc)
  421. /*
  422. /* 4.  Calculate psychoacoustic masking levels using selected
  423. /* psychoacoustic model.
  424. /* (*_Psycho_One, psycho_anal)
  425. /*
  426. /* 5.  Perform iterative bit allocation for subbands with low
  427. /* mask_to_noise ratios using masking levels from step 4.
  428. /* (*_main_bit_allocation)
  429. /*
  430. /* 6.  If error protection flag is active, add redundancy for
  431. /* error protection.
  432. /* (*_CRC_calc)
  433. /*
  434. /* 7.  Pack bit allocation, scalefactors, and scalefactor select
  435. /* information (layer 2) onto bitstream.
  436. /* (*_encode_bit_alloc,*_encode_scale,II_transmission_pattern)
  437. /*
  438. /* 8.  Quantize subbands and pack them into bitstream
  439. /* (*_subband_quantization, *_sample_encoding)
  440. /*
  441. /************************************************************************/
  442.  
  443. EXPORT TOMPGRET CALLBACK TOMPEG_PCM2MP(const char *tempfile,
  444.                                          const TOMPEG_AUDIO_FORMAT* pTompegAudioFormat,
  445.                                          bool(* CallBack)(TOMPEG_PROCESS_PARAM,int))
  446. {
  447.     double sb_sample[2][3][SCALE_BLOCK][SBLIMIT];
  448.     double j_sample[3][SCALE_BLOCK][SBLIMIT];
  449.     double win_que[2][HAN_SIZE];
  450.     unsigned int subband[2][3][SCALE_BLOCK][SBLIMIT];
  451.  
  452.     BitStreamStruct   bs;
  453.     layer info;
  454.     frame_params fr_ps(&info);
  455.     short *win_buf[2] = {NULL,NULL};
  456.     short buffer[2][1152];
  457.     unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT];
  458.     unsigned int scalar[2][3][SBLIMIT], j_scale[3][SBLIMIT];
  459.     double ltmin[2][SBLIMIT], lgmin[2][SBLIMIT], max_sc[2][SBLIMIT];
  460.     double snr32[32];
  461.     short sam[2][1056];
  462.     int whole_SpF, extra_slot = 0;
  463.     double avg_slots_per_frame, frac_SpF, slot_lag;
  464.     int stereo;
  465.     bool error_protection;
  466.     unsigned int crc;
  467.     int i, j, k, adb;
  468.     unsigned long bitsPerSlot, samplesPerFrame, frameNum = 0;
  469.     unsigned long frameBits, sentBits = 0;
  470.     unsigned long num_samples;
  471.     long length;
  472.  
  473.     TOMPGRET ret;
  474.     g_nLastSample = 0;
  475.     g_nBytesProcessed = 0;
  476.  
  477.     if(pTompegAudioFormat->uAudioLayerParam!=0&&pTompegAudioFormat->uAudioLayerParam!=1)
  478.         return TR_ERR_AUDIO_PARAM;
  479.  
  480.     g_pAudioStream = pTompegAudioFormat->pAudioStream;
  481.     if (AVIStreamInfo(g_pAudioStream, &g_stAudioStreamInfo, sizeof(g_stAudioStreamInfo)))
  482.     {
  483.         return TR_AVISTREAMINFO_ERR;
  484.     }
  485.  
  486.      AVIStreamReadFormat(g_pAudioStream, 0, 0, (long*)&length);
  487.  
  488.     if(AVIStreamReadFormat(g_pAudioStream, 0, &g_stWavFormat, (long*)&length))
  489.     {
  490.         return TR_AVISTREAMREADFORMAT_ERR;
  491.     }
  492.  
  493.     /* Most large variables are declared dynamically to ensure
  494.        compatibility with smaller machines */
  495.  
  496.     ZeroMemory(sb_sample,sizeof(sb_sample));
  497.     ZeroMemory(j_sample,sizeof(j_sample));
  498.     ZeroMemory(win_que,sizeof(win_que));
  499.     ZeroMemory(subband,sizeof(subband));
  500.  
  501.     /* clear buffers */
  502.     ZeroMemory(buffer,sizeof(buffer));
  503.      ZeroMemory(bit_alloc,sizeof(bit_alloc));
  504.     ZeroMemory(scfsi,sizeof(scfsi));
  505.     ZeroMemory(scalar,sizeof(scalar));
  506.     ZeroMemory(j_scale,sizeof(j_scale));
  507.     ZeroMemory(ltmin,sizeof(ltmin));
  508.     ZeroMemory(lgmin,sizeof(lgmin));
  509.     ZeroMemory(max_sc,sizeof(max_sc));
  510.     ZeroMemory(snr32,sizeof(snr32));
  511.     ZeroMemory(sam,sizeof(sam));
  512.  
  513.     info.version = MPEG_AUDIO_ID;
  514.  
  515.     if((ret = set_parms(&fr_ps, 
  516.         &bs, 
  517.         &num_samples, 
  518.         tempfile, 
  519.         pTompegAudioFormat->uAudioLayerParam, 
  520.         pTompegAudioFormat->bJointStereoParam, 
  521.         pTompegAudioFormat->uAudioBitrateParam))!=TR_OK)
  522.     {
  523.         bs.CloseBitStreamW();
  524.         return ret;
  525.     }
  526.  
  527.     if(!hdr_to_frps(&fr_ps))
  528.     {
  529.         bs.CloseBitStreamW();
  530.         return TR_HDR_TO_FRPS_ERR;
  531.     }
  532.     stereo = fr_ps.stereo;
  533.     error_protection = info.error_protection;
  534.  
  535.     if (info.lay == 0)
  536.     {
  537.         bitsPerSlot = 32;
  538.         samplesPerFrame = 384;
  539.     }
  540.     else
  541.     {
  542.         bitsPerSlot = 8;
  543.         samplesPerFrame = 1152;
  544.     }
  545.     /* Figure average number of 'slots' per frame. */
  546.     /* Bitrate means TOTAL for both channels, not per side. */
  547.     avg_slots_per_frame = (((double)samplesPerFrame) /
  548.                g_fSamplingFrequency[info.sampling_frequency]) *
  549.               (((double)g_uBitRateArray[info.lay][info.bitrate_index]) /
  550.                ((double)bitsPerSlot));
  551.     whole_SpF = (int)(avg_slots_per_frame);
  552.     //printf("slots/frame = %d\n",whole_SpF);
  553.     frac_SpF  = avg_slots_per_frame - (double)whole_SpF;
  554.     slot_lag  = -frac_SpF;
  555.  
  556.     if (frac_SpF != 0)
  557.        {}
  558.     else
  559.         info.padding = 0;
  560.  
  561.     while(1)
  562.     {
  563.         const unsigned char get_audio_return = get_audio(buffer, num_samples, stereo, info.lay);
  564.         
  565.         if(CallBack!=NULL)
  566.         {
  567.             if(!CallBack(TOMPEG_PROCESS_ENCODE_MP2,100*(num_samples-g_nBytesProcessed)/num_samples))
  568.             {
  569.                 bs.CloseBitStreamW();
  570.                 return TR_CANCEL;
  571.             }
  572.         }
  573.         if(get_audio_return==0)
  574.         {
  575.             // æ▒ìs
  576.         }
  577.         else if(get_audio_return==1)
  578.         {
  579.             bs.CloseBitStreamW();
  580.             return TR_ERR;
  581.         }
  582.         else
  583.         {
  584.             // while âïü[âvé╠ÅIù╣
  585.             break;
  586.         }
  587.  
  588.        //_proc( "\raudio frame %u", frameNum++); fflush(stderr);
  589.         //_proc( "\r%5.1f%% complete", ((float)(num_samples - bytes_processed)/(float)num_samples)*100.0);
  590.  
  591.         win_buf[0] = &buffer[0][0];
  592.         win_buf[1] = &buffer[1][0];
  593.         
  594.         if (frac_SpF != 0)
  595.         {
  596.             if (slot_lag > (frac_SpF-1.0) )
  597.             {
  598.                 slot_lag -= frac_SpF;
  599.                 extra_slot = 0;
  600.                 info.padding = 0;
  601.                 /*  printf("No padding for this frame\n"); */
  602.             }
  603.             else
  604.             {
  605.                 extra_slot = 1;
  606.                 info.padding = 1;
  607.                 slot_lag += (1.0-frac_SpF);
  608.                 /*  printf("Padding for this frame\n");    */
  609.             }
  610.         }
  611.         adb = (whole_SpF+extra_slot) * bitsPerSlot;
  612.  
  613.        switch (info.lay)
  614.        {
  615.  
  616. /***************************** Layer I **********************************/
  617.  
  618.        case 0 :
  619.           for (j=0;j<SCALE_BLOCK;j++)
  620.              for (k=0;k<stereo;k++)
  621.              {
  622.                  window_subband(&win_buf[k], &(win_que)[k][0], k);
  623.                  filter_subband(&(win_que)[k][0], &(sb_sample)[k][0][j][0]);
  624.              }
  625.  
  626.           I_scale_factor_calc(sb_sample, scalar, stereo);
  627.           if(fr_ps.actual_mode == MPG_MD_JOINT_STEREO)
  628.           {
  629.              I_combine_LR(sb_sample, j_sample);
  630.              I_scale_factor_calc(&j_sample, &j_scale, 1);
  631.           }
  632.  
  633.           put_scale(scalar, &fr_ps, max_sc);
  634.  
  635.           for (k=0;k<stereo;k++)
  636.           {
  637.               if((ret = psycho_anal(&buffer[k][0],&sam[k][0], k, info.lay, snr32,
  638.                           (double)g_fSamplingFrequency[info.sampling_frequency]*1000))!=TR_OK)
  639.               {
  640.                   bs.CloseBitStreamW();
  641.                   return ret;
  642.               }
  643.               for (i=0;i<SBLIMIT;i++)
  644.                  ltmin[k][i] = (double) snr32[i];
  645.           }
  646.  
  647.           if(!I_main_bit_allocation(ltmin, bit_alloc, &adb, &fr_ps))
  648.           {
  649.               bs.CloseBitStreamW();
  650.               return TR_I_MAIN_BIT_ALLOCATION_ERR;
  651.           }
  652.  
  653.           if (error_protection)
  654.              I_CRC_calc(&fr_ps, bit_alloc, &crc);
  655.  
  656.           encode_info(&fr_ps, &bs);
  657.  
  658.           if (error_protection)
  659.              encode_CRC(crc, &bs);
  660.  
  661.           I_encode_bit_alloc(bit_alloc, &fr_ps, &bs);
  662.           I_encode_scale(scalar,bit_alloc,&fr_ps, &bs);
  663.           I_subband_quantization(scalar, sb_sample, j_scale, j_sample,
  664.                     bit_alloc, subband, &fr_ps);
  665.           I_sample_encoding(subband, bit_alloc, &fr_ps, &bs);
  666.           for (i=0;i<adb;i++)
  667.               bs.PutBit(0);
  668.              //put1bit(&bs, 0);
  669.       break;
  670.  
  671. /***************************** Layer 2 **********************************/
  672.  
  673.       case 1 :
  674.         for (i=0;i<3;i++)
  675.              for (j=0;j<SCALE_BLOCK;j++)
  676.                  for (k=0;k<stereo;k++)
  677.                  {
  678.                      window_subband(&win_buf[k], &(win_que)[k][0], k);
  679.                      filter_subband(&(win_que)[k][0], &(sb_sample)[k][i][j][0]);
  680.                  }
  681.  
  682.          II_scale_factor_calc(sb_sample, scalar, stereo, fr_ps.sblimit);
  683.          pick_scale(scalar, &fr_ps, max_sc);
  684.          if(fr_ps.actual_mode == MPG_MD_JOINT_STEREO)
  685.          {
  686.              II_combine_LR(sb_sample, j_sample, fr_ps.sblimit);
  687.              II_scale_factor_calc(&j_sample, &j_scale, 1, fr_ps.sblimit);
  688.          }       /* this way we calculate more mono than we need */
  689.                  /* but it is cheap */
  690.  
  691.          for (k=0;k<stereo;k++)
  692.          {
  693.              if((ret = psycho_anal(&buffer[k][0],&sam[k][0], k, 
  694.                          info.lay, snr32,
  695.                          g_fSamplingFrequency[info.sampling_frequency]*1000))!=TR_OK)
  696.              {
  697.                  return ret;
  698.              }
  699.              for (i=0;i<SBLIMIT;i++)
  700.                   ltmin[k][i] = snr32[i];
  701.          }
  702.  
  703.          II_transmission_pattern(scalar, scfsi, &fr_ps);
  704.          if(!II_main_bit_allocation(ltmin, scfsi, bit_alloc, &adb, &fr_ps))
  705.          {
  706.              return TR_II_MAIN_BIT_ALLOCATION_ERR;
  707.          }
  708.  
  709.          if (error_protection)
  710.          {
  711.              II_CRC_calc(&fr_ps, bit_alloc, scfsi, &crc);
  712.          }
  713.  
  714.          encode_info(&fr_ps, &bs);
  715.  
  716.          if (error_protection)
  717.          {
  718.              encode_CRC(crc, &bs);
  719.          }
  720.  
  721.          II_encode_bit_alloc(bit_alloc, &fr_ps, &bs);
  722.          II_encode_scale(bit_alloc, scfsi, scalar, &fr_ps, &bs);
  723.          II_subband_quantization(scalar, sb_sample, j_scale,
  724.                   j_sample, bit_alloc, subband, &fr_ps);
  725.          II_sample_encoding(subband, bit_alloc, &fr_ps, &bs);
  726.          for (i=0;i<adb;i++)
  727.          {
  728.              bs.PutBit(0);
  729.          }
  730.       break;
  731.  
  732.       }
  733.       frameBits = bs.sstell() - sentBits;
  734.       
  735.       sentBits += frameBits;
  736.  
  737.     }
  738.  
  739.     bs.CloseBitStreamW();
  740.  
  741.     return TR_OK;
  742. }
  743.  
  744.  
  745. void low_pass(short* buffer,unsigned int length,unsigned int stereo,unsigned int mult)
  746. {
  747.     static short work_buffer[PCM_BUFFER + 8];
  748.     unsigned int i;
  749.     static bool init = false;
  750.     static short pass1[8], pass2[8], pass3[8], pass4[8];
  751.  
  752.     if(!init)
  753.     {
  754.         for(i=0; i<8; i++)
  755.         {
  756.             work_buffer[i] = 0; // first time thru we need 0's in first 8 samples
  757.             pass1[i] = pass2[i] = pass3[i] = pass4[i] = 0;
  758.         }
  759.         init = true;
  760.     }
  761.     
  762.     for(i=0; i<length; i++)
  763.         work_buffer[i+8] = buffer[i]; // copy samples to work buffer
  764.  
  765.     // retrieve first 8 samples from last time
  766.     for(i=0; i<8; i++)
  767.         work_buffer[i] = pass1[i];
  768.  
  769.     //save last 8 samples for next time
  770.     for(i=0; i<8; i++)
  771.         pass1[i] = buffer[length - 8 + i];
  772.  
  773.     filter( work_buffer, length, stereo, mult); //apply 1st order filter
  774.  
  775.     // a first order filter really doesn't roll off quickly enough, but if we
  776.     // apply it four times, it does. 
  777.  
  778.     for(i=0; i<8; i++)
  779.         work_buffer[i] = pass2[i];
  780.     for(i=0; i<8; i++)
  781.         pass2[i] = buffer[length - 8 + i];
  782.     filter( work_buffer, length, stereo, mult); //apply 1st order filter
  783.  
  784.     for(i=0; i<8; i++)
  785.         work_buffer[i] = pass3[i];
  786.     for(i=0; i<8; i++)
  787.         pass3[i] = buffer[length - 8 + i];
  788.     filter( work_buffer, length, stereo, mult); //apply 1st order filter
  789.  
  790.     for(i=0; i<8; i++)
  791.         work_buffer[i] = pass4[i];
  792.     for(i=0; i<8; i++)
  793.         pass4[i] = buffer[length - 8 + i];
  794.     filter( work_buffer, length, stereo, mult); //apply 1st order filter
  795.  
  796.     for(i=0; i<length; i++)
  797.         buffer[i] = work_buffer [i+8];
  798. }
  799.  
  800. void filter(short* work_buffer,unsigned int length,unsigned int stereo,unsigned int mult)
  801. {
  802.     short temp_buffer[PCM_BUFFER];
  803.     unsigned int i;
  804.  
  805.     if(stereo)
  806.     {
  807.         if(mult == 2)
  808.         {
  809.             //stereo at 22050
  810.             for(i=0; i<length; i++)
  811.                 temp_buffer[i] = (short)(0.612626*work_buffer[i+8] +
  812.                                  0.375311*work_buffer[i+6]);
  813.         }
  814.         else
  815.         {
  816.             //stereo at 11025
  817.             for(i=0; i<length; i++)
  818.                 temp_buffer[i] = (short)(0.516851*work_buffer[i+8] +
  819.                                  0.267135*work_buffer[i+6] +
  820.                                  0.138069*work_buffer[i+4] +
  821.                                  0.071361*work_buffer[i+2]);
  822.         }
  823.     }
  824.     else // mono
  825.     {
  826.         if(mult == 2)
  827.         {
  828.             //mono at 22050
  829.             for (i=0; i<length; i++)
  830.                 temp_buffer[i] = (short)(0.612626*work_buffer[i+8] +
  831.                                  0.375311*work_buffer[i+7]);
  832.         }
  833.         else
  834.         {
  835.             //mono at 11025
  836.             for (i=0; i<length; i++)
  837.                 temp_buffer[i] = (short)(0.516851*work_buffer[i+8] +
  838.                                  0.267135*work_buffer[i+7] +
  839.                                  0.138069*work_buffer[i+6] +
  840.                                  0.071361*work_buffer[i+5]);
  841.         }
  842.     }
  843.     for(i=0; i<length; i++)
  844.         work_buffer[i+8] = temp_buffer[i];
  845. }
  846.  
  847. /************************************************************************/
  848. /*
  849. /* read_samples()
  850. /*
  851. /* PURPOSE:  reads the PCM samples from avi file to the buffer
  852. /*
  853. /* Restrictions: only works with uncompressed 8 & 16 bit audio at
  854. /*               at 11.025, 22.05, and 44.1Khz sample rate
  855. /*
  856. /*  SEMANTICS:
  857. /* Reads #samples_read# number of shorts from #pAudioStream# avi file
  858. /* into #sample_buffer[]#. If 8 bit, data is expanded to 16 bit.
  859. /* If sample rate is 11.025 or 22.05 Khz, then duplicate (or quadruple)
  860. /* samples and apply low pass filter. Returns the number of samples read.
  861. /*
  862. /************************************************************************/
  863. static unsigned long read_samples(short sample_buffer[PCM_BUFFER],
  864.                                  const long num_samples,
  865.                                  const long frame_size,
  866.                                  bool* error)
  867. {
  868.     long samples_read, written,nsamples;
  869.     static unsigned long samples_to_read = num_samples;
  870.     long avi_samples;
  871.     int result;
  872.     int i;
  873.     short *dest, *source;
  874.     unsigned char *csource;
  875.  
  876.     if(g_nBytesProcessed == num_samples)
  877.     {
  878.         if(error!=NULL)
  879.             *error = true;
  880.         return 0;
  881.     }
  882.     if(error!=NULL)
  883.         *error = false;
  884.     
  885.     if (samples_to_read >= frame_size)
  886.         samples_read = frame_size;
  887.     else
  888.         samples_read = samples_to_read;
  889.  
  890.     if (g_stWavFormat.nChannels == 2)
  891.         avi_samples = samples_read/2; // stereo - request half as many avi samples!
  892.     else
  893.         avi_samples = samples_read;
  894.  
  895.     if(g_stWavFormat.nSamplesPerSec == 22050)
  896.         avi_samples = avi_samples/2; // will have to double samples
  897.  
  898.     if(g_stWavFormat.nSamplesPerSec == 11025)
  899.         avi_samples = avi_samples/4; // will have to quadruple samples
  900.  
  901.     result=-1; // See below
  902.     if (avi_samples==0)
  903.         nsamples=0;
  904.     else
  905.         result = AVIStreamRead(g_pAudioStream,
  906.                     g_nLastSample, avi_samples,
  907.                     sample_buffer,
  908.                     (PCM_BUFFER)*sizeof(short),
  909.                     &written, &nsamples);
  910.     
  911.     g_nLastSample += nsamples;
  912.  
  913.     if(avi_samples != nsamples)
  914.     {
  915.         csource = (unsigned char*)sample_buffer;
  916.         for(i = nsamples; i < avi_samples; i++)
  917.         {
  918.             //bad_audio_count++;
  919.             if(g_stWavFormat.wBitsPerSample == 8)
  920.             {
  921.                 *csource++ = 128;
  922.                 i++;
  923.             }
  924.             else
  925.             {
  926.                 *csource++ = 0;
  927.                 *csource++ = 0;
  928.             }
  929.         }
  930.     }
  931.  
  932. // Check, if there are no more samples to read and no new audio-files to open
  933. // if samples_to_read==0 and result!=0 we have to skip the audio manipulation
  934. // section to prevent running out of the buffer area. Apr. 10, 2000
  935. // Volker Bartheld (entwicklung@reetcom.de)
  936.  
  937.     if(samples_to_read&&!result)
  938.     {
  939.       samples_to_read -= samples_read;
  940.  
  941.         if(g_stWavFormat.wBitsPerSample == 8)
  942.         {
  943.             dest = sample_buffer + written - 1;
  944.             csource = ((unsigned char*)(sample_buffer)) + written - 1;
  945.             // audio is 8 bit, we have to expand it to 16 bit
  946.             for(i = 0; i < written; i++)
  947.                 *dest-- = (*csource-- - 128) << 8;
  948.             written = written * 2;
  949.         }
  950.  
  951.         if((g_stWavFormat.nSamplesPerSec == 22050)
  952.             &&(g_stWavFormat.nChannels == 1))
  953.         {
  954.             // we have to double up the samples
  955.             dest = sample_buffer + PCM_BUFFER - 1;
  956.             source = sample_buffer + PCM_BUFFER/2 - 1;
  957.             for(i = 0; i < PCM_BUFFER/2; i++)
  958.             {
  959.                 *dest-- = *source;
  960.                 *dest-- = *source--;
  961.             }
  962.             low_pass(sample_buffer, samples_read, 0, 2);
  963.         }
  964.  
  965.         if((g_stWavFormat.nSamplesPerSec == 22050)
  966.             &&(g_stWavFormat.nChannels == 2))
  967.         {
  968.             // we have to double up the samples
  969.             dest = sample_buffer + PCM_BUFFER - 1;
  970.             source = sample_buffer + PCM_BUFFER/2 - 1;
  971.             for(i = 0; i < PCM_BUFFER/4; i++)
  972.             {
  973.                 *dest = *source;
  974.                 *(dest - 2) = *source--;
  975.                 dest--;
  976.                 *dest = *source;
  977.                 *(dest - 2) = *source--;
  978.                 dest = dest - 3;
  979.             }
  980.             low_pass(sample_buffer, samples_read, 1, 2);
  981.         }
  982.  
  983.         if((g_stWavFormat.nSamplesPerSec == 11025)
  984.             &&(g_stWavFormat.nChannels == 1))
  985.         {
  986.             // we have to quadruple samples
  987.             dest = sample_buffer + PCM_BUFFER - 1;
  988.             source = sample_buffer + PCM_BUFFER/4 - 1;
  989.             for(i = 0; i < PCM_BUFFER/4; i++)
  990.             {
  991.                 *dest-- = *source;
  992.                 *dest-- = *source;
  993.                 *dest-- = *source;
  994.                 *dest-- = *source--;
  995.             }
  996.             low_pass(sample_buffer, samples_read, 0, 4);
  997.         }
  998.  
  999.         if((g_stWavFormat.nSamplesPerSec == 11025)
  1000.             &&(g_stWavFormat.nChannels == 2))
  1001.         {
  1002.             // we have to quadruple samples
  1003.             dest = sample_buffer + PCM_BUFFER - 1;
  1004.             source = sample_buffer + PCM_BUFFER/4 - 1;
  1005.             for(i = 0; i < PCM_BUFFER/8; i++)
  1006.             {
  1007.                 *dest = *source;
  1008.                 *(dest - 2) = *source;
  1009.                 *(dest - 4) = *source;
  1010.                 *(dest - 6) = *source--;
  1011.                 dest--;
  1012.                 *dest = *source;
  1013.                 *(dest - 2) = *source;
  1014.                 *(dest - 4) = *source;
  1015.                 *(dest - 6) = *source--;
  1016.                 dest = dest - 7;
  1017.             }
  1018.             low_pass(sample_buffer, samples_read, 1, 4);
  1019.         }
  1020.  
  1021.         if (samples_read < frame_size && samples_read > 0)
  1022.         {
  1023.             //printf("Insufficient PCM input for one frame - fillout with zeros\n");
  1024.             for (; samples_read < frame_size; sample_buffer[samples_read++] = 0);
  1025.             samples_to_read = 0;
  1026.         }
  1027.         g_nBytesProcessed = samples_to_read;
  1028.  
  1029.         return samples_read;
  1030.     }
  1031.     else
  1032.         return 0;  // No more samples to read from AVI-File
  1033. }
  1034.  
  1035. /************************************************************************/
  1036. /*
  1037. /* get_audio()
  1038. /*
  1039. /* PURPOSE:  reads a frame of audio data from a file to the buffer,
  1040. /*   aligns the data for future processing, and separates the
  1041. /*   left and right channels
  1042. /*
  1043. /*  SEMANTICS:
  1044. /* Calls read_samples() to read a frame of audio data from filepointer
  1045. /* #musicin# to #insampl[]#.  The data is shifted to make sure the data
  1046. /* is centered for the 1024pt window to be used by the psychoacoustic model,
  1047. /* and to compensate for the 256 sample delay from the filter bank. For
  1048. /* stereo, the channels are also demultiplexed into #buffer[0][]# and
  1049. /* #buffer[1][]#
  1050. /*
  1051. /************************************************************************/
  1052.  
  1053. static inline unsigned char get_audio(short buffer[2][1152],unsigned long num_samples,
  1054.                                     int stereo,int lay)
  1055. {
  1056.    int j;
  1057.    short insamp[2304];
  1058.    unsigned long samples_read;
  1059.    bool error = false;
  1060.  
  1061.    if (lay == 0)
  1062.    {
  1063.       if(stereo == 2)
  1064.       { /* layer 1, stereo */
  1065.          samples_read = read_samples(insamp, num_samples,
  1066.                                      (unsigned long) 768,
  1067.                                      &error);
  1068.          for(j=0;j<448;j++)
  1069.          {
  1070.             if(j<64)
  1071.             {
  1072.                buffer[0][j] = buffer[0][j+384];
  1073.                buffer[1][j] = buffer[1][j+384];
  1074.             }
  1075.             else
  1076.             {
  1077.                buffer[0][j] = insamp[2*j-128];
  1078.                buffer[1][j] = insamp[2*j-127];
  1079.             }
  1080.          }
  1081.       }
  1082.       else
  1083.       { /* layer 1, mono */
  1084.          samples_read = read_samples(insamp, num_samples,
  1085.                                      (unsigned long) 384,
  1086.                                      &error);
  1087.          for(j=0;j<448;j++)
  1088.          {
  1089.             if(j<64)
  1090.             {
  1091.                buffer[0][j] = buffer[0][j+384];
  1092.                buffer[1][j] = 0;
  1093.             }
  1094.             else
  1095.             {
  1096.                buffer[0][j] = insamp[j-64];
  1097.                buffer[1][j] = 0;
  1098.             }
  1099.          }
  1100.       }
  1101.    }
  1102.    else
  1103.    {
  1104.       if(stereo == 2)
  1105.       { /* layer 2 (or 3), stereo */
  1106.          samples_read = read_samples(insamp, num_samples,
  1107.                                      (unsigned long) 2304,
  1108.                                      &error);
  1109.          for(j=0;j<1152;j++)
  1110.          {
  1111.             buffer[0][j] = insamp[2*j];
  1112.             buffer[1][j] = insamp[2*j+1];
  1113.          }
  1114.       }
  1115.       else
  1116.       { /* layer 2 (or 3), mono */
  1117.          samples_read = read_samples(insamp, num_samples,
  1118.                                      (unsigned long) 1152,
  1119.                                      &error);
  1120.          for(j=0;j<1152;j++)
  1121.          {
  1122.             buffer[0][j] = insamp[j];
  1123.             buffer[1][j] = 0;
  1124.          }
  1125.       }
  1126.    }
  1127.    if(samples_read>0)
  1128.    {
  1129.        return 0;
  1130.    }
  1131.    else if(error)
  1132.    {
  1133.        return 1;
  1134.    }
  1135.    return 2;
  1136. }
  1137.  
  1138. /************************************************************************/
  1139. /*
  1140. /* window_subband()
  1141. /*
  1142. /* PURPOSE:  Overlapping window on PCM samples
  1143. /*
  1144. /* SEMANTICS:
  1145. /* 32 16-bit pcm samples are scaled to fractional 2's complement and
  1146. /* concatenated to the end of the window buffer #x#. The updated window
  1147. /* buffer #x# is then windowed by the analysis window #c# to produce the
  1148. /* windowed sample #z#
  1149. /*
  1150. /************************************************************************/
  1151.  
  1152. static void window_subband(short** buffer,double z[],int k)
  1153. {
  1154.     static double x[2][HAN_SIZE];
  1155.     int i, j;
  1156.     static off[2] = {0,0};
  1157.     static bool init = false;
  1158.     static const double c[HAN_SIZE] =
  1159.     {
  1160.         0.000000000, -0.000000477, -0.000000477, -0.000000477, 
  1161.         -0.000000477, -0.000000477, -0.000000477, -0.000000954, 
  1162.         -0.000000954, -0.000000954, -0.000000954, -0.000001431, 
  1163.         -0.000001431, -0.000001907, -0.000001907, -0.000002384, 
  1164.         -0.000002384, -0.000002861, -0.000003338, -0.000003338, 
  1165.         -0.000003815, -0.000004292, -0.000004768, -0.000005245, 
  1166.         -0.000006199, -0.000006676, -0.000007629, -0.000008106, 
  1167.         -0.000009060, -0.000010014, -0.000011444, -0.000012398, 
  1168.         -0.000013828, -0.000014782, -0.000016689, -0.000018120, 
  1169.         -0.000019550, -0.000021458, -0.000023365, -0.000025272, 
  1170.         -0.000027657, -0.000030041, -0.000032425, -0.000034809, 
  1171.         -0.000037670, -0.000040531, -0.000043392, -0.000046253, 
  1172.         -0.000049591, -0.000052929, -0.000055790, -0.000059605, 
  1173.         -0.000062943, -0.000066280, -0.000070095, -0.000073433, 
  1174.         -0.000076771, -0.000080585, -0.000083923, -0.000087261, 
  1175.         -0.000090599, -0.000093460, -0.000096321, -0.000099182, 
  1176.         0.000101566, 0.000103951, 0.000105858, 0.000107288, 
  1177.         0.000108242, 0.000108719, 0.000108719, 0.000108242, 
  1178.         0.000106812, 0.000105381, 0.000102520, 0.000099182, 
  1179.         0.000095367, 0.000090122, 0.000084400, 0.000077724, 
  1180.         0.000069618, 0.000060558, 0.000050545, 0.000039577, 
  1181.         0.000027180, 0.000013828, -0.000000954, -0.000017166, 
  1182.         -0.000034332, -0.000052929, -0.000072956, -0.000093937, 
  1183.         -0.000116348, -0.000140190, -0.000165462, -0.000191212, 
  1184.         -0.000218868, -0.000247478, -0.000277042, -0.000307560, 
  1185.         -0.000339031, -0.000371456, -0.000404358, -0.000438213, 
  1186.         -0.000472546, -0.000507355, -0.000542164, -0.000576973, 
  1187.         -0.000611782, -0.000646591, -0.000680923, -0.000714302, 
  1188.         -0.000747204, -0.000779152, -0.000809669, -0.000838757, 
  1189.         -0.000866413, -0.000891685, -0.000915051, -0.000935555, 
  1190.         -0.000954151, -0.000968933, -0.000980854, -0.000989437, 
  1191.         -0.000994205, -0.000995159, -0.000991821, -0.000983715, 
  1192.         0.000971317, 0.000953674, 0.000930786, 0.000902653, 
  1193.         0.000868797, 0.000829220, 0.000783920, 0.000731945, 
  1194.         0.000674248, 0.000610352, 0.000539303, 0.000462532, 
  1195.         0.000378609, 0.000288486, 0.000191689, 0.000088215, 
  1196.         -0.000021458, -0.000137329, -0.000259876, -0.000388145, 
  1197.         -0.000522137, -0.000661850, -0.000806808, -0.000956535, 
  1198.         -0.001111031, -0.001269817, -0.001432419, -0.001597881, 
  1199.         -0.001766682, -0.001937389, -0.002110004, -0.002283096, 
  1200.         -0.002457142, -0.002630711, -0.002803326, -0.002974033, 
  1201.         -0.003141880, -0.003306866, -0.003467083, -0.003622532, 
  1202.         -0.003771782, -0.003914356, -0.004048824, -0.004174709, 
  1203.         -0.004290581, -0.004395962, -0.004489899, -0.004570484, 
  1204.         -0.004638195, -0.004691124, -0.004728317, -0.004748821, 
  1205.         -0.004752159, -0.004737377, -0.004703045, -0.004649162, 
  1206.         -0.004573822, -0.004477024, -0.004357815, -0.004215240, 
  1207.         -0.004049301, -0.003858566, -0.003643036, -0.003401756, 
  1208.         0.003134727, 0.002841473, 0.002521515, 0.002174854, 
  1209.         0.001800537, 0.001399517, 0.000971317, 0.000515938, 
  1210.         0.000033379, -0.000475883, -0.001011848, -0.001573563, 
  1211.         -0.002161503, -0.002774239, -0.003411293, -0.004072189, 
  1212.         -0.004756451, -0.005462170, -0.006189346, -0.006937027, 
  1213.         -0.007703304, -0.008487225, -0.009287834, -0.010103703, 
  1214.         -0.010933399, -0.011775017, -0.012627602, -0.013489246, 
  1215.         -0.014358521, -0.015233517, -0.016112804, -0.016994476, 
  1216.         -0.017876148, -0.018756866, -0.019634247, -0.020506859, 
  1217.         -0.021372318, -0.022228718, -0.023074150, -0.023907185, 
  1218.         -0.024725437, -0.025527000, -0.026310921, -0.027073860, 
  1219.         -0.027815342, -0.028532982, -0.029224873, -0.029890060, 
  1220.         -0.030526638, -0.031132698, -0.031706810, -0.032248020, 
  1221.         -0.032754898, -0.033225536, -0.033659935, -0.034055710, 
  1222.         -0.034412861, -0.034730434, -0.035007000, -0.035242081, 
  1223.         -0.035435200, -0.035586357, -0.035694122, -0.035758972, 
  1224.         0.035780907, 0.035758972, 0.035694122, 0.035586357, 
  1225.         0.035435200, 0.035242081, 0.035007000, 0.034730434, 
  1226.         0.034412861, 0.034055710, 0.033659935, 0.033225536, 
  1227.         0.032754898, 0.032248020, 0.031706810, 0.031132698, 
  1228.         0.030526638, 0.029890060, 0.029224873, 0.028532982, 
  1229.         0.027815342, 0.027073860, 0.026310921, 0.025527000, 
  1230.         0.024725437, 0.023907185, 0.023074150, 0.022228718, 
  1231.         0.021372318, 0.020506859, 0.019634247, 0.018756866, 
  1232.         0.017876148, 0.016994476, 0.016112804, 0.015233517, 
  1233.         0.014358521, 0.013489246, 0.012627602, 0.011775017, 
  1234.         0.010933399, 0.010103703, 0.009287834, 0.008487225, 
  1235.         0.007703304, 0.006937027, 0.006189346, 0.005462170, 
  1236.         0.004756451, 0.004072189, 0.003411293, 0.002774239, 
  1237.         0.002161503, 0.001573563, 0.001011848, 0.000475883, 
  1238.         -0.000033379, -0.000515938, -0.000971317, -0.001399517, 
  1239.         -0.001800537, -0.002174854, -0.002521515, -0.002841473, 
  1240.         0.003134727, 0.003401756, 0.003643036, 0.003858566, 
  1241.         0.004049301, 0.004215240, 0.004357815, 0.004477024, 
  1242.         0.004573822, 0.004649162, 0.004703045, 0.004737377, 
  1243.         0.004752159, 0.004748821, 0.004728317, 0.004691124, 
  1244.         0.004638195, 0.004570484, 0.004489899, 0.004395962, 
  1245.         0.004290581, 0.004174709, 0.004048824, 0.003914356, 
  1246.         0.003771782, 0.003622532, 0.003467083, 0.003306866, 
  1247.         0.003141880, 0.002974033, 0.002803326, 0.002630711, 
  1248.         0.002457142, 0.002283096, 0.002110004, 0.001937389, 
  1249.         0.001766682, 0.001597881, 0.001432419, 0.001269817, 
  1250.         0.001111031, 0.000956535, 0.000806808, 0.000661850, 
  1251.         0.000522137, 0.000388145, 0.000259876, 0.000137329, 
  1252.         0.000021458, -0.000088215, -0.000191689, -0.000288486, 
  1253.         -0.000378609, -0.000462532, -0.000539303, -0.000610352, 
  1254.         -0.000674248, -0.000731945, -0.000783920, -0.000829220, 
  1255.         -0.000868797, -0.000902653, -0.000930786, -0.000953674, 
  1256.         0.000971317, 0.000983715, 0.000991821, 0.000995159, 
  1257.         0.000994205, 0.000989437, 0.000980854, 0.000968933, 
  1258.         0.000954151, 0.000935555, 0.000915051, 0.000891685, 
  1259.         0.000866413, 0.000838757, 0.000809669, 0.000779152, 
  1260.         0.000747204, 0.000714302, 0.000680923, 0.000646591, 
  1261.         0.000611782, 0.000576973, 0.000542164, 0.000507355, 
  1262.         0.000472546, 0.000438213, 0.000404358, 0.000371456, 
  1263.         0.000339031, 0.000307560, 0.000277042, 0.000247478, 
  1264.         0.000218868, 0.000191212, 0.000165462, 0.000140190, 
  1265.         0.000116348, 0.000093937, 0.000072956, 0.000052929, 
  1266.         0.000034332, 0.000017166, 0.000000954, -0.000013828, 
  1267.         -0.000027180, -0.000039577, -0.000050545, -0.000060558, 
  1268.         -0.000069618, -0.000077724, -0.000084400, -0.000090122, 
  1269.         -0.000095367, -0.000099182, -0.000102520, -0.000105381, 
  1270.         -0.000106812, -0.000108242, -0.000108719, -0.000108719, 
  1271.         -0.000108242, -0.000107288, -0.000105858, -0.000103951,
  1272.         0.000101566, 0.000099182, 0.000096321, 0.000093460, 
  1273.         0.000090599, 0.000087261, 0.000083923, 0.000080585, 
  1274.         0.000076771, 0.000073433, 0.000070095, 0.000066280, 
  1275.         0.000062943, 0.000059605, 0.000055790, 0.000052929, 
  1276.         0.000049591, 0.000046253, 0.000043392, 0.000040531, 
  1277.         0.000037670, 0.000034809, 0.000032425, 0.000030041, 
  1278.         0.000027657, 0.000025272, 0.000023365, 0.000021458, 
  1279.         0.000019550, 0.000018120, 0.000016689, 0.000014782, 
  1280.         0.000013828, 0.000012398, 0.000011444, 0.000010014, 
  1281.         0.000009060, 0.000008106, 0.000007629, 0.000006676, 
  1282.         0.000006199, 0.000005245, 0.000004768, 0.000004292, 
  1283.         0.000003815, 0.000003338, 0.000003338, 0.000002861, 
  1284.         0.000002384, 0.000002384, 0.000001907, 0.000001907, 
  1285.         0.000001431, 0.000001431, 0.000000954, 0.000000954, 
  1286.         0.000000954, 0.000000954, 0.000000477, 0.000000477, 
  1287.         0.000000477, 0.000000477, 0.000000477, 0.000000477
  1288.     };
  1289.     if (!init)
  1290.     {
  1291.         for (i=0;i<2;i++)
  1292.             for (j=0;j<HAN_SIZE;j++)
  1293.                 x[i][j] = 0;
  1294.         init = true;
  1295.     }
  1296.  
  1297.     /* replace 32 oldest samples with 32 new samples */
  1298.     for (i=0;i<32;i++)
  1299.         x[k][31-i+off[k]] = (double) *(*buffer)++/SCALE;
  1300.     /* shift samples into proper window positions */
  1301.     for (i=0;i<HAN_SIZE;i++)
  1302.         z[i] = x[k][(i+off[k])&(HAN_SIZE-1)] * c[i];
  1303.     off[k] += 480;              /*offset is modulo (HAN_SIZE-1)*/
  1304.     off[k] &= HAN_SIZE-1;
  1305.  
  1306. }
  1307.  
  1308. /************************************************************************/
  1309. /*
  1310. /* create_ana_filter()
  1311. /*
  1312. /* PURPOSE:  Calculates the analysis filter bank coefficients
  1313. /*
  1314. /* SEMANTICS:
  1315. /* Calculates the analysis filterbank coefficients and rounds to the
  1316. /* 9th decimal place accuracy of the filterbank tables in the ISO
  1317. /* document.  The coefficients are stored in #filter#
  1318. /*
  1319. /************************************************************************/
  1320.  
  1321. static inline void create_ana_filter(double filter[SBLIMIT][64])
  1322. {
  1323.    register int i,k;
  1324.  
  1325.    for (i=0; i<32; i++)
  1326.       for (k=0; k<64; k++)
  1327.       {
  1328.           if ((filter[i][k] = 1e9*cos(((double)((2*i+1)*(16-k)))*PI64)) >= 0)
  1329.              modf(filter[i][k]+0.5, &filter[i][k]);
  1330.           else
  1331.              modf(filter[i][k]-0.5, &filter[i][k]);
  1332.           filter[i][k] *= 1e-9;
  1333.       }
  1334. }
  1335.  
  1336. /************************************************************************/
  1337. /*
  1338. /* filter_subband()
  1339. /*
  1340. /* PURPOSE:  Calculates the analysis filter bank coefficients
  1341. /*
  1342. /* SEMANTICS:
  1343. /*      The windowed samples #z# is filtered by the digital filter matrix #m#
  1344. /* to produce the subband samples #s#. This done by first selectively
  1345. /* picking out values from the windowed samples, and then multiplying
  1346. /* them by the filter matrix, producing 32 subband samples.
  1347. /*
  1348. /************************************************************************/
  1349.  
  1350. static void filter_subband(double z[HAN_SIZE],double s[SBLIMIT])
  1351. {
  1352.    double y[64];
  1353.    int i,j;
  1354.    static bool init = false;
  1355.    static double m[SBLIMIT][64];
  1356.    long SIZE_OF_MM;
  1357.    SIZE_OF_MM = SBLIMIT*64;
  1358.    SIZE_OF_MM *= 8;
  1359.    if(!init)
  1360.    {
  1361.        create_ana_filter(m);
  1362.        init = true;
  1363.    }
  1364.    for (i=0;i<64;i++)
  1365.        for (j=0, y[i] = 0;j<8;j++)
  1366.            y[i] += z[i+64*j];
  1367.    for (i=0;i<SBLIMIT;i++)
  1368.        for (j=0, s[i]= 0;j<64;j++)
  1369.            s[i] += m[i][j] * y[j];
  1370. }
  1371.  
  1372. /************************************************************************/
  1373. /*
  1374. /* encode_info()
  1375. /*
  1376. /* PURPOSE:  Puts the syncword and header information on the output
  1377. /* bitstream.
  1378. /*
  1379. /************************************************************************/
  1380.  
  1381. static void encode_info(frame_params* fr_ps,BitStreamStruct* bs)
  1382. {
  1383.     layer *info = fr_ps->header;
  1384.  
  1385.     bs->PutBitStream(0xfff,12); 
  1386.     //putabits(bs,0xfff,12);                    /* syncword 12 bits */
  1387.     bs->PutBit(info->version);
  1388.     //put1bit(bs,info->version);               /* ID        1 bit  */
  1389.     bs->PutBitStream(3-info->lay,2);
  1390.     //putabits(bs,4-info->lay,2);               /* layer     2 bits */
  1391.     bs->PutBit(!info->error_protection);
  1392.     //put1bit(bs,!info->error_protection);     /* bit set => no err prot */
  1393.     bs->PutBitStream(info->bitrate_index,4);
  1394.     // putabits(bs,info->bitrate_index,4);
  1395.     bs->PutBitStream(info->sampling_frequency,2);
  1396.     //putabits(bs,info->sampling_frequency,2);
  1397.     bs->PutBit(info->padding);
  1398.     //put1bit(bs,info->padding);
  1399.     bs->PutBit(info->extension);
  1400.     //put1bit(bs,info->extension);             /* private_bit */
  1401.     bs->PutBitStream(info->mode,2);
  1402.     //putabits(bs,info->mode,2);
  1403.     bs->PutBitStream(info->mode_ext,2);
  1404.     //putabits(bs,info->mode_ext,2);
  1405.     bs->PutBit(info->copyright);
  1406.     //put1bit(bs,info->copyright);
  1407.     bs->PutBit(info->original);
  1408.     //put1bit(bs,info->original);
  1409.     bs->PutBitStream(info->emphasis,2);
  1410.     //putabits(bs,info->emphasis,2);
  1411. }
  1412. /************************************************************************/
  1413. /*
  1414. /* I_combine_LR    (Layer I)
  1415. /* II_combine_LR   (Layer II)
  1416. /*
  1417. /* PURPOSE:Combines left and right channels into a mono channel
  1418. /*
  1419. /* SEMANTICS:  The average of left and right subband samples is put into
  1420. /* #joint_sample#
  1421. /*
  1422. /* Layer I and II differ in frame length and # subbands used
  1423. /*
  1424. /************************************************************************/
  1425.  
  1426. static inline void I_combine_LR(double sb_sample[2][3][SCALE_BLOCK][SBLIMIT],
  1427.                            double joint_sample[3][SCALE_BLOCK][SBLIMIT])
  1428. {   /* make a filtered mono for joint stereo */
  1429.     int sb, smp;
  1430.  
  1431.    for(sb = 0; sb<SBLIMIT; ++sb)
  1432.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  1433.         joint_sample[0][smp][sb] = .5 *
  1434.                     (sb_sample[0][0][smp][sb] + sb_sample[1][0][smp][sb]);
  1435. }
  1436.  
  1437. static inline void II_combine_LR(double sb_sample[2][3][SCALE_BLOCK][SBLIMIT],
  1438.                                  double joint_sample[3][SCALE_BLOCK][SBLIMIT],
  1439.                                  int sblimit)
  1440. {
  1441.     /* make a filtered mono for joint stereo */
  1442.    int sb, smp, sufr;
  1443.  
  1444.    for(sb = 0; sb<sblimit; ++sb)
  1445.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  1446.          for(sufr = 0; sufr<3; ++sufr)
  1447.             joint_sample[sufr][smp][sb] = .5 * (sb_sample[0][sufr][smp][sb]
  1448.                                            + sb_sample[1][sufr][smp][sb]);
  1449. }
  1450.  
  1451. /************************************************************************
  1452. /*
  1453. /* I_scale_factor_calc     (Layer I)
  1454. /* II_scale_factor_calc    (Layer II)
  1455. /*
  1456. /* PURPOSE:For each subband, calculate the scale factor for each set
  1457. /* of the 12 subband samples
  1458. /*
  1459. /* SEMANTICS:  Pick the scalefactor #multiple[]# just larger than the
  1460. /* absolute value of the peak subband sample of 12 samples,
  1461. /* and store the corresponding scalefactor index in #scalar#.
  1462. /*
  1463. /* Layer II has three sets of 12-subband samples for a given
  1464. /* subband.
  1465. /*
  1466. /************************************************************************/
  1467.  
  1468. static void I_scale_factor_calc(double sb_sample[][3][SCALE_BLOCK][SBLIMIT],unsigned int scalar[][3][SBLIMIT],int stereo)
  1469. {
  1470.    int i,j, k;
  1471.    double s[SBLIMIT];
  1472.  
  1473.    for (k=0;k<stereo;k++)
  1474.    {
  1475.      for (i=0;i<SBLIMIT;i++)
  1476.        for (j=1, s[i] = fabs(sb_sample[k][0][0][i]);j<SCALE_BLOCK;j++)
  1477.          if (fabs(sb_sample[k][0][j][i]) > s[i])
  1478.             s[i] = fabs(sb_sample[k][0][j][i]);
  1479.  
  1480.      for (i=0;i<SBLIMIT;i++)
  1481.        for (j=SCALE_RANGE-2,scalar[k][0][i]=0;j>=0;j--) /* $A 6/16/92 */
  1482.          if (s[i] <= g_fMultiple[j])
  1483.          {
  1484.             scalar[k][0][i] = j;
  1485.             break;
  1486.          }
  1487.    }
  1488. }
  1489.  
  1490. /******************************** Layer II ******************************/
  1491.  
  1492. static void II_scale_factor_calc(double sb_sample[][3][SCALE_BLOCK][SBLIMIT],
  1493.                                  unsigned int scalar[][3][SBLIMIT],
  1494.                                  int stereo,int sblimit)
  1495. {
  1496.     int i,j, k,t;
  1497.     double s[SBLIMIT];
  1498.  
  1499.     for (k=0;k<stereo;k++) for (t=0;t<3;t++)
  1500.     {
  1501.         for (i=0;i<sblimit;i++)
  1502.             for (j=1, s[i] = fabs(sb_sample[k][t][0][i]);j<SCALE_BLOCK;j++)
  1503.                 if (fabs(sb_sample[k][t][j][i]) > s[i])
  1504.                     s[i] = fabs(sb_sample[k][t][j][i]);
  1505.  
  1506.         for (i=0;i<sblimit;i++)
  1507.             for (j=SCALE_RANGE-2,scalar[k][t][i]=0;j>=0;j--)    /* $A 6/16/92 */
  1508.                 if (s[i] <= g_fMultiple[j])
  1509.                 {
  1510.                     scalar[k][t][i] = j;
  1511.                     break;
  1512.                 }
  1513.         for (i=sblimit;i<SBLIMIT;i++)
  1514.             scalar[k][t][i] = SCALE_RANGE-1;
  1515.     }
  1516.  
  1517. }
  1518.  
  1519. /************************************************************************
  1520. /*
  1521. /* pick_scale  (Layer II)
  1522. /*
  1523. /* PURPOSE:For each subband, puts the smallest scalefactor of the 3
  1524. /* associated with a frame into #max_sc#.  This is used
  1525. /* used by Psychoacoustic Model I.
  1526. /* (I would recommend changin max_sc to min_sc)
  1527. /*
  1528. /************************************************************************/
  1529.  
  1530. static inline void pick_scale(unsigned int scalar[2][3][SBLIMIT],
  1531.                               frame_params* fr_ps,
  1532.                               double max_sc[2][SBLIMIT])
  1533. {
  1534.     int i,j,k;
  1535.     unsigned int max;
  1536.     const int stereo  = fr_ps->stereo;
  1537.     const int sblimit = fr_ps->sblimit;
  1538.  
  1539.     for (k=0;k<stereo;k++)
  1540.         for (i=0;i<sblimit;max_sc[k][i] = g_fMultiple[max],i++)
  1541.             for (j=1, max = scalar[k][0][i];j<3;j++)
  1542.                 if (max > scalar[k][j][i])
  1543.                     max = scalar[k][j][i];
  1544.     for (i=sblimit;i<SBLIMIT;i++)
  1545.         max_sc[0][i] = max_sc[1][i] = 1E-20;
  1546. }
  1547.  
  1548. /************************************************************************
  1549. /*
  1550. /* put_scale   (Layer I)
  1551. /*
  1552. /* PURPOSE:Sets #max_sc# to the scalefactor index in #scalar.
  1553. /* This is used by Psychoacoustic Model I
  1554. /*
  1555. /************************************************************************/
  1556.  
  1557. static inline void put_scale(unsigned int scalar[][3][SBLIMIT],
  1558.                              const frame_params* fr_ps,
  1559.                              double max_sc[2][SBLIMIT])
  1560. {
  1561.    int i,k;
  1562.    const int stereo  = fr_ps->stereo;
  1563.    const int sblimit = fr_ps->sblimit;
  1564.  
  1565.    for (k=0;k<stereo;k++)
  1566.        for (i=0;i<SBLIMIT;i++)
  1567.            max_sc[k][i] = g_fMultiple[scalar[k][0][i]];
  1568. }
  1569.  
  1570. /************************************************************************
  1571. /*
  1572. /* II_transmission_pattern (Layer II only)
  1573. /*
  1574. /* PURPOSE:For a given subband, determines whether to send 1, 2, or
  1575. /* all 3 of the scalefactors, and fills in the scalefactor
  1576. /* select information accordingly
  1577. /*
  1578. /* SEMANTICS:  The subbands and channels are classified based on how much
  1579. /* the scalefactors changes over its three values (corresponding
  1580. /* to the 3 sets of 12 samples per subband).  The classification
  1581. /* will send 1 or 2 scalefactors instead of three if the scalefactors
  1582. /* do not change much.  The scalefactor select information,
  1583. /* #scfsi#, is filled in accordingly.
  1584. /*
  1585. /************************************************************************/
  1586.  
  1587. static inline void II_transmission_pattern(unsigned int scalar[2][3][SBLIMIT],
  1588.                              unsigned int scfsi[2][SBLIMIT],
  1589.                              frame_params* fr_ps)
  1590. {
  1591.     const int stereo  = fr_ps->stereo;
  1592.     const int sblimit = fr_ps->sblimit;
  1593.     int dscf[2];
  1594.     int sclass[2],i,j,k;
  1595.     static int pattern[5][5] = {0x123, 0x122, 0x122, 0x133, 0x123,
  1596.                                 0x113, 0x111, 0x111, 0x444, 0x113,
  1597.                                 0x111, 0x111, 0x111, 0x333, 0x113,
  1598.                                 0x222, 0x222, 0x222, 0x333, 0x123,
  1599.                                 0x123, 0x122, 0x122, 0x133, 0x123};
  1600.  
  1601.     for (k=0;k<stereo;k++)
  1602.         for (i=0;i<sblimit;i++)
  1603.         {
  1604.             dscf[0] =  (scalar[k][0][i]-scalar[k][1][i]);
  1605.             dscf[1] =  (scalar[k][1][i]-scalar[k][2][i]);
  1606.             for (j=0;j<2;j++)
  1607.             {
  1608.                 if (dscf[j]<=-3)
  1609.                     sclass[j] = 0;
  1610.                 else if (dscf[j] > -3 && dscf[j] <0)
  1611.                     sclass[j] = 1;
  1612.                 else if (dscf[j] == 0)
  1613.                     sclass[j] = 2;
  1614.                 else if (dscf[j] > 0 && dscf[j] < 3)
  1615.                     sclass[j] = 3;
  1616.                 else sclass[j] = 4;
  1617.             }
  1618.             switch (pattern[sclass[0]][sclass[1]])
  1619.             {
  1620.             case 0x123 :
  1621.                 scfsi[k][i] = 0;
  1622.                 break;
  1623.             case 0x122 :
  1624.                 scfsi[k][i] = 3;
  1625.                 scalar[k][2][i] = scalar[k][1][i];
  1626.                 break;
  1627.             case 0x133 :
  1628.                 scfsi[k][i] = 3;
  1629.                 scalar[k][1][i] = scalar[k][2][i];
  1630.                 break;
  1631.             case 0x113 :
  1632.                 scfsi[k][i] = 1;
  1633.                 scalar[k][1][i] = scalar[k][0][i];
  1634.                 break;
  1635.             case 0x111 :
  1636.                 scfsi[k][i] = 2;
  1637.                 scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  1638.                 break;
  1639.             case 0x222 :
  1640.                 scfsi[k][i] = 2;
  1641.                 scalar[k][0][i] = scalar[k][2][i] = scalar[k][1][i];
  1642.                 break;
  1643.             case 0x333 :
  1644.                 scfsi[k][i] = 2;
  1645.                 scalar[k][0][i] = scalar[k][1][i] = scalar[k][2][i];
  1646.                 break;
  1647.             case 0x444 :
  1648.                 scfsi[k][i] = 2;
  1649.                 if (scalar[k][0][i] > scalar[k][2][i])
  1650.                     scalar[k][0][i] = scalar[k][2][i];
  1651.                 scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  1652.         }
  1653.     }
  1654. }
  1655.  
  1656. /************************************************************************
  1657. /*
  1658. /* I_encode_scale  (Layer I)
  1659. /* II_encode_scale (Layer II)
  1660. /*
  1661. /* PURPOSE:The encoded scalar factor information is arranged and
  1662. /* queued into the output fifo to be transmitted.
  1663. /*
  1664. /* For Layer II, the three scale factors associated with
  1665. /* a given subband and channel are transmitted in accordance
  1666. /* with the scfsi, which is transmitted first.
  1667. /*
  1668. /************************************************************************/
  1669.  
  1670. static inline void I_encode_scale(
  1671.                     unsigned int scalar[2][3][SBLIMIT],
  1672.                     const unsigned int bit_alloc[2][SBLIMIT],
  1673.                     const frame_params* fr_ps,
  1674.                     BitStreamStruct* bs)
  1675. {
  1676.    const int stereo  = fr_ps->stereo;
  1677.    const int sblimit = fr_ps->sblimit;
  1678.    int i,j;
  1679.  
  1680.    for (i=0;i<SBLIMIT;i++)
  1681.        for (j=0;j<stereo;j++)
  1682.            if (bit_alloc[j][i])
  1683.                bs->PutBitStream(scalar[j][0][i],6);
  1684.                //putabits(bs,scalar[j][0][i],6);
  1685. }
  1686.  
  1687. /***************************** Layer II  ********************************/
  1688.  
  1689. static inline void II_encode_scale(unsigned int bit_alloc[2][SBLIMIT],
  1690.                      unsigned int scfsi[2][SBLIMIT],
  1691.                      unsigned int scalar[2][3][SBLIMIT],
  1692.                      frame_params* fr_ps,BitStreamStruct* bs)
  1693. {
  1694.     const int stereo  = fr_ps->stereo;
  1695.     const int sblimit = fr_ps->sblimit;
  1696.     const int jsbound = fr_ps->jsbound;
  1697.     int i,j,k;
  1698.  
  1699.     for (i=0;i<sblimit;i++)
  1700.         for (k=0;k<stereo;k++)
  1701.             if (bit_alloc[k][i])
  1702.                 bs->PutBitStream(scfsi[k][i],2);
  1703.                 //putabits(bs,scfsi[k][i],2);
  1704.  
  1705.     for (i=0;i<sblimit;i++)
  1706.         for (k=0;k<stereo;k++)
  1707.             if (bit_alloc[k][i])  /* above jsbound, bit_alloc[0][i] == ba[1][i] */
  1708.                 switch (scfsi[k][i])
  1709.                 {
  1710.                 case 0: 
  1711.                     for (j=0;j<3;j++)
  1712.                         bs->PutBitStream(scalar[k][j][i],6);
  1713.                         //putabits(bs,scalar[k][j][i],6);
  1714.                     break;
  1715.                 case 1:
  1716.                 case 3:
  1717.                     bs->PutBitStream(scalar[k][0][i],6);
  1718.                     //putabits(bs,scalar[k][0][i],6);
  1719.                     bs->PutBitStream(scalar[k][2][i],6);
  1720.                     //putabits(bs,scalar[k][2][i],6);
  1721.                     break;
  1722.                 case 2:
  1723.                     bs->PutBitStream(scalar[k][0][i],6);
  1724.                     //putabits(bs,scalar[k][0][i],6);
  1725.                 }
  1726. }
  1727.  
  1728. /*=======================================================================\
  1729. |                                                                        |
  1730. |      The following routines are done after the masking threshold       |
  1731. | has been calculated by the fft analysis routines in the Psychoacoustic |
  1732. | model. Using the MNR calculated, the actual number of bits allocated   |
  1733. | to each subband is found iteratively.                                  |
  1734. |                                                                        |
  1735. \=======================================================================*/
  1736.  
  1737. /************************************************************************
  1738. /*
  1739. /* I_bits_for_nonoise  (Layer I)
  1740. /* II_bits_for_nonoise (Layer II)
  1741. /*
  1742. /* PURPOSE:Returns the number of bits required to produce a
  1743. /* mask-to-noise ratio better or equal to the noise/no_noise threshold.
  1744. /*
  1745. /* SEMANTICS:
  1746. /* bbal = # bits needed for encoding bit allocation
  1747. /* bsel = # bits needed for encoding scalefactor select information
  1748. /* banc = # bits needed for ancillary data (header info included)
  1749. /*
  1750. /* For each subband and channel, will add bits until one of the
  1751. /* following occurs:
  1752. /* - Hit maximum number of bits we can allocate for that subband
  1753. /* - MNR is better than or equal to the minimum masking level
  1754. /*   (NOISY_MIN_MNR)
  1755. /* Then the bits required for scalefactors, scfsi, bit allocation,
  1756. /* and the subband samples are tallied (#req_bits#) and returned.
  1757. /*
  1758. /* (NOISY_MIN_MNR) is the smallest MNR a subband can have before it is
  1759. /* counted as 'noisy' by the logic which chooses the number of JS
  1760. /* subbands.
  1761. /*
  1762. /* Joint stereo is supported.
  1763. /*
  1764. /************************************************************************/
  1765.  
  1766. static double g_fSnr[18] = {0.00, 7.00, 11.00, 16.00, 20.84,
  1767.                          25.28, 31.59, 37.75, 43.84,
  1768.                          49.89, 55.93, 61.96, 67.98, 74.01,
  1769.                          80.03, 86.05, 92.01, 98.01};
  1770.  
  1771. static int I_bits_for_nonoise(const double perm_smr[2][SBLIMIT],
  1772.                               const frame_params* fr_ps)
  1773. {
  1774.     int i,j,k;
  1775.     const int stereo  = fr_ps->stereo;
  1776.     const int sblimit = fr_ps->sblimit;
  1777.     const int jsbound = fr_ps->jsbound;
  1778.     int req_bits = 0;
  1779.  
  1780.     /* initial b_anc (header) allocation bits */
  1781.     req_bits = 32 + 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  1782.  
  1783.     for(i=0; i<SBLIMIT; ++i)
  1784.         for(j=0; j<((i<jsbound)?stereo:1); ++j)
  1785.         {
  1786.             for(k=0;k<14; ++k)
  1787.                 if( (-perm_smr[j][i] + g_fSnr[k]) >= NOISY_MIN_MNR)
  1788.                     break; /* we found enough bits */
  1789.             if(stereo == 2 && i >= jsbound)     /* check other JS channel */
  1790.                 for(;k<14; ++k)
  1791.                     if( (-perm_smr[1-j][i] + g_fSnr[k]) >= NOISY_MIN_MNR)
  1792.                         break;
  1793.             if(k>0)
  1794.                 req_bits += (k+1)*SCALE_BLOCK + 6*((i>=jsbound)?stereo:1);
  1795.         }
  1796.     return req_bits;
  1797. }
  1798.  
  1799. /***************************** Layer II  ********************************/
  1800.  
  1801. static int II_bits_for_nonoise(const double perm_smr[2][SBLIMIT],
  1802.                                const unsigned int scfsi[2][SBLIMIT],
  1803.                                const frame_params* fr_ps)
  1804. {
  1805.    int sb,ch,ba;
  1806.    const int stereo  = fr_ps->stereo;
  1807.    const int sblimit = fr_ps->sblimit;
  1808.    const int jsbound = fr_ps->jsbound;
  1809.    al_table *alloc = fr_ps->alloc;
  1810.    int req_bits = 0, bbal = 0, berr = 0, banc = 32;
  1811.    int maxAlloc, sel_bits, sc_bits, smp_bits;
  1812.     static const int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  1813.  
  1814.    /* added 92-08-11 shn */
  1815.    if (fr_ps->header->error_protection) berr=16; else berr=0; 
  1816.  
  1817.    for (sb=0; sb<jsbound; ++sb)
  1818.      bbal += stereo * (*alloc)[sb][0].bits;
  1819.    for (sb=jsbound; sb<sblimit; ++sb)
  1820.      bbal += (*alloc)[sb][0].bits;
  1821.    req_bits = banc + bbal + berr;
  1822.  
  1823.    for(sb=0; sb<sblimit; ++sb)
  1824.      for(ch=0; ch<((sb<jsbound)?stereo:1); ++ch) {
  1825.        maxAlloc = (1<<(*alloc)[sb][0].bits)-1;
  1826.        sel_bits = sc_bits = smp_bits = 0;
  1827.        for(ba=0;ba<maxAlloc-1; ++ba)
  1828.          if( (-perm_smr[ch][sb] + g_fSnr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  1829.              >= NOISY_MIN_MNR)
  1830.             break;      /* we found enough bits */
  1831.        if(stereo == 2 && sb >= jsbound) /* check other JS channel */
  1832.          for(;ba<maxAlloc-1; ++ba)
  1833.            if( (-perm_smr[1-ch][sb]+ g_fSnr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  1834.                >= NOISY_MIN_MNR)
  1835.              break;
  1836.        if(ba>0) {
  1837.          smp_bits = SCALE_BLOCK * ((*alloc)[sb][ba].group * (*alloc)[sb][ba].bits);
  1838.          /* scale factor bits required for subband */
  1839.          sel_bits = 2;
  1840.          sc_bits  = 6 * sfsPerScfsi[scfsi[ch][sb]];
  1841.          if(stereo == 2 && sb >= jsbound) {
  1842.            /* each new js sb has L+R scfsis */
  1843.            sel_bits += 2;
  1844.            sc_bits  += 6 * sfsPerScfsi[scfsi[1-ch][sb]];
  1845.          }
  1846.          req_bits += smp_bits+sel_bits+sc_bits;
  1847.        }
  1848.    }
  1849.    return req_bits;
  1850. }
  1851.  
  1852. /************************************************************************
  1853. /*
  1854. /* I_main_bit_allocation   (Layer I)
  1855. /* II_main_bit_allocation  (Layer II)
  1856. /*
  1857. /* PURPOSE:For joint stereo mode, determines which of the 4 joint
  1858. /* stereo modes is needed.  Then calls *_a_bit_allocation(), which
  1859. /* allocates bits for each of the subbands until there are no more bits
  1860. /* left, or the MNR is at the noise/no_noise threshold.
  1861. /*
  1862. /* SEMANTICS:
  1863. /*
  1864. /* For joint stereo mode, joint stereo is changed to stereo if
  1865. /* there are enough bits to encode stereo at or better than the
  1866. /* no-noise threshold (NOISY_MIN_MNR).  Otherwise, the system
  1867. /* iteratively allocates less bits by using joint stereo until one
  1868. /* of the following occurs:
  1869. /* - there are no more noisy subbands (MNR >= NOISY_MIN_MNR)
  1870. /* - mode_ext has been reduced to 0, which means that all but the
  1871. /*   lowest 4 subbands have been converted from stereo to joint
  1872. /*   stereo, and no more subbands may be converted
  1873. /*
  1874. /*     This function calls *_bits_for_nonoise() and *_a_bit_allocation().
  1875. /*
  1876. /************************************************************************/
  1877.  
  1878. static inline bool I_main_bit_allocation(const double perm_smr[2][SBLIMIT],
  1879.                            unsigned int bit_alloc[2][SBLIMIT],
  1880.                            int* adb,frame_params* fr_ps)
  1881. {
  1882.     int  noisy_sbs;
  1883.     int  mode, mode_ext, lay, i;
  1884.     int  rq_db, av_db = *adb;
  1885.     static bool init = false;
  1886.     bool error = false;
  1887.  
  1888.     if(!init)
  1889.     {
  1890.         /* rearrange snr for layer I */
  1891.         g_fSnr[2] = g_fSnr[3];
  1892.         for (i=3;i<16;i++)
  1893.             g_fSnr[i] = g_fSnr[i+2];
  1894.         init = true;
  1895.     }
  1896.  
  1897.     if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO)
  1898.     {
  1899.         fr_ps->header->mode = MPG_MD_STEREO;
  1900.         fr_ps->header->mode_ext = 0;
  1901.         fr_ps->jsbound = fr_ps->sblimit;
  1902.         if(rq_db = I_bits_for_nonoise(perm_smr, fr_ps) > *adb)
  1903.         {
  1904.             fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  1905.             mode_ext = 4;           /* 3 is least severe reduction */
  1906.             lay = fr_ps->header->lay;
  1907.             do
  1908.             {
  1909.                 --mode_ext;
  1910.                 if((fr_ps->jsbound = js_bound(lay, mode_ext))<0)
  1911.                 {
  1912.                     return false;
  1913.                 }
  1914.                 rq_db = I_bits_for_nonoise(perm_smr, fr_ps);
  1915.             } while( (rq_db > *adb) && (mode_ext > 0));
  1916.             fr_ps->header->mode_ext = mode_ext;
  1917.         }    /* well we either eliminated noisy sbs or mode_ext == 0 */
  1918.     }
  1919.     noisy_sbs = I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps);
  1920.     return true;
  1921. }
  1922.  
  1923. /***************************** Layer II  ********************************/
  1924.  
  1925. static inline bool II_main_bit_allocation(
  1926.                             const double perm_smr[2][SBLIMIT],
  1927.                             const unsigned int scfsi[2][SBLIMIT],
  1928.                             unsigned int bit_alloc[2][SBLIMIT],
  1929.                             int *adb,
  1930.                             frame_params *fr_ps)
  1931. {
  1932.     int  noisy_sbs;
  1933.     int  mode, mode_ext, lay;
  1934.     int  rq_db, av_db = *adb;
  1935.  
  1936.     if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO)
  1937.     {
  1938.         fr_ps->header->mode = MPG_MD_STEREO;
  1939.         fr_ps->header->mode_ext = 0;
  1940.         fr_ps->jsbound = fr_ps->sblimit;
  1941.         if((rq_db=II_bits_for_nonoise(perm_smr, scfsi, fr_ps)) > *adb)
  1942.         {
  1943.             fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  1944.             mode_ext = 4;           /* 3 is least severe reduction */
  1945.             lay = fr_ps->header->lay;
  1946.             do
  1947.             {
  1948.                 --mode_ext;
  1949.                 fr_ps->jsbound = js_bound(lay, mode_ext);
  1950.                 rq_db = II_bits_for_nonoise(perm_smr, scfsi, fr_ps);
  1951.             } while( (rq_db > *adb) && (mode_ext > 0));
  1952.             fr_ps->header->mode_ext = mode_ext;
  1953.         }    /* well we either eliminated noisy sbs or mode_ext == 0 */
  1954.     }
  1955.     noisy_sbs = II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps);
  1956.  
  1957.     return true;
  1958. }
  1959.  
  1960. /************************************************************************
  1961. /*
  1962. /* I_a_bit_allocation  (Layer I)
  1963. /* II_a_bit_allocation (Layer II)
  1964. /*
  1965. /* PURPOSE:Adds bits to the subbands with the lowest mask-to-noise
  1966. /* ratios, until the maximum number of bits for the subband has
  1967. /* been allocated.
  1968. /*
  1969. /* SEMANTICS:
  1970. /* 1. Find the subband and channel with the smallest MNR (#min_sb#,
  1971. /*    and #min_ch#)
  1972. /* 2. Calculate the increase in bits needed if we increase the bit
  1973. /*    allocation to the next higher level
  1974. /* 3. If there are enough bits available for increasing the resolution
  1975. /*    in #min_sb#, #min_ch#, and the subband has not yet reached its
  1976. /*    maximum allocation, update the bit allocation, MNR, and bits
  1977. /*    available accordingly
  1978. /* 4. Repeat until there are no more bits left, or no more available
  1979. /*    subbands. (A subband is still available until the maximum
  1980. /*    number of bits for the subband has been allocated, or there
  1981. /*    aren't enough bits to go to the next higher resolution in the
  1982. /*    subband.)
  1983. /*
  1984. /************************************************************************/
  1985.  
  1986. static inline int I_a_bit_allocation(
  1987.                         const double perm_smr[2][SBLIMIT],
  1988.                         unsigned int bit_alloc[2][SBLIMIT],
  1989.                         int* adb,
  1990.                         const frame_params* fr_ps)
  1991. {
  1992.    int i, k, smpl_bits, scale_bits, min_sb, min_ch, oth_ch;
  1993.    int bspl, bscf, ad, noisy_sbs, done = 0, bbal ;
  1994.    double mnr[2][SBLIMIT];
  1995.    double smallm;
  1996.    char used[2][SBLIMIT];
  1997.    const int stereo  = fr_ps->stereo;
  1998.    const int sblimit = fr_ps->sblimit;
  1999.    const int jsbound = fr_ps->jsbound;
  2000.    static int banc=32, berr=(fr_ps->header->error_protection?16:0);
  2001.  
  2002.    bbal = 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  2003.    *adb -= bbal + berr + banc;
  2004.    ad= *adb;
  2005.  
  2006.    for (i=0;i<SBLIMIT;i++)
  2007.        for (k=0;k<stereo;k++)
  2008.         {
  2009.             mnr[k][i]=g_fSnr[0]-perm_smr[k][i];
  2010.             bit_alloc[k][i] = 0;
  2011.             used[k][i] = 0;
  2012.         }
  2013.    bspl = bscf = 0;
  2014.  
  2015.    do
  2016.    {
  2017.      /* locate the subband with minimum SMR */
  2018.      smallm = mnr[0][0]+1;    min_sb = -1; min_ch = -1;
  2019.      for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++)
  2020.        /* go on only if there are bits left */
  2021.        if (used[k][i] != 2 && smallm > mnr[k][i])
  2022.        {
  2023.          smallm = mnr[k][i];
  2024.          min_sb = i;  min_ch = k;
  2025.        }
  2026.      if(min_sb > -1) {   /* there was something to find */
  2027.        /* first step of bit allocation is biggest */
  2028.        if (used[min_ch][min_sb])
  2029.        {
  2030.            smpl_bits = SCALE_BLOCK;
  2031.            scale_bits = 0;
  2032.        }
  2033.        else
  2034.        {
  2035.            smpl_bits = 24;
  2036.            scale_bits = 6;
  2037.        }
  2038.        if(min_sb >= jsbound)
  2039.            scale_bits *= stereo;
  2040.  
  2041.        /* check to see enough bits were available for */
  2042.        /* increasing resolution in the minimum band */
  2043.  
  2044.        if (ad >= bspl + bscf + scale_bits + smpl_bits)
  2045.        {
  2046.          bspl += smpl_bits; /* bit for subband sample */
  2047.          bscf += scale_bits; /* bit for scale factor */
  2048.          bit_alloc[min_ch][min_sb]++;
  2049.          used[min_ch][min_sb] = 1; /* subband has bits */
  2050.          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb]
  2051.                                + g_fSnr[bit_alloc[min_ch][min_sb]];
  2052.          /* Check if subband has been fully allocated max bits */
  2053.          if (bit_alloc[min_ch][min_sb] ==  14 )
  2054.              used[min_ch][min_sb] = 2;
  2055.        }
  2056.        else            /* no room to improve this band */
  2057.          used[min_ch][min_sb] = 2; /*   for allocation anymore */
  2058.        if(stereo == 2 && min_sb >= jsbound)
  2059.        {
  2060.          oth_ch = 1-min_ch;  /* joint-st : fix other ch */
  2061.          bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  2062.          used[oth_ch][min_sb] = used[min_ch][min_sb];
  2063.          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb]
  2064.                                + g_fSnr[bit_alloc[oth_ch][min_sb]];
  2065.        }
  2066.      }
  2067.    } while(min_sb>-1);     /* i.e. still some sub-bands to find */
  2068.  
  2069.    /* Calculate the number of bits left, add on to pointed var */
  2070.    ad -= bspl+bscf;
  2071.    *adb = ad;
  2072.  
  2073.    /* see how many channels are noisy */
  2074.    noisy_sbs = 0; smallm = mnr[0][0];
  2075.    for(k=0; k<stereo; ++k)
  2076.    {
  2077.      for(i = 0; i< SBLIMIT; ++i)
  2078.      {
  2079.        if(mnr[k][i] < NOISY_MIN_MNR)
  2080.            ++noisy_sbs;
  2081.        if(smallm > mnr[k][i])
  2082.            smallm = mnr[k][i];
  2083.      }
  2084.    }
  2085.    return noisy_sbs;
  2086. }
  2087.  
  2088. /***************************** Layer II  ********************************/
  2089. static inline int II_a_bit_allocation(
  2090.                         const double perm_smr[][SBLIMIT],
  2091.                         const unsigned int scfsi[][SBLIMIT],
  2092.                         unsigned int bit_alloc[][SBLIMIT],
  2093.                         int* adb,
  2094.                         const frame_params* fr_ps)
  2095. {
  2096.     int i, min_ch, min_sb, oth_ch, k, increment, scale, seli, ba;
  2097.     int bspl, bscf, bsel, ad, noisy_sbs, bbal=0;
  2098.     double mnr[2][SBLIMIT], smallm;
  2099.     char used[2][SBLIMIT];
  2100.     const int stereo  = fr_ps->stereo;
  2101.     const int sblimit = fr_ps->sblimit;
  2102.     const int jsbound = fr_ps->jsbound;
  2103.     al_table *alloc = fr_ps->alloc;
  2104.     static int banc=32, berr=(fr_ps->header->error_protection?16:0);
  2105.     static const int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  2106.  
  2107.     
  2108.     for (i=0; i<jsbound; ++i)
  2109.      bbal += stereo * (*alloc)[i][0].bits;
  2110.    for (i=jsbound; i<sblimit; ++i)
  2111.      bbal += (*alloc)[i][0].bits;
  2112.    *adb -= bbal + berr + banc;
  2113.    ad = *adb;
  2114.  
  2115.    for (i=0;i<sblimit;i++)
  2116.        for (k=0;k<stereo;k++)
  2117.        {
  2118.             mnr[k][i]=g_fSnr[0]-perm_smr[k][i];
  2119.             bit_alloc[k][i] = 0;
  2120.             used[k][i] = 0;
  2121.         }
  2122.    bspl = bscf = bsel = 0;
  2123.  
  2124.    do  {
  2125.      /* locate the subband with minimum SMR */
  2126.      smallm = 999999.0; min_sb = -1; min_ch = -1;
  2127.      for (i=0;i<sblimit;i++) for(k=0;k<stereo;++k)
  2128.        if (used[k][i]  != 2 && smallm > mnr[k][i]) {
  2129.          smallm = mnr[k][i];
  2130.          min_sb = i;  min_ch = k;
  2131.      }
  2132.      if(min_sb > -1) {   /* there was something to find */
  2133.        /* find increase in bit allocation in subband [min] */
  2134.        increment = SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].group *
  2135.                         (*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].bits);
  2136.        if (used[min_ch][min_sb])
  2137.          increment -= SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]].group*
  2138.                            (*alloc)[min_sb][bit_alloc[min_ch][min_sb]].bits);
  2139.  
  2140.        /* scale factor bits required for subband [min] */
  2141.        oth_ch = 1 - min_ch;    /* above js bound, need both chans */
  2142.        if (used[min_ch][min_sb]) scale = seli = 0;
  2143.        else {          /* this channel had no bits or scfs before */
  2144.          seli = 2;
  2145.          scale = 6 * sfsPerScfsi[scfsi[min_ch][min_sb]];
  2146.          if(stereo == 2 && min_sb >= jsbound) {
  2147.            /* each new js sb has L+R scfsis */
  2148.            seli += 2;
  2149.            scale += 6 * sfsPerScfsi[scfsi[oth_ch][min_sb]];
  2150.          }
  2151.        }
  2152.        /* check to see enough bits were available for */
  2153.        /* increasing resolution in the minimum band */
  2154.        if (ad >= bspl + bscf + bsel + seli + scale + increment) {
  2155.          ba = ++bit_alloc[min_ch][min_sb]; /* next up alloc */
  2156.          bspl += increment;  /* bits for subband sample */
  2157.          bscf += scale;      /* bits for scale factor */
  2158.          bsel += seli;       /* bits for scfsi code */
  2159.          used[min_ch][min_sb] = 1; /* subband has bits */
  2160.          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb] +
  2161.                                g_fSnr[(*alloc)[min_sb][ba].quant+1];
  2162.          /* Check if subband has been fully allocated max bits */
  2163.          if (ba >= (1<<(*alloc)[min_sb][0].bits)-1) used[min_ch][min_sb] = 2;
  2164.        }
  2165.        else used[min_ch][min_sb] = 2; /* can't increase this alloc */
  2166.        if(min_sb >= jsbound && stereo == 2) {
  2167.          /* above jsbound, alloc applies L+R */
  2168.          ba = bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  2169.          used[oth_ch][min_sb] = used[min_ch][min_sb];
  2170.          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb] +
  2171.                                g_fSnr[(*alloc)[min_sb][ba].quant+1];
  2172.        }
  2173.      }
  2174.    } while(min_sb > -1);   /* until could find no channel */
  2175.    /* Calculate the number of bits left */
  2176.    ad -= bspl+bscf+bsel;   *adb = ad;
  2177.    for (i=sblimit;i<SBLIMIT;i++) for (k=0;k<stereo;k++) bit_alloc[k][i]=0;
  2178.  
  2179.    noisy_sbs = 0;  smallm = mnr[0][0];      /* calc worst noise in case */
  2180.    for(k=0;k<stereo;++k) {
  2181.      for (i=0;i<sblimit;i++) {
  2182.        if (smallm > mnr[k][i]) smallm = mnr[k][i];
  2183.        if(mnr[k][i] < NOISY_MIN_MNR) ++noisy_sbs; /* noise is not masked */
  2184.  
  2185.      }
  2186.    }
  2187.  
  2188.    return noisy_sbs;
  2189. }
  2190.  
  2191. /************************************************************************
  2192. /*
  2193. /* I_subband_quantization  (Layer I)
  2194. /* II_subband_quantization (Layer II)
  2195. /*
  2196. /* PURPOSE:Quantizes subband samples to appropriate number of bits
  2197. /*
  2198. /* SEMANTICS:  Subband samples are divided by their scalefactors, which
  2199. /* makes the quantization more efficient. The scaled samples are
  2200. /* quantized by the function a*x+b, where a and b are functions of
  2201. /* the number of quantization levels. The result is then truncated
  2202. /* to the appropriate number of bits and the MSB is inverted.
  2203. /*
  2204. /* Note that for fractional 2's complement, inverting the MSB for a
  2205. /* negative number x is equivalent to adding 1 to it.
  2206. /*
  2207. /************************************************************************/
  2208.  
  2209. static double g_fA[17] = {
  2210.     0.750000000, 0.625000000, 0.875000000, 0.562500000, 0.937500000,
  2211.     0.968750000, 0.984375000, 0.992187500, 0.996093750, 0.998046875,
  2212.     0.999023438, 0.999511719, 0.999755859, 0.999877930, 0.999938965,
  2213.     0.999969482, 0.999984741 };
  2214.  
  2215. static double g_fB[17] = {
  2216.     -0.250000000, -0.375000000, -0.125000000, -0.437500000, -0.062500000,
  2217.     -0.031250000, -0.015625000, -0.007812500, -0.003906250, -0.001953125,
  2218.     -0.000976563, -0.000488281, -0.000244141, -0.000122070, -0.000061035,
  2219.     -0.000030518, -0.000015259 };
  2220.  
  2221. static inline void I_subband_quantization(
  2222.                             unsigned int scalar[2][3][SBLIMIT],
  2223.                             double sb_samples[2][3][SCALE_BLOCK][SBLIMIT],
  2224.                             unsigned int j_scale[3][SBLIMIT],
  2225.                             double j_samps[3][SCALE_BLOCK][SBLIMIT], /* L+R for j-stereo if necess */
  2226.                             unsigned int bit_alloc[2][SBLIMIT],
  2227.                             unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT],
  2228.                             frame_params* fr_ps)
  2229. {
  2230.     int i, j, k, n, sig;
  2231.     const int stereo  = fr_ps->stereo;
  2232.     const int sblimit = fr_ps->sblimit;
  2233.     const int jsbound = fr_ps->jsbound;
  2234.     double d;
  2235.     static bool init = false;
  2236.  
  2237.     if (!init)
  2238.     {
  2239.         init = true;
  2240.         /* rearrange quantization coef to correspond to layer I table */
  2241.         g_fA[1] = g_fA[2];
  2242.         g_fB[1] = g_fB[2];
  2243.         for (i=2;i<15;i++)
  2244.         {
  2245.             g_fA[i] = g_fA[i+2];
  2246.             g_fB[i] = g_fB[i+2];
  2247.         }
  2248.     }
  2249.     for (j=0;j<SCALE_BLOCK;j++)
  2250.         for (i=0;i<SBLIMIT;i++)
  2251.             for (k=0;k<((i<jsbound)?stereo:1);k++)
  2252.                 if (bit_alloc[k][i])
  2253.                 {
  2254.                     /* for joint stereo mode, have to construct a single subband stream
  2255.                     for the js channels.  At present, we calculate a set of mono
  2256.                     subband samples and pass them through the scaling system to
  2257.                     generate an alternate normalised sample stream.
  2258.  
  2259.                     Could normalise both streams (divide by their scfs), then average
  2260.                     them.  In bad conditions, this could give rise to spurious
  2261.                     cancellations.  Instead, we could just select the sb stream from
  2262.                     the larger channel (higher scf), in which case _that_ channel
  2263.                     would be 'properly' reconstructed, and the mate would just be a
  2264.                     scaled version.  Spec recommends averaging the two (unnormalised)
  2265.                     subband channels, then normalising this new signal without
  2266.                     actually sending this scale factor... This means looking ahead.
  2267.                     */
  2268.                     if(stereo == 2 && i>=jsbound)
  2269.                         /* use the joint data passed in */
  2270.                         d = j_samps[0][j][i] / g_fMultiple[j_scale[0][i]];
  2271.                     else
  2272.                         d = sb_samples[k][0][j][i] / g_fMultiple[scalar[k][0][i]];
  2273.                     /* scale and quantize floating point sample */
  2274.                     n = bit_alloc[k][i];
  2275.                     d = d * g_fA[n-1] + g_fB[n-1];
  2276.                     /* extract MSB N-1 bits from the floating point sample */
  2277.                     if (d >= 0)
  2278.                         sig = 1;
  2279.                     else
  2280.                     {
  2281.                         sig = 0;
  2282.                         d += 1.0;
  2283.                     }
  2284.                     sbband[k][0][j][i] = (unsigned int) (d * (double) (1L<<n));
  2285.                     /* tag the inverted sign bit to sbband at position N */
  2286.                     if (sig)
  2287.                         sbband[k][0][j][i] |= 1<<n;
  2288.                 }
  2289. }
  2290.  
  2291. /***************************** Layer II  ********************************/
  2292.  
  2293. static inline void II_subband_quantization(
  2294.                                 unsigned int scalar[2][3][SBLIMIT],
  2295.                                 double sb_samples[2][3][SCALE_BLOCK][SBLIMIT],
  2296.                                 unsigned int j_scale[3][SBLIMIT],
  2297.                                 double j_samps[3][SCALE_BLOCK][SBLIMIT],
  2298.                                 unsigned int bit_alloc[2][SBLIMIT],
  2299.                                 unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT],
  2300.                                 frame_params* fr_ps)
  2301. {
  2302.     int i, j, k, s, n, qnt, sig;
  2303.     int stereo  = fr_ps->stereo;
  2304.     int sblimit = fr_ps->sblimit;
  2305.     int jsbound = fr_ps->jsbound;
  2306.     double d;
  2307.     al_table *alloc = fr_ps->alloc;
  2308.  
  2309.     for (s=0;s<3;s++)
  2310.         for (j=0;j<SCALE_BLOCK;j++)
  2311.             for (i=0;i<sblimit;i++)
  2312.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  2313.                     if (bit_alloc[k][i])
  2314.                     {
  2315.                         /* scale and quantize floating point sample */
  2316.                         if(stereo == 2 && i>=jsbound)       /* use j-stereo samples */
  2317.                             d = j_samps[s][j][i] / g_fMultiple[j_scale[s][i]];
  2318.                         else
  2319.                             d = sb_samples[k][s][j][i] / g_fMultiple[scalar[k][s][i]];
  2320.                         qnt = (*alloc)[i][bit_alloc[k][i]].quant;
  2321.                         d = d * g_fA[qnt] + g_fB[qnt];
  2322.                         /* extract MSB N-1 bits from the floating point sample */
  2323.                         if (d >= 0)
  2324.                             sig = 1;
  2325.                         else
  2326.                         {
  2327.                             sig = 0;
  2328.                             d += 1.0;
  2329.                         }
  2330.                         n = 0;
  2331.                         while  ( ( (unsigned long)(1L<<(long)n) <
  2332.                                 ((unsigned long) ((*alloc)[i][bit_alloc[k][i]].steps)
  2333.                                 & 0xffff
  2334.                                 )
  2335.                                 ) && ( n <16)
  2336.                                 ) n++;
  2337.                         n--;
  2338.                         sbband[k][s][j][i] = (unsigned int) (d * (double) (1L<<n));
  2339.                         /* tag the inverted sign bit to sbband at position N */
  2340.                         /* The bit inversion is a must for grouping with 3,5,9 steps
  2341.                         so it is done for all subbands */
  2342.                         if (sig)
  2343.                             sbband[k][s][j][i] |= 1<<n;
  2344.                     }
  2345.     for (s=0;s<3;s++)
  2346.         for (j=sblimit;j<SBLIMIT;j++)
  2347.             for (i=0;i<SCALE_BLOCK;i++)
  2348.                 for (k=0;k<stereo;k++)
  2349.                     sbband[k][s][i][j] = 0;
  2350. }
  2351.  
  2352. /************************************************************************
  2353. /*
  2354. /* I_encode_bit_alloc  (Layer I)
  2355. /* II_encode_bit_alloc (Layer II)
  2356. /*
  2357. /* PURPOSE:Writes bit allocation information onto bitstream
  2358. /*
  2359. /* Layer I uses 4 bits/subband for bit allocation information,
  2360. /* and Layer II uses 4,3,2, or 0 bits depending on the
  2361. /* quantization table used.
  2362. /*
  2363. /************************************************************************/
  2364.  
  2365. static inline void I_encode_bit_alloc(
  2366.                         const unsigned int bit_alloc[][SBLIMIT],
  2367.                         const frame_params* fr_ps,
  2368.                         BitStreamStruct* bs)
  2369. {
  2370.    int i,k;
  2371.    const int stereo  = fr_ps->stereo;
  2372.    const int sblimit = fr_ps->sblimit;
  2373.    const int jsbound = fr_ps->jsbound;
  2374.  
  2375.    for (i=0;i<SBLIMIT;i++)
  2376.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  2377.          bs->PutBitStream(bit_alloc[k][i],4);
  2378.          //putabits(bs,bit_alloc[k][i],4);
  2379. }
  2380.  
  2381. /***************************** Layer II  ********************************/
  2382.  
  2383. static inline void II_encode_bit_alloc(
  2384.                             const unsigned int bit_alloc[][SBLIMIT],
  2385.                             const frame_params* fr_ps,
  2386.                             BitStreamStruct* bs)
  2387. {
  2388.    int i,k;
  2389.    const int stereo  = fr_ps->stereo;
  2390.    const int sblimit = fr_ps->sblimit;
  2391.    const int jsbound = fr_ps->jsbound;
  2392.    al_table *alloc = fr_ps->alloc;
  2393.  
  2394.    for (i=0;i<sblimit;i++)
  2395.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  2396.          bs->PutBitStream(bit_alloc[k][i],(*alloc)[i][0].bits);
  2397.        //putabits(bs,bit_alloc[k][i],(*alloc)[i][0].bits);
  2398. }
  2399.  
  2400. /************************************************************************
  2401. /*
  2402. /* I_sample_encoding   (Layer I)
  2403. /* II_sample_encoding  (Layer II)
  2404. /*
  2405. /* PURPOSE:Put one frame of subband samples on to the bitstream
  2406. /*
  2407. /* SEMANTICS:  The number of bits allocated per sample is read from
  2408. /* the bit allocation information #bit_alloc#.  Layer 2
  2409. /* supports writing grouped samples for quantization steps
  2410. /* that are not a power of 2.
  2411. /*
  2412. /************************************************************************/
  2413.  
  2414. static inline void I_sample_encoding(
  2415.                         unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT],
  2416.                         unsigned int bit_alloc[2][SBLIMIT],
  2417.                         frame_params* fr_ps,
  2418.                         BitStreamStruct* bs)
  2419. {
  2420.     int i,j,k;
  2421.     const int stereo  = fr_ps->stereo;
  2422.     const int sblimit = fr_ps->sblimit;
  2423.     const int jsbound = fr_ps->jsbound;
  2424.  
  2425.     for(j=0;j<SCALE_BLOCK;j++)
  2426.     {
  2427.         for(i=0;i<SBLIMIT;i++)
  2428.             for(k=0;k<((i<jsbound)?stereo:1);k++)
  2429.                 if(bit_alloc[k][i])
  2430.                     bs->PutBitStream(sbband[k][0][j][i],bit_alloc[k][i]+1);
  2431.                     //putabits(bs,sbband[k][0][j][i],bit_alloc[k][i]+1);
  2432.     }
  2433. }
  2434.  
  2435. /***************************** Layer II  ********************************/
  2436.  
  2437. static inline void II_sample_encoding(
  2438.                         unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT],
  2439.                         unsigned int bit_alloc[2][SBLIMIT],
  2440.                         frame_params* fr_ps,
  2441.                         BitStreamStruct* bs)
  2442. {
  2443.     unsigned int temp;
  2444.     unsigned int j,s,x,y;
  2445.     int i, k;
  2446.     const int stereo  = fr_ps->stereo;
  2447.     const int sblimit = fr_ps->sblimit;
  2448.     const int jsbound = fr_ps->jsbound;
  2449.     al_table *alloc = fr_ps->alloc;
  2450.  
  2451.     for (s=0;s<3;s++)
  2452.         for (j=0;j<SCALE_BLOCK;j+=3)
  2453.             for (i=0;i<sblimit;i++)
  2454.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  2455.                     if (bit_alloc[k][i])
  2456.                     {
  2457.                         if ((*alloc)[i][bit_alloc[k][i]].group == 3)
  2458.                         {
  2459.                             for (x=0;x<3;x++)
  2460.                                 bs->PutBitStream(sbband[k][s][j+x][i],(*alloc)[i][bit_alloc[k][i]].bits);
  2461.                                 //putabits(bs,sbband[k][s][j+x][i],(*alloc)[i][bit_alloc[k][i]].bits);
  2462.                         }
  2463.                         else
  2464.                         {
  2465.                             y =(*alloc)[i][bit_alloc[k][i]].steps;
  2466.                             temp = sbband[k][s][j][i] +
  2467.                             sbband[k][s][j+1][i] * y +
  2468.                             sbband[k][s][j+2][i] * y * y;
  2469.                             bs->PutBitStream(temp,(*alloc)[i][bit_alloc[k][i]].bits);
  2470.                             //putabits(bs,temp,(*alloc)[i][bit_alloc[k][i]].bits);
  2471.                         }
  2472.                     }
  2473. }
  2474.  
  2475. /************************************************************************
  2476. /*
  2477. /* encode_CRC
  2478. /*
  2479. /************************************************************************/
  2480.  
  2481. static inline void encode_CRC(unsigned int crc,BitStreamStruct* bs)
  2482. {
  2483.     bs->PutBitStream(crc, 16);
  2484.    //putabits(bs, crc, 16);
  2485. }
  2486.  
  2487. static inline int read_bit_alloc(int table,al_table* alloc)        /* read in table, return # subbands */
  2488. {
  2489.     unsigned int i, j, k;
  2490.  
  2491.     int sblim;
  2492.  
  2493.     switch (table)
  2494.     {
  2495.     case 1 :
  2496.         //printf("using bit allocation table 1\n");
  2497.         sblim = sblim_1;
  2498.         k = 0;
  2499.         while (k < alloc_1_size)
  2500.         {
  2501.             i = alloc_1[k][0];
  2502.             j = alloc_1[k][1];
  2503.             (*alloc)[i][j].steps = alloc_1[k][2];
  2504.             (*alloc)[i][j].bits  = alloc_1[k][3];
  2505.             (*alloc)[i][j].group = alloc_1[k][4];
  2506.             (*alloc)[i][j].quant = alloc_1[k][5];
  2507.             k++;
  2508.         }
  2509.         break;
  2510.     case 2 :
  2511.         //printf("using bit allocation table 2\n");
  2512.         sblim = sblim_2;
  2513.         k = 0;
  2514.         while (k < alloc_2_size)
  2515.         {
  2516.             i = alloc_2[k][0];
  2517.             j = alloc_2[k][1];
  2518.             (*alloc)[i][j].steps = alloc_2[k][2];
  2519.             (*alloc)[i][j].bits  = alloc_2[k][3];
  2520.             (*alloc)[i][j].group = alloc_2[k][4];
  2521.             (*alloc)[i][j].quant = alloc_2[k][5];
  2522.             k++;
  2523.         }
  2524.         break;
  2525.     case 3:
  2526.         sblim = sblim_3;
  2527.         k = 0;
  2528.         while (k < alloc_3_size)
  2529.         {
  2530.             i = alloc_3[k][0];
  2531.             j = alloc_3[k][1];
  2532.             (*alloc)[i][j].steps = alloc_3[k][2];
  2533.             (*alloc)[i][j].bits  = alloc_3[k][3];
  2534.             (*alloc)[i][j].group = alloc_3[k][4];
  2535.             (*alloc)[i][j].quant = alloc_3[k][5];
  2536.             k++;
  2537.         }
  2538.         break;
  2539.     case 0 :
  2540.     default :
  2541.         //printf("using bit allocation table 0\n");
  2542.         sblim = sblim_0;
  2543.         k = 0;
  2544.         while (k < alloc_0_size)
  2545.         {
  2546.             i = alloc_0[k][0];
  2547.             j = alloc_0[k][1];
  2548.             (*alloc)[i][j].steps = alloc_0[k][2];
  2549.             (*alloc)[i][j].bits  = alloc_0[k][3];
  2550.             (*alloc)[i][j].group = alloc_0[k][4];
  2551.             (*alloc)[i][j].quant = alloc_0[k][5];
  2552.             k++;
  2553.         }
  2554.     }
  2555.  
  2556.     return sblim;
  2557. }
  2558.  
  2559. /***********************************************************************
  2560. /*
  2561. /* Using the decoded info the appropriate possible quantization per
  2562. /* subband table is loaded
  2563. /*
  2564. /**********************************************************************/
  2565.  
  2566. static inline int pick_table(frame_params* fr_ps,bool* error)   /* choose table, load if necess, return # sb's */
  2567. {
  2568.     int table, lay, bsp, br_per_ch, sfrq;
  2569.     int sblimit = fr_ps->sblimit;
  2570.  
  2571.     lay = fr_ps->header->lay;
  2572.     bsp = fr_ps->header->bitrate_index;
  2573.     br_per_ch = g_uBitRateArray[lay][bsp] / fr_ps->stereo;
  2574.     sfrq = (int)g_fSamplingFrequency[fr_ps->header->sampling_frequency];
  2575.     /* decision rules refer to per-channel bitrates (kbits/sec/chan) */
  2576.     if((sfrq == 48 && br_per_ch >= 56) ||
  2577.         (br_per_ch >= 56 && br_per_ch <= 80))
  2578.     {
  2579.         table = 0;
  2580.     }
  2581.     else if(sfrq != 48 && br_per_ch >= 96)
  2582.     {
  2583.         table = 1;
  2584.     }
  2585.     else if(sfrq != 32 && br_per_ch <= 48)
  2586.     {
  2587.         table = 2;
  2588.     }
  2589.     else
  2590.     {
  2591.         table = 3;
  2592.     }
  2593.  
  2594.     if (fr_ps->tab_num != table)
  2595.     {
  2596.         if(!fr_ps->alloc_table())
  2597.         {
  2598.             if(error!=NULL)
  2599.             {
  2600.                 *error = true;
  2601.             }
  2602.             return 0;
  2603.         }
  2604.         sblimit = read_bit_alloc(fr_ps->tab_num = table, fr_ps->alloc);
  2605.     }
  2606.     if(error!=NULL)
  2607.     {
  2608.         *error = false;
  2609.     }
  2610.     return sblimit;
  2611. }
  2612.  
  2613. static int js_bound(const int lay,const int m_ext)
  2614. {
  2615.     static int jsb_table[2][4] =  { { 4, 8, 12, 16 }, { 4, 8, 12, 16} };  /* lay+m_e -> jsbound */
  2616.  
  2617.     if(lay<0 || lay >1 || m_ext<0 || m_ext>3) {
  2618.         return -1;
  2619.     }
  2620.  
  2621.     return jsb_table[lay][m_ext];
  2622. }
  2623.  
  2624. static inline bool hdr_to_frps(frame_params* fr_ps) /* interpret data in hdr str to fields in fr_ps */
  2625. {
  2626.     const layer *hdr = fr_ps->header;     /* (or pass in as arg?) */
  2627.     bool error = false;
  2628.  
  2629.     fr_ps->actual_mode = hdr->mode;
  2630.     fr_ps->stereo = (hdr->mode == MPG_MD_MONO) ? 1 : 2;
  2631.     if (hdr->lay == 1)
  2632.     {
  2633.         fr_ps->sblimit = pick_table(fr_ps,&error);
  2634.         if(error)
  2635.         {
  2636.             return false;
  2637.         }
  2638.     }
  2639.     else
  2640.         fr_ps->sblimit = SBLIMIT;
  2641.  
  2642.     if(hdr->mode == MPG_MD_JOINT_STEREO)
  2643.     {
  2644.         if((fr_ps->jsbound = js_bound(hdr->lay, hdr->mode_ext))<0)
  2645.         {
  2646.             return false;
  2647.         }
  2648.     }
  2649.     else
  2650.     {
  2651.         fr_ps->jsbound = fr_ps->sblimit;
  2652.     }
  2653.  
  2654.     return true;
  2655. }
  2656.  
  2657.  
  2658. static inline int BitrateIndex(const int layr,const unsigned int bRate)   /* convert bitrate in kbps to index */
  2659. {
  2660.     int index;
  2661.  
  2662.     for(index = 1;index < 15; index++ )
  2663.     {
  2664.         if(g_uBitRateArray[layr][index] == bRate)
  2665.             return index;
  2666.     }
  2667.     return -1;
  2668. }
  2669.  
  2670. static inline int SmpFrqIndex(long sRate)  /* convert samp frq in Hz to index */
  2671. {
  2672.     if(sRate == 44100L)
  2673.         return(0);
  2674.     else if(sRate == 48000L)
  2675.         return(1);
  2676.     else if(sRate == 32000L)
  2677.         return(2);
  2678.     else {
  2679.         //_proc( "SmpFrqIndex: %ld is not a legal sample rate\n", sRate);
  2680.         return(-1);      /* Error! */
  2681.     }
  2682. }
  2683. /*****************************************************************************
  2684. *
  2685. *  CRC error protection package
  2686. *
  2687. *****************************************************************************/
  2688.  
  2689. static inline void I_CRC_calc(frame_params* fr_ps,
  2690.                               unsigned int bit_alloc[2][SBLIMIT],
  2691.                               unsigned int* crc)
  2692. {
  2693.         int i, k;
  2694.         layer *info = fr_ps->header;
  2695.         const int stereo  = fr_ps->stereo;
  2696.         const int jsbound = fr_ps->jsbound;
  2697.  
  2698.         *crc = 0xffff; /* changed from '0' 92-08-11 shn */
  2699.         update_CRC(info->bitrate_index, 4, crc);
  2700.         update_CRC(info->sampling_frequency, 2, crc);
  2701.         update_CRC(info->padding, 1, crc);
  2702.         update_CRC(info->extension, 1, crc);
  2703.         update_CRC(info->mode, 2, crc);
  2704.         update_CRC(info->mode_ext, 2, crc);
  2705.         update_CRC(info->copyright, 1, crc);
  2706.         update_CRC(info->original, 1, crc);
  2707.         update_CRC(info->emphasis, 2, crc);
  2708.  
  2709.         for (i=0;i<SBLIMIT;i++)
  2710.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  2711.                         update_CRC(bit_alloc[k][i], 4, crc);
  2712. }
  2713.  
  2714. static inline void II_CRC_calc(frame_params* fr_ps,
  2715.                  unsigned int bit_alloc[2][SBLIMIT],
  2716.                  unsigned int scfsi[2][SBLIMIT],
  2717.                  unsigned int* crc)
  2718. {
  2719.     int i, k;
  2720.     layer *info = fr_ps->header;
  2721.     const int stereo  = fr_ps->stereo;
  2722.     const int sblimit = fr_ps->sblimit;
  2723.     const int jsbound = fr_ps->jsbound;
  2724.     al_table *alloc = fr_ps->alloc;
  2725.  
  2726.     *crc = 0xffff; /* changed from '0' 92-08-11 shn */
  2727.     update_CRC(info->bitrate_index, 4, crc);
  2728.     update_CRC(info->sampling_frequency, 2, crc);
  2729.     update_CRC(info->padding, 1, crc);
  2730.     update_CRC(info->extension, 1, crc);
  2731.     update_CRC(info->mode, 2, crc);
  2732.     update_CRC(info->mode_ext, 2, crc);
  2733.     update_CRC(info->copyright, 1, crc);
  2734.     update_CRC(info->original, 1, crc);
  2735.     update_CRC(info->emphasis, 2, crc);
  2736.  
  2737.     for (i=0;i<sblimit;i++)
  2738.         for (k=0;k<((i<jsbound)?stereo:1);k++)
  2739.             update_CRC(bit_alloc[k][i], (*alloc)[i][0].bits, crc);
  2740.  
  2741.     for (i=0;i<sblimit;i++)
  2742.         for (k=0;k<stereo;k++)
  2743.             if (bit_alloc[k][i])
  2744.                 update_CRC(scfsi[k][i], 2, crc);
  2745. }
  2746.  
  2747. static void update_CRC(unsigned int data,unsigned int length,unsigned int* crc)
  2748. {
  2749.     unsigned int  masking, carry;
  2750.  
  2751.     masking = 1 << length;
  2752.  
  2753.     while((masking >>= 1)){
  2754.         carry = *crc & 0x8000;
  2755.         *crc <<= 1;
  2756.         if (!carry ^ !(data & masking))
  2757.             *crc ^= CRC16_POLYNOMIAL;
  2758.     }
  2759.     *crc &= 0xffff;
  2760. }
  2761. static inline bool read_absthr(double* absthr,const int sfreq_idx)
  2762. {
  2763.     switch(sfreq_idx)
  2764.     {
  2765.     case 0:
  2766.         memcpy(absthr,absthr_0,sizeof(absthr_0));
  2767.         break;
  2768.     case 1:
  2769.         memcpy(absthr,absthr_1,sizeof(absthr_1));
  2770.         break;
  2771.     case 2:
  2772.         memcpy(absthr,absthr_2,sizeof(absthr_2));
  2773.         break;
  2774.     default:
  2775.         return false;
  2776.     }
  2777.  
  2778.     return true;
  2779. }
  2780.  
  2781. static TOMPGRET psycho_anal(
  2782.                  const short* buffer,short int savebuf[1056],
  2783.                  const int chn,const int lay,
  2784.                  double snr32[],const double sfreq)
  2785. {
  2786.     unsigned int    i, j, k;
  2787.     int                sfreq_idx;
  2788.     int                buffer_address = 0;
  2789.     double          r_prime, phi_prime;
  2790.     double          freq_mult, bval_lo, minthres, sum_energy;
  2791.     double            tb, temp1, temp2, temp3;
  2792.  
  2793.  
  2794. /* The static variables "r", "phi_sav", "recent", "old" and "oldest" have    */
  2795. /* to be remembered for the unpredictability measure.  For "r" and        */
  2796. /* "phi_sav", the first index from the left is the channel select and     */
  2797. /* the second index is the "age" of the data.                             */
  2798.  
  2799.     static int recent = 0, old = 1, oldest = 0;
  2800.     static int flush, sync_flush, syncsize;
  2801.     static bool    init = false;
  2802.  
  2803. /* The following static variables are constants.                           */
  2804.  
  2805.     static double  nmt = 5.5;
  2806.  
  2807.     static const double crit_band[27] = {0,  100,  200, 300, 400, 510, 630,  770,
  2808.                                        920, 1080, 1270,1480,1720,2000,2320, 2700,
  2809.                                       3150, 3700, 4400,5300,6400,7700,9500,12000,
  2810.                                      15500,25000,30000};
  2811.  
  2812.     static const double bmax[27] = {20.0, 20.0, 20.0, 20.0, 20.0, 17.0, 15.0,
  2813.                             10.0,  7.0,  4.4,  4.5,  4.5,  4.5,  4.5,
  2814.                              4.5,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5,
  2815.                              4.5,  4.5,  4.5,  3.5,  3.5,  3.5};
  2816.  
  2817. /* The following pointer variables point to large areas of memory         */
  2818. /* dynamically allocated by the mem_alloc() function.  Dynamic memory     */
  2819. /* allocation is used in order to avoid stack frame or data area          */
  2820. /* overflow errors that otherwise would have occurred at compile time     */
  2821. /* on the Macintosh computer.                                             */
  2822.  
  2823.     static int numlines[CBANDS];
  2824.     static int partition[HBLKSIZE];
  2825.     static double cbval[CBANDS];
  2826.     static double rnorm[CBANDS];
  2827.     static double window[BLKSIZE];
  2828.     static double absthr[HBLKSIZE];
  2829.     static double tmn[CBANDS];
  2830.     static double s[CBANDS][CBANDS];
  2831.     static double lthr[2][HBLKSIZE];
  2832.     static double r[2][2][HBLKSIZE];
  2833.     static double phi_sav[2][2][HBLKSIZE];
  2834.  
  2835. /* These dynamic memory allocations simulate "automatic" variables        */
  2836. /* placed on the stack.  For each mem_alloc() call here, there must be    */
  2837. /* a corresponding mem_free() call at the end of this function.           */
  2838.  
  2839.     double grouped_c[CBANDS];
  2840.     double grouped_e[CBANDS];
  2841.     double nb[CBANDS];
  2842.     double cb[CBANDS];
  2843.     double ecb[CBANDS];
  2844.     double bc[CBANDS];
  2845.     double wsamp_r[BLKSIZE];
  2846.     double wsamp_i[BLKSIZE];
  2847.     double phi[BLKSIZE];
  2848.     double energy[BLKSIZE];
  2849.     double c[HBLKSIZE];
  2850.     double fthr[HBLKSIZE];
  2851.     double snrtmp[2][32];
  2852.  
  2853.     ZeroMemory(grouped_c,sizeof(grouped_c));
  2854.     ZeroMemory(grouped_e,sizeof(grouped_e));
  2855.     ZeroMemory(nb,sizeof(nb));
  2856.     ZeroMemory(cb,sizeof(cb));
  2857.     ZeroMemory(ecb,sizeof(ecb));
  2858.     ZeroMemory(bc,sizeof(bc));
  2859.     ZeroMemory(wsamp_r,sizeof(wsamp_r));
  2860.     ZeroMemory(wsamp_i,sizeof(wsamp_i));
  2861.     ZeroMemory(phi,sizeof(phi));
  2862.     ZeroMemory(energy,sizeof(energy));
  2863.     ZeroMemory(c,sizeof(c));
  2864.     ZeroMemory(fthr,sizeof(fthr));
  2865.     ZeroMemory(snrtmp,sizeof(snrtmp));
  2866.  
  2867.     if(!init)
  2868.     {
  2869.         init = true;
  2870.  
  2871.         /* These dynamic memory allocations simulate "static" variables placed    */
  2872.         /* in the data space.  Each mem_alloc() call here occurs only once at     */
  2873.         /* initialization time.  The mem_free() function must not be called.      */
  2874.  
  2875.         ZeroMemory(numlines,sizeof(numlines));
  2876.         ZeroMemory(partition,sizeof(partition));
  2877.         ZeroMemory(cbval,sizeof(cbval));
  2878.         ZeroMemory(rnorm,sizeof(rnorm));
  2879.         ZeroMemory(window,sizeof(window));
  2880.         ZeroMemory(tmn,sizeof(tmn));
  2881.         ZeroMemory(absthr,sizeof(absthr));
  2882.         ZeroMemory(s,sizeof(s));
  2883.         ZeroMemory(lthr,sizeof(lthr));
  2884.         ZeroMemory(r,sizeof(r));
  2885.         ZeroMemory(phi_sav,sizeof(phi_sav));
  2886.  
  2887.  
  2888.         switch((unsigned int)(sfreq + 0.5)){
  2889.         case 32000:
  2890.             sfreq_idx = 0;
  2891.             break;
  2892.         case 44100:
  2893.             sfreq_idx = 1;
  2894.             break;
  2895.         case 48000:
  2896.             sfreq_idx = 2;
  2897.             break;
  2898.         default:
  2899.             return TR_SAMPLING_FREQUENCY_ERR;
  2900.         }
  2901.         read_absthr(absthr, sfreq_idx);
  2902.         
  2903.         if(lay==0)
  2904.         {
  2905.             flush = 384;
  2906.             syncsize = 1024;
  2907.             sync_flush = 576;
  2908.         }
  2909.         else
  2910.         {
  2911.             flush = (int)(384.0*3.0/2.0);
  2912.             syncsize = 1056;
  2913.             sync_flush = syncsize - flush;
  2914.         }
  2915.         /* calculate HANN window coefficients */
  2916.         /*   for(i=0;i<BLKSIZE;i++)window[i]=0.5*(1-cos(2.0*PI*i/(BLKSIZE-1.0))); */
  2917.         for(i=0;i<BLKSIZE;i++)
  2918.             window[i]=0.5*(1.0-cos(2.0*PI*(((double)i)-0.5)/BLKSIZE));
  2919.         /* reset states used in unpredictability measure */
  2920.         for(i=0;i<HBLKSIZE;i++)
  2921.         {
  2922.             r[0][0][i]=r[1][0][i]=r[0][1][i]=r[1][1][i]=0.0;
  2923.             phi_sav[0][0][i]=phi_sav[1][0][i]=0.0;
  2924.             phi_sav[0][1][i]=phi_sav[1][1][i]=0.0;
  2925.             lthr[0][i] = 60802371420160.0;
  2926.             lthr[1][i] = 60802371420160.0;
  2927.         }
  2928.         /*****************************************************************************
  2929.         * Initialization: Compute the following constants for use later             *
  2930.         *    partition[HBLKSIZE] = the partition number associated with each        *
  2931.         *                          frequency line                                   *
  2932.         *    cbval[CBANDS]       = the center (average) bark value of each          *
  2933.         *                          partition                                        *
  2934.         *    numlines[CBANDS]    = the number of frequency lines in each partition  *
  2935.         *    tmn[CBANDS]         = tone masking noise                               *
  2936.         *****************************************************************************/
  2937.         /* compute fft frequency multiplicand */
  2938.         freq_mult = sfreq/BLKSIZE;
  2939.  
  2940.         /* calculate fft frequency, then bval of each line (use fthr[] as tmp storage)*/
  2941.         for(i=0;i<HBLKSIZE;i++)
  2942.         {
  2943.             temp1 = ((double)i)*freq_mult;
  2944.             j = 1;
  2945.             while(temp1>crit_band[j])
  2946.                 j++;
  2947.             fthr[i]=j-1+(temp1-crit_band[j-1])/(crit_band[j]-crit_band[j-1]);
  2948.         }
  2949.         partition[0] = 0;
  2950.         /* temp2 is the counter of the number of frequency lines in each partition */
  2951.         temp2 = 1;
  2952.         cbval[0]=fthr[0];
  2953.         bval_lo=fthr[0];
  2954.         for(i=1;i<HBLKSIZE;i++)
  2955.         {
  2956.             if((fthr[i]-bval_lo)>0.33)
  2957.             {
  2958.                 partition[i]=partition[i-1]+1;
  2959.                 cbval[partition[i-1]] = cbval[partition[i-1]]/temp2;
  2960.                 cbval[partition[i]] = fthr[i];
  2961.                 bval_lo = fthr[i];
  2962.                 numlines[partition[i-1]] = (int)temp2;
  2963.                 temp2 = 1;
  2964.             }
  2965.             else
  2966.             {
  2967.                 partition[i]=partition[i-1];
  2968.                 cbval[partition[i]] += fthr[i];
  2969.                 temp2++;
  2970.             }
  2971.         }
  2972.         numlines[partition[i-1]] = (int)temp2;
  2973.         cbval[partition[i-1]] = cbval[partition[i-1]]/temp2;
  2974.  
  2975.         /************************************************************************
  2976.         * Now compute the spreading function, s[j][i], the value of the spread-*
  2977.         * ing function, centered at band j, for band i, store for later use    *
  2978.         ************************************************************************/
  2979.         for(j=0;j<CBANDS;j++)
  2980.         {
  2981.             for(i=0;i<CBANDS;i++)
  2982.             {
  2983.                 temp1 = (cbval[i] - cbval[j])*1.05;
  2984.                 if(temp1>=0.5 && temp1<=2.5)
  2985.                 {
  2986.                     temp2 = temp1 - 0.5;
  2987.                     temp2 = 8.0 * (temp2*temp2 - 2.0 * temp2);
  2988.                 }
  2989.                 else
  2990.                     temp2 = 0;
  2991.  
  2992.                 temp1 += 0.474;
  2993.                 temp3 = 15.811389+7.5*temp1-17.5*sqrt((double) (1.0+temp1*temp1));
  2994.  
  2995.                 if(temp3 <= -100)
  2996.                     s[i][j] = 0;
  2997.                 else
  2998.                 {
  2999.                     temp3 = (temp2 + temp3)*LN_TO_LOG10;
  3000.                     s[i][j] = exp(temp3);
  3001.                 }
  3002.             }
  3003.         }
  3004.  
  3005.         /* Calculate Tone Masking Noise values */
  3006.         for(j=0;j<CBANDS;j++)
  3007.         {
  3008.             temp1 = 15.5 + cbval[j];
  3009.             tmn[j] = (temp1>24.5) ? temp1 : 24.5;
  3010.             /* Calculate normalization factors for the net spreading functions */
  3011.             rnorm[j] = 0;
  3012.             for(i=0;i<CBANDS;i++)
  3013.             {
  3014.                 rnorm[j] += s[j][i];
  3015.             }
  3016.         }
  3017.     }
  3018.  
  3019.     /************************* End of Initialization *****************************/
  3020.     switch(lay)
  3021.     {
  3022.     case 0:
  3023.     case 1:
  3024.         for(i=0; i<=(unsigned)lay; i++)
  3025.         {
  3026.             /*****************************************************************************
  3027.             * Net offset is 480 samples (1056-576) for layer 2; this is because one must*
  3028.             * stagger input data by 256 samples to synchronize psychoacoustic model with*
  3029.             * filter bank outputs, then stagger so that center of 1024 FFT window lines *
  3030.             * up with center of 576 "recent" audio samples.                                *
  3031.             *                                                                           *
  3032.             * For layer 1, the input data still needs to be staggered by 256 samples,   *
  3033.             * then it must be staggered again so that the 384 "recent" samples are centered*
  3034.             * in the 1024 FFT window.  The net offset is then 576 and you need 448 "recent"*
  3035.             * samples for each iteration to keep the 384 samples of interest centered   *
  3036.             *****************************************************************************/
  3037.             for(j=0; j<(unsigned)syncsize; j++)
  3038.             {
  3039.                 if(j<((unsigned)sync_flush))
  3040.                     savebuf[j] = savebuf[j+flush];
  3041.                 else
  3042.                 {
  3043.                     savebuf[j] = buffer[buffer_address];
  3044.                     buffer_address++;
  3045.                 }
  3046.  
  3047.                 if(j<BLKSIZE)
  3048.                 {
  3049.                     /**window data with HANN window***********************************************/
  3050.                     wsamp_r[j] = window[j]*((double) savebuf[j]);
  3051.                     wsamp_i[j] = 0;
  3052.                 }
  3053.             }
  3054.             /**Compute FFT****************************************************************/
  3055.             fft(wsamp_r,wsamp_i,energy,phi,1024);
  3056.             /*****************************************************************************
  3057.             * calculate the unpredictability measure, given energy[f] and phi[f]        *
  3058.             *****************************************************************************/
  3059.             /*only update data "age" pointers after you are done with both channels      */
  3060.             /*for layer 1 computations, for the layer 2 double computations, the pointers*/
  3061.             /*are reset automatically on the second pass                                 */
  3062.             if(lay==1 || (lay==0 && chn==0) )
  3063.             {
  3064.                 if(recent==0)
  3065.                 {
  3066.                     recent = 1;
  3067.                     oldest = 1;
  3068.                 }
  3069.                 else
  3070.                 {
  3071.                     recent = 0;
  3072.                     oldest = 0;
  3073.                 }
  3074.                 if(old==0)
  3075.                     old = 1;
  3076.                 else
  3077.                     old = 0;
  3078.             }
  3079.             for(j=0; j<HBLKSIZE; j++)
  3080.             {
  3081.                 r_prime = 2.0 * r[chn][old][j] - r[chn][oldest][j];
  3082.                 phi_prime = 2.0 * phi_sav[chn][old][j] - phi_sav[chn][oldest][j];
  3083.                 r[chn][recent][j] = sqrt(energy[j]);
  3084.                 phi_sav[chn][recent][j] = phi[j];
  3085.                 temp1=r[chn][recent][j] * cos(phi[j]) - r_prime * cos(phi_prime);
  3086.                 temp2=r[chn][recent][j] * sin(phi[j]) - r_prime * sin(phi_prime);
  3087.                 temp3=r[chn][recent][j] + fabs(r_prime);
  3088.                 if(temp3 != 0)
  3089.                     c[j]=sqrt(temp1*temp1+temp2*temp2)/temp3;
  3090.                 else
  3091.                     c[j] = 0;
  3092.             }
  3093.             /*****************************************************************************
  3094.             * Calculate the grouped, energy-weighted, unpredictability measure,         *
  3095.             * grouped_c[], and the grouped energy. grouped_e[]                          *
  3096.             *****************************************************************************/
  3097.             for(j=1;j<CBANDS;j++)
  3098.             {
  3099.                 grouped_e[j] = 0;
  3100.                 grouped_c[j] = 0;
  3101.             }
  3102.             grouped_e[0] = energy[0];
  3103.             grouped_c[0] = energy[0]*c[0];
  3104.             for(j=1;j<HBLKSIZE;j++)
  3105.             {
  3106.                 grouped_e[partition[j]] += energy[j];
  3107.                 grouped_c[partition[j]] += energy[j]*c[j];
  3108.             }
  3109.             /*****************************************************************************
  3110.             * convolve the grouped energy-weighted unpredictability measure             *
  3111.             * and the grouped energy with the spreading function, s[j][k]               *
  3112.             *****************************************************************************/
  3113.             for(j=0;j<CBANDS;j++)
  3114.             {
  3115.                 ecb[j] = 0;
  3116.                 cb[j] = 0;
  3117.                 for(k=0;k<CBANDS;k++)
  3118.                 {
  3119.                     if(s[j][k] != 0.0)
  3120.                     {
  3121.                         ecb[j] += s[j][k]*grouped_e[k];
  3122.                         cb[j] += s[j][k]*grouped_c[k];
  3123.                     }
  3124.                 }
  3125.                 if(ecb[j] !=0)
  3126.                     cb[j] = cb[j]/ecb[j];
  3127.                 else
  3128.                     cb[j] = 0;
  3129.             }
  3130.             /*****************************************************************************
  3131.             * Calculate the required SNR for each of the frequency partitions           *
  3132.             *         this whole section can be accomplished by a table lookup          *
  3133.             *****************************************************************************/
  3134.             for(j=0;j<CBANDS;j++){
  3135.                 if(cb[j]<.05)
  3136.                     cb[j]=0.05;
  3137.                 else if(cb[j]>.5)
  3138.                     cb[j]=0.5;
  3139.                 tb = -0.434294482*log(cb[j])-0.301029996;
  3140.                 bc[j] = tmn[j]*tb + nmt*(1.0-tb);
  3141.                 k = (unsigned int)(cbval[j] + 0.5);
  3142.                 bc[j] = (bc[j] > bmax[k]) ? bc[j] : bmax[k];
  3143.                 bc[j] = exp(-bc[j]*LN_TO_LOG10);
  3144.             }
  3145.             /*****************************************************************************
  3146.             * Calculate the permissible noise energy level in each of the frequency     *
  3147.             * partitions. Include absolute threshold and pre-echo controls              *
  3148.             *         this whole section can be accomplished by a table lookup          *
  3149.             *****************************************************************************/
  3150.             for(j=0;j<CBANDS;j++)
  3151.                 if(rnorm[j] && numlines[j])
  3152.                     nb[j] = ecb[j]*bc[j]/(rnorm[j]*numlines[j]);
  3153.                 else
  3154.                     nb[j] = 0;
  3155.             for(j=0;j<HBLKSIZE;j++)
  3156.             {
  3157.                 /*temp1 is the preliminary threshold */
  3158.                 temp1=nb[partition[j]];
  3159.                 temp1=(temp1>absthr[j])?temp1:absthr[j];
  3160.                 /*do not use pre-echo control for layer 2 because it may do bad things to the*/
  3161.                 /*  MUSICAM bit allocation algorithm                                         */
  3162.                 if(lay==0)
  3163.                 {
  3164.                     fthr[j] = (temp1 < lthr[chn][j]) ? temp1 : lthr[chn][j];
  3165.                     temp2 = temp1 * 0.00316;
  3166.                     fthr[j] = (temp2 > fthr[j]) ? temp2 : fthr[j];
  3167.                 }
  3168.                 else
  3169.                     fthr[j] = temp1;
  3170.                 lthr[chn][j] = LXMIN*temp1;
  3171.             }
  3172.             /*****************************************************************************
  3173.             * Translate the 512 threshold values to the 32 filter bands of the coder    *
  3174.             *****************************************************************************/
  3175.             for(j=0;j<193;j += 16)
  3176.             {
  3177.                 minthres = 60802371420160.0;
  3178.                 sum_energy = 0.0;
  3179.                 for(k=0;k<17;k++)
  3180.                 {
  3181.                     if(minthres>fthr[j+k])
  3182.                         minthres = fthr[j+k];
  3183.                     sum_energy += energy[j+k];
  3184.                 }
  3185.                 snrtmp[i][j/16] = sum_energy/(minthres * 17.0);
  3186.                 snrtmp[i][j/16] = 4.342944819 * log(snrtmp[i][j/16]);
  3187.             }
  3188.             for(j=208;j<(HBLKSIZE-1);j += 16)
  3189.             {
  3190.                 minthres = 0.0;
  3191.                 sum_energy = 0.0;
  3192.                 for(k=0;k<17;k++)
  3193.                 {
  3194.                     minthres += fthr[j+k];
  3195.                     sum_energy += energy[j+k];
  3196.                 }
  3197.                 snrtmp[i][j/16] = sum_energy/minthres;
  3198.                 snrtmp[i][j/16] = 4.342944819 * log(snrtmp[i][j/16]);
  3199.             }
  3200.         /*****************************************************************************
  3201.         * End of Psychoacuostic calculation loop                                    *
  3202.         *****************************************************************************/
  3203.         }
  3204.         for(i=0; i<32; i++)
  3205.         {
  3206.             if(lay==1)
  3207.                 snr32[i]=(snrtmp[0][i]>snrtmp[1][i])?snrtmp[0][i]:snrtmp[1][i];
  3208.             else
  3209.                 snr32[i]=snrtmp[0][i];
  3210.         }
  3211.         break;
  3212.     case 3:
  3213.         return TR_NO_SUPPORTED_AUDIO_LAYER;
  3214.     default:
  3215.         return TR_NO_SUPPORTED_AUDIO_LAYER;
  3216.     }
  3217.     return TR_OK;
  3218. }
  3219.  
  3220.