bitstream.c
Upload User: shenggui01
Upload Date: 2022-01-16
Package Size: 54k
Code Size: 15k
Category:

mpeg mp3

Development Platform:

C/C++

  1. /* bitstream.c */
  2. #include "types.h"
  3. extern int *scalefac_band_long;
  4. static void encodeSideInfo( L3_side_info_t  *si );
  5. static int encodeMainData(int l3_enc[2][2][samp_per_frame2],
  6.                 L3_side_info_t  *si );
  7. static void Huffmancodebits( int *ix, gr_info *gi );
  8. static int HuffmanCode(int table_select, int x, int y, unsigned long *code,
  9.                 unsigned long *extword, int *codebits, int *extbits);
  10. static int L3_huffman_coder_count1( struct huffcodetab *h,
  11.                 int v, int w, int x, int y );
  12. /* bitstream buffers.
  13.  * At a 24K samplerate and 8k bitrate in stereo, sideinfo can be up to 86 frames
  14.  * ahead of its main data ( very silly combination ) */
  15. #define FIFO_SIZE 128
  16. static struct
  17. {
  18.   int si_len; /* number of bytes in side info */
  19.   int fr_len; /* number of data bytes in frame */
  20.   unsigned char side[40]; /* side info max len = (288 bits / 8) + 1 which gets cleared */
  21. } fifo[FIFO_SIZE];
  22. static unsigned char main_[4096];  /* main data buffer (length always less than this) */
  23. static int wr, rd; /* read and write index for side fifo */
  24. static int by, bi; /* byte and bit counts within main or side stores */
  25. static int count;  /* byte counter within current frame */
  26. static int bits;   /* bit counter used when encoding side and main data */
  27. static struct
  28. {
  29.   FILE *f;          /* bitstream output file handle */
  30.   unsigned int i;   /* file buffer index */
  31.   unsigned char *b; /* buffer pointer */
  32. } bs;
  33. static unsigned char header[4];
  34. #define BUFFER_SIZE 0x8000     /* output buffer size in bytes */
  35. /*
  36.  * putbytes
  37.  * --------
  38.  * put n bytes in the output buffer. Empty the buffer when full.
  39.  */
  40. void putbytes(unsigned char *data, int n)
  41. {
  42.   unsigned int free = BUFFER_SIZE - bs.i;
  43.   if(n >= free)
  44.   {
  45. //    memcpy(&bs.b[bs.i],data,(short)free);
  46.     memcpy(&bs.b[bs.i],data,free);
  47.     n -= free;
  48.     fwrite(bs.b,sizeof(unsigned char),BUFFER_SIZE,bs.f);
  49. //    memcpy(bs.b,&data[free],(short)n);
  50.     memcpy(bs.b,&data[free],n);
  51.     bs.i = n;
  52.   }
  53.   else
  54.   {
  55. //    memcpy(&bs.b[bs.i],data,(short)n);
  56.     memcpy(&bs.b[bs.i],data,n);
  57.     bs.i += n;
  58.   }
  59. }
  60. /*
  61.  * setbytes
  62.  * --------
  63.  * set n bytes in the output buffer. Empty the buffer when full.
  64.  */
  65. void setbytes(unsigned char data, int n)
  66. {
  67.   unsigned int free = BUFFER_SIZE - bs.i;
  68.   if(n >= free)
  69.   {
  70. //    memset(&bs.b[bs.i],data,(short)free);
  71.     memset(&bs.b[bs.i],data,free);
  72.     n -= free;
  73.     fwrite(bs.b,sizeof(unsigned char),BUFFER_SIZE,bs.f);
  74. //    memset(bs.b,data,(short)n);
  75.     memset(bs.b,data,n);
  76.     bs.i = n;
  77.   }
  78.   else
  79.   {
  80. //    memset(&bs.b[bs.i],data,(short)n);
  81.     memset(&bs.b[bs.i],data,n);
  82.     bs.i += n;
  83.   }
  84. }
  85. /*
  86.  * open_bit_stream
  87.  * ---------------
  88.  * open the device to write the bit stream into it
  89.  */
  90. void open_bit_stream(char *filename)
  91. {
  92.   static unsigned char buff[BUFFER_SIZE];
  93.   if ((bs.f = fopen(filename, "wb")) == NULL)
  94.     error("Unable to open output file");
  95.   bs.b = buff;
  96.   bs.i = 0;
  97.   /* setup header (the only change between frames is the padding bit) */
  98.   header[0] = 0xff;
  99.   header[1] = 0xe0 |
  100.               (config.mpeg.type << 3) |
  101.               (config.mpeg.layr << 1) |
  102.               !config.mpeg.crc;
  103.   header[2] = (config.mpeg.bitrate_index << 4) |
  104.               (config.mpeg.samplerate_index << 2) |
  105.             /* config,mpeg.padding inserted later */
  106.                config.mpeg.ext;
  107.   header[3] = (config.mpeg.mode << 6) |
  108.               (config.mpeg.mode_ext << 4) |
  109.               (config.mpeg.copyright << 3) |
  110.               (config.mpeg.original << 2) |
  111.                config.mpeg.emph;
  112. }
  113. /*
  114.  * close_bit_stream
  115.  * ----------------
  116.  * close the device containing the bit stream
  117.  */
  118. void close_bit_stream(void)
  119. {
  120.   /* first we must complete the current frame then output more empty frames
  121.    * until all sideinfo from the side fifo have been output.
  122.    */
  123.   if(count)
  124.     setbytes(0,count); /* fill current frame */
  125.   while(rd != wr)
  126.   {
  127.     /* output next header/sideinfo */
  128.     putbytes(fifo[rd].side, fifo[rd].si_len);
  129.     setbytes(0, fifo[rd].fr_len); /* fill frame */
  130.     if(++rd == FIFO_SIZE) rd = 0; /* point to next header/sideinfo */
  131.   }
  132.   /* completely empty the buffer before closing the file */
  133.   if(bs.i)
  134. //    fwrite(bs.b,sizeof(unsigned char),(short)bs.i,bs.f);
  135.     fwrite(bs.b,sizeof(unsigned char),bs.i,bs.f);
  136.   fclose(bs.f);
  137. }
  138. /*
  139.  * L3_format_bitstream
  140.  * -------------------
  141.  * This is called after a frame of audio has been quantized and coded.
  142.  * It will write the encoded audio to the bitstream. Note that
  143.  * from a layer3 encoder's perspective the bit stream is primarily
  144.  * a series of main_data() blocks, with header and side information
  145.  * inserted at the proper locations to maintain framing. (See Figure A.7
  146.  * in the IS).
  147.  *
  148.  * note. both header/sideinfo and main data are multiples of 8 bits.
  149.  * this means that the encoded data can be manipulated as bytes
  150.  * which is easier and quicker than bits.
  151.  */
  152. void L3_format_bitstream( int l3_enc[2][2][samp_per_frame2], L3_side_info_t  *l3_side)
  153. {
  154.   int main_bytes;
  155.   encodeSideInfo( l3_side ); /* store in fifo */
  156.   main_bytes = encodeMainData( l3_enc, l3_side );
  157.   /* send data */
  158.   by = 0;
  159.   while(main_bytes)
  160.   {
  161.     if (!count)
  162.     { /* end of frame so output next header/sideinfo */
  163.       putbytes(fifo[rd].side, fifo[rd].si_len);
  164.       count = fifo[rd].fr_len;
  165.       if(++rd == FIFO_SIZE) rd = 0; /* point to next header/sideinfo */
  166.     }
  167.     if(main_bytes <= count)
  168.     { /* enough room in frame to output rest of main data, this will exit the while loop */
  169.       putbytes(&main_[by],main_bytes);
  170.       count -= main_bytes;
  171.       main_bytes = 0;
  172.     }
  173.     else
  174.     { /* fill current frame up, start new frame next time around the while loop */
  175.       putbytes(&main_[by],count);
  176.       main_bytes -= count;
  177.       by += count;
  178.       count = 0;
  179.     }
  180.   }
  181. }
  182. /*
  183.  * putbits:
  184.  * --------
  185.  * write N bits into the encoded data buffer.
  186.  * buf = encoded data buffer
  187.  * val = value to write into the buffer
  188.  * n = number of bits of val
  189.  *
  190.  * Bits in value are assumed to be right-justified.
  191.  */
  192. static void putbits (unsigned char *buf, unsigned long val, unsigned int n)
  193. {
  194.   static int mask[9]={0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff};
  195.   int k, tmp;
  196.   if (n > 32)
  197.     error("Cannot write more than 32 bits at a time");
  198.   bits += n;
  199.   while (n)
  200.   {
  201.     k = (n < bi) ? n : bi;
  202.     tmp = val >> (n - k);
  203.     buf[by] |= (tmp & mask[k]) << (bi - k);
  204.     bi -= k;
  205.     n -= k;
  206.     if (!bi)
  207.     {
  208.       bi = 8;
  209.       by++;
  210.       buf[by]=0;
  211.     }
  212.   }
  213. }
  214. /*
  215.  * encodeMainData
  216.  * --------------
  217.  * Encodes the spectrum and places the coded
  218.  * main data in the buffer main.
  219.  * Returns the number of bytes stored.
  220.  */
  221. static int encodeMainData(int l3_enc[2][2][samp_per_frame2],
  222.                            L3_side_info_t  *si)
  223. {
  224.   int gr, ch;
  225.   bits = 0;
  226.   by = 0;
  227.   bi = 8;
  228.   main_[0]=0;
  229.   /* huffmancodes plus reservoir stuffing */
  230.   for(gr = 0; gr < config.mpeg.granules; gr++)
  231.     for (ch = 0; ch < config.mpeg.channels; ch++)
  232.       Huffmancodebits( l3_enc[gr][ch], &si->gr[gr].ch[ch].tt ); /* encode the spectrum */
  233.   /* ancillary data, used for reservoir stuffing overflow */
  234.   if(si->resv_drain)
  235.   {
  236.     int words = si->resv_drain >> 5;
  237.     int remainder = si->resv_drain & 31;
  238.     /* pad with zeros */
  239.     while(words--)
  240.       putbits(main_, 0, 32 );
  241.     if(remainder)
  242.       putbits(main_, 0, remainder );
  243.   }
  244.   return bits >> 3;
  245. }
  246. /*
  247.  * encodeSideInfo
  248.  * --------------
  249.  * Encodes the header and sideinfo and stores the coded data
  250.  * in the side fifo for transmission at the appropriate place
  251.  * in the bitstream.
  252.  */
  253. static void encodeSideInfo( L3_side_info_t  *si )
  254. {
  255.   int gr, ch, region;
  256.   unsigned char * sf = fifo[wr].side;
  257.   /* header */
  258.   *sf     = header[0];
  259.   *(sf+1) = header[1];
  260.   *(sf+2) = header[2] | (config.mpeg.padding << 1);
  261.   *(sf+3) = header[3];
  262.   *(sf+4) = 0;
  263.   bits = 32;
  264.   by = 4;
  265.   bi = 8;
  266.   /* side info */
  267.   if(config.mpeg.type == MPEG1)
  268.   {
  269.     putbits(sf, si->main_data_begin, 9 );
  270.     putbits(sf, 0, ( config.mpeg.channels == 2 ) ? 3 : 5 ); /* private bits */
  271.     for ( ch = 0; ch < config.mpeg.channels; ch++ )
  272.       putbits(sf, 0, 4 ); /* scfsi */
  273.     for ( gr = 0; gr < 2; gr++ )
  274.       for ( ch = 0; ch < config.mpeg.channels ; ch++ )
  275.       {
  276.         gr_info *gi = &(si->gr[gr].ch[ch].tt);
  277.         putbits(sf, gi->part2_3_length,    12 );
  278.         putbits(sf, gi->big_values,         9 );
  279.         putbits(sf, gi->global_gain,        8 );
  280.         putbits(sf, 0, 5 ); /* scalefac_compress, window switching flag */
  281.         for ( region = 0; region < 3; region++ )
  282.           putbits(sf, gi->table_select[region], 5 );
  283.         putbits(sf, gi->region0_count,      4 );
  284.         putbits(sf, gi->region1_count,      3 );
  285.         putbits(sf, 0, 2 ); /* preflag, scalefac_scale */
  286.         putbits(sf, gi->count1table_select, 1 );
  287.       }
  288.   }
  289.   else /* mpeg 2/2.5 */
  290.   {
  291.     putbits(sf, si->main_data_begin, 8 );
  292.     putbits(sf, 0, ( config.mpeg.channels == 1 ) ? 1 : 2 ); /* private bits */
  293.     for ( ch = 0; ch < config.mpeg.channels ; ch++ )
  294.     {
  295.       gr_info *gi = &(si->gr[0].ch[ch].tt);
  296.       putbits(sf, gi->part2_3_length,    12 );
  297.       putbits(sf, gi->big_values,         9 );
  298.       putbits(sf, gi->global_gain,        8 );
  299.       putbits(sf, 0, 10 ); /* scalefac_compress, window switching flag */
  300.       for ( region = 0; region < 3; region++ )
  301.         putbits(sf, gi->table_select[region], 5 );
  302.       putbits(sf, gi->region0_count,      4 );
  303.       putbits(sf, gi->region1_count,      3 );
  304.       putbits(sf, 0, 1 ); /* scalefac_scale */
  305.       putbits(sf, gi->count1table_select, 1 );
  306.     }
  307.   }
  308.   fifo[wr].fr_len = (config.mpeg.bits_per_frame - bits) >> 3; /* data bytes in this frame */
  309.   fifo[wr].si_len = bits >> 3;                       /* bytes in side info */
  310.   if(++wr == FIFO_SIZE) wr = 0; /* point to next buffer */
  311. }
  312. /*
  313.  * Huffmancodebits
  314.  * ---------------
  315.  * Note the discussion of huffmancodebits() on pages 28
  316.  * and 29 of the IS, as well as the definitions of the side
  317.  * information on pages 26 and 27.
  318.  */
  319. static void Huffmancodebits( int *ix, gr_info *gi )
  320. {
  321.   int region1Start;
  322.   int region2Start;
  323.   int i, bigvalues, count1End;
  324.   int v, w, x, y, cx_bits, cbits, xbits, stuffingBits;
  325.   unsigned long code, ext;
  326.   struct huffcodetab *h;
  327.   int bvbits, c1bits, tablezeros, r0, r1, r2, rt, *pr;
  328.   int bitsWritten = 0;
  329. //  int idx = 0;
  330.   tablezeros = 0;
  331.   r0 = r1 = r2 = 0;
  332.   /* 1: Write the bigvalues */
  333.   bigvalues = gi->big_values <<1;
  334.   {
  335.     unsigned scalefac_index = 100;
  336.     scalefac_index = gi->region0_count + 1;
  337.     region1Start = scalefac_band_long[ scalefac_index ];
  338.     scalefac_index += gi->region1_count + 1;
  339.     region2Start = scalefac_band_long[ scalefac_index ];
  340.     for ( i = 0; i < bigvalues; i += 2 )
  341.     {
  342.       unsigned tableindex = 100;
  343.       /* get table pointer */
  344.       if ( i < region1Start )
  345.       {
  346.         tableindex = gi->table_select[0];
  347.         pr = &r0;
  348.       }
  349.       else if ( i < region2Start )
  350.       {
  351.         tableindex = gi->table_select[1];
  352.         pr = &r1;
  353.       }
  354.       else
  355.       {
  356.         tableindex = gi->table_select[2];
  357.         pr = &r2;
  358.       }
  359.       h = &ht[ tableindex ];
  360.       /* get huffman code */
  361.       x = ix[i];
  362.       y = ix[i + 1];
  363.       if ( tableindex )
  364.       {
  365.         cx_bits = HuffmanCode( tableindex, x, y, &code, &ext, &cbits, &xbits );
  366.         putbits(main_,  code, cbits );
  367.         putbits(main_,  ext, xbits );
  368.         bitsWritten += rt = cx_bits;
  369.         *pr += rt;
  370.       }
  371.       else
  372.       {
  373.         tablezeros += 1;
  374.         *pr = 0;
  375.       }
  376.     }
  377.   }
  378.   bvbits = bitsWritten;
  379.   /* 2: Write count1 area */
  380.   h = &ht[gi->count1table_select + 32];
  381.   count1End = bigvalues + (gi->count1 <<2);
  382.   for ( i = bigvalues; i < count1End; i += 4 )
  383.   {
  384.     v = ix[i];
  385.     w = ix[i+1];
  386.     x = ix[i+2];
  387.     y = ix[i+3];
  388.     bitsWritten += L3_huffman_coder_count1( h, v, w, x, y );
  389.   }
  390.   c1bits = bitsWritten - bvbits;
  391.   if ((stuffingBits = gi->part2_3_length - bitsWritten) != 0)
  392.   {
  393.     int words = stuffingBits >> 5;
  394.     int remainder = stuffingBits & 31;
  395.     /*
  396.      * Due to the nature of the Huffman code
  397.      * tables, we will pad with ones
  398.      */
  399.     while(words--)
  400.       putbits(main_, ~0, 32 );
  401.     if(remainder)
  402.       putbits(main_, ~0, remainder );
  403.   }
  404. }
  405. /*
  406.  * abs_and_sign
  407.  * ------------
  408.  */
  409. static int abs_and_sign( int *x )
  410. {
  411.   if ( *x > 0 ) return 0;
  412.   *x *= -1;
  413.   return 1;
  414. }
  415. /*
  416.  * L3_huffman_coder_count1
  417.  * -----------------------
  418.  */
  419. static int L3_huffman_coder_count1( struct huffcodetab *h, int v, int w, int x, int y )
  420. {
  421.   HUFFBITS huffbits;
  422.   unsigned int signv, signw, signx, signy, p;
  423.   int len;
  424.   int totalBits;
  425.   signv = abs_and_sign( &v );
  426.   signw = abs_and_sign( &w );
  427.   signx = abs_and_sign( &x );
  428.   signy = abs_and_sign( &y );
  429.   p = v + (w << 1) + (x << 2) + (y << 3);
  430.   huffbits = h->table[p];
  431.   len = h->hlen[p];
  432.   putbits(main_,  huffbits, len );
  433.   totalBits = len;
  434.   if ( v )
  435.   {
  436.     putbits(main_,  signv, 1 );
  437.     totalBits++;
  438.   }
  439.   if ( w )
  440.   {
  441.     putbits(main_,  signw, 1 );
  442.     totalBits++;
  443.   }
  444.   if ( x )
  445.   {
  446.     putbits(main_,  signx, 1 );
  447.     totalBits++;
  448.   }
  449.   if ( y )
  450.   {
  451.     putbits(main_,  signy, 1 );
  452.     totalBits++;
  453.   }
  454.   return totalBits;
  455. }
  456. /*
  457.  * HuffmanCode
  458.  * -----------
  459.  * Implements the pseudocode of page 98 of the IS
  460.  */
  461. static int HuffmanCode(int table_select, int x, int y, unsigned long *code,
  462.                 unsigned long *ext, int *cbits, int *xbits )
  463. {
  464.   unsigned signx, signy, linbitsx, linbitsy, linbits, xlen, ylen, idx;
  465.   struct huffcodetab *h;
  466.   *cbits = 0;
  467.   *xbits = 0;
  468.   *code  = 0;
  469.   *ext   = 0;
  470.   if(table_select==0) return 0;
  471.   signx = abs_and_sign( &x );
  472.   signy = abs_and_sign( &y );
  473.   h = &(ht[table_select]);
  474.   xlen = h->xlen;
  475.   ylen = h->ylen;
  476.   linbits = h->linbits;
  477.   linbitsx = linbitsy = 0;
  478.   if ( table_select > 15 )
  479.   { /* ESC-table is used */
  480.     if ( x > 14 )
  481.     {
  482.       linbitsx = x - 15;
  483.       x = 15;
  484.     }
  485.     if ( y > 14 )
  486.     {
  487.       linbitsy = y - 15;
  488.       y = 15;
  489.     }
  490.     idx = (x * ylen) + y;
  491.     *code  = h->table[idx];
  492.     *cbits = h->hlen [idx];
  493.     if ( x > 14 )
  494.     {
  495.       *ext   |= linbitsx;
  496.       *xbits += linbits;
  497.     }
  498.     if ( x != 0 )
  499.     {
  500.       *ext = ((*ext) << 1) | signx;
  501.       *xbits += 1;
  502.     }
  503.     if ( y > 14 )
  504.     {
  505.       *ext = ((*ext) << linbits) | linbitsy;
  506.       *xbits += linbits;
  507.     }
  508.     if ( y != 0 )
  509.     {
  510.       *ext = ((*ext) << 1) | signy;
  511.       *xbits += 1;
  512.     }
  513.   }
  514.   else
  515.   { /* No ESC-words */
  516.     idx = (x * ylen) + y;
  517.     *code = h->table[idx];
  518.     *cbits += h->hlen[ idx ];
  519.     if ( x != 0 )
  520.     {
  521.       *code = ((*code) << 1) | signx;
  522.       *cbits += 1;
  523.     }
  524.     if ( y != 0 )
  525.     {
  526.       *code = ((*code) << 1) | signy;
  527.       *cbits += 1;
  528.     }
  529.   }
  530.   return *cbits + *xbits;
  531. }