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