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