home *** CD-ROM | disk | FTP | other *** search
/ Magazyn Amiga 5 / MA_Cover_5.iso / ppc / wos_mpeg_encode / mpegaudio / encode.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-05-04  |  50.6 KB  |  1,324 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. encode.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 3.9t                                                       *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers         comment                               *
  14.  * 3/01/91  Douglas Wong,       start of version 1.1 records          *
  15.  *          Davis Pan                                                 *
  16.  * 3/06/91  Douglas Wong        rename: setup.h to endef.h            *
  17.  *                                      efilter to enfilter           *
  18.  *                                      ewindow to enwindow           *
  19.  *                              integrated "quantizer", "scalefactor",*
  20.  *                              and "transmission" files              *
  21.  *                              update routine "window_subband"       *
  22.  * 3/31/91  Bill Aspromonte     replaced read_filter by               *
  23.  *                              create_an_filter                      *
  24.  * 5/10/91  W. Joseph Carter    Ported to Macintosh and Unix.         *
  25.  *                              Incorporated Jean-Georges Fritsch's   *
  26.  *                              "bitstream.c" package.                *
  27.  *                              Incorporated Bill Aspromonte's        *
  28.  *                              filterbank coefficient matrix         *
  29.  *                              calculation routines and added        *
  30.  *                              roundoff to coincide with specs.      *
  31.  *                              Modified to strictly adhere to        *
  32.  *                              encoded bitstream specs, including    *
  33.  *                              "Berlin changes".                     *
  34.  *                              Modified PCM sound file handling to   *
  35.  *                              process all incoming samples and fill *
  36.  *                              out last encoded frame with zeros     *
  37.  *                              (silence) if needed.                  *
  38.  *                              Located and fixed numerous software   *
  39.  *                              bugs and table data errors.           *
  40.  * 19jun91  dpwe (Aware)        moved "alloc_*" reader to common.c    *
  41.  *                              Globals sblimit, alloc replaced by new*
  42.  *                              struct 'frame_params' passed as arg.  *
  43.  *                              Added JOINT STEREO coding, layers I,II*
  44.  *                              Affects: *_bit_allocation,            *
  45.  *                              subband_quantization, encode_bit_alloc*
  46.  *                              sample_encoding                       *
  47.  * 6/10/91  Earle Jennings      modified II_subband_quantization to   *
  48.  *                              resolve type cast problem for MS_DOS  *
  49.  * 6/11/91  Earle Jennings      modified to avoid overflow on MS_DOS  *
  50.  *                              in routine filter_subband             *
  51.  * 7/10/91  Earle Jennings      port to MsDos from MacIntosh version  *
  52.  * 8/ 8/91  Jens Spille         Change for MS-C6.00                   *
  53.  *10/ 1/91  S.I. Sudharsanan,   Ported to IBM AIX platform.           *
  54.  *          Don H. Lee,                                               *
  55.  *          Peter W. Farrett                                          *
  56.  *10/ 3/91  Don H. Lee          implemented CRC-16 error protection   *
  57.  *                              newly introduced function encode_CRC  *
  58.  *11/ 8/91  Kathy Wang          Documentation of code                 *
  59.  *                              All variablenames are referred to     *
  60.  *                              with surrounding pound (#) signs      *
  61.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  62.  *                              important fixes involved changing     *
  63.  *                              16-bit ints to long or unsigned in    *
  64.  *                              bit alloc routines for quant of 65535 *
  65.  *                              and passing proper function args.     *
  66.  *                              Removed "Other Joint Stereo" option   *
  67.  *                              and made bitrate be total channel     *
  68.  *                              bitrate, irrespective of the mode.    *
  69.  *                              Fixed many small bugs & reorganized.  *
  70.  * 6/16/92  Shaun Astarabadi    Changed I_scale_factor_calc() and     *
  71.  *                              II_scale_factor_calc() to use scale   *
  72.  *                              factor 0 thru 62 only and not to      *
  73.  *                              encode index 63 into the bit stream.  *
  74.  * 7/27/92  Mike Li             (re-)Port to MS-DOS                   *
  75.  * 9/22/92  jddevine@aware.com  Fixed _scale_factor_calc() defs       *
  76.  * 3/31/93  Giogio Dimino       changed II_a_bit_allocation() from:   *
  77.  *                              if( ad > ...) to if(ad >= ...)        *
  78.  * 8/05/93  TEST                changed I_a_bit_allocation() from:    *
  79.  *                              if( ad > ...) to if(ad >= ...)        *
  80.  **********************************************************************/
  81.  
  82. #include "common.h"
  83. #include "encoder.h"
  84.  
  85. #ifdef MS_DOS
  86. extern unsigned _stklen = 16384;
  87. #endif
  88.  
  89.  
  90. /*=======================================================================\
  91. |                                                                       |
  92. | This segment contains all the core routines of the encoder,           |
  93. | except for the psychoacoustic models.                                 |
  94. |                                                                       |
  95. | The user can select either one of the two psychoacoustic              |
  96. | models. Model I is a simple tonal and noise masking threshold         |
  97. | generator, and Model II is a more sophisticated cochlear masking      |
  98. | threshold generator. Model I is recommended for lower complexity      |
  99. | applications whereas Model II gives better subjective quality at low  |
  100. | bit rates.                                                            |
  101. |                                                                       |
  102. | Layers I and II of mono, stereo, and joint stereo modes are supported.|
  103. | Routines associated with a given layer are prefixed by "I_" for layer |
  104. | 1 and "II_" for layer 2.                                              |
  105. \=======================================================================*/
  106.  
  107. /************************************************************************/
  108. /*
  109. /* read_samples()
  110. /*
  111. /* PURPOSE:  reads the PCM samples from a file to the buffer
  112. /*
  113. /*  SEMANTICS:
  114. /* Reads #samples_read# number of shorts from #musicin# filepointer
  115. /* into #sample_buffer[]#.  Returns the number of samples read.
  116. /*
  117. /************************************************************************/
  118.  
  119. unsigned long read_samples(FILE *musicin, short sample_buffer[2304], unsigned long num_samples, unsigned long frame_size)
  120. {
  121.     unsigned long samples_read;
  122.     static unsigned long samples_to_read;
  123.     static char init = TRUE;
  124.  
  125.     if (init) {
  126.         samples_to_read = num_samples;
  127.         init = FALSE;
  128.     }
  129.     if (samples_to_read >= frame_size)
  130.         samples_read = frame_size;
  131.     else
  132.         samples_read = samples_to_read;
  133.     if ((samples_read =
  134.          fread(sample_buffer, sizeof(short), (int)samples_read, musicin)) == 0)
  135.         printf("Hit end of audio data\n");
  136.     samples_to_read -= samples_read;
  137.     if (samples_read < frame_size && samples_read > 0) {
  138.         printf("Insufficient PCM input for one frame - fillout with zeros\n");
  139.         for (; samples_read < frame_size; sample_buffer[samples_read++] = 0);
  140.         samples_to_read = 0;
  141.     }
  142.     return(samples_read);
  143. }
  144.  
  145. /************************************************************************/
  146. /*
  147. /* get_audio()
  148. /*
  149. /* PURPOSE:  reads a frame of audio data from a file to the buffer,
  150. /*   aligns the data for future processing, and separates the
  151. /*   left and right channels
  152. /*
  153. /*  SEMANTICS:
  154. /* Calls read_samples() to read a frame of audio data from filepointer
  155. /* #musicin# to #insampl[]#.  The data is shifted to make sure the data
  156. /* is centered for the 1024pt window to be used by the psychoacoustic model,
  157. /* and to compensate for the 256 sample delay from the filter bank. For
  158. /* stereo, the channels are also demultiplexed into #buffer[0][]# and
  159. /* #buffer[1][]#
  160. /*
  161. /************************************************************************/
  162.  
  163. unsigned long get_audio(FILE *musicin, short FAR buffer[2][1152], unsigned long num_samples, int stereo, int lay)
  164. {
  165.    int j;
  166.    short insamp[2304];
  167.    unsigned long samples_read;
  168.  
  169.    if (lay == 1){
  170.       if(stereo == 2){ /* layer 1, stereo */
  171.          samples_read = read_samples(musicin, insamp, num_samples,
  172.                                      (unsigned long) 768);
  173.          for(j=0;j<448;j++) {
  174.             if(j<64) {
  175.                buffer[0][j] = buffer[0][j+384];
  176.                buffer[1][j] = buffer[1][j+384];
  177.             }
  178.             else {
  179.                buffer[0][j] = insamp[2*j-128];
  180.                buffer[1][j] = insamp[2*j-127];
  181.             }
  182.          }
  183.       }
  184.       else { /* layer 1, mono */
  185.          samples_read = read_samples(musicin, insamp, num_samples,
  186.                                      (unsigned long) 384);
  187.          for(j=0;j<448;j++){
  188.             if(j<64) {
  189.                buffer[0][j] = buffer[0][j+384];
  190.                buffer[1][j] = 0;
  191.             }
  192.             else {
  193.                buffer[0][j] = insamp[j-64];
  194.                buffer[1][j] = 0;
  195.             }
  196.          }
  197.       }
  198.    }
  199.    else {
  200.       if(stereo == 2){ /* layer 2 (or 3), stereo */
  201.          samples_read = read_samples(musicin, insamp, num_samples,
  202.                                      (unsigned long) 2304);
  203.          for(j=0;j<1152;j++) {
  204.             buffer[0][j] = insamp[2*j];
  205.             buffer[1][j] = insamp[2*j+1];
  206.          }
  207.       }
  208.       else { /* layer 2 (or 3), mono */
  209.          samples_read = read_samples(musicin, insamp, num_samples,
  210.                                      (unsigned long) 1152);
  211.          for(j=0;j<1152;j++){
  212.             buffer[0][j] = insamp[j];
  213.             buffer[1][j] = 0;
  214.          }
  215.       }
  216.    }
  217.    return(samples_read);
  218. }
  219.  
  220. /************************************************************************/
  221. /*
  222. /* read_ana_window()
  223. /*
  224. /* PURPOSE:  Reads encoder window file "enwindow" into array #ana_win#
  225. /*
  226. /************************************************************************/
  227.  
  228. void read_ana_window(double FAR ana_win[HAN_SIZE])
  229. {
  230.     int i,j[4];
  231.     FILE *fp;
  232.     double f[4];
  233.     char t[150];
  234.  
  235.     if (!(fp = OpenTableFile("enwindow") ) ) {
  236.        printf("Please check analysis window table 'enwindow'\n");
  237.        exit(1);
  238.     }
  239.     for (i=0;i<512;i+=4) {
  240.        fgets(t, 150, fp);
  241.        sscanf(t,"C[%d] = %lf C[%d] = %lf C[%d] = %lf C[%d] = %lf\n",
  242.               j, f,j+1,f+1,j+2,f+2,j+3,f+3);
  243.        if (i==j[0]) {
  244.           ana_win[i] = f[0];
  245.           ana_win[i+1] = f[1];
  246.           ana_win[i+2] = f[2];
  247.           ana_win[i+3] = f[3];
  248.        }
  249.        else {
  250.           printf("Check index in analysis window table\n");
  251.           exit(1);
  252.        }
  253.        fgets(t,150,fp);
  254.     }
  255.     fclose(fp);
  256. }
  257.  
  258. /************************************************************************/
  259. /*
  260. /* window_subband()
  261. /*
  262. /* PURPOSE:  Overlapping window on PCM samples
  263. /*
  264. /* SEMANTICS:
  265. /* 32 16-bit pcm samples are scaled to fractional 2's complement and
  266. /* concatenated to the end of the window buffer #x#. The updated window
  267. /* buffer #x# is then windowed by the analysis window #c# to produce the
  268. /* windowed sample #z#
  269. /*
  270. /************************************************************************/
  271.  
  272. void window_subband(short FAR **buffer, double FAR z[HAN_SIZE], int k)
  273. {
  274.     typedef double FAR XX[2][HAN_SIZE];
  275.     static XX FAR *x;
  276.     int i, j;
  277.     static int off[2] = {0,0};
  278.     static char init = 0;
  279.     static double FAR *c;
  280.     if (!init) {
  281.         c = (double FAR *) mem_alloc(sizeof(double) * HAN_SIZE, "window");
  282.         read_ana_window(c);
  283.         x = (XX FAR *) mem_alloc(sizeof(XX),"x");
  284.         for (i=0;i<2;i++)
  285.             for (j=0;j<HAN_SIZE;j++)
  286.                 (*x)[i][j] = 0;
  287.         init = 1;
  288.     }
  289.  
  290.     /* replace 32 oldest samples with 32 new samples */
  291.     for (i=0;i<32;i++)
  292.     {
  293.      (*x)[k][31-i+off[k]] =
  294.      (double) *(*buffer)++/SCALE;
  295.     }
  296.     /* shift samples into proper window positions */
  297.     for (i=0;i<HAN_SIZE;i++) z[i] = (*x)[k][(i+off[k])&HAN_SIZE-1] * c[i];
  298.     off[k] += 480;              /*offset is modulo (HAN_SIZE-1)*/
  299.     off[k] &= HAN_SIZE-1;
  300.  
  301. }
  302.  
  303. /************************************************************************/
  304. /*
  305. /* create_ana_filter()
  306. /*
  307. /* PURPOSE:  Calculates the analysis filter bank coefficients
  308. /*
  309. /* SEMANTICS:
  310. /* Calculates the analysis filterbank coefficients and rounds to the
  311. /* 9th decimal place accuracy of the filterbank tables in the ISO
  312. /* document.  The coefficients are stored in #filter#
  313. /*
  314. /************************************************************************/
  315.  
  316. void create_ana_filter(double FAR filter[SBLIMIT][64])
  317. {
  318.    register int i,k;
  319.  
  320.    for (i=0; i<32; i++)
  321.       for (k=0; k<64; k++) {
  322.           if ((filter[i][k] = 1e9*cos((double)((2*i+1)*(16-k)*PI64))) >= 0)
  323.              modf(filter[i][k]+0.5, &filter[i][k]);
  324.           else
  325.              modf(filter[i][k]-0.5, &filter[i][k]);
  326.           filter[i][k] *= 1e-9;
  327.    }
  328. }
  329.  
  330. /************************************************************************/
  331. /*
  332. /* filter_subband()
  333. /*
  334. /* PURPOSE:  Calculates the analysis filter bank coefficients
  335. /*
  336. /* SEMANTICS:
  337. /*      The windowed samples #z# is filtered by the digital filter matrix #m#
  338. /* to produce the subband samples #s#. This done by first selectively
  339. /* picking out values from the windowed samples, and then multiplying
  340. /* them by the filter matrix, producing 32 subband samples.
  341. /*
  342. /************************************************************************/
  343.  
  344. void filter_subband(double FAR z[HAN_SIZE],double FAR s[SBLIMIT])
  345. {
  346.    double y[64];
  347.    int i,j;
  348. static char init = 0;
  349.    typedef double MM[SBLIMIT][64];
  350. static MM FAR *m;
  351. #ifdef MS_DOS
  352.    long    SIZE_OF_MM;
  353.    SIZE_OF_MM      = SBLIMIT*64;
  354.    SIZE_OF_MM      *= 8;
  355.    if (!init) {
  356.        m = (MM FAR *) mem_alloc(SIZE_OF_MM, "filter");
  357.        create_ana_filter(*m);
  358.        init = 1;
  359.    }
  360. #else
  361.    if (!init) {
  362.        m = (MM FAR *) mem_alloc(sizeof(MM), "filter");
  363.        create_ana_filter(*m);
  364.        init = 1;
  365.    }
  366. #endif
  367.    for (i=0;i<64;i++) for (j=0, y[i] = 0;j<8;j++) y[i] += z[i+64*j];
  368.    for (i=0;i<SBLIMIT;i++)
  369.        for (j=0, s[i]= 0;j<64;j++) s[i] += (*m)[i][j] * y[j];
  370. }
  371.  
  372. /************************************************************************/
  373. /*
  374. /* encode_info()
  375. /*
  376. /* PURPOSE:  Puts the syncword and header information on the output
  377. /* bitstream.
  378. /*
  379. /************************************************************************/
  380.  
  381. void encode_info(frame_params *fr_ps,Bit_stream_struc *bs)
  382. {
  383.         layer *info = fr_ps->header;
  384.  
  385.         putbits(bs,0xfff,12);                    /* syncword 12 bits */
  386.         put1bit(bs,info->version);               /* ID        1 bit  */
  387.         putbits(bs,4-info->lay,2);               /* layer     2 bits */
  388.         put1bit(bs,!info->error_protection);     /* bit set => no err prot */
  389.         putbits(bs,info->bitrate_index,4);
  390.         putbits(bs,info->sampling_frequency,2);
  391.         put1bit(bs,info->padding);
  392.         put1bit(bs,info->extension);             /* private_bit */
  393.         putbits(bs,info->mode,2);
  394.         putbits(bs,info->mode_ext,2);
  395.         put1bit(bs,info->copyright);
  396.         put1bit(bs,info->original);
  397.         putbits(bs,info->emphasis,2);
  398. }
  399.  
  400. /************************************************************************/
  401. /*
  402. /* mod()
  403. /*
  404. /* PURPOSE:  Returns the absolute value of its argument
  405. /*
  406. /************************************************************************/
  407.  
  408. double mod(double a)
  409. {
  410.     return (a > 0) ? a : -a;
  411. }
  412.  
  413. /************************************************************************/
  414. /*
  415. /* I_combine_LR    (Layer I)
  416. /* II_combine_LR   (Layer II)
  417. /*
  418. /* PURPOSE:Combines left and right channels into a mono channel
  419. /*
  420. /* SEMANTICS:  The average of left and right subband samples is put into
  421. /* #joint_sample#
  422. /*
  423. /* Layer I and II differ in frame length and # subbands used
  424. /*
  425. /************************************************************************/
  426.  
  427. void I_combine_LR(double FAR sb_sample[2][3][SCALE_BLOCK][SBLIMIT], double FAR joint_sample[3][SCALE_BLOCK][SBLIMIT])
  428. {   /* make a filtered mono for joint stereo */
  429.     int sb, smp;
  430.  
  431.    for(sb = 0; sb<SBLIMIT; ++sb)
  432.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  433.         joint_sample[0][smp][sb] = .5 *
  434.                     (sb_sample[0][0][smp][sb] + sb_sample[1][0][smp][sb]);
  435. }
  436.  
  437. void II_combine_LR(double FAR sb_sample[2][3][SCALE_BLOCK][SBLIMIT], double FAR joint_sample[3][SCALE_BLOCK][SBLIMIT], int sblimit)
  438. {  /* make a filtered mono for joint stereo */
  439.    int sb, smp, sufr;
  440.  
  441.    for(sb = 0; sb<sblimit; ++sb)
  442.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  443.          for(sufr = 0; sufr<3; ++sufr)
  444.             joint_sample[sufr][smp][sb] = .5 * (sb_sample[0][sufr][smp][sb]
  445.                                            + sb_sample[1][sufr][smp][sb]);
  446. }
  447.  
  448. /************************************************************************
  449. /*
  450. /* I_scale_factor_calc     (Layer I)
  451. /* II_scale_factor_calc    (Layer II)
  452. /*
  453. /* PURPOSE:For each subband, calculate the scale factor for each set
  454. /* of the 12 subband samples
  455. /*
  456. /* SEMANTICS:  Pick the scalefactor #multiple[]# just larger than the
  457. /* absolute value of the peak subband sample of 12 samples,
  458. /* and store the corresponding scalefactor index in #scalar#.
  459. /*
  460. /* Layer II has three sets of 12-subband samples for a given
  461. /* subband.
  462. /*
  463. /************************************************************************/
  464.  
  465. void I_scale_factor_calc(double FAR sb_sample[][3][SCALE_BLOCK][SBLIMIT],unsigned int scalar[][3][SBLIMIT],int stereo)
  466. {
  467.    int i,j, k;
  468.    double s[SBLIMIT];
  469.  
  470.    for (k=0;k<stereo;k++) {
  471.      for (i=0;i<SBLIMIT;i++)
  472.        for (j=1, s[i] = mod(sb_sample[k][0][0][i]);j<SCALE_BLOCK;j++)
  473.          if (mod(sb_sample[k][0][j][i]) > s[i])
  474.             s[i] = mod(sb_sample[k][0][j][i]);
  475.  
  476.      for (i=0;i<SBLIMIT;i++)
  477.        for (j=SCALE_RANGE-2,scalar[k][0][i]=0;j>=0;j--) /* $A 6/16/92 */
  478.          if (s[i] <= multiple[j]) {
  479.             scalar[k][0][i] = j;
  480.             break;
  481.          }
  482.    }
  483. }
  484.  
  485. /******************************** Layer II ******************************/
  486.  
  487. void II_scale_factor_calc(double FAR sb_sample[][3][SCALE_BLOCK][SBLIMIT],unsigned int scalar[][3][SBLIMIT],int stereo,int sblimit)
  488. {
  489.   int i,j, k,t;
  490.   double s[SBLIMIT];
  491.  
  492.   for (k=0;k<stereo;k++) for (t=0;t<3;t++) {
  493.     for (i=0;i<sblimit;i++)
  494.       for (j=1, s[i] = mod(sb_sample[k][t][0][i]);j<SCALE_BLOCK;j++)
  495.         if (mod(sb_sample[k][t][j][i]) > s[i])
  496.              s[i] = mod(sb_sample[k][t][j][i]);
  497.  
  498.   for (i=0;i<sblimit;i++)
  499.     for (j=SCALE_RANGE-2,scalar[k][t][i]=0;j>=0;j--)    /* $A 6/16/92 */
  500.       if (s[i] <= multiple[j]) {
  501.          scalar[k][t][i] = j;
  502.          break;
  503.       }
  504.       for (i=sblimit;i<SBLIMIT;i++) scalar[k][t][i] = SCALE_RANGE-1;
  505.     }
  506. }
  507.  
  508. /************************************************************************
  509. /*
  510. /* pick_scale  (Layer II)
  511. /*
  512. /* PURPOSE:For each subband, puts the smallest scalefactor of the 3
  513. /* associated with a frame into #max_sc#.  This is used
  514. /* used by Psychoacoustic Model I.
  515. /* (I would recommend changin max_sc to min_sc)
  516. /*
  517. /************************************************************************/
  518.  
  519. void pick_scale(unsigned int scalar[2][3][SBLIMIT], frame_params *fr_ps, double FAR max_sc[2][SBLIMIT])
  520. {
  521.   int i,j,k,max;
  522.   int stereo  = fr_ps->stereo;
  523.   int sblimit = fr_ps->sblimit;
  524.  
  525.   for (k=0;k<stereo;k++)
  526.     for (i=0;i<sblimit;max_sc[k][i] = multiple[max],i++)
  527.       for (j=1, max = scalar[k][0][i];j<3;j++)
  528.          if (max > scalar[k][j][i]) max = scalar[k][j][i];
  529.   for (i=sblimit;i<SBLIMIT;i++) max_sc[0][i] = max_sc[1][i] = 1E-20;
  530. }
  531.  
  532. /************************************************************************
  533. /*
  534. /* put_scale   (Layer I)
  535. /*
  536. /* PURPOSE:Sets #max_sc# to the scalefactor index in #scalar.
  537. /* This is used by Psychoacoustic Model I
  538. /*
  539. /************************************************************************/
  540.  
  541. void put_scale(unsigned int scalar[2][3][SBLIMIT], frame_params *fr_ps, double FAR max_sc[2][SBLIMIT])
  542. {
  543.    int i,j,k, max;
  544.    int stereo  = fr_ps->stereo;
  545.    int sblimit = fr_ps->sblimit;
  546.  
  547.    for (k=0;k<stereo;k++) for (i=0;i<SBLIMIT;i++)
  548.         max_sc[k][i] = multiple[scalar[k][0][i]];
  549. }
  550.  
  551. /************************************************************************
  552. /*
  553. /* II_transmission_pattern (Layer II only)
  554. /*
  555. /* PURPOSE:For a given subband, determines whether to send 1, 2, or
  556. /* all 3 of the scalefactors, and fills in the scalefactor
  557. /* select information accordingly
  558. /*
  559. /* SEMANTICS:  The subbands and channels are classified based on how much
  560. /* the scalefactors changes over its three values (corresponding
  561. /* to the 3 sets of 12 samples per subband).  The classification
  562. /* will send 1 or 2 scalefactors instead of three if the scalefactors
  563. /* do not change much.  The scalefactor select information,
  564. /* #scfsi#, is filled in accordingly.
  565. /*
  566. /************************************************************************/
  567.  
  568. void II_transmission_pattern(unsigned int scalar[2][3][SBLIMIT], unsigned int scfsi[2][SBLIMIT], frame_params *fr_ps)
  569. {
  570.    int stereo  = fr_ps->stereo;
  571.    int sblimit = fr_ps->sblimit;
  572.    int dscf[2];
  573.    int class[2],i,j,k;
  574. static int pattern[5][5] = {0x123, 0x122, 0x122, 0x133, 0x123,
  575.                             0x113, 0x111, 0x111, 0x444, 0x113,
  576.                             0x111, 0x111, 0x111, 0x333, 0x113,
  577.                             0x222, 0x222, 0x222, 0x333, 0x123,
  578.                             0x123, 0x122, 0x122, 0x133, 0x123};
  579.  
  580.    for (k=0;k<stereo;k++)
  581.      for (i=0;i<sblimit;i++) {
  582.        dscf[0] =  (scalar[k][0][i]-scalar[k][1][i]);
  583.        dscf[1] =  (scalar[k][1][i]-scalar[k][2][i]);
  584.        for (j=0;j<2;j++) {
  585.          if (dscf[j]<=-3) class[j] = 0;
  586.          else if (dscf[j] > -3 && dscf[j] <0) class[j] = 1;
  587.               else if (dscf[j] == 0) class[j] = 2;
  588.                    else if (dscf[j] > 0 && dscf[j] < 3) class[j] = 3;
  589.                         else class[j] = 4;
  590.        }
  591.        switch (pattern[class[0]][class[1]]) {
  592.          case 0x123 :    scfsi[k][i] = 0;
  593.                          break;
  594.          case 0x122 :    scfsi[k][i] = 3;
  595.                          scalar[k][2][i] = scalar[k][1][i];
  596.                          break;
  597.          case 0x133 :    scfsi[k][i] = 3;
  598.                          scalar[k][1][i] = scalar[k][2][i];
  599.                          break;
  600.          case 0x113 :    scfsi[k][i] = 1;
  601.                          scalar[k][1][i] = scalar[k][0][i];
  602.                          break;
  603.          case 0x111 :    scfsi[k][i] = 2;
  604.                          scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  605.                          break;
  606.          case 0x222 :    scfsi[k][i] = 2;
  607.                          scalar[k][0][i] = scalar[k][2][i] = scalar[k][1][i];
  608.                          break;
  609.          case 0x333 :    scfsi[k][i] = 2;
  610.                          scalar[k][0][i] = scalar[k][1][i] = scalar[k][2][i];
  611.                          break;
  612.          case 0x444 :    scfsi[k][i] = 2;
  613.                          if (scalar[k][0][i] > scalar[k][2][i])
  614.                               scalar[k][0][i] = scalar[k][2][i];
  615.                          scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  616.       }
  617.    }
  618. }
  619.  
  620. /************************************************************************
  621. /*
  622. /* I_encode_scale  (Layer I)
  623. /* II_encode_scale (Layer II)
  624. /*
  625. /* PURPOSE:The encoded scalar factor information is arranged and
  626. /* queued into the output fifo to be transmitted.
  627. /*
  628. /* For Layer II, the three scale factors associated with
  629. /* a given subband and channel are transmitted in accordance
  630. /* with the scfsi, which is transmitted first.
  631. /*
  632. /************************************************************************/
  633.  
  634. void I_encode_scale(unsigned int scalar[2][3][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], frame_params *fr_ps, Bit_stream_struc *bs)
  635. {
  636.    int stereo  = fr_ps->stereo;
  637.    int sblimit = fr_ps->sblimit;
  638.    int i,j;
  639.  
  640.    for (i=0;i<SBLIMIT;i++) for (j=0;j<stereo;j++)
  641.       if (bit_alloc[j][i]) putbits(bs,scalar[j][0][i],6);
  642. }
  643.  
  644. /***************************** Layer II  ********************************/
  645.  
  646. void II_encode_scale(unsigned int bit_alloc[2][SBLIMIT], unsigned int scfsi[2][SBLIMIT], unsigned int scalar[2][3][SBLIMIT], frame_params *fr_ps, Bit_stream_struc *bs)
  647. {
  648.    int stereo  = fr_ps->stereo;
  649.    int sblimit = fr_ps->sblimit;
  650.    int jsbound = fr_ps->jsbound;
  651.    int i,j,k;
  652.  
  653.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  654.      if (bit_alloc[k][i])  putbits(bs,scfsi[k][i],2);
  655.  
  656.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  657.      if (bit_alloc[k][i])  /* above jsbound, bit_alloc[0][i] == ba[1][i] */
  658.         switch (scfsi[k][i]) {
  659.            case 0: for (j=0;j<3;j++)
  660.                      putbits(bs,scalar[k][j][i],6);
  661.                    break;
  662.            case 1:
  663.            case 3: putbits(bs,scalar[k][0][i],6);
  664.                    putbits(bs,scalar[k][2][i],6);
  665.                    break;
  666.            case 2: putbits(bs,scalar[k][0][i],6);
  667.         }
  668. }
  669.  
  670. /*=======================================================================\
  671. |                                                                        |
  672. |      The following routines are done after the masking threshold       |
  673. | has been calculated by the fft analysis routines in the Psychoacoustic |
  674. | model. Using the MNR calculated, the actual number of bits allocated   |
  675. | to each subband is found iteratively.                                  |
  676. |                                                                        |
  677. \=======================================================================*/
  678.  
  679. /************************************************************************
  680. /*
  681. /* I_bits_for_nonoise  (Layer I)
  682. /* II_bits_for_nonoise (Layer II)
  683. /*
  684. /* PURPOSE:Returns the number of bits required to produce a
  685. /* mask-to-noise ratio better or equal to the noise/no_noise threshold.
  686. /*
  687. /* SEMANTICS:
  688. /* bbal = # bits needed for encoding bit allocation
  689. /* bsel = # bits needed for encoding scalefactor select information
  690. /* banc = # bits needed for ancillary data (header info included)
  691. /*
  692. /* For each subband and channel, will add bits until one of the
  693. /* following occurs:
  694. /* - Hit maximum number of bits we can allocate for that subband
  695. /* - MNR is better than or equal to the minimum masking level
  696. /*   (NOISY_MIN_MNR)
  697. /* Then the bits required for scalefactors, scfsi, bit allocation,
  698. /* and the subband samples are tallied (#req_bits#) and returned.
  699. /*
  700. /* (NOISY_MIN_MNR) is the smallest MNR a subband can have before it is
  701. /* counted as 'noisy' by the logic which chooses the number of JS
  702. /* subbands.
  703. /*
  704. /* Joint stereo is supported.
  705. /*
  706. /************************************************************************/
  707.  
  708. static double snr[18] = {0.00, 7.00, 11.00, 16.00, 20.84,
  709.                          25.28, 31.59, 37.75, 43.84,
  710.                          49.89, 55.93, 61.96, 67.98, 74.01,
  711.                          80.03, 86.05, 92.01, 98.01};
  712.  
  713. int I_bits_for_nonoise(double FAR perm_smr[2][SBLIMIT], frame_params *fr_ps)
  714. {
  715.    int i,j,k;
  716.    int stereo  = fr_ps->stereo;
  717.    int sblimit = fr_ps->sblimit;
  718.    int jsbound = fr_ps->jsbound;
  719.    int req_bits = 0;
  720.  
  721.    /* initial b_anc (header) allocation bits */
  722.    req_bits = 32 + 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  723.  
  724.    for(i=0; i<SBLIMIT; ++i)
  725.      for(j=0; j<((i<jsbound)?stereo:1); ++j) {
  726.        for(k=0;k<14; ++k)
  727.          if( (-perm_smr[j][i] + snr[k]) >= NOISY_MIN_MNR)
  728.            break; /* we found enough bits */
  729.          if(stereo == 2 && i >= jsbound)     /* check other JS channel */
  730.            for(;k<14; ++k)
  731.              if( (-perm_smr[1-j][i] + snr[k]) >= NOISY_MIN_MNR) break;
  732.          if(k>0) req_bits += (k+1)*SCALE_BLOCK + 6*((i>=jsbound)?stereo:1);
  733.    }
  734.    return req_bits;
  735. }
  736.  
  737. /***************************** Layer II  ********************************/
  738.  
  739. int II_bits_for_nonoise(double FAR perm_smr[2][SBLIMIT], unsigned int scfsi[2][SBLIMIT], frame_params *fr_ps)
  740. {
  741.    int sb,ch,ba;
  742.    int stereo  = fr_ps->stereo;
  743.    int sblimit = fr_ps->sblimit;
  744.    int jsbound = fr_ps->jsbound;
  745.    al_table *alloc = fr_ps->alloc;
  746.    int req_bits = 0, bbal = 0, berr = 0, banc = 32;
  747.    int maxAlloc, sel_bits, sc_bits, smp_bits;
  748. static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  749.  
  750.    /* added 92-08-11 shn */
  751.    if (fr_ps->header->error_protection) berr=16; else berr=0; 
  752.  
  753.    for (sb=0; sb<jsbound; ++sb)
  754.      bbal += stereo * (*alloc)[sb][0].bits;
  755.    for (sb=jsbound; sb<sblimit; ++sb)
  756.      bbal += (*alloc)[sb][0].bits;
  757.    req_bits = banc + bbal + berr;
  758.  
  759.    for(sb=0; sb<sblimit; ++sb)
  760.      for(ch=0; ch<((sb<jsbound)?stereo:1); ++ch) {
  761.        maxAlloc = (1<<(*alloc)[sb][0].bits)-1;
  762.        sel_bits = sc_bits = smp_bits = 0;
  763.        for(ba=0;ba<maxAlloc-1; ++ba)
  764.          if( (-perm_smr[ch][sb] + snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  765.              >= NOISY_MIN_MNR)
  766.             break;      /* we found enough bits */
  767.        if(stereo == 2 && sb >= jsbound) /* check other JS channel */
  768.          for(;ba<maxAlloc-1; ++ba)
  769.            if( (-perm_smr[1-ch][sb]+ snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  770.                >= NOISY_MIN_MNR)
  771.              break;
  772.        if(ba>0) {
  773.          smp_bits = SCALE_BLOCK * ((*alloc)[sb][ba].group * (*alloc)[sb][ba].bits);
  774.          /* scale factor bits required for subband */
  775.          sel_bits = 2;
  776.          sc_bits  = 6 * sfsPerScfsi[scfsi[ch][sb]];
  777.          if(stereo == 2 && sb >= jsbound) {
  778.            /* each new js sb has L+R scfsis */
  779.            sel_bits += 2;
  780.            sc_bits  += 6 * sfsPerScfsi[scfsi[1-ch][sb]];
  781.          }
  782.          req_bits += smp_bits+sel_bits+sc_bits;
  783.        }
  784.    }
  785.    return req_bits;
  786. }
  787.  
  788. /************************************************************************
  789. /*
  790. /* I_main_bit_allocation   (Layer I)
  791. /* II_main_bit_allocation  (Layer II)
  792. /*
  793. /* PURPOSE:For joint stereo mode, determines which of the 4 joint
  794. /* stereo modes is needed.  Then calls *_a_bit_allocation(), which
  795. /* allocates bits for each of the subbands until there are no more bits
  796. /* left, or the MNR is at the noise/no_noise threshold.
  797. /*
  798. /* SEMANTICS:
  799. /*
  800. /* For joint stereo mode, joint stereo is changed to stereo if
  801. /* there are enough bits to encode stereo at or better than the
  802. /* no-noise threshold (NOISY_MIN_MNR).  Otherwise, the system
  803. /* iteratively allocates less bits by using joint stereo until one
  804. /* of the following occurs:
  805. /* - there are no more noisy subbands (MNR >= NOISY_MIN_MNR)
  806. /* - mode_ext has been reduced to 0, which means that all but the
  807. /*   lowest 4 subbands have been converted from stereo to joint
  808. /*   stereo, and no more subbands may be converted
  809. /*
  810. /*     This function calls *_bits_for_nonoise() and *_a_bit_allocation().
  811. /*
  812. /************************************************************************/
  813.  
  814. void I_main_bit_allocation(double FAR perm_smr[2][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], int *adb, frame_params *fr_ps)
  815. {
  816.    int  noisy_sbs;
  817.    int  mode, mode_ext, lay, i;
  818.    int  rq_db, av_db = *adb;
  819. static  int init = 0;
  820.  
  821.    if(init == 0) {
  822.      /* rearrange snr for layer I */
  823.      snr[2] = snr[3];
  824.      for (i=3;i<16;i++) snr[i] = snr[i+2];
  825.      init = 1;
  826.    }
  827.  
  828.    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
  829.      fr_ps->header->mode = MPG_MD_STEREO;
  830.      fr_ps->header->mode_ext = 0;
  831.      fr_ps->jsbound = fr_ps->sblimit;
  832.      if(rq_db = I_bits_for_nonoise(perm_smr, fr_ps) > *adb) {
  833.        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  834.        mode_ext = 4;           /* 3 is least severe reduction */
  835.        lay = fr_ps->header->lay;
  836.        do {
  837.           --mode_ext;
  838.           fr_ps->jsbound = js_bound(lay, mode_ext);
  839.           rq_db = I_bits_for_nonoise(perm_smr, fr_ps);
  840.        } while( (rq_db > *adb) && (mode_ext > 0));
  841.        fr_ps->header->mode_ext = mode_ext;
  842.      }    /* well we either eliminated noisy sbs or mode_ext == 0 */
  843.    }
  844.    noisy_sbs = I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps);
  845. }
  846.  
  847. /***************************** Layer II  ********************************/
  848.  
  849. void II_main_bit_allocation(double FAR perm_smr[2][SBLIMIT], unsigned int scfsi[2][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], int *adb, frame_params *fr_ps)
  850. {
  851.    int  noisy_sbs, nn;
  852.    int  mode, mode_ext, lay;
  853.    int  rq_db, av_db = *adb;
  854.  
  855.    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
  856.      fr_ps->header->mode = MPG_MD_STEREO;
  857.      fr_ps->header->mode_ext = 0;
  858.      fr_ps->jsbound = fr_ps->sblimit;
  859.      if((rq_db=II_bits_for_nonoise(perm_smr, scfsi, fr_ps)) > *adb) {
  860.        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  861.        mode_ext = 4;           /* 3 is least severe reduction */
  862.        lay = fr_ps->header->lay;
  863.        do {
  864.          --mode_ext;
  865.          fr_ps->jsbound = js_bound(lay, mode_ext);
  866.          rq_db = II_bits_for_nonoise(perm_smr, scfsi, fr_ps);
  867.        } while( (rq_db > *adb) && (mode_ext > 0));
  868.        fr_ps->header->mode_ext = mode_ext;
  869.      }    /* well we either eliminated noisy sbs or mode_ext == 0 */
  870.    }
  871.    noisy_sbs = II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps);
  872. }
  873.  
  874. /************************************************************************
  875. /*
  876. /* I_a_bit_allocation  (Layer I)
  877. /* II_a_bit_allocation (Layer II)
  878. /*
  879. /* PURPOSE:Adds bits to the subbands with the lowest mask-to-noise
  880. /* ratios, until the maximum number of bits for the subband has
  881. /* been allocated.
  882. /*
  883. /* SEMANTICS:
  884. /* 1. Find the subband and channel with the smallest MNR (#min_sb#,
  885. /*    and #min_ch#)
  886. /* 2. Calculate the increase in bits needed if we increase the bit
  887. /*    allocation to the next higher level
  888. /* 3. If there are enough bits available for increasing the resolution
  889. /*    in #min_sb#, #min_ch#, and the subband has not yet reached its
  890. /*    maximum allocation, update the bit allocation, MNR, and bits
  891. /*    available accordingly
  892. /* 4. Repeat until there are no more bits left, or no more available
  893. /*    subbands. (A subband is still available until the maximum
  894. /*    number of bits for the subband has been allocated, or there
  895. /*    aren't enough bits to go to the next higher resolution in the
  896. /*    subband.)
  897. /*
  898. /************************************************************************/
  899.  
  900. int I_a_bit_allocation(double FAR perm_smr[2][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], int *adb, frame_params *fr_ps) /* return noisy sbs */
  901. {
  902.    int i, k, smpl_bits, scale_bits, min_sb, min_ch, oth_ch;
  903.    int bspl, bscf, ad, noisy_sbs, done = 0, bbal ;
  904.    double mnr[2][SBLIMIT], small;
  905.    char used[2][SBLIMIT];
  906.    int stereo  = fr_ps->stereo;
  907.    int sblimit = fr_ps->sblimit;
  908.    int jsbound = fr_ps->jsbound;
  909.    al_table *alloc = fr_ps->alloc;
  910. static char init= 0;
  911. static int banc=32, berr=0;
  912.  
  913.    if (!init) {
  914.       init = 1;
  915.       if (fr_ps->header->error_protection) berr = 16;  /* added 92-08-11 shn */
  916.    }
  917.    bbal = 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  918.    *adb -= bbal + berr + banc;
  919.    ad= *adb;
  920.  
  921.    for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++) {
  922.      mnr[k][i]=snr[0]-perm_smr[k][i];
  923.      bit_alloc[k][i] = 0;
  924.      used[k][i] = 0;
  925.    }
  926.    bspl = bscf = 0;
  927.  
  928.    do  {
  929.      /* locate the subband with minimum SMR */
  930.      small = mnr[0][0]+1;    min_sb = -1; min_ch = -1;
  931.      for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++)
  932.        /* go on only if there are bits left */
  933.        if (used[k][i] != 2 && small > mnr[k][i]) {
  934.          small = mnr[k][i];
  935.          min_sb = i;  min_ch = k;
  936.        }
  937.      if(min_sb > -1) {   /* there was something to find */
  938.        /* first step of bit allocation is biggest */
  939.        if (used[min_ch][min_sb])  { smpl_bits = SCALE_BLOCK; scale_bits = 0; }
  940.        else                       { smpl_bits = 24; scale_bits = 6; }
  941.        if(min_sb >= jsbound)        scale_bits *= stereo;
  942.  
  943.        /* check to see enough bits were available for */
  944.        /* increasing resolution in the minimum band */
  945.  
  946.        if (ad >= bspl + bscf + scale_bits + smpl_bits) {
  947.          bspl += smpl_bits; /* bit for subband sample */
  948.          bscf += scale_bits; /* bit for scale factor */
  949.          bit_alloc[min_ch][min_sb]++;
  950.          used[min_ch][min_sb] = 1; /* subband has bits */
  951.          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb]
  952.                                + snr[bit_alloc[min_ch][min_sb]];
  953.          /* Check if subband has been fully allocated max bits */
  954.          if (bit_alloc[min_ch][min_sb] ==  14 ) used[min_ch][min_sb] = 2;
  955.        }
  956.        else            /* no room to improve this band */
  957.          used[min_ch][min_sb] = 2; /*   for allocation anymore */
  958.        if(stereo == 2 && min_sb >= jsbound) {
  959.          oth_ch = 1-min_ch;  /* joint-st : fix other ch */
  960.          bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  961.          used[oth_ch][min_sb] = used[min_ch][min_sb];
  962.          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb]
  963.                                + snr[bit_alloc[oth_ch][min_sb]];
  964.        }
  965.      }
  966.    } while(min_sb>-1);     /* i.e. still some sub-bands to find */
  967.  
  968.    /* Calculate the number of bits left, add on to pointed var */
  969.    ad -= bspl+bscf;
  970.    *adb = ad;
  971.  
  972.    /* see how many channels are noisy */
  973.    noisy_sbs = 0; small = mnr[0][0];
  974.    for(k=0; k<stereo; ++k) {
  975.      for(i = 0; i< SBLIMIT; ++i) {
  976.        if(mnr[k][i] < NOISY_MIN_MNR)   ++noisy_sbs;
  977.        if(small > mnr[k][i])           small = mnr[k][i];
  978.      }
  979.    }
  980.    return noisy_sbs;
  981. }
  982.  
  983. /***************************** Layer II  ********************************/
  984.  
  985. int II_a_bit_allocation(double FAR perm_smr[2][SBLIMIT],unsigned int scfsi[2][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], int *adb, frame_params *fr_ps)
  986. {
  987.    int i, min_ch, min_sb, oth_ch, k, increment, scale, seli, ba;
  988.    int bspl, bscf, bsel, ad, noisy_sbs, bbal=0;
  989.    double mnr[2][SBLIMIT], small;
  990.    char used[2][SBLIMIT];
  991.    int stereo  = fr_ps->stereo;
  992.    int sblimit = fr_ps->sblimit;
  993.    int jsbound = fr_ps->jsbound;
  994.    al_table *alloc = fr_ps->alloc;
  995. static char init= 0;
  996. static int banc=32, berr=0;
  997. static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  998.  
  999.    if (!init) { 
  1000.        init = 1;  
  1001.        if (fr_ps->header->error_protection) berr=16; /* added 92-08-11 shn */
  1002.    }
  1003.    for (i=0; i<jsbound; ++i)
  1004.      bbal += stereo * (*alloc)[i][0].bits;
  1005.    for (i=jsbound; i<sblimit; ++i)
  1006.      bbal += (*alloc)[i][0].bits;
  1007.    *adb -= bbal + berr + banc;
  1008.    ad = *adb;
  1009.  
  1010.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++) {
  1011.      mnr[k][i]=snr[0]-perm_smr[k][i];
  1012.      bit_alloc[k][i] = 0;
  1013.      used[k][i] = 0;
  1014.    }
  1015.    bspl = bscf = bsel = 0;
  1016.  
  1017.    do  {
  1018.      /* locate the subband with minimum SMR */
  1019.      small = 999999.0; min_sb = -1; min_ch = -1;
  1020.      for (i=0;i<sblimit;i++) for(k=0;k<stereo;++k)
  1021.        if (used[k][i]  != 2 && small > mnr[k][i]) {
  1022.          small = mnr[k][i];
  1023.          min_sb = i;  min_ch = k;
  1024.      }
  1025.      if(min_sb > -1) {   /* there was something to find */
  1026.        /* find increase in bit allocation in subband [min] */
  1027.        increment = SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].group *
  1028.                         (*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].bits);
  1029.        if (used[min_ch][min_sb])
  1030.          increment -= SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]].group*
  1031.                            (*alloc)[min_sb][bit_alloc[min_ch][min_sb]].bits);
  1032.  
  1033.        /* scale factor bits required for subband [min] */
  1034.        oth_ch = 1 - min_ch;    /* above js bound, need both chans */
  1035.        if (used[min_ch][min_sb]) scale = seli = 0;
  1036.        else {          /* this channel had no bits or scfs before */
  1037.          seli = 2;
  1038.          scale = 6 * sfsPerScfsi[scfsi[min_ch][min_sb]];
  1039.          if(stereo == 2 && min_sb >= jsbound) {
  1040.            /* each new js sb has L+R scfsis */
  1041.            seli += 2;
  1042.            scale += 6 * sfsPerScfsi[scfsi[oth_ch][min_sb]];
  1043.          }
  1044.        }
  1045.        /* check to see enough bits were available for */
  1046.        /* increasing resolution in the minimum band */
  1047.        if (ad >= bspl + bscf + bsel + seli + scale + increment) {
  1048.          ba = ++bit_alloc[min_ch][min_sb]; /* next up alloc */
  1049.          bspl += increment;  /* bits for subband sample */
  1050.          bscf += scale;      /* bits for scale factor */
  1051.          bsel += seli;       /* bits for scfsi code */
  1052.          used[min_ch][min_sb] = 1; /* subband has bits */
  1053.          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb] +
  1054.                                snr[(*alloc)[min_sb][ba].quant+1];
  1055.          /* Check if subband has been fully allocated max bits */
  1056.          if (ba >= (1<<(*alloc)[min_sb][0].bits)-1) used[min_ch][min_sb] = 2;
  1057.        }
  1058.        else used[min_ch][min_sb] = 2; /* can't increase this alloc */
  1059.        if(min_sb >= jsbound && stereo == 2) {
  1060.          /* above jsbound, alloc applies L+R */
  1061.          ba = bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  1062.          used[oth_ch][min_sb] = used[min_ch][min_sb];
  1063.          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb] +
  1064.                                snr[(*alloc)[min_sb][ba].quant+1];
  1065.        }
  1066.      }
  1067.    } while(min_sb > -1);   /* until could find no channel */
  1068.    /* Calculate the number of bits left */
  1069.    ad -= bspl+bscf+bsel;   *adb = ad;
  1070.    for (i=sblimit;i<SBLIMIT;i++) for (k=0;k<stereo;k++) bit_alloc[k][i]=0;
  1071.  
  1072.    noisy_sbs = 0;  small = mnr[0][0];      /* calc worst noise in case */
  1073.    for(k=0;k<stereo;++k) {
  1074.      for (i=0;i<sblimit;i++) {
  1075.        if (small > mnr[k][i]) small = mnr[k][i];
  1076.        if(mnr[k][i] < NOISY_MIN_MNR) ++noisy_sbs; /* noise is not masked */
  1077.  
  1078.      }
  1079.    }
  1080.    return noisy_sbs;
  1081. }
  1082.  
  1083. /************************************************************************
  1084. /*
  1085. /* I_subband_quantization  (Layer I)
  1086. /* II_subband_quantization (Layer II)
  1087. /*
  1088. /* PURPOSE:Quantizes subband samples to appropriate number of bits
  1089. /*
  1090. /* SEMANTICS:  Subband samples are divided by their scalefactors, which
  1091. /* makes the quantization more efficient. The scaled samples are
  1092. /* quantized by the function a*x+b, where a and b are functions of
  1093. /* the number of quantization levels. The result is then truncated
  1094. /* to the appropriate number of bits and the MSB is inverted.
  1095. /*
  1096. /* Note that for fractional 2's complement, inverting the MSB for a
  1097. /* negative number x is equivalent to adding 1 to it.
  1098. /*
  1099. /************************************************************************/
  1100.  
  1101. static double a[17] = {
  1102.   0.750000000, 0.625000000, 0.875000000, 0.562500000, 0.937500000,
  1103.   0.968750000, 0.984375000, 0.992187500, 0.996093750, 0.998046875,
  1104.   0.999023438, 0.999511719, 0.999755859, 0.999877930, 0.999938965,
  1105.   0.999969482, 0.999984741 };
  1106.  
  1107. static double b[17] = {
  1108.   -0.250000000, -0.375000000, -0.125000000, -0.437500000, -0.062500000,
  1109.   -0.031250000, -0.015625000, -0.007812500, -0.003906250, -0.001953125,
  1110.   -0.000976563, -0.000488281, -0.000244141, -0.000122070, -0.000061035,
  1111.   -0.000030518, -0.000015259 };
  1112.  
  1113. void I_subband_quantization(unsigned int scalar[2][3][SBLIMIT], double FAR sb_samples[2][3][SCALE_BLOCK][SBLIMIT], unsigned int j_scale[3][SBLIMIT], double j_samps[3][SCALE_BLOCK][SBLIMIT],
  1114.                             unsigned int bit_alloc[2][SBLIMIT],unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT], frame_params *fr_ps)
  1115. {
  1116.    int i, j, k, n, sig;
  1117.    int stereo  = fr_ps->stereo;
  1118.    int sblimit = fr_ps->sblimit;
  1119.    int jsbound = fr_ps->jsbound;
  1120.    double d;
  1121. static char init = 0;
  1122.  
  1123.    if (!init) {
  1124.      init = 1;
  1125.      /* rearrange quantization coef to correspond to layer I table */
  1126.      a[1] = a[2]; b[1] = b[2];
  1127.      for (i=2;i<15;i++) { a[i] = a[i+2]; b[i] = b[i+2]; }
  1128.    }
  1129.    for (j=0;j<SCALE_BLOCK;j++) for (i=0;i<SBLIMIT;i++)
  1130.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1131.        if (bit_alloc[k][i]) {
  1132.          /* for joint stereo mode, have to construct a single subband stream
  1133.             for the js channels.  At present, we calculate a set of mono
  1134.             subband samples and pass them through the scaling system to
  1135.             generate an alternate normalised sample stream.
  1136.  
  1137.             Could normalise both streams (divide by their scfs), then average
  1138.             them.  In bad conditions, this could give rise to spurious
  1139.             cancellations.  Instead, we could just select the sb stream from
  1140.             the larger channel (higher scf), in which case _that_ channel
  1141.             would be 'properly' reconstructed, and the mate would just be a
  1142.             scaled version.  Spec recommends averaging the two (unnormalised)
  1143.             subband channels, then normalising this new signal without
  1144.             actually sending this scale factor... This means looking ahead.
  1145.          */
  1146.          if(stereo == 2 && i>=jsbound)
  1147.            /* use the joint data passed in */
  1148.            d = j_samps[0][j][i] / multiple[j_scale[0][i]];
  1149.          else
  1150.            d = sb_samples[k][0][j][i] / multiple[scalar[k][0][i]];
  1151.          /* scale and quantize floating point sample */
  1152.          n = bit_alloc[k][i];
  1153.          d = d * a[n-1] + b[n-1];
  1154.          /* extract MSB N-1 bits from the floating point sample */
  1155.          if (d >= 0) sig = 1;
  1156.          else { sig = 0; d += 1.0; }
  1157.          sbband[k][0][j][i] = (unsigned int) (d * (double) (1L<<n));
  1158.          /* tag the inverted sign bit to sbband at position N */
  1159.          if (sig) sbband[k][0][j][i] |= 1<<n;
  1160.        }
  1161. }
  1162.  
  1163. /***************************** Layer II  ********************************/
  1164.  
  1165. void II_subband_quantization(unsigned int scalar[2][3][SBLIMIT], double FAR sb_samples[2][3][SCALE_BLOCK][SBLIMIT], unsigned int j_scale[3][SBLIMIT], double FAR j_samps[3][SCALE_BLOCK][SBLIMIT],
  1166.                              unsigned int bit_alloc[2][SBLIMIT], unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT], frame_params *fr_ps)
  1167. {
  1168.    int i, j, k, s, n, qnt, sig;
  1169.    int stereo  = fr_ps->stereo;
  1170.    int sblimit = fr_ps->sblimit;
  1171.    int jsbound = fr_ps->jsbound;
  1172.    unsigned int stps;
  1173.    double d;
  1174.    al_table *alloc = fr_ps->alloc;
  1175.  
  1176.    for (s=0;s<3;s++)
  1177.      for (j=0;j<SCALE_BLOCK;j++)
  1178.        for (i=0;i<sblimit;i++)
  1179.          for (k=0;k<((i<jsbound)?stereo:1);k++)
  1180.            if (bit_alloc[k][i]) {
  1181.              /* scale and quantize floating point sample */
  1182.              if(stereo == 2 && i>=jsbound)       /* use j-stereo samples */
  1183.                d = j_samps[s][j][i] / multiple[j_scale[s][i]];
  1184.              else
  1185.                d = sb_samples[k][s][j][i] / multiple[scalar[k][s][i]];
  1186.              if (mod(d) > 1.0)
  1187.                printf("Not scaled properly %d %d %d %d\n",k,s,j,i);
  1188.              qnt = (*alloc)[i][bit_alloc[k][i]].quant;
  1189.              d = d * a[qnt] + b[qnt];
  1190.              /* extract MSB N-1 bits from the floating point sample */
  1191.              if (d >= 0) sig = 1;
  1192.              else { sig = 0; d += 1.0; }
  1193.              n = 0;
  1194. #ifndef MS_DOS
  1195.              stps = (*alloc)[i][bit_alloc[k][i]].steps;
  1196.              while ((1L<<n) < stps) n++;
  1197. #else
  1198.              while  ( ( (unsigned long)(1L<<(long)n) <
  1199.                        ((unsigned long) ((*alloc)[i][bit_alloc[k][i]].steps)
  1200.                         & 0xffff
  1201.                         )
  1202.                        ) && ( n <16)
  1203.                      ) n++;
  1204. #endif
  1205.              n--;
  1206.              sbband[k][s][j][i] = (unsigned int) (d * (double) (1L<<n));
  1207.              /* tag the inverted sign bit to sbband at position N */
  1208.              /* The bit inversion is a must for grouping with 3,5,9 steps
  1209.                 so it is done for all subbands */
  1210.              if (sig) sbband[k][s][j][i] |= 1<<n;
  1211.            }
  1212.            for (s=0;s<3;s++)
  1213.              for (j=sblimit;j<SBLIMIT;j++)
  1214.                for (i=0;i<SCALE_BLOCK;i++) for (k=0;k<stereo;k++) sbband[k][s][i][j] = 0;
  1215. }
  1216.  
  1217. /************************************************************************
  1218. /*
  1219. /* I_encode_bit_alloc  (Layer I)
  1220. /* II_encode_bit_alloc (Layer II)
  1221. /*
  1222. /* PURPOSE:Writes bit allocation information onto bitstream
  1223. /*
  1224. /* Layer I uses 4 bits/subband for bit allocation information,
  1225. /* and Layer II uses 4,3,2, or 0 bits depending on the
  1226. /* quantization table used.
  1227. /*
  1228. /************************************************************************/
  1229.  
  1230. void I_encode_bit_alloc(unsigned int bit_alloc[2][SBLIMIT], frame_params *fr_ps, Bit_stream_struc *bs)
  1231. {
  1232.    int i,k;
  1233.    int stereo  = fr_ps->stereo;
  1234.    int sblimit = fr_ps->sblimit;
  1235.    int jsbound = fr_ps->jsbound;
  1236.  
  1237.    for (i=0;i<SBLIMIT;i++)
  1238.      for (k=0;k<((i<jsbound)?stereo:1);k++) putbits(bs,bit_alloc[k][i],4);
  1239. }
  1240.  
  1241. /***************************** Layer II  ********************************/
  1242.  
  1243. void II_encode_bit_alloc(unsigned int bit_alloc[2][SBLIMIT], frame_params *fr_ps, Bit_stream_struc *bs)
  1244. {
  1245.    int i,k;
  1246.    int stereo  = fr_ps->stereo;
  1247.    int sblimit = fr_ps->sblimit;
  1248.    int jsbound = fr_ps->jsbound;
  1249.    al_table *alloc = fr_ps->alloc;
  1250.  
  1251.    for (i=0;i<sblimit;i++)
  1252.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1253.        putbits(bs,bit_alloc[k][i],(*alloc)[i][0].bits);
  1254. }
  1255.  
  1256. /************************************************************************
  1257. /*
  1258. /* I_sample_encoding   (Layer I)
  1259. /* II_sample_encoding  (Layer II)
  1260. /*
  1261. /* PURPOSE:Put one frame of subband samples on to the bitstream
  1262. /*
  1263. /* SEMANTICS:  The number of bits allocated per sample is read from
  1264. /* the bit allocation information #bit_alloc#.  Layer 2
  1265. /* supports writing grouped samples for quantization steps
  1266. /* that are not a power of 2.
  1267. /*
  1268. /************************************************************************/
  1269.  
  1270. void I_sample_encoding(unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], frame_params *fr_ps, Bit_stream_struc *bs)
  1271. {
  1272.    int i,j,k;
  1273.    int stereo  = fr_ps->stereo;
  1274.    int sblimit = fr_ps->sblimit;
  1275.    int jsbound = fr_ps->jsbound;
  1276.  
  1277.    for(j=0;j<SCALE_BLOCK;j++) {
  1278.      for(i=0;i<SBLIMIT;i++)
  1279.        for(k=0;k<((i<jsbound)?stereo:1);k++)
  1280.          if(bit_alloc[k][i]) putbits(bs,sbband[k][0][j][i],bit_alloc[k][i]+1);
  1281.    }
  1282. }
  1283.  
  1284. /***************************** Layer II  ********************************/
  1285.  
  1286. void II_sample_encoding(unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], frame_params *fr_ps, Bit_stream_struc *bs)
  1287. {
  1288.    unsigned int temp;
  1289.    unsigned int i,j,k,s,x,y;
  1290.    int stereo  = fr_ps->stereo;
  1291.    int sblimit = fr_ps->sblimit;
  1292.    int jsbound = fr_ps->jsbound;
  1293.    al_table *alloc = fr_ps->alloc;
  1294.  
  1295.    for (s=0;s<3;s++)
  1296.      for (j=0;j<SCALE_BLOCK;j+=3)
  1297.        for (i=0;i<sblimit;i++)
  1298.          for (k=0;k<((i<jsbound)?stereo:1);k++)
  1299.            if (bit_alloc[k][i]) {
  1300.              if ((*alloc)[i][bit_alloc[k][i]].group == 3) {
  1301.                for (x=0;x<3;x++) putbits(bs,sbband[k][s][j+x][i],
  1302.                                          (*alloc)[i][bit_alloc[k][i]].bits);
  1303.              }
  1304.              else {
  1305.                y =(*alloc)[i][bit_alloc[k][i]].steps;
  1306.                temp = sbband[k][s][j][i] +
  1307.                       sbband[k][s][j+1][i] * y +
  1308.                       sbband[k][s][j+2][i] * y * y;
  1309.                putbits(bs,temp,(*alloc)[i][bit_alloc[k][i]].bits);
  1310.              }
  1311.            }
  1312. }
  1313.  
  1314. /************************************************************************
  1315. /*
  1316. /* encode_CRC
  1317. /*
  1318. /************************************************************************/
  1319.  
  1320. void encode_CRC(unsigned int crc, Bit_stream_struc *bs)
  1321. {
  1322.    putbits(bs, crc, 16);
  1323. }
  1324.