⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bitstream.c

📁 音频编码
💻 C
📖 第 1 页 / 共 2 页
字号:
	if (x1 != 0) {	    if (gi->xr[index] < 0)		ext++;	    cbits--;	}	if (tableindex > 15) {	    /* use ESC-words */	    if (x1 > 14) {		int linbits_x1 = x1 - 15;		assert ( linbits_x1 <= h->linmax );		ext   |= linbits_x1 << 1;		xbits  = linbits;		x1     = 15;	    }	    if (x2 > 14) {		int linbits_x2 = x2 - 15;		assert ( linbits_x2 <= h->linmax );		ext  <<= linbits;		ext   |= linbits_x2;		xbits += linbits;		x2     = 15;	    }	    xlen = 16;	}	if (x2 != 0) {	    ext <<= 1;	    if (gi->xr[index+1] < 0)		ext++;	    cbits--;	}	assert ( (x1|x2) < 16u );	x1 = x1 * xlen + x2;	xbits -= cbits;	cbits += h->hlen  [x1];	assert ( cbits <= MAX_LENGTH );	assert ( xbits <= MAX_LENGTH );	putbits2(gfc, h->table [x1], cbits );	putbits2(gfc, ext,  xbits );	bits += cbits + xbits;    }    return bits;}/*  Note the discussion of huffmancodebits() on pages 28  and 29 of the IS, as well as the definitions of the side  information on pages 26 and 27.  */static intShortHuffmancodebits(lame_internal_flags *gfc, gr_info *gi){    int bits;    int region1Start;        region1Start = 3*gfc->scalefac_band.s[3];    if (region1Start > gi->big_values)	region1Start = gi->big_values;    /* short blocks do not have a region2 */    bits  = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);    bits += Huffmancode(gfc, gi->table_select[1], region1Start, gi->big_values, gi);    return bits;}static intLongHuffmancodebits(lame_internal_flags *gfc, gr_info *gi){    int i, bigvalues, bits;    int region1Start, region2Start;    bigvalues = gi->big_values;    assert(0 <= bigvalues && bigvalues <= 576);    i = gi->region0_count + 1;    assert(i < 23);    region1Start = gfc->scalefac_band.l[i];    i += gi->region1_count + 1;    assert(i < 23);    region2Start = gfc->scalefac_band.l[i];    if (region1Start > bigvalues)	region1Start = bigvalues;    if (region2Start > bigvalues)	region2Start = bigvalues;    bits  =Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);    bits +=Huffmancode(gfc, gi->table_select[1], region1Start, region2Start, gi);    bits +=Huffmancode(gfc, gi->table_select[2], region2Start, bigvalues, gi);    return bits;}inline static intwriteMainData ( lame_global_flags * const gfp){    int gr, ch, sfb,data_bits,tot_bits=0;    lame_internal_flags *gfc=gfp->internal_flags;    III_side_info_t *l3_side;    l3_side = &gfc->l3_side;    if (gfp->version == 1) {	/* MPEG 1 */	for (gr = 0; gr < 2; gr++) {	    for (ch = 0; ch < gfc->channels_out; ch++) {		gr_info *gi = &l3_side->tt[gr][ch];		int slen1 = slen1_tab[gi->scalefac_compress];		int slen2 = slen2_tab[gi->scalefac_compress];		data_bits=0;#ifdef DEBUG		hogege = gfc->bs.totbit;#endif		for (sfb = 0; sfb < gi->sfbdivide; sfb++) {		    if (gi->scalefac[sfb] == -1)			continue; /* scfsi is used */		    putbits2(gfc, gi->scalefac[sfb], slen1);		    data_bits += slen1;		}		for (; sfb < gi->sfbmax; sfb++) {		    if (gi->scalefac[sfb] == -1)			continue; /* scfsi is used */		    putbits2(gfc, gi->scalefac[sfb], slen2);		    data_bits += slen2;		}		assert(data_bits == gi->part2_length);		if (gi->block_type == SHORT_TYPE) {		    data_bits += ShortHuffmancodebits(gfc, gi);		} else {		    data_bits += LongHuffmancodebits(gfc, gi);		}		data_bits += huffman_coder_count1(gfc, gi);#ifdef DEBUG		DEBUGF(gfc,"<%ld> ", gfc->bs.totbit-hogege);#endif		/* does bitcount in quantize.c agree with actual bit count?*/		assert(data_bits == gi->part2_3_length + gi->part2_length);		tot_bits += data_bits;	    } /* for ch */	} /* for gr */    } else {	/* MPEG 2 */	gr = 0;	for (ch = 0; ch < gfc->channels_out; ch++) {	    gr_info *gi = &l3_side->tt[gr][ch];	    int i, sfb_partition, scale_bits=0;	    assert(gi->sfb_partition_table);	    data_bits = 0;#ifdef DEBUG	    hogege = gfc->bs.totbit;#endif	    sfb = 0;	    sfb_partition = 0;	    if (gi->block_type == SHORT_TYPE) {		for (; sfb_partition < 4; sfb_partition++) {		    int sfbs = gi->sfb_partition_table[sfb_partition] / 3;		    int slen = gi->slen[sfb_partition];		    for (i = 0; i < sfbs; i++, sfb++) {			putbits2(gfc, Max(gi->scalefac[sfb*3+0], 0U), slen);			putbits2(gfc, Max(gi->scalefac[sfb*3+1], 0U), slen);			putbits2(gfc, Max(gi->scalefac[sfb*3+2], 0U), slen);			scale_bits += 3*slen;		    }		}		data_bits += ShortHuffmancodebits(gfc, gi);	    } else {		for (; sfb_partition < 4; sfb_partition++) {		    int sfbs = gi->sfb_partition_table[sfb_partition];		    int slen = gi->slen[sfb_partition];		    for (i = 0; i < sfbs; i++, sfb++) {			putbits2(gfc, Max(gi->scalefac[sfb], 0U), slen);			scale_bits += slen;		    }		}		data_bits +=LongHuffmancodebits(gfc, gi);	    }	    data_bits +=huffman_coder_count1(gfc, gi);#ifdef DEBUG	    DEBUGF(gfc,"<%ld> ", gfc->bs.totbit-hogege);#endif	    /* does bitcount in quantize.c agree with actual bit count?*/	    assert(data_bits==gi->part2_3_length);	    assert(scale_bits==gi->part2_length);	    tot_bits += scale_bits + data_bits;	} /* for ch */    } /* for gf */    return tot_bits;} /* main_data *//* compute the number of bits required to flush all mp3 frames   currently in the buffer.  This should be the same as the   reservoir size.  Only call this routine between frames - i.e.   only after all headers and data have been added to the buffer   by format_bitstream().   Also compute total_bits_output =        size of mp3 buffer (including frame headers which may not       have yet been send to the mp3 buffer) +        number of bits needed to flush all mp3 frames.   total_bytes_output is the size of the mp3 output buffer if    lame_encode_flush_nogap() was called right now.  */intcompute_flushbits( const lame_global_flags * gfp, int *total_bytes_output ){  lame_internal_flags *gfc=gfp->internal_flags;  int flushbits,remaining_headers;  int bitsPerFrame;  int last_ptr,first_ptr;  first_ptr=gfc->w_ptr;           /* first header to add to bitstream */  last_ptr = gfc->h_ptr - 1;   /* last header to add to bitstream */  if (last_ptr==-1) last_ptr=MAX_HEADER_BUF-1;     /* add this many bits to bitstream so we can flush all headers */  flushbits = gfc->header[last_ptr].write_timing - gfc->bs.totbit;  *total_bytes_output=flushbits;  if (flushbits >= 0) {    /* if flushbits >= 0, some headers have not yet been written */    /* reduce flushbits by the size of the headers */    remaining_headers= 1+last_ptr - first_ptr;    if (last_ptr < first_ptr)       remaining_headers= 1+last_ptr - first_ptr + MAX_HEADER_BUF;    flushbits -= remaining_headers*8*gfc->sideinfo_len;  }  /* finally, add some bits so that the last frame is complete   * these bits are not necessary to decode the last frame, but   * some decoders will ignore last frame if these bits are missing    */  bitsPerFrame = getframebits(gfp);  flushbits += bitsPerFrame;  *total_bytes_output += bitsPerFrame;  /* round up:   */  if (*total_bytes_output % 8)       *total_bytes_output = 1 + (*total_bytes_output/8);  else      *total_bytes_output = (*total_bytes_output/8);  *total_bytes_output +=  gfc->bs.buf_byte_idx + 1;  if (flushbits<0) {#if 0    /* if flushbits < 0, this would mean that the buffer looks like:     * (data...)  last_header  (data...)  (extra data that should not be here...)     */    DEBUGF(gfc,"last header write_timing = %i \n",gfc->header[last_ptr].write_timing);    DEBUGF(gfc,"first header write_timing = %i \n",gfc->header[first_ptr].write_timing);    DEBUGF(gfc,"bs.totbit:                 %i \n",gfc->bs.totbit);    DEBUGF(gfc,"first_ptr, last_ptr        %i %i \n",first_ptr,last_ptr);    DEBUGF(gfc,"remaining_headers =        %i \n",remaining_headers);    DEBUGF(gfc,"bitsperframe:              %i \n",bitsPerFrame);    DEBUGF(gfc,"sidelen:                   %i \n",gfc->sideinfo_len);#endif    ERRORF(gfc,"strange error flushing buffer ... \n");  }  return flushbits;}voidflush_bitstream(lame_global_flags *gfp){  lame_internal_flags *gfc=gfp->internal_flags;  III_side_info_t *l3_side;  int nbytes;  int flushbits;  int last_ptr,first_ptr;  first_ptr=gfc->w_ptr;           /* first header to add to bitstream */  last_ptr = gfc->h_ptr - 1;   /* last header to add to bitstream */  if (last_ptr==-1) last_ptr=MAX_HEADER_BUF-1;     l3_side = &gfc->l3_side;  if ((flushbits = compute_flushbits(gfp,&nbytes)) < 0) return;    drain_into_ancillary(gfp, flushbits);  /* check that the 100% of the last frame has been written to bitstream */  assert (gfc->header[last_ptr].write_timing + getframebits(gfp)	  == gfc->bs.totbit);  /* we have padded out all frames with ancillary data, which is the     same as filling the bitreservoir with ancillary data, so : */  gfc->ResvSize=0;  l3_side->main_data_begin = 0;  /* save the ReplayGain value */  if (gfc->findReplayGain) {    FLOAT RadioGain = (FLOAT) GetTitleGain(gfc->rgdata);    assert(RadioGain != GAIN_NOT_ENOUGH_SAMPLES);     gfc->RadioGain = (int) floor( RadioGain * 10.0 + 0.5 ); /* round to nearest */  }  /* find the gain and scale change required for no clipping */  if (gfc->findPeakSample) {    gfc->noclipGainChange = (int) ceil(log10(gfc->PeakSample / 32767.0) *20.0*10.0);  /* round up */        if (gfc->noclipGainChange > 0) { /* clipping occurs */      if (gfp->scale == 1.0 || gfp->scale == 0.0) 	gfc->noclipScale = floor( (32767.0 / gfc->PeakSample) * 100.0 ) / 100.0;  /* round down */      else        /* the user specified his own scaling factor. We could suggest          * the scaling factor of (32767.0/gfp->PeakSample)*(gfp->scale)         * but it's usually very inaccurate. So we'd rather not advice him         * on the scaling factor. */        gfc->noclipScale = -1;    }    else  /* no clipping */      gfc->noclipScale = -1;  }}void  add_dummy_byte ( lame_global_flags* const gfp, unsigned char val ){  lame_internal_flags *gfc = gfp->internal_flags;  int i;  putbits_noheaders(gfc, val, 8);     for (i=0 ; i< MAX_HEADER_BUF ; ++i)     gfc->header[i].write_timing += 8;}/*  format_bitstream()  This is called after a frame of audio has been quantized and coded.  It will write the encoded audio to the bitstream. Note that  from a layer3 encoder's perspective the bit stream is primarily  a series of main_data() blocks, with header and side information  inserted at the proper locations to maintain framing. (See Figure A.7  in the IS).  */intformat_bitstream(lame_global_flags *gfp){    lame_internal_flags *gfc=gfp->internal_flags;    int bits,nbytes;    III_side_info_t *l3_side;    int bitsPerFrame;    l3_side = &gfc->l3_side;    bitsPerFrame = getframebits(gfp);    drain_into_ancillary(gfp, l3_side->resvDrain_pre);    encodeSideInfo2(gfp,bitsPerFrame);    bits = 8*gfc->sideinfo_len;    bits+=writeMainData(gfp);    drain_into_ancillary(gfp, l3_side->resvDrain_post);    bits += l3_side->resvDrain_post;    l3_side->main_data_begin += (bitsPerFrame-bits)/8;    /* compare number of bits needed to clear all buffered mp3 frames     * with what we think the resvsize is: */    if (compute_flushbits(gfp,&nbytes) != gfc->ResvSize) {        ERRORF(gfc,"Internal buffer inconsistency. flushbits <> ResvSize");    }    /* compare main_data_begin for the next frame with what we     * think the resvsize is: */    if ((l3_side->main_data_begin * 8) != gfc->ResvSize ) {      ERRORF(gfc,"bit reservoir error: \n"             "l3_side->main_data_begin: %i \n"             "Resvoir size:             %i \n"             "resv drain (post)         %i \n"             "resv drain (pre)          %i \n"             "header and sideinfo:      %i \n"             "data bits:                %i \n"             "total bits:               %i (remainder: %i) \n"             "bitsperframe:             %i \n",             8*l3_side->main_data_begin,             gfc->ResvSize,             l3_side->resvDrain_post,             l3_side->resvDrain_pre,             8*gfc->sideinfo_len,             bits-l3_side->resvDrain_post-8*gfc->sideinfo_len,             bits, bits % 8,             bitsPerFrame      );      ERRORF(gfc,"This is a fatal error.  It has several possible causes:");      ERRORF(gfc,"90%  LAME compiled with buggy version of gcc using advanced optimizations");      ERRORF(gfc," 9%  Your system is overclocked");      ERRORF(gfc," 1%  bug in LAME encoding library");      gfc->ResvSize = l3_side->main_data_begin*8;    };    assert(gfc->bs.totbit % 8 == 0);    if (gfc->bs.totbit > 1000000000  ) {      /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter*/      int i;      for (i=0 ; i< MAX_HEADER_BUF ; ++i) 	gfc->header[i].write_timing -= gfc->bs.totbit;            gfc->bs.totbit=0;    }    return 0;}/* copy data out of the internal MP3 bit buffer into a user supplied   unsigned char buffer.   mp3data=0      indicates data in buffer is an id3tags and VBR tags   mp3data=1      data is real mp3 frame data. */int copy_buffer(lame_internal_flags *gfc,unsigned char *buffer,int size,int mp3data) {    Bit_stream_struc *bs=&gfc->bs;    int minimum = bs->buf_byte_idx + 1;    if (minimum <= 0) return 0;    if (size!=0 && minimum>size) return -1; /* buffer is too small */    memcpy(buffer,bs->buf,minimum);    bs->buf_byte_idx = -1;    bs->buf_bit_idx = 0;        if (mp3data) {        UpdateMusicCRC(&gfc->nMusicCRC,buffer,minimum);#ifdef DECODE_ON_THE_FLY         if (gfc->decode_on_the_fly) {  /* decode the frame */          sample_t pcm_buf[2][1152];	  int mp3_in = minimum;          int samples_out = -1;          int i;          /* re-synthesis to pcm.  Repeat until we get a samples_out=0 */          while(samples_out != 0) {            samples_out=lame_decode1_unclipped(buffer,mp3_in,pcm_buf[0],pcm_buf[1]);             /* samples_out = 0:  need more data to decode              * samples_out = -1:  error.  Lets assume 0 pcm output              * samples_out = number of samples output */	    	    /* set the lenght of the mp3 input buffer to zero, so that in the 	     * next iteration of the loop we will be querying mpglib about 	     * buffered data */	    mp3_in = 0;                          if (samples_out==-1) {                /* error decoding. Not fatal, but might screw up                  * the ReplayGain tag. What should we do? Ignore for now */                samples_out=0;            }            if (samples_out>0) {                /* process the PCM data */              /* this should not be possible, and indicates we have                * overflown the pcm_buf buffer */              assert(samples_out <= 1152);              if (gfc->findPeakSample) {                for (i=0; i<samples_out; i++) {                      if (pcm_buf[0][i] > gfc->PeakSample)                     gfc->PeakSample = pcm_buf[0][i];                   else if (-pcm_buf[0][i] > gfc->PeakSample)                     gfc->PeakSample = -pcm_buf[0][i];                 }                if (gfc->channels_out > 1)                  for (i=0; i<samples_out; i++) {                    if (pcm_buf[1][i] > gfc->PeakSample)                      gfc->PeakSample = pcm_buf[1][i];                    else if (-pcm_buf[1][i] > gfc->PeakSample)                      gfc->PeakSample = -pcm_buf[1][i];                  }              }              if (gfc->findReplayGain)                if (AnalyzeSamples(gfc->rgdata, pcm_buf[0], pcm_buf[1], samples_out, gfc->channels_out) == GAIN_ANALYSIS_ERROR)                   return -6;		               } /* if (samples_out>0) */          } /* while (samples_out!=0) */        } /* if (gfc->decode_on_the_fly) */ #endif      } /* if (mp3data) */    return minimum;}void init_bit_stream_w(lame_internal_flags *gfc){   gfc->bs.buf = (unsigned char *)       malloc(BUFFER_SIZE);   gfc->bs.buf_size = BUFFER_SIZE;   gfc->h_ptr = gfc->w_ptr = 0;   gfc->header[gfc->h_ptr].write_timing = 0;   gfc->bs.buf_byte_idx = -1;   gfc->bs.buf_bit_idx = 0;   gfc->bs.totbit = 0;}/* end of bitstream.c */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -