bitstream.c

Go to the documentation of this file.
00001 /*
00002  *      MP3 bitstream Output interface for LAME
00003  *
00004  *      Copyright (c) 1999-2000 Mark Taylor
00005  *      Copyright (c) 1999-2002 Takehiro Tominaga
00006  *
00007  * This library is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2 of the License, or (at your option) any later version.
00011  *
00012  * This library is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Library General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with this library; if not, write to the
00019  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00020  * Boston, MA 02111-1307, USA.
00021  *
00022  * $Id: bitstream.c,v 1.79 2007/07/24 17:46:10 bouvigne Exp $
00023  */
00024 
00025 
00026 #ifdef HAVE_CONFIG_H
00027 #include <config.h>
00028 #endif
00029 
00030 #include <stdlib.h>
00031 #include <stdio.h>
00032 
00033 #include "lame.h"
00034 #include "machine.h"
00035 #include "encoder.h"
00036 #include "util.h"
00037 #include "tables.h"
00038 #include "quantize_pvt.h"
00039 #include "lame_global_flags.h"
00040 #include "gain_analysis.h"
00041 #include "VbrTag.h"
00042 #include "bitstream.h"
00043 
00044 
00045 
00046 /* unsigned int is at least this large:  */
00047 /* we work with ints, so when doing bit manipulation, we limit
00048  * ourselves to MAX_LENGTH-2 just to be on the safe side */
00049 #define MAX_LENGTH      32
00050 
00051 
00052 
00053 #ifdef DEBUG
00054 static int hoge, hogege;
00055 #endif
00056 
00057 
00058 
00059 
00060 
00061 /***********************************************************************
00062  * compute bitsperframe and mean_bits for a layer III frame
00063  **********************************************************************/
00064 int
00065 getframebits(const lame_global_flags * gfp)
00066 {
00067     lame_internal_flags const *const gfc = gfp->internal_flags;
00068     int     bit_rate;
00069 
00070     /* get bitrate in kbps [?] */
00071     if (gfc->bitrate_index)
00072         bit_rate = bitrate_table[gfp->version][gfc->bitrate_index];
00073     else
00074         bit_rate = gfp->brate;
00075     /*assert(bit_rate <= 550);*/
00076     assert(8 <= bit_rate && bit_rate <= 640);
00077 
00078     /* main encoding routine toggles padding on and off */
00079     /* one Layer3 Slot consists of 8 bits */
00080     return 8 * ((gfp->version + 1) * 72000 * bit_rate / gfp->out_samplerate + gfc->padding);
00081 }
00082 
00083 
00084 
00085 
00086 void
00087 putheader_bits(lame_internal_flags * gfc)
00088 {
00089     Bit_stream_struc *bs;
00090     bs = &gfc->bs;
00091 #ifdef DEBUG
00092     hoge += gfc->sideinfo_len * 8;
00093     hogege += gfc->sideinfo_len * 8;
00094 #endif
00095     memcpy(&bs->buf[bs->buf_byte_idx], gfc->header[gfc->w_ptr].buf, gfc->sideinfo_len);
00096     bs->buf_byte_idx += gfc->sideinfo_len;
00097     bs->totbit += gfc->sideinfo_len * 8;
00098     gfc->w_ptr = (gfc->w_ptr + 1) & (MAX_HEADER_BUF - 1);
00099 }
00100 
00101 
00102 
00103 
00104 /*write j bits into the bit stream */
00105 inline static void
00106 putbits2(lame_internal_flags * gfc, int val, int j)
00107 {
00108     Bit_stream_struc *bs;
00109     bs = &gfc->bs;
00110 
00111     assert(j < MAX_LENGTH - 2);
00112 
00113     while (j > 0) {
00114         int     k;
00115         if (bs->buf_bit_idx == 0) {
00116             bs->buf_bit_idx = 8;
00117             bs->buf_byte_idx++;
00118             assert(bs->buf_byte_idx < BUFFER_SIZE);
00119             assert(gfc->header[gfc->w_ptr].write_timing >= bs->totbit);
00120             if (gfc->header[gfc->w_ptr].write_timing == bs->totbit) {
00121                 putheader_bits(gfc);
00122             }
00123             bs->buf[bs->buf_byte_idx] = 0;
00124         }
00125 
00126         k = Min(j, bs->buf_bit_idx);
00127         j -= k;
00128 
00129         bs->buf_bit_idx -= k;
00130 
00131         assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
00132         assert(bs->buf_bit_idx < MAX_LENGTH);
00133 
00134         bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
00135         bs->totbit += k;
00136     }
00137 }
00138 
00139 /*write j bits into the bit stream, ignoring frame headers */
00140 inline static void
00141 putbits_noheaders(lame_internal_flags * gfc, int val, int j)
00142 {
00143     Bit_stream_struc *bs;
00144     bs = &gfc->bs;
00145 
00146     assert(j < MAX_LENGTH - 2);
00147 
00148     while (j > 0) {
00149         int     k;
00150         if (bs->buf_bit_idx == 0) {
00151             bs->buf_bit_idx = 8;
00152             bs->buf_byte_idx++;
00153             assert(bs->buf_byte_idx < BUFFER_SIZE);
00154             bs->buf[bs->buf_byte_idx] = 0;
00155         }
00156 
00157         k = Min(j, bs->buf_bit_idx);
00158         j -= k;
00159 
00160         bs->buf_bit_idx -= k;
00161 
00162         assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
00163         assert(bs->buf_bit_idx < MAX_LENGTH);
00164 
00165         bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
00166         bs->totbit += k;
00167     }
00168 }
00169 
00170 
00171 /*
00172   Some combinations of bitrate, Fs, and stereo make it impossible to stuff
00173   out a frame using just main_data, due to the limited number of bits to
00174   indicate main_data_length. In these situations, we put stuffing bits into
00175   the ancillary data...
00176 */
00177 
00178 inline static void
00179 drain_into_ancillary(lame_global_flags const *gfp, int remainingBits)
00180 {
00181     lame_internal_flags *const gfc = gfp->internal_flags;
00182     int     i;
00183     assert(remainingBits >= 0);
00184 
00185     if (remainingBits >= 8) {
00186         putbits2(gfc, 0x4c, 8);
00187         remainingBits -= 8;
00188     }
00189     if (remainingBits >= 8) {
00190         putbits2(gfc, 0x41, 8);
00191         remainingBits -= 8;
00192     }
00193     if (remainingBits >= 8) {
00194         putbits2(gfc, 0x4d, 8);
00195         remainingBits -= 8;
00196     }
00197     if (remainingBits >= 8) {
00198         putbits2(gfc, 0x45, 8);
00199         remainingBits -= 8;
00200     }
00201 
00202     if (remainingBits >= 32) {
00203         const char *const version = get_lame_short_version();
00204         if (remainingBits >= 32)
00205             for (i = 0; i < (int) strlen(version) && remainingBits >= 8; ++i) {
00206                 remainingBits -= 8;
00207                 putbits2(gfc, version[i], 8);
00208             }
00209     }
00210 
00211     for (; remainingBits >= 1; remainingBits -= 1) {
00212         putbits2(gfc, gfc->ancillary_flag, 1);
00213         gfc->ancillary_flag ^= !gfp->disable_reservoir;
00214     }
00215 
00216     assert(remainingBits == 0);
00217 
00218 }
00219 
00220 /*write N bits into the header */
00221 inline static void
00222 writeheader(lame_internal_flags * gfc, int val, int j)
00223 {
00224     int     ptr = gfc->header[gfc->h_ptr].ptr;
00225 
00226     while (j > 0) {
00227         int const k = Min(j, 8 - (ptr & 7));
00228         j -= k;
00229         assert(j < MAX_LENGTH); /* >> 32  too large for 32 bit machines */
00230         gfc->header[gfc->h_ptr].buf[ptr >> 3]
00231             |= ((val >> j)) << (8 - (ptr & 7) - k);
00232         ptr += k;
00233     }
00234     gfc->header[gfc->h_ptr].ptr = ptr;
00235 }
00236 
00237 
00238 static int
00239 CRC_update(int value, int crc)
00240 {
00241     int     i;
00242     value <<= 8;
00243     for (i = 0; i < 8; i++) {
00244         value <<= 1;
00245         crc <<= 1;
00246 
00247         if (((crc ^ value) & 0x10000))
00248             crc ^= CRC16_POLYNOMIAL;
00249     }
00250     return crc;
00251 }
00252 
00253 
00254 void
00255 CRC_writeheader(lame_internal_flags const *gfc, char *header)
00256 {
00257     int     crc = 0xffff;    /* (jo) init crc16 for error_protection */
00258     int     i;
00259 
00260     crc = CRC_update(((unsigned char *) header)[2], crc);
00261     crc = CRC_update(((unsigned char *) header)[3], crc);
00262     for (i = 6; i < gfc->sideinfo_len; i++) {
00263         crc = CRC_update(((unsigned char *) header)[i], crc);
00264     }
00265 
00266     header[4] = crc >> 8;
00267     header[5] = crc & 255;
00268 }
00269 
00270 inline static void
00271 encodeSideInfo2(lame_global_flags const *gfp, int bitsPerFrame)
00272 {
00273     lame_internal_flags *const gfc = gfp->internal_flags;
00274     III_side_info_t *l3_side;
00275     int     gr, ch;
00276 
00277     l3_side = &gfc->l3_side;
00278     gfc->header[gfc->h_ptr].ptr = 0;
00279     memset(gfc->header[gfc->h_ptr].buf, 0, gfc->sideinfo_len);
00280     if (gfp->out_samplerate < 16000)
00281         writeheader(gfc, 0xffe, 12);
00282     else
00283         writeheader(gfc, 0xfff, 12);
00284     writeheader(gfc, (gfp->version), 1);
00285     writeheader(gfc, 4 - 3, 2);
00286     writeheader(gfc, (!gfp->error_protection), 1);
00287     writeheader(gfc, (gfc->bitrate_index), 4);
00288     writeheader(gfc, (gfc->samplerate_index), 2);
00289     writeheader(gfc, (gfc->padding), 1);
00290     writeheader(gfc, (gfp->extension), 1);
00291     writeheader(gfc, (gfp->mode), 2);
00292     writeheader(gfc, (gfc->mode_ext), 2);
00293     writeheader(gfc, (gfp->copyright), 1);
00294     writeheader(gfc, (gfp->original), 1);
00295     writeheader(gfc, (gfp->emphasis), 2);
00296     if (gfp->error_protection) {
00297         writeheader(gfc, 0, 16); /* dummy */
00298     }
00299 
00300     if (gfp->version == 1) {
00301         /* MPEG1 */
00302         assert(l3_side->main_data_begin >= 0);
00303         writeheader(gfc, (l3_side->main_data_begin), 9);
00304 
00305         if (gfc->channels_out == 2)
00306             writeheader(gfc, l3_side->private_bits, 3);
00307         else
00308             writeheader(gfc, l3_side->private_bits, 5);
00309 
00310         for (ch = 0; ch < gfc->channels_out; ch++) {
00311             int     band;
00312             for (band = 0; band < 4; band++) {
00313                 writeheader(gfc, l3_side->scfsi[ch][band], 1);
00314             }
00315         }
00316 
00317         for (gr = 0; gr < 2; gr++) {
00318             for (ch = 0; ch < gfc->channels_out; ch++) {
00319                 gr_info *const gi = &l3_side->tt[gr][ch];
00320                 writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
00321                 writeheader(gfc, gi->big_values / 2, 9);
00322                 writeheader(gfc, gi->global_gain, 8);
00323                 writeheader(gfc, gi->scalefac_compress, 4);
00324 
00325                 if (gi->block_type != NORM_TYPE) {
00326                     writeheader(gfc, 1, 1); /* window_switching_flag */
00327                     writeheader(gfc, gi->block_type, 2);
00328                     writeheader(gfc, gi->mixed_block_flag, 1);
00329 
00330                     if (gi->table_select[0] == 14)
00331                         gi->table_select[0] = 16;
00332                     writeheader(gfc, gi->table_select[0], 5);
00333                     if (gi->table_select[1] == 14)
00334                         gi->table_select[1] = 16;
00335                     writeheader(gfc, gi->table_select[1], 5);
00336 
00337                     writeheader(gfc, gi->subblock_gain[0], 3);
00338                     writeheader(gfc, gi->subblock_gain[1], 3);
00339                     writeheader(gfc, gi->subblock_gain[2], 3);
00340                 }
00341                 else {
00342                     writeheader(gfc, 0, 1); /* window_switching_flag */
00343                     if (gi->table_select[0] == 14)
00344                         gi->table_select[0] = 16;
00345                     writeheader(gfc, gi->table_select[0], 5);
00346                     if (gi->table_select[1] == 14)
00347                         gi->table_select[1] = 16;
00348                     writeheader(gfc, gi->table_select[1], 5);
00349                     if (gi->table_select[2] == 14)
00350                         gi->table_select[2] = 16;
00351                     writeheader(gfc, gi->table_select[2], 5);
00352 
00353                     assert(gi->region0_count < 16U);
00354                     assert(gi->region1_count < 8U);
00355                     writeheader(gfc, gi->region0_count, 4);
00356                     writeheader(gfc, gi->region1_count, 3);
00357                 }
00358                 writeheader(gfc, gi->preflag, 1);
00359                 writeheader(gfc, gi->scalefac_scale, 1);
00360                 writeheader(gfc, gi->count1table_select, 1);
00361             }
00362         }
00363     }
00364     else {
00365         /* MPEG2 */
00366         assert(l3_side->main_data_begin >= 0);
00367         writeheader(gfc, (l3_side->main_data_begin), 8);
00368         writeheader(gfc, l3_side->private_bits, gfc->channels_out);
00369 
00370         gr = 0;
00371         for (ch = 0; ch < gfc->channels_out; ch++) {
00372             gr_info *const gi = &l3_side->tt[gr][ch];
00373             writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
00374             writeheader(gfc, gi->big_values / 2, 9);
00375             writeheader(gfc, gi->global_gain, 8);
00376             writeheader(gfc, gi->scalefac_compress, 9);
00377 
00378             if (gi->block_type != NORM_TYPE) {
00379                 writeheader(gfc, 1, 1); /* window_switching_flag */
00380                 writeheader(gfc, gi->block_type, 2);
00381                 writeheader(gfc, gi->mixed_block_flag, 1);
00382 
00383                 if (gi->table_select[0] == 14)
00384                     gi->table_select[0] = 16;
00385                 writeheader(gfc, gi->table_select[0], 5);
00386                 if (gi->table_select[1] == 14)
00387                     gi->table_select[1] = 16;
00388                 writeheader(gfc, gi->table_select[1], 5);
00389 
00390                 writeheader(gfc, gi->subblock_gain[0], 3);
00391                 writeheader(gfc, gi->subblock_gain[1], 3);
00392                 writeheader(gfc, gi->subblock_gain[2], 3);
00393             }
00394             else {
00395                 writeheader(gfc, 0, 1); /* window_switching_flag */
00396                 if (gi->table_select[0] == 14)
00397                     gi->table_select[0] = 16;
00398                 writeheader(gfc, gi->table_select[0], 5);
00399                 if (gi->table_select[1] == 14)
00400                     gi->table_select[1] = 16;
00401                 writeheader(gfc, gi->table_select[1], 5);
00402                 if (gi->table_select[2] == 14)
00403                     gi->table_select[2] = 16;
00404                 writeheader(gfc, gi->table_select[2], 5);
00405 
00406                 assert(gi->region0_count < 16U);
00407                 assert(gi->region1_count < 8U);
00408                 writeheader(gfc, gi->region0_count, 4);
00409                 writeheader(gfc, gi->region1_count, 3);
00410             }
00411 
00412             writeheader(gfc, gi->scalefac_scale, 1);
00413             writeheader(gfc, gi->count1table_select, 1);
00414         }
00415     }
00416 
00417     if (gfp->error_protection) {
00418         /* (jo) error_protection: add crc16 information to header */
00419         CRC_writeheader(gfc, gfc->header[gfc->h_ptr].buf);
00420     }
00421 
00422     {
00423         int const old = gfc->h_ptr;
00424         assert(gfc->header[old].ptr == gfc->sideinfo_len * 8);
00425 
00426         gfc->h_ptr = (old + 1) & (MAX_HEADER_BUF - 1);
00427         gfc->header[gfc->h_ptr].write_timing = gfc->header[old].write_timing + bitsPerFrame;
00428 
00429         if (gfc->h_ptr == gfc->w_ptr) {
00430             /* yikes! we are out of header buffer space */
00431             ERRORF(gfc, "Error: MAX_HEADER_BUF too small in bitstream.c \n");
00432         }
00433 
00434     }
00435 }
00436 
00437 
00438 inline static int
00439 huffman_coder_count1(lame_internal_flags * gfc, gr_info const *gi)
00440 {
00441     /* Write count1 area */
00442     struct huffcodetab const *const h = &ht[gi->count1table_select + 32];
00443     int     i, bits = 0;
00444 #ifdef DEBUG
00445     int     gegebo = gfc->bs.totbit;
00446 #endif
00447 
00448     int const *ix = &gi->l3_enc[gi->big_values];
00449     FLOAT const *xr = &gi->xr[gi->big_values];
00450     assert(gi->count1table_select < 2);
00451 
00452     for (i = (gi->count1 - gi->big_values) / 4; i > 0; --i) {
00453         int     huffbits = 0;
00454         int     p = 0, v;
00455 
00456         v = ix[0];
00457         if (v) {
00458             p += 8;
00459             if (xr[0] < 0)
00460                 huffbits++;
00461             assert(v <= 1u);
00462         }
00463 
00464         v = ix[1];
00465         if (v) {
00466             p += 4;
00467             huffbits *= 2;
00468             if (xr[1] < 0)
00469                 huffbits++;
00470             assert(v <= 1u);
00471         }
00472 
00473         v = ix[2];
00474         if (v) {
00475             p += 2;
00476             huffbits *= 2;
00477             if (xr[2] < 0)
00478                 huffbits++;
00479             assert(v <= 1u);
00480         }
00481 
00482         v = ix[3];
00483         if (v) {
00484             p++;
00485             huffbits *= 2;
00486             if (xr[3] < 0)
00487                 huffbits++;
00488             assert(v <= 1u);
00489         }
00490 
00491         ix += 4;
00492         xr += 4;
00493         putbits2(gfc, huffbits + h->table[p], h->hlen[p]);
00494         bits += h->hlen[p];
00495     }
00496 #ifdef DEBUG
00497     DEBUGF(gfc, "count1: real: %ld counted:%d (bigv %d count1len %d)\n",
00498            gfc->bs.totbit - gegebo, gi->count1bits, gi->big_values, gi->count1);
00499 #endif
00500     return bits;
00501 }
00502 
00503 
00504 
00505 /*
00506   Implements the pseudocode of page 98 of the IS
00507   */
00508 inline static int
00509 Huffmancode(lame_internal_flags * const gfc, const unsigned int tableindex,
00510             int start, int end, gr_info const *gi)
00511 {
00512     struct huffcodetab const *const h = &ht[tableindex];
00513     int     index, bits = 0;
00514 
00515     assert(tableindex < 32u);
00516     if (!tableindex)
00517         return bits;
00518 
00519     for (index = start; index < end; index += 2) {
00520         int     cbits = 0;
00521         int     xbits = 0;
00522         int const linbits = h->xlen;
00523         int     xlen = h->xlen;
00524         int     ext = 0;
00525         int     x1 = gi->l3_enc[index];
00526         int     x2 = gi->l3_enc[index + 1];
00527 
00528         if (x1 != 0) {
00529             if (gi->xr[index] < 0)
00530                 ext++;
00531             cbits--;
00532         }
00533 
00534         if (tableindex > 15) {
00535             /* use ESC-words */
00536             if (x1 > 14) {
00537                 int const linbits_x1 = x1 - 15;
00538                 assert(linbits_x1 <= h->linmax);
00539                 ext |= linbits_x1 << 1;
00540                 xbits = linbits;
00541                 x1 = 15;
00542             }
00543 
00544             if (x2 > 14) {
00545                 int const linbits_x2 = x2 - 15;
00546                 assert(linbits_x2 <= h->linmax);
00547                 ext <<= linbits;
00548                 ext |= linbits_x2;
00549                 xbits += linbits;
00550                 x2 = 15;
00551             }
00552             xlen = 16;
00553         }
00554 
00555         if (x2 != 0) {
00556             ext <<= 1;
00557             if (gi->xr[index + 1] < 0)
00558                 ext++;
00559             cbits--;
00560         }
00561 
00562         assert((x1 | x2) < 16u);
00563 
00564         x1 = x1 * xlen + x2;
00565         xbits -= cbits;
00566         cbits += h->hlen[x1];
00567 
00568         assert(cbits <= MAX_LENGTH);
00569         assert(xbits <= MAX_LENGTH);
00570 
00571         putbits2(gfc, h->table[x1], cbits);
00572         putbits2(gfc, ext, xbits);
00573         bits += cbits + xbits;
00574     }
00575     return bits;
00576 }
00577 
00578 /*
00579   Note the discussion of huffmancodebits() on pages 28
00580   and 29 of the IS, as well as the definitions of the side
00581   information on pages 26 and 27.
00582   */
00583 static int
00584 ShortHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
00585 {
00586     int     bits;
00587     int     region1Start;
00588 
00589     region1Start = 3 * gfc->scalefac_band.s[3];
00590     if (region1Start > gi->big_values)
00591         region1Start = gi->big_values;
00592 
00593     /* short blocks do not have a region2 */
00594     bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
00595     bits += Huffmancode(gfc, gi->table_select[1], region1Start, gi->big_values, gi);
00596     return bits;
00597 }
00598 
00599 static int
00600 LongHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
00601 {
00602     int     i, bigvalues, bits;
00603     int     region1Start, region2Start;
00604 
00605     bigvalues = gi->big_values;
00606     assert(0 <= bigvalues && bigvalues <= 576);
00607 
00608     i = gi->region0_count + 1;
00609     assert(i < sizeof(gfc->scalefac_band.l)/sizeof(gfc->scalefac_band.l[0]));
00610     region1Start = gfc->scalefac_band.l[i];
00611     i += gi->region1_count + 1;
00612     assert(i < sizeof(gfc->scalefac_band.l)/sizeof(gfc->scalefac_band.l[0]) );
00613     region2Start = gfc->scalefac_band.l[i];
00614 
00615     if (region1Start > bigvalues)
00616         region1Start = bigvalues;
00617 
00618     if (region2Start > bigvalues)
00619         region2Start = bigvalues;
00620 
00621     bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
00622     bits += Huffmancode(gfc, gi->table_select[1], region1Start, region2Start, gi);
00623     bits += Huffmancode(gfc, gi->table_select[2], region2Start, bigvalues, gi);
00624     return bits;
00625 }
00626 
00627 inline static int
00628 writeMainData(lame_global_flags const *const gfp)
00629 {
00630     int     gr, ch, sfb, data_bits, tot_bits = 0;
00631     lame_internal_flags *const gfc = gfp->internal_flags;
00632     III_side_info_t const *const l3_side = &gfc->l3_side;
00633 
00634     if (gfp->version == 1) {
00635         /* MPEG 1 */
00636         for (gr = 0; gr < 2; gr++) {
00637             for (ch = 0; ch < gfc->channels_out; ch++) {
00638                 gr_info const *const gi = &l3_side->tt[gr][ch];
00639                 int const slen1 = slen1_tab[gi->scalefac_compress];
00640                 int const slen2 = slen2_tab[gi->scalefac_compress];
00641                 data_bits = 0;
00642 #ifdef DEBUG
00643                 hogege = gfc->bs.totbit;
00644 #endif
00645                 for (sfb = 0; sfb < gi->sfbdivide; sfb++) {
00646                     if (gi->scalefac[sfb] == -1)
00647                         continue; /* scfsi is used */
00648                     putbits2(gfc, gi->scalefac[sfb], slen1);
00649                     data_bits += slen1;
00650                 }
00651                 for (; sfb < gi->sfbmax; sfb++) {
00652                     if (gi->scalefac[sfb] == -1)
00653                         continue; /* scfsi is used */
00654                     putbits2(gfc, gi->scalefac[sfb], slen2);
00655                     data_bits += slen2;
00656                 }
00657                 assert(data_bits == gi->part2_length);
00658 
00659                 if (gi->block_type == SHORT_TYPE) {
00660                     data_bits += ShortHuffmancodebits(gfc, gi);
00661                 }
00662                 else {
00663                     data_bits += LongHuffmancodebits(gfc, gi);
00664                 }
00665                 data_bits += huffman_coder_count1(gfc, gi);
00666 #ifdef DEBUG
00667                 DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
00668 #endif
00669                 /* does bitcount in quantize.c agree with actual bit count? */
00670                 assert(data_bits == gi->part2_3_length + gi->part2_length);
00671                 tot_bits += data_bits;
00672             }           /* for ch */
00673         }               /* for gr */
00674     }
00675     else {
00676         /* MPEG 2 */
00677         gr = 0;
00678         for (ch = 0; ch < gfc->channels_out; ch++) {
00679             gr_info const *const gi = &l3_side->tt[gr][ch];
00680             int     i, sfb_partition, scale_bits = 0;
00681             assert(gi->sfb_partition_table);
00682             data_bits = 0;
00683 #ifdef DEBUG
00684             hogege = gfc->bs.totbit;
00685 #endif
00686             sfb = 0;
00687             sfb_partition = 0;
00688 
00689             if (gi->block_type == SHORT_TYPE) {
00690                 for (; sfb_partition < 4; sfb_partition++) {
00691                     int const sfbs = gi->sfb_partition_table[sfb_partition] / 3;
00692                     int const slen = gi->slen[sfb_partition];
00693                     for (i = 0; i < sfbs; i++, sfb++) {
00694                         putbits2(gfc, Max(gi->scalefac[sfb * 3 + 0], 0U), slen);
00695                         putbits2(gfc, Max(gi->scalefac[sfb * 3 + 1], 0U), slen);
00696                         putbits2(gfc, Max(gi->scalefac[sfb * 3 + 2], 0U), slen);
00697                         scale_bits += 3 * slen;
00698                     }
00699                 }
00700                 data_bits += ShortHuffmancodebits(gfc, gi);
00701             }
00702             else {
00703                 for (; sfb_partition < 4; sfb_partition++) {
00704                     int const sfbs = gi->sfb_partition_table[sfb_partition];
00705                     int const slen = gi->slen[sfb_partition];
00706                     for (i = 0; i < sfbs; i++, sfb++) {
00707                         putbits2(gfc, Max(gi->scalefac[sfb], 0U), slen);
00708                         scale_bits += slen;
00709                     }
00710                 }
00711                 data_bits += LongHuffmancodebits(gfc, gi);
00712             }
00713             data_bits += huffman_coder_count1(gfc, gi);
00714 #ifdef DEBUG
00715             DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
00716 #endif
00717             /* does bitcount in quantize.c agree with actual bit count? */
00718             assert(data_bits == gi->part2_3_length);
00719             assert(scale_bits == gi->part2_length);
00720             tot_bits += scale_bits + data_bits;
00721         }               /* for ch */
00722     }                   /* for gf */
00723     return tot_bits;
00724 }                       /* main_data */
00725 
00726 
00727 
00728 /* compute the number of bits required to flush all mp3 frames
00729    currently in the buffer.  This should be the same as the
00730    reservoir size.  Only call this routine between frames - i.e.
00731    only after all headers and data have been added to the buffer
00732    by format_bitstream().
00733 
00734    Also compute total_bits_output =
00735        size of mp3 buffer (including frame headers which may not
00736        have yet been send to the mp3 buffer) +
00737        number of bits needed to flush all mp3 frames.
00738 
00739    total_bytes_output is the size of the mp3 output buffer if
00740    lame_encode_flush_nogap() was called right now.
00741 
00742  */
00743 int
00744 compute_flushbits(const lame_global_flags * gfp, int *total_bytes_output)
00745 {
00746     lame_internal_flags const *const gfc = gfp->internal_flags;
00747     int     flushbits, remaining_headers;
00748     int     bitsPerFrame;
00749     int     last_ptr, first_ptr;
00750     first_ptr = gfc->w_ptr; /* first header to add to bitstream */
00751     last_ptr = gfc->h_ptr - 1; /* last header to add to bitstream */
00752     if (last_ptr == -1)
00753         last_ptr = MAX_HEADER_BUF - 1;
00754 
00755     /* add this many bits to bitstream so we can flush all headers */
00756     flushbits = gfc->header[last_ptr].write_timing - gfc->bs.totbit;
00757     *total_bytes_output = flushbits;
00758 
00759     if (flushbits >= 0) {
00760         /* if flushbits >= 0, some headers have not yet been written */
00761         /* reduce flushbits by the size of the headers */
00762         remaining_headers = 1 + last_ptr - first_ptr;
00763         if (last_ptr < first_ptr)
00764             remaining_headers = 1 + last_ptr - first_ptr + MAX_HEADER_BUF;
00765         flushbits -= remaining_headers * 8 * gfc->sideinfo_len;
00766     }
00767 
00768 
00769     /* finally, add some bits so that the last frame is complete
00770      * these bits are not necessary to decode the last frame, but
00771      * some decoders will ignore last frame if these bits are missing
00772      */
00773     bitsPerFrame = getframebits(gfp);
00774     flushbits += bitsPerFrame;
00775     *total_bytes_output += bitsPerFrame;
00776     /* round up:   */
00777     if (*total_bytes_output % 8)
00778         *total_bytes_output = 1 + (*total_bytes_output / 8);
00779     else
00780         *total_bytes_output = (*total_bytes_output / 8);
00781     *total_bytes_output += gfc->bs.buf_byte_idx + 1;
00782 
00783 
00784     if (flushbits < 0) {
00785 #if 0
00786         /* if flushbits < 0, this would mean that the buffer looks like:
00787          * (data...)  last_header  (data...)  (extra data that should not be here...)
00788          */
00789         DEBUGF(gfc, "last header write_timing = %i \n", gfc->header[last_ptr].write_timing);
00790         DEBUGF(gfc, "first header write_timing = %i \n", gfc->header[first_ptr].write_timing);
00791         DEBUGF(gfc, "bs.totbit:                 %i \n", gfc->bs.totbit);
00792         DEBUGF(gfc, "first_ptr, last_ptr        %i %i \n", first_ptr, last_ptr);
00793         DEBUGF(gfc, "remaining_headers =        %i \n", remaining_headers);
00794         DEBUGF(gfc, "bitsperframe:              %i \n", bitsPerFrame);
00795         DEBUGF(gfc, "sidelen:                   %i \n", gfc->sideinfo_len);
00796 #endif
00797         ERRORF(gfc, "strange error flushing buffer ... \n");
00798     }
00799     return flushbits;
00800 }
00801 
00802 
00803 
00804 void
00805 flush_bitstream(lame_global_flags const *gfp)
00806 {
00807     lame_internal_flags *const gfc = gfp->internal_flags;
00808     III_side_info_t *l3_side;
00809     int     nbytes;
00810     int     flushbits;
00811     //int first_ptr=gfc->w_ptr;           /* first header to add to bitstream */
00812     int     last_ptr = gfc->h_ptr - 1; /* last header to add to bitstream */
00813     if (last_ptr == -1)
00814         last_ptr = MAX_HEADER_BUF - 1;
00815     l3_side = &gfc->l3_side;
00816 
00817 
00818     if ((flushbits = compute_flushbits(gfp, &nbytes)) < 0)
00819         return;
00820     drain_into_ancillary(gfp, flushbits);
00821 
00822     /* check that the 100% of the last frame has been written to bitstream */
00823     assert(gfc->header[last_ptr].write_timing + getframebits(gfp)
00824            == gfc->bs.totbit);
00825 
00826     /* we have padded out all frames with ancillary data, which is the
00827        same as filling the bitreservoir with ancillary data, so : */
00828     gfc->ResvSize = 0;
00829     l3_side->main_data_begin = 0;
00830 
00831 
00832     /* save the ReplayGain value */
00833     if (gfc->findReplayGain) {
00834         FLOAT const RadioGain = (FLOAT) GetTitleGain(gfc->rgdata);
00835         assert(RadioGain != GAIN_NOT_ENOUGH_SAMPLES);
00836         gfc->RadioGain = (int) floor(RadioGain * 10.0 + 0.5); /* round to nearest */
00837     }
00838 
00839     /* find the gain and scale change required for no clipping */
00840     if (gfc->findPeakSample) {
00841         gfc->noclipGainChange = (int) ceil(log10(gfc->PeakSample / 32767.0) * 20.0 * 10.0); /* round up */
00842 
00843         if (gfc->noclipGainChange > 0) { /* clipping occurs */
00844             if (gfp->scale == 1.0 || gfp->scale == 0.0)
00845                 gfc->noclipScale = floor((32767.0 / gfc->PeakSample) * 100.0) / 100.0; /* round down */
00846             else
00847                 /* the user specified his own scaling factor. We could suggest
00848                  * the scaling factor of (32767.0/gfp->PeakSample)*(gfp->scale)
00849                  * but it's usually very inaccurate. So we'd rather not advice him
00850                  * on the scaling factor. */
00851                 gfc->noclipScale = -1;
00852         }
00853         else            /* no clipping */
00854             gfc->noclipScale = -1;
00855     }
00856 }
00857 
00858 
00859 
00860 
00861 void
00862 add_dummy_byte(lame_global_flags const *const gfp, unsigned char val, unsigned int n)
00863 {
00864     lame_internal_flags *const gfc = gfp->internal_flags;
00865     int     i;
00866 
00867     while (n-- > 0) {
00868         putbits_noheaders(gfc, val, 8);
00869 
00870         for (i = 0; i < MAX_HEADER_BUF; ++i)
00871             gfc->header[i].write_timing += 8;
00872         }
00873 }
00874 
00875 
00876 /*
00877   format_bitstream()
00878 
00879   This is called after a frame of audio has been quantized and coded.
00880   It will write the encoded audio to the bitstream. Note that
00881   from a layer3 encoder's perspective the bit stream is primarily
00882   a series of main_data() blocks, with header and side information
00883   inserted at the proper locations to maintain framing. (See Figure A.7
00884   in the IS).
00885   */
00886 int
00887 format_bitstream(lame_global_flags const *gfp)
00888 {
00889     lame_internal_flags *const gfc = gfp->internal_flags;
00890     int     bits, nbytes;
00891     III_side_info_t *l3_side;
00892     int     bitsPerFrame;
00893     l3_side = &gfc->l3_side;
00894 
00895     bitsPerFrame = getframebits(gfp);
00896     drain_into_ancillary(gfp, l3_side->resvDrain_pre);
00897 
00898     encodeSideInfo2(gfp, bitsPerFrame);
00899     bits = 8 * gfc->sideinfo_len;
00900     bits += writeMainData(gfp);
00901     drain_into_ancillary(gfp, l3_side->resvDrain_post);
00902     bits += l3_side->resvDrain_post;
00903 
00904     l3_side->main_data_begin += (bitsPerFrame - bits) / 8;
00905 
00906     /* compare number of bits needed to clear all buffered mp3 frames
00907      * with what we think the resvsize is: */
00908     if (compute_flushbits(gfp, &nbytes) != gfc->ResvSize) {
00909         ERRORF(gfc, "Internal buffer inconsistency. flushbits <> ResvSize");
00910     }
00911 
00912 
00913     /* compare main_data_begin for the next frame with what we
00914      * think the resvsize is: */
00915     if ((l3_side->main_data_begin * 8) != gfc->ResvSize) {
00916         ERRORF(gfc, "bit reservoir error: \n"
00917                "l3_side->main_data_begin: %i \n"
00918                "Resvoir size:             %i \n"
00919                "resv drain (post)         %i \n"
00920                "resv drain (pre)          %i \n"
00921                "header and sideinfo:      %i \n"
00922                "data bits:                %i \n"
00923                "total bits:               %i (remainder: %i) \n"
00924                "bitsperframe:             %i \n",
00925                8 * l3_side->main_data_begin,
00926                gfc->ResvSize,
00927                l3_side->resvDrain_post,
00928                l3_side->resvDrain_pre,
00929                8 * gfc->sideinfo_len,
00930                bits - l3_side->resvDrain_post - 8 * gfc->sideinfo_len,
00931                bits, bits % 8, bitsPerFrame);
00932 
00933         ERRORF(gfc, "This is a fatal error.  It has several possible causes:");
00934         ERRORF(gfc, "90%%  LAME compiled with buggy version of gcc using advanced optimizations");
00935         ERRORF(gfc, " 9%%  Your system is overclocked");
00936         ERRORF(gfc, " 1%%  bug in LAME encoding library");
00937 
00938         gfc->ResvSize = l3_side->main_data_begin * 8;
00939     };
00940     assert(gfc->bs.totbit % 8 == 0);
00941 
00942     if (gfc->bs.totbit > 1000000000) {
00943         /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter */
00944         int     i;
00945         for (i = 0; i < MAX_HEADER_BUF; ++i)
00946             gfc->header[i].write_timing -= gfc->bs.totbit;
00947         gfc->bs.totbit = 0;
00948     }
00949 
00950 
00951     return 0;
00952 }
00953 
00954 
00955 
00956 
00957 
00958 /* copy data out of the internal MP3 bit buffer into a user supplied
00959    unsigned char buffer.
00960 
00961    mp3data=0      indicates data in buffer is an id3tags and VBR tags
00962    mp3data=1      data is real mp3 frame data.
00963 
00964 
00965 */
00966 int
00967 copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size, int mp3data)
00968 {
00969     Bit_stream_struc *const bs = &gfc->bs;
00970     int const minimum = bs->buf_byte_idx + 1;
00971     if (minimum <= 0)
00972         return 0;
00973     if (size != 0 && minimum > size)
00974         return -1;      /* buffer is too small */
00975     memcpy(buffer, bs->buf, minimum);
00976     bs->buf_byte_idx = -1;
00977     bs->buf_bit_idx = 0;
00978 
00979     if (mp3data) {
00980         UpdateMusicCRC(&gfc->nMusicCRC, buffer, minimum);
00981         
00985         if (minimum > 0) {
00986             gfc->VBR_seek_table.nBytesWritten += minimum;
00987         }
00988 
00989 #ifdef DECODE_ON_THE_FLY
00990         if (gfc->decode_on_the_fly) { /* decode the frame */
00991             sample_t pcm_buf[2][1152];
00992             int     mp3_in = minimum;
00993             int     samples_out = -1;
00994             int     i;
00995 
00996             /* re-synthesis to pcm.  Repeat until we get a samples_out=0 */
00997             while (samples_out != 0) {
00998 
00999                 samples_out = lame_decode1_unclipped(buffer, mp3_in, pcm_buf[0], pcm_buf[1]);
01000                 /* samples_out = 0:  need more data to decode
01001                  * samples_out = -1:  error.  Lets assume 0 pcm output
01002                  * samples_out = number of samples output */
01003 
01004                 /* set the lenght of the mp3 input buffer to zero, so that in the
01005                  * next iteration of the loop we will be querying mpglib about
01006                  * buffered data */
01007                 mp3_in = 0;
01008 
01009                 if (samples_out == -1) {
01010                     /* error decoding. Not fatal, but might screw up
01011                      * the ReplayGain tag. What should we do? Ignore for now */
01012                     samples_out = 0;
01013                 }
01014                 if (samples_out > 0) {
01015                     /* process the PCM data */
01016 
01017                     /* this should not be possible, and indicates we have
01018                      * overflown the pcm_buf buffer */
01019                     assert(samples_out <= 1152);
01020 
01021                     if (gfc->findPeakSample) {
01022                         for (i = 0; i < samples_out; i++) {
01023                             if (pcm_buf[0][i] > gfc->PeakSample)
01024                                 gfc->PeakSample = pcm_buf[0][i];
01025                             else if (-pcm_buf[0][i] > gfc->PeakSample)
01026                                 gfc->PeakSample = -pcm_buf[0][i];
01027                         }
01028                         if (gfc->channels_out > 1)
01029                             for (i = 0; i < samples_out; i++) {
01030                                 if (pcm_buf[1][i] > gfc->PeakSample)
01031                                     gfc->PeakSample = pcm_buf[1][i];
01032                                 else if (-pcm_buf[1][i] > gfc->PeakSample)
01033                                     gfc->PeakSample = -pcm_buf[1][i];
01034                             }
01035                     }
01036 
01037                     if (gfc->findReplayGain)
01038                         if (AnalyzeSamples
01039                             (gfc->rgdata, pcm_buf[0], pcm_buf[1], samples_out,
01040                              gfc->channels_out) == GAIN_ANALYSIS_ERROR)
01041                             return -6;
01042 
01043                 }       /* if (samples_out>0) */
01044             }           /* while (samples_out!=0) */
01045         }               /* if (gfc->decode_on_the_fly) */
01046 #endif
01047 
01048     }                   /* if (mp3data) */
01049     return minimum;
01050 }
01051 
01052 
01053 void
01054 init_bit_stream_w(lame_internal_flags * gfc)
01055 {
01056     gfc->bs.buf = (unsigned char *) malloc(BUFFER_SIZE);
01057     gfc->bs.buf_size = BUFFER_SIZE;
01058 
01059     gfc->h_ptr = gfc->w_ptr = 0;
01060     gfc->header[gfc->h_ptr].write_timing = 0;
01061     gfc->bs.buf_byte_idx = -1;
01062     gfc->bs.buf_bit_idx = 0;
01063     gfc->bs.totbit = 0;
01064 }
01065 
01066 /* end of bitstream.c */

Generated on Sun Dec 2 11:34:18 2007 for LAME by  doxygen 1.5.2