fix crashes reported by Debian Cylab Mayhem Team
[swftools.git] / lib / lame / bitstream.c
blobc343b3c8d572bc7219c3a138bd156e41f08a73f0
1 /*
2 * MP3 bitstream Output interface for LAME
4 * Copyright (c) 1999 Takehiro TOMINAGA
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.
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.
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.
21 * $Id: bitstream.c,v 1.3 2006/02/09 16:56:23 kramm Exp $
25 #include <stdlib.h>
26 #include "config_static.h"
28 #include <stdlib.h>
29 #include <assert.h>
30 #include <stdio.h>
31 #include "tables.h"
32 #include "bitstream.h"
33 #include "quantize.h"
34 #include "quantize_pvt.h"
35 #include "version.h"
36 #include "VbrTag.h"
38 #ifdef WITH_DMALLOC
39 #include <dmalloc.h>
40 #endif
42 /* This is the scfsi_band table from 2.4.2.7 of the IS */
43 const int scfsi_band[5] = { 0, 6, 11, 16, 21 };
46 /* unsigned int is at least this large: */
47 /* we work with ints, so when doing bit manipulation, we limit
48 * ourselves to MAX_LENGTH-2 just to be on the safe side */
49 #define MAX_LENGTH 32
53 #ifdef DEBUG
54 static int hoge, hogege;
55 #endif
61 void putheader_bits(lame_internal_flags *gfc,int w_ptr)
63 Bit_stream_struc *bs;
64 bs = &gfc->bs;
65 #ifdef DEBUG
66 hoge += gfc->sideinfo_len * 8;
67 hogege += gfc->sideinfo_len * 8;
68 #endif
69 memcpy(&bs->buf[bs->buf_byte_idx], gfc->header[gfc->w_ptr].buf,
70 gfc->sideinfo_len);
71 bs->buf_byte_idx += gfc->sideinfo_len;
72 bs->totbit += gfc->sideinfo_len * 8;
73 gfc->w_ptr = (gfc->w_ptr + 1) & (MAX_HEADER_BUF - 1);
79 /*write j bits into the bit stream */
80 inline static void
81 putbits2(lame_global_flags *gfp, int val, int j)
83 lame_internal_flags *gfc=gfp->internal_flags;
84 Bit_stream_struc *bs;
85 bs = &gfc->bs;
87 assert(j < MAX_LENGTH-2);
89 while (j > 0) {
90 int k;
91 if (bs->buf_bit_idx == 0) {
92 bs->buf_bit_idx = 8;
93 bs->buf_byte_idx++;
94 assert(bs->buf_byte_idx < BUFFER_SIZE);
95 assert(gfc->header[gfc->w_ptr].write_timing >= bs->totbit);
96 if (gfc->header[gfc->w_ptr].write_timing == bs->totbit) {
97 putheader_bits(gfc,gfc->w_ptr);
99 bs->buf[bs->buf_byte_idx] = 0;
102 k = Min(j, bs->buf_bit_idx);
103 j -= k;
105 bs->buf_bit_idx -= k;
107 assert (j < MAX_LENGTH); /* 32 too large on 32 bit machines */
108 assert (bs->buf_bit_idx < MAX_LENGTH);
110 bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
111 bs->totbit += k;
115 /*write j bits into the bit stream, ignoring frame headers */
116 inline static void
117 putbits_noheaders(lame_global_flags *gfp, int val, int j)
119 lame_internal_flags *gfc=gfp->internal_flags;
120 Bit_stream_struc *bs;
121 bs = &gfc->bs;
123 assert(j < MAX_LENGTH-2);
125 while (j > 0) {
126 int k;
127 if (bs->buf_bit_idx == 0) {
128 bs->buf_bit_idx = 8;
129 bs->buf_byte_idx++;
130 assert(bs->buf_byte_idx < BUFFER_SIZE);
131 bs->buf[bs->buf_byte_idx] = 0;
134 k = Min(j, bs->buf_bit_idx);
135 j -= k;
137 bs->buf_bit_idx -= k;
139 assert (j < MAX_LENGTH); /* 32 too large on 32 bit machines */
140 assert (bs->buf_bit_idx < MAX_LENGTH);
142 bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
143 bs->totbit += k;
149 Some combinations of bitrate, Fs, and stereo make it impossible to stuff
150 out a frame using just main_data, due to the limited number of bits to
151 indicate main_data_length. In these situations, we put stuffing bits into
152 the ancillary data...
155 inline static void
156 drain_into_ancillary(lame_global_flags *gfp,int remainingBits)
158 lame_internal_flags *gfc=gfp->internal_flags;
159 int i;
160 assert(remainingBits >= 0);
162 if (remainingBits >= 8) {
163 putbits2(gfp,0x4c,8);
164 remainingBits -= 8;
166 if (remainingBits >= 8) {
167 putbits2(gfp,0x41,8);
168 remainingBits -= 8;
170 if (remainingBits >= 8) {
171 putbits2(gfp,0x4d,8);
172 remainingBits -= 8;
174 if (remainingBits >= 8) {
175 putbits2(gfp,0x45,8);
176 remainingBits -= 8;
179 if (remainingBits >= 32) {
180 const char *version = get_lame_short_version ();
181 if (remainingBits >= 32)
182 for (i=0; i<(int)strlen(version) && remainingBits >=8 ; ++i) {
183 remainingBits -= 8;
184 putbits2(gfp,version[i],8);
188 for (; remainingBits >= 1; remainingBits -= 1 ) {
189 putbits2 ( gfp, gfc->ancillary_flag, 1 );
190 gfc->ancillary_flag ^= 1;
193 assert (remainingBits == 0);
197 /*write N bits into the header */
198 inline static void
199 writeheader(lame_internal_flags *gfc,int val, int j)
201 int ptr = gfc->header[gfc->h_ptr].ptr;
203 while (j > 0) {
204 int k = Min(j, 8 - (ptr & 7));
205 j -= k;
206 assert (j < MAX_LENGTH); /* >> 32 too large for 32 bit machines */
207 gfc->header[gfc->h_ptr].buf[ptr >> 3]
208 |= ((val >> j)) << (8 - (ptr & 7) - k);
209 ptr += k;
211 gfc->header[gfc->h_ptr].ptr = ptr;
215 static int
216 CRC_update(int value, int crc)
218 int i;
219 value <<= 8;
220 for (i = 0; i < 8; i++) {
221 value <<= 1;
222 crc <<= 1;
224 if (((crc ^ value) & 0x10000))
225 crc ^= CRC16_POLYNOMIAL;
227 return crc;
231 void
232 CRC_writeheader(lame_internal_flags *gfc, char *header)
234 int crc = 0xffff; /* (jo) init crc16 for error_protection */
235 int i;
237 crc = CRC_update(((unsigned char*)header)[2], crc);
238 crc = CRC_update(((unsigned char*)header)[3], crc);
239 for (i = 6; i < gfc->sideinfo_len; i++) {
240 crc = CRC_update(((unsigned char*)header)[i], crc);
243 header[4] = crc >> 8;
244 header[5] = crc & 255;
247 inline static void
248 encodeSideInfo2(lame_global_flags *gfp,int bitsPerFrame)
250 lame_internal_flags *gfc=gfp->internal_flags;
251 III_side_info_t *l3_side;
252 int gr, ch;
254 l3_side = &gfc->l3_side;
255 gfc->header[gfc->h_ptr].ptr = 0;
256 memset(gfc->header[gfc->h_ptr].buf, 0, gfc->sideinfo_len);
257 if (gfp->out_samplerate < 16000)
258 writeheader(gfc,0xffe, 12);
259 else
260 writeheader(gfc,0xfff, 12);
261 writeheader(gfc,(gfp->version), 1);
262 writeheader(gfc,4 - 3, 2);
263 writeheader(gfc,(!gfp->error_protection), 1);
264 writeheader(gfc,(gfc->bitrate_index), 4);
265 writeheader(gfc,(gfc->samplerate_index), 2);
266 writeheader(gfc,(gfc->padding), 1);
267 writeheader(gfc,(gfp->extension), 1);
268 writeheader(gfc,(gfp->mode), 2);
269 writeheader(gfc,(gfc->mode_ext), 2);
270 writeheader(gfc,(gfp->copyright), 1);
271 writeheader(gfc,(gfp->original), 1);
272 writeheader(gfc,(gfp->emphasis), 2);
273 if (gfp->error_protection) {
274 writeheader(gfc,0, 16); /* dummy */
277 if (gfp->version == 1) {
278 /* MPEG1 */
279 assert(l3_side->main_data_begin >= 0);
280 writeheader(gfc,(l3_side->main_data_begin), 9);
282 if (gfc->channels_out == 2)
283 writeheader(gfc,l3_side->private_bits, 3);
284 else
285 writeheader(gfc,l3_side->private_bits, 5);
287 for (ch = 0; ch < gfc->channels_out; ch++) {
288 int band;
289 for (band = 0; band < 4; band++) {
290 writeheader(gfc,l3_side->scfsi[ch][band], 1);
294 for (gr = 0; gr < 2; gr++) {
295 for (ch = 0; ch < gfc->channels_out; ch++) {
296 gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
297 writeheader(gfc,gi->part2_3_length, 12);
298 writeheader(gfc,gi->big_values / 2, 9);
299 writeheader(gfc,gi->global_gain, 8);
300 writeheader(gfc,gi->scalefac_compress, 4);
301 writeheader(gfc,gi->window_switching_flag, 1);
303 if (gi->window_switching_flag) {
304 writeheader(gfc,gi->block_type, 2);
305 writeheader(gfc,gi->mixed_block_flag, 1);
307 if (gi->table_select[0] == 14)
308 gi->table_select[0] = 16;
309 writeheader(gfc,gi->table_select[0], 5);
310 if (gi->table_select[1] == 14)
311 gi->table_select[1] = 16;
312 writeheader(gfc,gi->table_select[1], 5);
314 writeheader(gfc,gi->subblock_gain[0], 3);
315 writeheader(gfc,gi->subblock_gain[1], 3);
316 writeheader(gfc,gi->subblock_gain[2], 3);
317 } else {
318 assert(gi->block_type == NORM_TYPE);
319 if (gi->table_select[0] == 14)
320 gi->table_select[0] = 16;
321 writeheader(gfc,gi->table_select[0], 5);
322 if (gi->table_select[1] == 14)
323 gi->table_select[1] = 16;
324 writeheader(gfc,gi->table_select[1], 5);
325 if (gi->table_select[2] == 14)
326 gi->table_select[2] = 16;
327 writeheader(gfc,gi->table_select[2], 5);
329 assert(gi->region0_count < 16U);
330 assert(gi->region1_count < 8U);
331 writeheader(gfc,gi->region0_count, 4);
332 writeheader(gfc,gi->region1_count, 3);
334 writeheader(gfc,gi->preflag, 1);
335 writeheader(gfc,gi->scalefac_scale, 1);
336 writeheader(gfc,gi->count1table_select, 1);
339 } else {
340 /* MPEG2 */
341 assert(l3_side->main_data_begin >= 0);
342 writeheader(gfc,(l3_side->main_data_begin), 8);
343 writeheader(gfc,l3_side->private_bits, gfc->channels_out);
345 gr = 0;
346 for (ch = 0; ch < gfc->channels_out; ch++) {
347 gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
348 writeheader(gfc,gi->part2_3_length, 12);
349 writeheader(gfc,gi->big_values / 2, 9);
350 writeheader(gfc,gi->global_gain, 8);
351 writeheader(gfc,gi->scalefac_compress, 9);
352 writeheader(gfc,gi->window_switching_flag, 1);
354 if (gi->window_switching_flag) {
355 writeheader(gfc,gi->block_type, 2);
356 writeheader(gfc,gi->mixed_block_flag, 1);
358 if (gi->table_select[0] == 14)
359 gi->table_select[0] = 16;
360 writeheader(gfc,gi->table_select[0], 5);
361 if (gi->table_select[1] == 14)
362 gi->table_select[1] = 16;
363 writeheader(gfc,gi->table_select[1], 5);
365 writeheader(gfc,gi->subblock_gain[0], 3);
366 writeheader(gfc,gi->subblock_gain[1], 3);
367 writeheader(gfc,gi->subblock_gain[2], 3);
368 } else {
369 if (gi->table_select[0] == 14)
370 gi->table_select[0] = 16;
371 writeheader(gfc,gi->table_select[0], 5);
372 if (gi->table_select[1] == 14)
373 gi->table_select[1] = 16;
374 writeheader(gfc,gi->table_select[1], 5);
375 if (gi->table_select[2] == 14)
376 gi->table_select[2] = 16;
377 writeheader(gfc,gi->table_select[2], 5);
379 assert(gi->region0_count < 16U);
380 assert(gi->region1_count < 8U);
381 writeheader(gfc,gi->region0_count, 4);
382 writeheader(gfc,gi->region1_count, 3);
385 writeheader(gfc,gi->scalefac_scale, 1);
386 writeheader(gfc,gi->count1table_select, 1);
390 if (gfp->error_protection) {
391 /* (jo) error_protection: add crc16 information to header */
392 CRC_writeheader(gfc, gfc->header[gfc->h_ptr].buf);
396 int old = gfc->h_ptr;
397 assert(gfc->header[old].ptr == gfc->sideinfo_len * 8);
399 gfc->h_ptr = (old + 1) & (MAX_HEADER_BUF - 1);
400 gfc->header[gfc->h_ptr].write_timing =
401 gfc->header[old].write_timing + bitsPerFrame;
403 if (gfc->h_ptr == gfc->w_ptr) {
404 /* yikes! we are out of header buffer space */
405 ERRORF(gfc,"Error: MAX_HEADER_BUF too small in bitstream.c \n");
412 inline static int
413 huffman_coder_count1(lame_global_flags *gfp,int *ix, gr_info *gi)
415 #ifdef DEBUG
416 lame_internal_flags *gfc = gfp->internal_flags;
417 #endif
418 /* Write count1 area */
419 const struct huffcodetab *h = &ht[gi->count1table_select + 32];
420 int i,bits=0;
421 #ifdef DEBUG
422 int gegebo = gfc->bs.totbit;
423 #endif
425 ix += gi->big_values;
426 assert(gi->count1table_select < 2);
429 for (i = (gi->count1 - gi->big_values) / 4; i > 0; --i) {
430 int huffbits = 0;
431 int p = 0, v;
433 v = ix[0];
434 if (v) {
435 p += 8;
436 if (v < 0)
437 huffbits++;
438 assert(-1 <= v && v <= 1);
441 v = ix[1];
442 if (v) {
443 p += 4;
444 huffbits *= 2;
445 if (v < 0)
446 huffbits++;
447 assert(-1 <= v && v <= 1);
450 v = ix[2];
451 if (v) {
452 p += 2;
453 huffbits *= 2;
454 if (v < 0)
455 huffbits++;
456 assert(-1 <= v && v <= 1);
459 v = ix[3];
460 if (v) {
461 p++;
462 huffbits *= 2;
463 if (v < 0)
464 huffbits++;
465 assert(-1 <= v && v <= 1);
468 ix += 4;
469 putbits2(gfp,huffbits + h->table[p], h->hlen[p]);
470 bits += h->hlen[p];
472 #ifdef DEBUG
473 DEBUGF(gfc,"%ld %d %d %d\n",gfc->bs.totbit -gegebo, gi->count1bits, gi->big_values, gi->count1);
474 #endif
475 return bits;
481 Implements the pseudocode of page 98 of the IS
484 inline static int
485 HuffmanCode ( lame_global_flags* const gfp, const int table_select, int x1, int x2 )
487 const struct huffcodetab* h = ht + table_select;
488 int code = 0;
489 int cbits = 0;
490 int xbits = 0;
491 int sgn_x1 = 0;
492 int sgn_x2 = 0;
493 int linbits = h->xlen;
494 int xlen = h->xlen;
495 int ext;
497 assert ( table_select > 0 );
499 if (x1 < 0) {
500 sgn_x1++;
501 x1 = -x1;
504 if (x2 < 0) {
505 sgn_x2++;
506 x2 = -x2;
509 ext = sgn_x1;
511 if (table_select > 15) {
512 /* use ESC-words */
513 if (x1 > 14) {
514 int linbits_x1 = x1 - 15;
515 assert ( linbits_x1 <= h->linmax );
516 ext |= linbits_x1 << 1;
517 xbits = linbits;
518 x1 = 15;
521 if (x2 > 14) {
522 int linbits_x2 = x2 - 15;
523 assert ( linbits_x2 <= h->linmax );
524 ext <<= linbits;
525 ext |= linbits_x2;
526 xbits += linbits;
527 x2 = 15;
529 xlen = 16;
532 if (x1 != 0) {
533 cbits--;
536 if (x2 != 0) {
537 ext <<= 1;
538 ext |= sgn_x2;
539 cbits--;
542 xbits -= cbits;
544 assert ( (x1|x2) < 16u );
546 x1 = x1 * xlen + x2;
548 code = h->table [x1];
549 cbits += h->hlen [x1];
551 assert ( cbits <= MAX_LENGTH );
552 assert ( xbits <= MAX_LENGTH );
554 putbits2 ( gfp, code, cbits );
555 putbits2 ( gfp, ext, xbits );
557 return cbits + xbits;
560 static int
561 Huffmancodebits(lame_global_flags *gfp, int tableindex, int start, int end, int *ix)
563 int i,bits;
565 assert(tableindex < 32);
566 if (!tableindex) return 0;
568 bits=0;
569 for (i = start; i < end; i += 2) {
570 bits +=HuffmanCode(gfp,tableindex, ix[i], ix[i + 1]);
572 return bits;
578 Note the discussion of huffmancodebits() on pages 28
579 and 29 of the IS, as well as the definitions of the side
580 information on pages 26 and 27.
582 static int
583 ShortHuffmancodebits(lame_global_flags *gfp,int *ix, gr_info *gi)
585 lame_internal_flags *gfc=gfp->internal_flags;
586 int bits;
587 int region1Start;
589 region1Start = 3*gfc->scalefac_band.s[3];
590 if (region1Start > gi->big_values)
591 region1Start = gi->big_values;
593 /* short blocks do not have a region2 */
594 bits = Huffmancodebits(gfp,gi->table_select[0], 0, region1Start, ix);
595 bits += Huffmancodebits(gfp,gi->table_select[1], region1Start, gi->big_values, ix);
596 return bits;
599 static int
600 LongHuffmancodebits(lame_global_flags *gfp,int *ix, gr_info *gi)
602 lame_internal_flags *gfc=gfp->internal_flags;
603 int i, bigvalues,bits=0;
604 int region1Start, region2Start;
606 bigvalues = gi->big_values;
607 assert(0 <= bigvalues && bigvalues <= 576);
609 i = gi->region0_count + 1;
610 assert(i < 23);
611 region1Start = gfc->scalefac_band.l[i];
612 i += gi->region1_count + 1;
613 assert(i < 23);
614 region2Start = gfc->scalefac_band.l[i];
616 if (region1Start > bigvalues)
617 region1Start = bigvalues;
619 if (region2Start > bigvalues)
620 region2Start = bigvalues;
622 bits +=Huffmancodebits(gfp,gi->table_select[0], 0, region1Start, ix);
623 bits +=Huffmancodebits(gfp,gi->table_select[1], region1Start, region2Start, ix);
624 bits +=Huffmancodebits(gfp,gi->table_select[2], region2Start, bigvalues, ix);
625 return bits;
628 inline static int
629 writeMainData ( lame_global_flags * const gfp,
630 int l3_enc [2] [2] [576],
631 III_scalefac_t scalefac [2] [2] )
633 int gr, ch, sfb,data_bits,scale_bits,tot_bits=0;
634 lame_internal_flags *gfc=gfp->internal_flags;
635 III_side_info_t *l3_side;
637 l3_side = &gfc->l3_side;
638 if (gfp->version == 1) {
639 /* MPEG 1 */
640 for (gr = 0; gr < 2; gr++) {
641 for (ch = 0; ch < gfc->channels_out; ch++) {
642 gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
643 int slen1 = slen1_tab[gi->scalefac_compress];
644 int slen2 = slen2_tab[gi->scalefac_compress];
645 data_bits=0;
646 scale_bits=0;
648 #ifdef DEBUG
649 hogege = gfc->bs.totbit;
650 #endif
651 if (gi->block_type == SHORT_TYPE) {
652 for (sfb = 0; sfb < SBPSY_s; sfb++) {
653 int slen = sfb < 6 ? slen1 : slen2;
655 assert(scalefac[gr][ch].s[sfb][0]>=0);
656 assert(scalefac[gr][ch].s[sfb][1]>=0);
657 assert(scalefac[gr][ch].s[sfb][2]>=0);
659 putbits2(gfp,scalefac[gr][ch].s[sfb][0], slen);
660 putbits2(gfp,scalefac[gr][ch].s[sfb][1], slen);
661 putbits2(gfp,scalefac[gr][ch].s[sfb][2], slen);
662 scale_bits += 3*slen;
664 data_bits += ShortHuffmancodebits(gfp,l3_enc[gr][ch], gi);
665 } else {
666 int i;
667 for (i = 0; i < sizeof(scfsi_band) / sizeof(int) - 1;
668 i++) {
669 if (gr != 0 && l3_side->scfsi[ch][i])
670 continue;
672 for (sfb = scfsi_band[i]; sfb < scfsi_band[i + 1];
673 sfb++) {
675 assert(scalefac[gr][ch].l[sfb]>=0);
676 putbits2(gfp,scalefac[gr][ch].l[sfb],
677 sfb < 11 ? slen1 : slen2);
678 scale_bits += sfb < 11 ? slen1 : slen2;
681 data_bits +=LongHuffmancodebits(gfp,l3_enc[gr][ch], gi);
683 data_bits +=huffman_coder_count1(gfp,l3_enc[gr][ch], gi);
684 #ifdef DEBUG
685 DEBUGF(gfc,"<%ld> ", gfc->bs.totbit-hogege);
686 #endif
687 /* does bitcount in quantize.c agree with actual bit count?*/
688 assert(data_bits==gi->part2_3_length-gi->part2_length);
689 assert(scale_bits==gi->part2_length);
690 tot_bits += scale_bits + data_bits;
692 } /* for ch */
693 } /* for gr */
694 } else {
695 /* MPEG 2 */
696 gr = 0;
697 for (ch = 0; ch < gfc->channels_out; ch++) {
698 gr_info *gi = &l3_side->gr[gr].ch[ch].tt;
699 int i, sfb_partition;
700 assert(gi->sfb_partition_table);
701 data_bits = 0;
702 scale_bits=0;
704 sfb = 0;
705 sfb_partition = 0;
706 if (gi->block_type == SHORT_TYPE) {
707 for (; sfb_partition < 4; sfb_partition++) {
708 int sfbs = gi->sfb_partition_table[sfb_partition] / 3;
709 int slen = gi->slen[sfb_partition];
710 for (i = 0; i < sfbs; i++, sfb++) {
711 putbits2(gfp,Max(scalefac[gr][ch].s[sfb][0], 0U), slen);
712 putbits2(gfp,Max(scalefac[gr][ch].s[sfb][1], 0U), slen);
713 putbits2(gfp,Max(scalefac[gr][ch].s[sfb][2], 0U), slen);
714 scale_bits += 3*slen;
717 data_bits += ShortHuffmancodebits(gfp,l3_enc[gr][ch], gi);
718 } else {
719 for (; sfb_partition < 4; sfb_partition++) {
720 int sfbs = gi->sfb_partition_table[sfb_partition];
721 int slen = gi->slen[sfb_partition];
722 for (i = 0; i < sfbs; i++, sfb++) {
723 putbits2(gfp,Max(scalefac[gr][ch].l[sfb], 0U), slen);
724 scale_bits += slen;
727 data_bits +=LongHuffmancodebits(gfp,l3_enc[gr][ch], gi);
729 data_bits +=huffman_coder_count1(gfp,l3_enc[gr][ch], gi);
731 /* does bitcount in quantize.c agree with actual bit count?*/
732 assert(data_bits==gi->part2_3_length-gi->part2_length);
733 assert(scale_bits==gi->part2_length);
734 tot_bits += scale_bits + data_bits;
735 } /* for ch */
736 } /* for gf */
737 return tot_bits;
738 } /* main_data */
742 /* compute the number of bits required to flush all mp3 frames
743 currently in the buffer. This should be the same as the
744 reservoir size. Only call this routine between frames - i.e.
745 only after all headers and data have been added to the buffer
746 by format_bitstream().
748 Also compute total_bits_output =
749 size of mp3 buffer (including frame headers which may not
750 have yet been send to the mp3 buffer) +
751 number of bits needed to flush all mp3 frames.
753 total_bytes_output is the size of the mp3 output buffer if
754 lame_encode_flush_nogap() was called right now.
758 compute_flushbits( const lame_global_flags * gfp, int *total_bytes_output )
760 lame_internal_flags *gfc=gfp->internal_flags;
761 int flushbits,remaining_headers;
762 int bitsPerFrame, mean_bits;
763 int last_ptr,first_ptr;
764 first_ptr=gfc->w_ptr; /* first header to add to bitstream */
765 last_ptr = gfc->h_ptr - 1; /* last header to add to bitstream */
766 if (last_ptr==-1) last_ptr=MAX_HEADER_BUF-1;
768 /* add this many bits to bitstream so we can flush all headers */
769 flushbits = gfc->header[last_ptr].write_timing - gfc->bs.totbit;
770 *total_bytes_output=flushbits;
772 if (flushbits >= 0) {
773 /* if flushbits >= 0, some headers have not yet been written */
774 /* reduce flushbits by the size of the headers */
775 remaining_headers= 1+last_ptr - first_ptr;
776 if (last_ptr < first_ptr)
777 remaining_headers= 1+last_ptr - first_ptr + MAX_HEADER_BUF;
778 flushbits -= remaining_headers*8*gfc->sideinfo_len;
782 /* finally, add some bits so that the last frame is complete
783 * these bits are not necessary to decode the last frame, but
784 * some decoders will ignore last frame if these bits are missing
786 getframebits(gfp,&bitsPerFrame,&mean_bits);
787 flushbits += bitsPerFrame;
788 *total_bytes_output += bitsPerFrame;
789 // round up:
790 if (*total_bytes_output % 8)
791 *total_bytes_output = 1 + (*total_bytes_output/8);
792 else
793 *total_bytes_output = (*total_bytes_output/8);
794 *total_bytes_output += gfc->bs.buf_byte_idx + 1;
797 if (flushbits<0) {
798 #if 0
799 /* if flushbits < 0, this would mean that the buffer looks like:
800 * (data...) last_header (data...) (extra data that should not be here...)
802 DEBUGF(gfc,"last header write_timing = %i \n",gfc->header[last_ptr].write_timing);
803 DEBUGF(gfc,"first header write_timing = %i \n",gfc->header[first_ptr].write_timing);
804 DEBUGF(gfc,"bs.totbit: %i \n",gfc->bs.totbit);
805 DEBUGF(gfc,"first_ptr, last_ptr %i %i \n",first_ptr,last_ptr);
806 DEBUGF(gfc,"remaining_headers = %i \n",remaining_headers);
807 DEBUGF(gfc,"bitsperframe: %i \n",bitsPerFrame);
808 DEBUGF(gfc,"sidelen: %i \n",gfc->sideinfo_len);
809 #endif
810 // ERRORF(gfc,"strange error flushing buffer ... \n");
812 return flushbits;
817 void
818 flush_bitstream(lame_global_flags *gfp)
820 lame_internal_flags *gfc=gfp->internal_flags;
821 III_side_info_t *l3_side;
822 int nbytes;
823 int flushbits;
824 int bitsPerFrame, mean_bits;
825 int last_ptr,first_ptr;
826 first_ptr=gfc->w_ptr; /* first header to add to bitstream */
827 last_ptr = gfc->h_ptr - 1; /* last header to add to bitstream */
828 if (last_ptr==-1) last_ptr=MAX_HEADER_BUF-1;
829 l3_side = &gfc->l3_side;
832 if ((flushbits = compute_flushbits(gfp,&nbytes)) < 0) return;
833 drain_into_ancillary(gfp,flushbits);
835 /* check that the 100% of the last frame has been written to bitstream */
836 getframebits(gfp,&bitsPerFrame,&mean_bits);
837 assert (gfc->header[last_ptr].write_timing + bitsPerFrame == gfc->bs.totbit);
839 /* we have padded out all frames with ancillary data, which is the
840 same as filling the bitreservoir with ancillary data, so : */
841 gfc->ResvSize=0;
842 l3_side->main_data_begin = 0;
849 void add_dummy_byte ( lame_global_flags* const gfp, unsigned char val )
851 lame_internal_flags *gfc = gfp->internal_flags;
852 int i;
854 putbits_noheaders(gfp,val,8);
856 for (i=0 ; i< MAX_HEADER_BUF ; ++i)
857 gfc->header[i].write_timing += 8;
862 format_bitstream()
864 This is called after a frame of audio has been quantized and coded.
865 It will write the encoded audio to the bitstream. Note that
866 from a layer3 encoder's perspective the bit stream is primarily
867 a series of main_data() blocks, with header and side information
868 inserted at the proper locations to maintain framing. (See Figure A.7
869 in the IS).
872 format_bitstream(lame_global_flags *gfp, int bitsPerFrame,
873 int l3_enc[2][2][576],
874 III_scalefac_t scalefac[2][2] )
876 lame_internal_flags *gfc=gfp->internal_flags;
877 int bits,nbytes;
878 III_side_info_t *l3_side;
879 l3_side = &gfc->l3_side;
881 drain_into_ancillary(gfp,l3_side->resvDrain_pre);
883 encodeSideInfo2(gfp,bitsPerFrame);
884 bits = 8*gfc->sideinfo_len;
885 bits+=writeMainData(gfp,l3_enc,scalefac);
886 drain_into_ancillary(gfp,l3_side->resvDrain_post);
887 bits += l3_side->resvDrain_post;
889 l3_side->main_data_begin += (bitsPerFrame-bits)/8;
891 /* compare number of bits needed to clear all buffered mp3 frames
892 * with what we think the resvsize is: */
893 if (compute_flushbits(gfp,&nbytes) != gfc->ResvSize) {
894 ERRORF(gfc,"Internal buffer inconsistency. flushbits <> ResvSize");
898 /* compare main_data_begin for the next frame with what we
899 * think the resvsize is: */
900 if ((l3_side->main_data_begin * 8) != gfc->ResvSize ) {
901 ERRORF(gfc,"bit reservoir error: \n"
902 "l3_side->main_data_begin: %i \n"
903 "Resvoir size: %i \n"
904 "resv drain (post) %i \n"
905 "resv drain (pre) %i \n"
906 "header and sideinfo: %i \n"
907 "data bits: %i \n"
908 "total bits: %i (remainder: %i) \n"
909 "bitsperframe: %i \n",
911 8*l3_side->main_data_begin,
912 gfc->ResvSize,
913 l3_side->resvDrain_post,
914 l3_side->resvDrain_pre,
915 8*gfc->sideinfo_len,
916 bits-l3_side->resvDrain_post-8*gfc->sideinfo_len,
917 bits, bits % 8,
918 bitsPerFrame
921 gfc->ResvSize = l3_side->main_data_begin*8;
923 assert(gfc->bs.totbit % 8 == 0);
925 if (gfc->bs.totbit > 1000000000 ) {
926 /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter*/
927 int i;
928 for (i=0 ; i< MAX_HEADER_BUF ; ++i)
929 gfc->header[i].write_timing -= gfc->bs.totbit;
930 gfc->bs.totbit=0;
934 return 0;
941 /* copy data out of the internal MP3 bit buffer into a user supplied
942 unsigned char buffer.
944 mp3data=0 indicates data in buffer is an id3tags and VBR tags
945 mp3data=1 data is real mp3 frame data.
949 int copy_buffer(lame_internal_flags *gfc,unsigned char *buffer,int size,int mp3data)
951 Bit_stream_struc *bs=&gfc->bs;
952 int minimum = bs->buf_byte_idx + 1;
953 if (minimum <= 0) return 0;
954 if (size!=0 && minimum>size) return -1; /* buffer is too small */
955 memcpy(buffer,bs->buf,minimum);
956 bs->buf_byte_idx = -1;
957 bs->buf_bit_idx = 0;
959 if (mp3data) {
960 UpdateMusicCRC(&gfc->nMusicCRC,buffer,minimum);
962 return minimum;
966 void init_bit_stream_w(lame_internal_flags *gfc)
968 gfc->bs.buf = (unsigned char *) malloc(BUFFER_SIZE);
969 gfc->bs.buf_size = BUFFER_SIZE;
971 gfc->h_ptr = gfc->w_ptr = 0;
972 gfc->header[gfc->h_ptr].write_timing = 0;
973 gfc->bs.buf_byte_idx = -1;
974 gfc->bs.buf_bit_idx = 0;
975 gfc->bs.totbit = 0;
978 /* end of bitstream.c */