home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 13 / AACD13.ISO / AACD / Sound / LAME / src / bitstream.c < prev    next >
C/C++ Source or Header  |  2000-08-01  |  24KB  |  851 lines

  1. /*
  2.  *    MP3 bitstream Output interface for LAME
  3.  *
  4.  *    Copyright (c) 1999 Takehiro TOMINAGA
  5.  *
  6.  * This library is free software; you can redistribute it and/or
  7.  * modify it under the terms of the GNU Library General Public
  8.  * License as published by the Free Software Foundation; either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * This library is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
  14.  * Library General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU Library General Public
  17.  * License along with this library; if not, write to the
  18.  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19.  * Boston, MA 02111-1307, USA.
  20.  */
  21.  
  22. #include <stdlib.h>
  23. #include <assert.h>
  24. #include <stdio.h>
  25. #include "tables.h"
  26. #include "bitstream.h"
  27. #include "quantize.h"
  28. #include "quantize-pvt.h"
  29. #include "version.h"
  30.  
  31. /* This is the scfsi_band table from 2.4.2.7 of the IS */
  32. const int scfsi_band[5] = { 0, 6, 11, 16, 21 };
  33.  
  34.  
  35.  
  36. #define MAX_LENGTH      32   /* Maximum length of word written or
  37.                                         read from bit stream */
  38.  
  39.  
  40. #ifdef DEBUG
  41. static int hoge, hogege;
  42. #endif
  43.  
  44.  
  45.  
  46.  
  47.  
  48. const int pmask[8]={0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff};
  49.  
  50.  
  51.  
  52. void putheader_bits(lame_internal_flags *gfc,int w_ptr)
  53. {
  54.     Bit_stream_struc *bs;
  55.     bs = &gfc->bs;
  56. #ifdef DEBUG
  57.     hoge += gfc->sideinfo_len * 8;
  58.     hogege += gfc->sideinfo_len * 8;
  59. #endif
  60.     memcpy(&bs->buf[bs->buf_byte_idx], gfc->header[gfc->w_ptr].buf,
  61.        gfc->sideinfo_len);
  62.     bs->buf_byte_idx += gfc->sideinfo_len;
  63.     bs->totbit += gfc->sideinfo_len * 8;
  64.     gfc->w_ptr = (gfc->w_ptr + 1) & (MAX_HEADER_BUF - 1);
  65. }
  66.  
  67.  
  68.  
  69.  
  70. /*write N bits into the bit stream */
  71. static INLINE void
  72. putbits2(lame_global_flags *gfp, unsigned int val, int j)
  73. {
  74.     lame_internal_flags *gfc=gfp->internal_flags;
  75.     Bit_stream_struc *bs;
  76.     bs = &gfc->bs;
  77.  
  78.     assert(j <= MAX_LENGTH);
  79.     if (j<MAX_LENGTH)
  80.       {
  81.     if (val >= (1 << j)) {
  82.       DEBUGF("val=%ui %i \n",val,(1<<j));
  83.     }
  84.       assert(val < (1 << j));  /* 1 << 32 wont work on 32 bit machines */
  85.       }
  86.  
  87.     while (j > 0) {
  88.     int k;
  89.     if (bs->buf_bit_idx == 0) {
  90.         bs->buf_bit_idx = 8;
  91.         bs->buf_byte_idx++;
  92.         assert(bs->buf_byte_idx < BUFFER_SIZE);
  93.         assert(gfc->header[gfc->w_ptr].write_timing >= bs->totbit);
  94.         if (gfc->header[gfc->w_ptr].write_timing == bs->totbit) {
  95.           putheader_bits(gfc,gfc->w_ptr);
  96.         }
  97.         bs->buf[bs->buf_byte_idx] = 0;
  98.     }
  99.  
  100.     k = Min(j, bs->buf_bit_idx);
  101.  
  102.     bs->buf[bs->buf_byte_idx]
  103.         |= ((val >> (j-k)) & pmask[k - 1]) << (bs->buf_bit_idx - k);
  104.     bs->buf_bit_idx -= k;
  105.     j -= k;
  106.     bs->totbit += k;
  107.     }
  108. }
  109.  
  110. /*
  111.   Some combinations of bitrate, Fs, and stereo make it impossible to stuff
  112.   out a frame using just main_data, due to the limited number of bits to
  113.   indicate main_data_length. In these situations, we put stuffing bits into
  114.   the ancillary data...
  115. */
  116.  
  117. static INLINE void
  118. drain_into_ancillary(lame_global_flags *gfp,int remainingBits)
  119. {
  120.     lame_internal_flags *gfc=gfp->internal_flags;
  121.     int i,bits;
  122.     assert(remainingBits >= 0);
  123. #ifdef DEBUG
  124.     DEBUGF("remain %d\n",remainingBits);
  125.     hoge += remainingBits;
  126.     hogege += remainingBits;
  127. #endif
  128.  
  129.     if (remainingBits >= 8) {
  130.       putbits2(gfp,0x4c,8);
  131.       remainingBits -= 8;
  132.     }
  133.     if (remainingBits >= 8) {
  134.       putbits2(gfp,0x41,8);
  135.       remainingBits -= 8;
  136.     }
  137.     if (remainingBits >= 8) {
  138.       putbits2(gfp,0x4d,8);
  139.       remainingBits -= 8;
  140.     }
  141.     if (remainingBits >= 8) {
  142.       putbits2(gfp,0x45,8);
  143.       remainingBits -= 8;
  144.     }
  145.       
  146.     if (remainingBits >= 32) {
  147.       char * version;
  148.       version = get_lame_version();
  149.       if (remainingBits >= 32) 
  150.     for (i=0; i<strlen(version) && remainingBits >=8 ; ++i) {
  151.       remainingBits -= 8;
  152.       putbits2(gfp,(unsigned int)version[i],8);
  153.     }
  154.     }
  155.  
  156.  
  157.     bits = remainingBits & (MAX_LENGTH - 1);
  158.     for (i=0; i<bits; ++i) {
  159.       putbits2(gfp,gfc->ancillary_flag,1);
  160.       gfc->ancillary_flag = 1-gfc->ancillary_flag;
  161.     }
  162.  
  163.     remainingBits /= MAX_LENGTH;
  164.     for (; remainingBits > 0; remainingBits--) {
  165.       if (gfc->ancillary_flag)
  166.     putbits2(gfp,0xAAAAAAAA, MAX_LENGTH);
  167.       else
  168.     putbits2(gfp,0x55555555, MAX_LENGTH);
  169.     }
  170. }
  171.  
  172. /*write N bits into the header */
  173. static INLINE void
  174. writeheader(lame_internal_flags *gfc,unsigned int val, int j)
  175. {
  176.     int ptr = gfc->header[gfc->h_ptr].ptr;
  177.     assert(j <= MAX_LENGTH);
  178.  
  179.     while (j > 0) {
  180.     int k = Min(j, 8 - (ptr & 7));
  181.     gfc->header[gfc->h_ptr].buf[ptr >> 3]
  182.         |= ((val >> (j-k)) & pmask[k-1]) << (8 - (ptr & 7) - k);
  183.     ptr += k;
  184.     j -= k;
  185.     }
  186.     gfc->header[gfc->h_ptr].ptr = ptr;
  187. }
  188.  
  189.  
  190. /* (jo) this wrapper function for BF_addEntry() updates also the crc */
  191. static void
  192. CRC_writeheader(lame_internal_flags *gfc,unsigned int value, int length,unsigned int *crc)
  193. {
  194.    unsigned int bit = 1 << length;
  195.  
  196.    while((bit >>= 1)){
  197.       *crc <<= 1;
  198.       if (!(*crc & 0x10000) ^ !(value & bit))
  199.     *crc ^= CRC16_POLYNOMIAL;
  200.    }
  201.    *crc &= 0xffff;
  202.    writeheader(gfc,value, length);
  203. }
  204.  
  205. static INLINE void
  206. encodeSideInfo2(lame_global_flags *gfp,int bitsPerFrame)
  207. {
  208.     lame_internal_flags *gfc=gfp->internal_flags;
  209.     III_side_info_t *l3_side;
  210.     int gr, ch;
  211.     unsigned int crc;
  212.     
  213.     l3_side = &gfc->l3_side;
  214.     gfc->header[gfc->h_ptr].ptr = 0;
  215.     memset(gfc->header[gfc->h_ptr].buf, 0, gfc->sideinfo_len);
  216.     crc = 0xffff; /* (jo) init crc16 for error_protection */
  217.     if (gfp->out_samplerate < 16000) 
  218.       writeheader(gfc,0xffe,                12);
  219.     else
  220.       writeheader(gfc,0xfff,                12);
  221.     writeheader(gfc,(unsigned int)(gfp->version),            1);
  222.     writeheader(gfc,4 - 3,                 2);
  223.     writeheader(gfc,(unsigned int)(!gfp->error_protection),  1);
  224.     /* (jo) from now on call the CRC_writeheader() wrapper to update crc */
  225.     CRC_writeheader(gfc,(unsigned int)(gfc->bitrate_index),      4,&crc);
  226.     CRC_writeheader(gfc,(unsigned int)(gfc->samplerate_index),   2,&crc);
  227.     CRC_writeheader(gfc,(unsigned int)(gfc->padding),            1,&crc);
  228.     CRC_writeheader(gfc,(unsigned int)(gfp->extension),          1,&crc);
  229.     CRC_writeheader(gfc,(unsigned int)(gfp->mode),               2,&crc);
  230.     CRC_writeheader(gfc,(unsigned int)(gfc->mode_ext),           2,&crc);
  231.     CRC_writeheader(gfc,(unsigned int)(gfp->copyright),          1,&crc);
  232.     CRC_writeheader(gfc,(unsigned int)(gfp->original),           1,&crc);
  233.     CRC_writeheader(gfc,(unsigned int)(gfp->emphasis),           2,&crc);
  234.     if (gfp->error_protection) {
  235.     writeheader(gfc,0, 16); /* dummy */
  236.     }
  237.  
  238.     if (gfp->version == 1) {
  239.     /* MPEG1 */
  240.     assert(l3_side->main_data_begin >= 0);
  241.     CRC_writeheader(gfc,(unsigned int)(l3_side->main_data_begin), 9,&crc);
  242.  
  243.     if (gfc->stereo == 2)
  244.         CRC_writeheader(gfc,l3_side->private_bits, 3,&crc);
  245.     else
  246.         CRC_writeheader(gfc,l3_side->private_bits, 5,&crc);
  247.  
  248.     for (ch = 0; ch < gfc->stereo; ch++) {
  249.         int band;
  250.         for (band = 0; band < 4; band++) {
  251.         CRC_writeheader(gfc,l3_side->scfsi[ch][band], 1,&crc);
  252.         }
  253.     }
  254.  
  255.     for (gr = 0; gr < 2; gr++) {
  256.         for (ch = 0; ch < gfc->stereo; ch++) {
  257.         gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
  258.         CRC_writeheader(gfc,gi->part2_3_length,       12,&crc);
  259.         CRC_writeheader(gfc,gi->big_values / 2,        9,&crc);
  260.         CRC_writeheader(gfc,gi->global_gain,           8,&crc);
  261.         CRC_writeheader(gfc,gi->scalefac_compress,     4,&crc);
  262.         CRC_writeheader(gfc,gi->window_switching_flag, 1,&crc);
  263.  
  264.         if (gi->window_switching_flag) {
  265.             CRC_writeheader(gfc,gi->block_type,       2,&crc);
  266.             CRC_writeheader(gfc,gi->mixed_block_flag, 1,&crc);
  267.  
  268.             if (gi->table_select[0] == 14)
  269.             gi->table_select[0] = 16;
  270.             CRC_writeheader(gfc,gi->table_select[0],  5,&crc);
  271.             if (gi->table_select[1] == 14)
  272.             gi->table_select[1] = 16;
  273.             CRC_writeheader(gfc,gi->table_select[1],  5,&crc);
  274.  
  275.             CRC_writeheader(gfc,gi->subblock_gain[0], 3,&crc);
  276.             CRC_writeheader(gfc,gi->subblock_gain[1], 3,&crc);
  277.             CRC_writeheader(gfc,gi->subblock_gain[2], 3,&crc);
  278.         } else {
  279.             assert(gi->block_type == NORM_TYPE);
  280.             if (gi->table_select[0] == 14)
  281.             gi->table_select[0] = 16;
  282.             CRC_writeheader(gfc,gi->table_select[0], 5,&crc);
  283.             if (gi->table_select[1] == 14)
  284.             gi->table_select[1] = 16;
  285.             CRC_writeheader(gfc,gi->table_select[1], 5,&crc);
  286.             if (gi->table_select[2] == 14)
  287.             gi->table_select[2] = 16;
  288.             CRC_writeheader(gfc,gi->table_select[2], 5,&crc);
  289.  
  290.             assert(gi->region0_count < 16U);
  291.             assert(gi->region1_count < 8U);
  292.             CRC_writeheader(gfc,gi->region0_count, 4,&crc);
  293.             CRC_writeheader(gfc,gi->region1_count, 3,&crc);
  294.         }
  295.         CRC_writeheader(gfc,gi->preflag,            1,&crc);
  296.         CRC_writeheader(gfc,gi->scalefac_scale,     1,&crc);
  297.         CRC_writeheader(gfc,gi->count1table_select, 1,&crc);
  298.         }
  299.     }
  300.     } else {
  301.     /* MPEG2 */
  302.     assert(l3_side->main_data_begin >= 0);
  303.     CRC_writeheader(gfc,(unsigned int)(l3_side->main_data_begin), 8,&crc);
  304.     CRC_writeheader(gfc,l3_side->private_bits, gfc->stereo,&crc);
  305.  
  306.     gr = 0;
  307.     for (ch = 0; ch < gfc->stereo; ch++) {
  308.         gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
  309.         CRC_writeheader(gfc,gi->part2_3_length,       12,&crc);
  310.         CRC_writeheader(gfc,gi->big_values / 2,        9,&crc);
  311.         CRC_writeheader(gfc,gi->global_gain,           8,&crc);
  312.         CRC_writeheader(gfc,gi->scalefac_compress,     9,&crc);
  313.         CRC_writeheader(gfc,gi->window_switching_flag, 1,&crc);
  314.  
  315.         if (gi->window_switching_flag) {
  316.         CRC_writeheader(gfc,gi->block_type,       2,&crc);
  317.         CRC_writeheader(gfc,gi->mixed_block_flag, 1,&crc);
  318.  
  319.         if (gi->table_select[0] == 14)
  320.             gi->table_select[0] = 16;
  321.         CRC_writeheader(gfc,gi->table_select[0],  5,&crc);
  322.         if (gi->table_select[1] == 14)
  323.             gi->table_select[1] = 16;
  324.         CRC_writeheader(gfc,gi->table_select[1],  5,&crc);
  325.  
  326.         CRC_writeheader(gfc,gi->subblock_gain[0], 3,&crc);
  327.         CRC_writeheader(gfc,gi->subblock_gain[1], 3,&crc);
  328.         CRC_writeheader(gfc,gi->subblock_gain[2], 3,&crc);
  329.         } else {
  330.         if (gi->table_select[0] == 14)
  331.             gi->table_select[0] = 16;
  332.         CRC_writeheader(gfc,gi->table_select[0], 5,&crc);
  333.         if (gi->table_select[1] == 14)
  334.             gi->table_select[1] = 16;
  335.         CRC_writeheader(gfc,gi->table_select[1], 5,&crc);
  336.         if (gi->table_select[2] == 14)
  337.             gi->table_select[2] = 16;
  338.         CRC_writeheader(gfc,gi->table_select[2], 5,&crc);
  339.  
  340.         assert(gi->region0_count < 16U);
  341.         assert(gi->region1_count < 8U);
  342.         CRC_writeheader(gfc,gi->region0_count, 4,&crc);
  343.         CRC_writeheader(gfc,gi->region1_count, 3,&crc);
  344.         }
  345.  
  346.         CRC_writeheader(gfc,gi->scalefac_scale,     1,&crc);
  347.         CRC_writeheader(gfc,gi->count1table_select, 1,&crc);
  348.     }
  349.     }
  350.  
  351.     if (gfp->error_protection) {
  352.     /* (jo) error_protection: add crc16 information to header */
  353.     gfc->header[gfc->h_ptr].buf[4] = crc >> 8;
  354.     gfc->header[gfc->h_ptr].buf[5] = crc & 255;
  355.     }
  356.  
  357.     {
  358.     int old = gfc->h_ptr;
  359.     assert(gfc->header[old].ptr == gfc->sideinfo_len * 8);
  360.  
  361.     gfc->h_ptr = (old + 1) & (MAX_HEADER_BUF - 1);
  362.     gfc->header[gfc->h_ptr].write_timing =
  363.         gfc->header[old].write_timing + bitsPerFrame;
  364.  
  365.     if (gfc->h_ptr == gfc->w_ptr) {
  366.       /* yikes! we are out of header buffer space */
  367.       ERRORF("Error: MAX_HEADER_BUF too small in bitstream.c \n");
  368.     }
  369.  
  370.     }
  371. }
  372.  
  373.  
  374.  
  375. static INLINE int
  376. huffman_coder_count1(lame_global_flags *gfp,int *ix, gr_info *gi)
  377. {
  378. #ifdef DEBUG
  379.     lame_internal_flags *gfc = gfp->internal_flags;
  380. #endif
  381.     /* Write count1 area */
  382.     const struct huffcodetab *h = &ht[gi->count1table_select + 32];
  383.     int i,bits=0;
  384. #ifdef DEBUG
  385.     int gegebo = gfc->bs.totbit;
  386. #endif
  387.  
  388.     ix += gi->big_values;
  389.     assert(gi->count1table_select < 2);
  390.  
  391.  
  392.     for (i = (gi->count1 - gi->big_values) / 4; i > 0; --i) {
  393.     HUFFBITS huffbits = 0;
  394.     int p = 0, v;
  395.  
  396.     v = ix[0];
  397.     if (v) {
  398.         p += 8;
  399.         if (v < 0)
  400.         huffbits++;
  401.         assert(-1 <= v && v <= 1);
  402.     }
  403.  
  404.     v = ix[1];
  405.     if (v) {
  406.         p += 4;
  407.         huffbits *= 2;
  408.         if (v < 0)
  409.         huffbits++;
  410.         assert(-1 <= v && v <= 1);
  411.     }
  412.  
  413.     v = ix[2];
  414.     if (v) {
  415.         p += 2;
  416.         huffbits *= 2;
  417.         if (v < 0)
  418.         huffbits++;
  419.         assert(-1 <= v && v <= 1);
  420.     }
  421.  
  422.     v = ix[3];
  423.     if (v) {
  424.         p++;
  425.         huffbits *= 2;
  426.         if (v < 0)
  427.         huffbits++;
  428.         assert(-1 <= v && v <= 1);
  429.     }
  430.  
  431.     ix += 4;
  432.     putbits2(gfp,huffbits + h->table[p], h->hlen[p]);
  433.     bits += h->hlen[p];
  434.     }
  435. #ifdef DEBUG
  436.     DEBUGF("%ld %d %d %d\n",gfc->bs.totbit -gegebo, gi->count1bits, gi->big_values, gi->count1);
  437. #endif
  438.     return bits;
  439. }
  440.  
  441. /*
  442.   Implements the pseudocode of page 98 of the IS
  443.   */
  444.  
  445. static INLINE int
  446. HuffmanCode(lame_global_flags *gfp, unsigned int table_select, int x, int y)
  447. {
  448.   /*    lame_internal_flags *gfc=gfp->internal_flags;*/
  449.     unsigned int code, ext, xlen;
  450.     int cbits, xbits;
  451.     unsigned int signx, signy, linbits;
  452.     const struct huffcodetab *h;
  453.  
  454.     cbits = 0;
  455.     xbits = 0;
  456.     code  = 0;
  457.     signx = signy = 0;
  458.  
  459.     if (x < 0) {
  460.     signx++;
  461.     x = -x;
  462.     }
  463.  
  464.     if (y < 0) {
  465.     signy++;
  466.     y = -y;
  467.     }
  468.  
  469.     assert(table_select>0);
  470.     h = &(ht[table_select]);
  471.     linbits = h->xlen;
  472.     ext = signx;
  473.     xlen = h->xlen;
  474.  
  475.     if (table_select > 15) {
  476.     /* use ESC-words */
  477.     if (x > 14) {
  478.         int linbitsx = x - 15;
  479.         assert(linbitsx <= h->linmax);
  480.         ext |= linbitsx << 1;
  481.         xbits = linbits;
  482.         x = 15;
  483.     }
  484.  
  485.     if (y > 14) {
  486.         int linbitsy = y - 15;
  487.         assert(linbitsy <= h->linmax);
  488.         ext <<= linbits;
  489.         ext |= linbitsy;
  490.         xbits += linbits;
  491.         y = 15;
  492.     }
  493.     xlen = 16;
  494.     }
  495.  
  496.     if (x != 0) {
  497.     cbits--;
  498.     }
  499.  
  500.     if (y != 0) {
  501.     ext <<= 1;
  502.     ext |= signy;
  503.     cbits--;
  504.     }
  505.  
  506.     xbits -= cbits;
  507.  
  508.     assert(x <= 15);
  509.     assert(y <= 15);
  510.     assert(x >= 0);
  511.     assert(y >= 0);
  512.  
  513.     x = x * xlen + y;
  514.  
  515.     code = h->table[x];
  516.     cbits += h->hlen[x];
  517.  
  518.     assert(cbits <= 32);
  519.     assert(xbits <= 32);
  520.  
  521.     putbits2(gfp,code, cbits);
  522.     putbits2(gfp, ext, xbits);
  523.     return cbits+xbits;
  524. }
  525.  
  526. static int
  527. Huffmancodebits(lame_global_flags *gfp,unsigned int tableindex, int start, int end, int *ix)
  528. {
  529.     int i,bits;
  530.  
  531.     assert(tableindex < 32);
  532.     if (!tableindex) return 0;
  533.  
  534.     bits=0;
  535.     for (i = start; i < end; i += 2) {
  536.       bits +=HuffmanCode(gfp,tableindex, ix[i], ix[i + 1]);
  537.     }
  538.     return bits;
  539. }
  540.  
  541.  
  542.  
  543. /*
  544.   Note the discussion of huffmancodebits() on pages 28
  545.   and 29 of the IS, as well as the definitions of the side
  546.   information on pages 26 and 27.
  547.   */
  548. static int
  549. ShortHuffmancodebits(lame_global_flags *gfp,int *ix, gr_info *gi)
  550. {
  551.     lame_internal_flags *gfc=gfp->internal_flags;
  552.     int bits;
  553.     int region1Start;
  554.     
  555.     region1Start=3*gfc->scalefac_band.s[3];
  556.     if (region1Start > gi->big_values)     region1Start = gi->big_values;
  557.  
  558.     /* short blocks do not have a region2 */
  559.     bits  = Huffmancodebits(gfp,gi->table_select[0], 0, region1Start, ix);
  560.     bits += Huffmancodebits(gfp,gi->table_select[1], region1Start, gi->big_values, ix);
  561.     return bits;
  562. }
  563.  
  564. static int
  565. LongHuffmancodebits(lame_global_flags *gfp,int *ix, gr_info *gi)
  566. {
  567.     lame_internal_flags *gfc=gfp->internal_flags;
  568.     int i, bigvalues,bits=0;
  569.     int region1Start, region2Start;
  570.  
  571.     bigvalues = gi->big_values;
  572.     assert(0 <= bigvalues && bigvalues <= 576);
  573.  
  574.     i = gi->region0_count + 1;
  575.     assert(i < 23);
  576.     region1Start = gfc->scalefac_band.l[i];
  577.     i += gi->region1_count + 1;
  578.     assert(i < 23);
  579.     region2Start = gfc->scalefac_band.l[i];
  580.  
  581.     if (region1Start > bigvalues)
  582.     region1Start = bigvalues;
  583.  
  584.     if (region2Start > bigvalues)
  585.     region2Start = bigvalues;
  586.  
  587.     bits +=Huffmancodebits(gfp,gi->table_select[0], 0, region1Start, ix);
  588.     bits +=Huffmancodebits(gfp,gi->table_select[1], region1Start, region2Start, ix);
  589.     bits +=Huffmancodebits(gfp,gi->table_select[2], region2Start, bigvalues, ix);
  590.     return bits;
  591. }
  592.  
  593. static INLINE int
  594. writeMainData(lame_global_flags *gfp,
  595.       int              l3_enc[2][2][576],
  596.       III_scalefac_t   scalefac[2][2] )
  597. {
  598.     int gr, ch, sfb,data_bits,scale_bits,tot_bits=0;
  599.     lame_internal_flags *gfc=gfp->internal_flags;
  600.     III_side_info_t *l3_side;
  601.  
  602.     l3_side = &gfc->l3_side;
  603.     if (gfp->version == 1) {
  604.     /* MPEG 1 */
  605.     for (gr = 0; gr < 2; gr++) {
  606.         for (ch = 0; ch < gfc->stereo; ch++) {
  607.         gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
  608.         int slen1 = slen1_tab[gi->scalefac_compress];
  609.         int slen2 = slen2_tab[gi->scalefac_compress];
  610.         data_bits=0;
  611.         scale_bits=0;
  612.  
  613. #ifdef DEBUG
  614.         hogege = gfc->bs.totbit;
  615. #endif
  616.         if (gi->block_type == SHORT_TYPE) {
  617.             for (sfb = 0; sfb < SBPSY_s; sfb++) {
  618.             int slen = sfb < 6 ? slen1 : slen2;
  619.  
  620.             assert(scalefac[gr][ch].s[sfb][0]>=0);
  621.             assert(scalefac[gr][ch].s[sfb][1]>=0);
  622.             assert(scalefac[gr][ch].s[sfb][2]>=0);
  623.  
  624.             putbits2(gfp,scalefac[gr][ch].s[sfb][0], slen);
  625.             putbits2(gfp,scalefac[gr][ch].s[sfb][1], slen);
  626.             putbits2(gfp,scalefac[gr][ch].s[sfb][2], slen);
  627.             scale_bits += 3*slen;
  628.             }
  629.             data_bits += ShortHuffmancodebits(gfp,l3_enc[gr][ch], gi);
  630.         } else {
  631.             int i;
  632.             for (i = 0; i < sizeof(scfsi_band) / sizeof(int) - 1;
  633.              i++) {
  634.             if (gr != 0 && l3_side->scfsi[ch][i])
  635.                 continue;
  636.  
  637.             for (sfb = scfsi_band[i]; sfb < scfsi_band[i + 1];
  638.                  sfb++) {
  639.  
  640.                 assert(scalefac[gr][ch].l[sfb]>=0);
  641.                 putbits2(gfp,scalefac[gr][ch].l[sfb],
  642.                     sfb < 11 ? slen1 : slen2);
  643.                 scale_bits += sfb < 11 ? slen1 : slen2;
  644.             }
  645.             }
  646.             data_bits +=LongHuffmancodebits(gfp,l3_enc[gr][ch], gi);
  647.         }
  648.         data_bits +=huffman_coder_count1(gfp,l3_enc[gr][ch], gi);
  649. #ifdef DEBUG
  650.         DEBUGF("<%ld> ", gfc->bs.totbit-hogege);
  651. #endif
  652.         /* does bitcount in quantize.c agree with actual bit count?*/
  653.         assert(data_bits==gi->part2_3_length-gi->part2_length);
  654.         assert(scale_bits==gi->part2_length);
  655.         tot_bits += scale_bits + data_bits;
  656.  
  657.         } /* for ch */
  658.     } /* for gr */
  659.     } else {
  660.     /* MPEG 2 */
  661.     gr = 0;
  662.     for (ch = 0; ch < gfc->stereo; ch++) {
  663.         gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
  664.         int i, sfb_partition;
  665.         assert(gi->sfb_partition_table);
  666.         data_bits = 0;
  667.         scale_bits=0;
  668.  
  669.         sfb = 0;
  670.         sfb_partition = 0;
  671.         if (gi->block_type == SHORT_TYPE) {
  672.         for (; sfb_partition < 4; sfb_partition++) {
  673.             int sfbs = gi->sfb_partition_table[sfb_partition] / 3;
  674.             int slen = gi->slen[sfb_partition];
  675.             for (i = 0; i < sfbs; i++, sfb++) {
  676.             putbits2(gfp,Max(scalefac[gr][ch].s[sfb][0], 0U), slen);
  677.             putbits2(gfp,Max(scalefac[gr][ch].s[sfb][1], 0U), slen);
  678.             putbits2(gfp,Max(scalefac[gr][ch].s[sfb][2], 0U), slen);
  679.             scale_bits += 3*slen;
  680.             }
  681.         }
  682.         data_bits += ShortHuffmancodebits(gfp,l3_enc[gr][ch], gi);
  683.         } else {
  684.         for (; sfb_partition < 4; sfb_partition++) {
  685.             int sfbs = gi->sfb_partition_table[sfb_partition];
  686.             int slen = gi->slen[sfb_partition];
  687.             for (i = 0; i < sfbs; i++, sfb++) {
  688.             putbits2(gfp,Max(scalefac[gr][ch].l[sfb], 0U), slen);
  689.             scale_bits += slen;
  690.             }
  691.         }
  692.         data_bits +=LongHuffmancodebits(gfp,l3_enc[gr][ch], gi);
  693.         }
  694.         data_bits +=huffman_coder_count1(gfp,l3_enc[gr][ch], gi);
  695.  
  696.         /* does bitcount in quantize.c agree with actual bit count?*/
  697.         assert(data_bits==gi->part2_3_length-gi->part2_length);
  698.         assert(scale_bits==gi->part2_length);
  699.         tot_bits += scale_bits + data_bits;
  700.     } /* for ch */
  701.     } /* for gf */
  702.     return tot_bits;
  703. } /* main_data */
  704.  
  705.  
  706.  
  707.  
  708. void
  709. flush_bitstream(lame_global_flags *gfp)
  710. {
  711.   lame_internal_flags *gfc=gfp->internal_flags;
  712.   int flushbits,remaining_headers;
  713.   int bitsPerFrame, mean_bits;
  714.   int last_ptr,first_ptr;
  715.   first_ptr=gfc->w_ptr;           /* first header to add to bitstream */
  716.   last_ptr = gfc->h_ptr - 1;   /* last header to add to bitstream */
  717.   if (last_ptr==-1) last_ptr=MAX_HEADER_BUF-1;   
  718.  
  719.   /* add this many bits to bitstream so we can flush all headers */
  720.   flushbits = gfc->header[last_ptr].write_timing - gfc->bs.totbit;
  721.  
  722.   if (flushbits >= 0) {
  723.     /* if flushbits >= 0, some headers have not yet been written */
  724.     /* reduce flushbits by the size of the headers */
  725.     remaining_headers= 1+last_ptr - first_ptr;
  726.     if (last_ptr < first_ptr) 
  727.       remaining_headers= 1+last_ptr - first_ptr + MAX_HEADER_BUF;
  728.     flushbits -= remaining_headers*8*gfc->sideinfo_len;
  729.   }
  730.  
  731.  
  732.   /* finally, add some bits so that the last frame is complete
  733.    * these bits are not necessary to decode the last frame, but
  734.    * some decoders will ignore last frame if these bits are missing 
  735.    */
  736.   getframebits(gfp,&bitsPerFrame,&mean_bits);
  737.   flushbits += bitsPerFrame;
  738.   if (flushbits<0) {
  739. #if 0
  740.     /* if flushbits < 0, this would mean that the buffer looks like:
  741.      * (data...)  last_header  (data...)  (extra data that should not be here...)
  742.      */
  743.     DEBUGF("last header write_timing = %i \n",gfc->header[last_ptr].write_timing);
  744.     DEBUGF("first header write_timing = %i \n",gfc->header[first_ptr].write_timing);
  745.     DEBUGF("bs.totbit:                 %i \n",gfc->bs.totbit);
  746.     DEBUGF("first_ptr, last_ptr        %i %i \n",first_ptr,last_ptr);
  747.     DEBUGF("remaining_headers =        %i \n",remaining_headers);
  748.     DEBUGF("bitsperframe:              %i \n",bitsPerFrame);
  749.     DEBUGF("sidelen:                   %i \n",gfc->sideinfo_len);
  750. #endif
  751.     ERRORF("strange error flushing buffer ... \n");
  752.   } else {
  753.     drain_into_ancillary(gfp,flushbits);
  754.   }
  755.  
  756.   assert (gfc->header[last_ptr].write_timing + bitsPerFrame  == gfc->bs.totbit);
  757. }
  758.  
  759.  
  760.  
  761.  
  762. void add_dummy_vbrframe(lame_global_flags *gfp,int bitsPerFrame)
  763. {
  764.   lame_internal_flags *gfc = gfp->internal_flags;
  765.   int bits;
  766.  
  767.   gfc->header[gfc->h_ptr].ptr = 0;
  768.   memset(gfc->header[gfc->h_ptr].buf, 0, gfc->sideinfo_len);
  769.   bits = bitsPerFrame-8*gfc->sideinfo_len;
  770.  
  771.   /* add one byte, cause header to be written */
  772.   putbits2(gfp,0,8);   
  773.   /* setup for next header */
  774.   gfc->h_ptr = (gfc->h_ptr + 1) & (MAX_HEADER_BUF - 1);
  775.   gfc->header[gfc->h_ptr].write_timing = bitsPerFrame;
  776.  
  777.   drain_into_ancillary(gfp,bits-8);
  778.  
  779. }
  780.  
  781.  
  782.  
  783. /*
  784.   format_bitstream()
  785.  
  786.   This is called after a frame of audio has been quantized and coded.
  787.   It will write the encoded audio to the bitstream. Note that
  788.   from a layer3 encoder's perspective the bit stream is primarily
  789.   a series of main_data() blocks, with header and side information
  790.   inserted at the proper locations to maintain framing. (See Figure A.7
  791.   in the IS).
  792.   */
  793. int
  794. format_bitstream(lame_global_flags *gfp, int bitsPerFrame,
  795.       int              l3_enc[2][2][576],
  796.       III_scalefac_t   scalefac[2][2] )
  797. {
  798.     lame_internal_flags *gfc=gfp->internal_flags;
  799.     int bits;
  800.     III_side_info_t *l3_side;
  801.     l3_side = &gfc->l3_side;
  802.  
  803.     drain_into_ancillary(gfp,l3_side->resvDrain_pre);
  804.  
  805.     encodeSideInfo2(gfp,bitsPerFrame);
  806.     bits = 8*gfc->sideinfo_len;
  807.     bits+=writeMainData(gfp,l3_enc,scalefac);
  808.     drain_into_ancillary(gfp,l3_side->resvDrain_post);
  809.     bits += l3_side->resvDrain_post;
  810.  
  811.     l3_side->main_data_begin += (bitsPerFrame-bits)/8;
  812.     if ((l3_side->main_data_begin * 8) != gfc->ResvSize ) {
  813.       ERRORF("bit reservoir error: \n"
  814.              "l3_side->main_data_begin: %i \n"
  815.              "Resvoir size:             %i \n"
  816.              "resv drain (post)         %i \n"
  817.              "resv drain (pre)          %i \n"
  818.              "header and sideinfo:      %i \n"
  819.              "data bits:                %i \n"
  820.              "total bits:               %i (remainder: %i) \n"
  821.              "bitsperframe:             %i \n",
  822.  
  823.              8*l3_side->main_data_begin,
  824.              gfc->ResvSize,
  825.              l3_side->resvDrain_post,
  826.              l3_side->resvDrain_pre,
  827.              8*gfc->sideinfo_len,
  828.              bits-l3_side->resvDrain_post-8*gfc->sideinfo_len,
  829.              bits, bits % 8,
  830.              bitsPerFrame
  831.       );
  832.  
  833.       gfc->ResvSize = l3_side->main_data_begin*8;
  834.     };
  835.     assert(gfc->bs.totbit % 8 == 0);
  836.  
  837.     if (gfc->bs.totbit > 1000000000UL ) {
  838.       /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter*/
  839.       int i;
  840.       for (i=0 ; i< MAX_HEADER_BUF ; ++i) 
  841.     gfc->header[i].write_timing -= gfc->bs.totbit;      
  842.       gfc->bs.totbit=0;
  843.     }
  844.     return 0;
  845. }
  846.  
  847.  
  848.  
  849.  
  850.  
  851.