1 /*
2  *      MP3 bitstream Output interface for LAME
3  *
4  *      Copyright (c) 1999-2000 Mark Taylor
5  *      Copyright (c) 1999-2002 Takehiro Tominaga
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * $Id: bitstream.c,v 1.97 2011/05/07 16:05:17 rbrito Exp $
23  */
24 
25 
26 #ifdef HAVE_CONFIG_H
27 #include <config.h>
28 #elif IDE_COMPILE
29 #include "lame-config.h"
30 #endif
31 
32 #include <stdlib.h>
33 #include <stdio.h>
34 
35 #include "lame.h"
36 #include "lame-machine.h"
37 #include "encoder.h"
38 #include "util.h"
39 #include "tables.h"
40 #include "quantize_pvt.h"
41 #include "lame_global_flags.h"
42 #include "gain_analysis.h"
43 #include "VbrTag.h"
44 #include "bitstream.h"
45 #include "tables.h"
46 
47 
48 
49 /* unsigned int is at least this large:  */
50 /* we work with ints, so when doing bit manipulation, we limit
51  * ourselves to MAX_LENGTH-2 just to be on the safe side */
52 #define MAX_LENGTH      32
53 
54 
55 
56 #ifdef DEBUG
57 static int hogege;
58 #endif
59 
60 
61 
62 static int
calcFrameLength(SessionConfig_t const * const cfg,int kbps,int pad)63 calcFrameLength(SessionConfig_t const *const cfg, int kbps, int pad)
64 {
65   return 8 * ((cfg->version + 1) * 72000 * kbps / cfg->samplerate_out + pad);
66 }
67 
68 
69 /***********************************************************************
70  * compute bitsperframe and mean_bits for a layer III frame
71  **********************************************************************/
72 int
getframebits(const lame_internal_flags * gfc)73 getframebits(const lame_internal_flags * gfc)
74 {
75     SessionConfig_t const *const cfg = &gfc->cfg;
76     EncResult_t const *const eov = &gfc->ov_enc;
77     int     bit_rate;
78 
79     /* get bitrate in kbps [?] */
80     if (eov->bitrate_index)
81         bit_rate = bitrate_table[cfg->version][eov->bitrate_index];
82     else
83         bit_rate = cfg->avg_bitrate;
84     /*assert(bit_rate <= 550); */
85     assert(8 <= bit_rate && bit_rate <= 640);
86 
87     /* main encoding routine toggles padding on and off */
88     /* one Layer3 Slot consists of 8 bits */
89     return calcFrameLength(cfg, bit_rate, eov->padding);
90 }
91 
92 int
get_max_frame_buffer_size_by_constraint(SessionConfig_t const * cfg,int constraint)93 get_max_frame_buffer_size_by_constraint(SessionConfig_t const * cfg, int constraint)
94 {
95     int     maxmp3buf = 0;
96     if (cfg->avg_bitrate > 320) {
97         /* in freeformat the buffer is constant */
98         if (constraint == MDB_STRICT_ISO) {
99             maxmp3buf = calcFrameLength(cfg, cfg->avg_bitrate, 0);
100         }
101         else {
102             /* maximum allowed bits per granule are 7680 */
103             maxmp3buf = 7680 * (cfg->version + 1);
104         }
105     }
106     else {
107         int     max_kbps;
108         if (cfg->samplerate_out < 16000) {
109             max_kbps = bitrate_table[cfg->version][8]; /* default: allow 64 kbps (MPEG-2.5) */
110         }
111         else {
112             max_kbps = bitrate_table[cfg->version][14];
113         }
114         switch (constraint)
115         {
116         default:
117         case MDB_DEFAULT:
118             /* Bouvigne suggests this more lax interpretation of the ISO doc instead of using 8*960. */
119             /* All mp3 decoders should have enough buffer to handle this value: size of a 320kbps 32kHz frame */
120             maxmp3buf = 8 * 1440;
121             break;
122         case MDB_STRICT_ISO:
123             maxmp3buf = calcFrameLength(cfg, max_kbps, 0);
124             break;
125         case MDB_MAXIMUM:
126             maxmp3buf = 7680 * (cfg->version + 1);
127             break;
128         }
129     }
130     return maxmp3buf;
131 }
132 
133 
134 static void
putheader_bits(lame_internal_flags * gfc)135 putheader_bits(lame_internal_flags * gfc)
136 {
137     SessionConfig_t const *const cfg = &gfc->cfg;
138     EncStateVar_t *const esv = &gfc->sv_enc;
139     Bit_stream_struc *bs = &gfc->bs;
140 #ifdef DEBUG
141     hogege += cfg->sideinfo_len * 8;
142 #endif
143     memcpy(&bs->buf[bs->buf_byte_idx], esv->header[esv->w_ptr].buf, cfg->sideinfo_len);
144     bs->buf_byte_idx += cfg->sideinfo_len;
145     bs->totbit += cfg->sideinfo_len * 8;
146     esv->w_ptr = (esv->w_ptr + 1) & (MAX_HEADER_BUF - 1);
147 }
148 
149 
150 
151 
152 /*write j bits into the bit stream */
153 inline static void
putbits2(lame_internal_flags * gfc,int val,int j)154 putbits2(lame_internal_flags * gfc, int val, int j)
155 {
156     EncStateVar_t const *const esv = &gfc->sv_enc;
157     Bit_stream_struc *bs;
158     bs = &gfc->bs;
159 
160     assert(j < MAX_LENGTH - 2);
161 
162     while (j > 0) {
163         int     k;
164         if (bs->buf_bit_idx == 0) {
165             bs->buf_bit_idx = 8;
166             bs->buf_byte_idx++;
167             assert(bs->buf_byte_idx < BUFFER_SIZE);
168             assert(esv->header[esv->w_ptr].write_timing >= bs->totbit);
169             if (esv->header[esv->w_ptr].write_timing == bs->totbit) {
170                 putheader_bits(gfc);
171             }
172             bs->buf[bs->buf_byte_idx] = 0;
173         }
174 
175         k = Min(j, bs->buf_bit_idx);
176         j -= k;
177 
178         bs->buf_bit_idx -= k;
179 
180         assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
181         assert(bs->buf_bit_idx < MAX_LENGTH);
182 
183         bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
184         bs->totbit += k;
185     }
186 }
187 
188 /*write j bits into the bit stream, ignoring frame headers */
189 inline static void
putbits_noheaders(lame_internal_flags * gfc,int val,int j)190 putbits_noheaders(lame_internal_flags * gfc, int val, int j)
191 {
192     Bit_stream_struc *bs;
193     bs = &gfc->bs;
194 
195     assert(j < MAX_LENGTH - 2);
196 
197     while (j > 0) {
198         int     k;
199         if (bs->buf_bit_idx == 0) {
200             bs->buf_bit_idx = 8;
201             bs->buf_byte_idx++;
202             assert(bs->buf_byte_idx < BUFFER_SIZE);
203             bs->buf[bs->buf_byte_idx] = 0;
204         }
205 
206         k = Min(j, bs->buf_bit_idx);
207         j -= k;
208 
209         bs->buf_bit_idx -= k;
210 
211         assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
212         assert(bs->buf_bit_idx < MAX_LENGTH);
213 
214         bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
215         bs->totbit += k;
216     }
217 }
218 
219 
220 /*
221   Some combinations of bitrate, Fs, and stereo make it impossible to stuff
222   out a frame using just main_data, due to the limited number of bits to
223   indicate main_data_length. In these situations, we put stuffing bits into
224   the ancillary data...
225 */
226 
227 inline static void
drain_into_ancillary(lame_internal_flags * gfc,int remainingBits)228 drain_into_ancillary(lame_internal_flags * gfc, int remainingBits)
229 {
230     SessionConfig_t const *const cfg = &gfc->cfg;
231     EncStateVar_t *const esv = &gfc->sv_enc;
232     int     i;
233     assert(remainingBits >= 0);
234 
235     if (remainingBits >= 8) {
236         putbits2(gfc, 0x4c, 8);
237         remainingBits -= 8;
238     }
239     if (remainingBits >= 8) {
240         putbits2(gfc, 0x41, 8);
241         remainingBits -= 8;
242     }
243     if (remainingBits >= 8) {
244         putbits2(gfc, 0x4d, 8);
245         remainingBits -= 8;
246     }
247     if (remainingBits >= 8) {
248         putbits2(gfc, 0x45, 8);
249         remainingBits -= 8;
250     }
251 
252     if (remainingBits >= 32) {
253         const char *const version = get_lame_short_version();
254         if (remainingBits >= 32)
255             for (i = 0; i < (int) strlen(version) && remainingBits >= 8; ++i) {
256                 remainingBits -= 8;
257                 putbits2(gfc, version[i], 8);
258             }
259     }
260 
261     for (; remainingBits >= 1; remainingBits -= 1) {
262         putbits2(gfc, esv->ancillary_flag, 1);
263         esv->ancillary_flag ^= !cfg->disable_reservoir;
264     }
265 
266     assert(remainingBits == 0);
267 
268 }
269 
270 /*write N bits into the header */
271 inline static void
writeheader(lame_internal_flags * gfc,int val,int j)272 writeheader(lame_internal_flags * gfc, int val, int j)
273 {
274     EncStateVar_t *const esv = &gfc->sv_enc;
275     int     ptr = esv->header[esv->h_ptr].ptr;
276 
277     while (j > 0) {
278         int const k = Min(j, 8 - (ptr & 7));
279         j -= k;
280         assert(j < MAX_LENGTH); /* >> 32  too large for 32 bit machines */
281         esv->header[esv->h_ptr].buf[ptr >> 3]
282             |= ((val >> j)) << (8 - (ptr & 7) - k);
283         ptr += k;
284     }
285     esv->header[esv->h_ptr].ptr = ptr;
286 }
287 
288 
289 static int
CRC_update(int value,int crc)290 CRC_update(int value, int crc)
291 {
292     int     i;
293     value <<= 8;
294     for (i = 0; i < 8; i++) {
295         value <<= 1;
296         crc <<= 1;
297 
298         if (((crc ^ value) & 0x10000))
299             crc ^= CRC16_POLYNOMIAL;
300     }
301     return crc;
302 }
303 
304 
305 void
CRC_writeheader(lame_internal_flags const * gfc,char * header)306 CRC_writeheader(lame_internal_flags const *gfc, char *header)
307 {
308     SessionConfig_t const *const cfg = &gfc->cfg;
309     int     crc = 0xffff;    /* (jo) init crc16 for error_protection */
310     int     i;
311 
312     crc = CRC_update(((unsigned char *) header)[2], crc);
313     crc = CRC_update(((unsigned char *) header)[3], crc);
314     for (i = 6; i < cfg->sideinfo_len; i++) {
315         crc = CRC_update(((unsigned char *) header)[i], crc);
316     }
317 
318     header[4] = crc >> 8;
319     header[5] = crc & 255;
320 }
321 
322 inline static void
encodeSideInfo2(lame_internal_flags * gfc,int bitsPerFrame)323 encodeSideInfo2(lame_internal_flags * gfc, int bitsPerFrame)
324 {
325     SessionConfig_t const *const cfg = &gfc->cfg;
326     EncResult_t const *const eov = &gfc->ov_enc;
327     EncStateVar_t *const esv = &gfc->sv_enc;
328     III_side_info_t *l3_side;
329     int     gr, ch;
330 
331     l3_side = &gfc->l3_side;
332     esv->header[esv->h_ptr].ptr = 0;
333     memset(esv->header[esv->h_ptr].buf, 0, cfg->sideinfo_len);
334     if (cfg->samplerate_out < 16000)
335         writeheader(gfc, 0xffe, 12);
336     else
337         writeheader(gfc, 0xfff, 12);
338     writeheader(gfc, (cfg->version), 1);
339     writeheader(gfc, 4 - 3, 2);
340     writeheader(gfc, (!cfg->error_protection), 1);
341     writeheader(gfc, (eov->bitrate_index), 4);
342     writeheader(gfc, (cfg->samplerate_index), 2);
343     writeheader(gfc, (eov->padding), 1);
344     writeheader(gfc, (cfg->extension), 1);
345     writeheader(gfc, (cfg->mode), 2);
346     writeheader(gfc, (eov->mode_ext), 2);
347     writeheader(gfc, (cfg->copyright), 1);
348     writeheader(gfc, (cfg->original), 1);
349     writeheader(gfc, (cfg->emphasis), 2);
350     if (cfg->error_protection) {
351         writeheader(gfc, 0, 16); /* dummy */
352     }
353 
354     if (cfg->version == 1) {
355         /* MPEG1 */
356         assert(l3_side->main_data_begin >= 0);
357         writeheader(gfc, (l3_side->main_data_begin), 9);
358 
359         if (cfg->channels_out == 2)
360             writeheader(gfc, l3_side->private_bits, 3);
361         else
362             writeheader(gfc, l3_side->private_bits, 5);
363 
364         for (ch = 0; ch < cfg->channels_out; ch++) {
365             int     band;
366             for (band = 0; band < 4; band++) {
367                 writeheader(gfc, l3_side->scfsi[ch][band], 1);
368             }
369         }
370 
371         for (gr = 0; gr < 2; gr++) {
372             for (ch = 0; ch < cfg->channels_out; ch++) {
373                 gr_info *const gi = &l3_side->tt[gr][ch];
374                 writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
375                 writeheader(gfc, gi->big_values / 2, 9);
376                 writeheader(gfc, gi->global_gain, 8);
377                 writeheader(gfc, gi->scalefac_compress, 4);
378 
379                 if (gi->block_type != NORM_TYPE) {
380                     writeheader(gfc, 1, 1); /* window_switching_flag */
381                     writeheader(gfc, gi->block_type, 2);
382                     writeheader(gfc, gi->mixed_block_flag, 1);
383 
384                     if (gi->table_select[0] == 14)
385                         gi->table_select[0] = 16;
386                     writeheader(gfc, gi->table_select[0], 5);
387                     if (gi->table_select[1] == 14)
388                         gi->table_select[1] = 16;
389                     writeheader(gfc, gi->table_select[1], 5);
390 
391                     writeheader(gfc, gi->subblock_gain[0], 3);
392                     writeheader(gfc, gi->subblock_gain[1], 3);
393                     writeheader(gfc, gi->subblock_gain[2], 3);
394                 }
395                 else {
396                     writeheader(gfc, 0, 1); /* window_switching_flag */
397                     if (gi->table_select[0] == 14)
398                         gi->table_select[0] = 16;
399                     writeheader(gfc, gi->table_select[0], 5);
400                     if (gi->table_select[1] == 14)
401                         gi->table_select[1] = 16;
402                     writeheader(gfc, gi->table_select[1], 5);
403                     if (gi->table_select[2] == 14)
404                         gi->table_select[2] = 16;
405                     writeheader(gfc, gi->table_select[2], 5);
406 
407                     assert(0 <= gi->region0_count && gi->region0_count < 16);
408                     assert(0 <= gi->region1_count && gi->region1_count < 8);
409                     writeheader(gfc, gi->region0_count, 4);
410                     writeheader(gfc, gi->region1_count, 3);
411                 }
412                 writeheader(gfc, gi->preflag, 1);
413                 writeheader(gfc, gi->scalefac_scale, 1);
414                 writeheader(gfc, gi->count1table_select, 1);
415             }
416         }
417     }
418     else {
419         /* MPEG2 */
420         assert(l3_side->main_data_begin >= 0);
421         writeheader(gfc, (l3_side->main_data_begin), 8);
422         writeheader(gfc, l3_side->private_bits, cfg->channels_out);
423 
424         gr = 0;
425         for (ch = 0; ch < cfg->channels_out; ch++) {
426             gr_info *const gi = &l3_side->tt[gr][ch];
427             writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
428             writeheader(gfc, gi->big_values / 2, 9);
429             writeheader(gfc, gi->global_gain, 8);
430             writeheader(gfc, gi->scalefac_compress, 9);
431 
432             if (gi->block_type != NORM_TYPE) {
433                 writeheader(gfc, 1, 1); /* window_switching_flag */
434                 writeheader(gfc, gi->block_type, 2);
435                 writeheader(gfc, gi->mixed_block_flag, 1);
436 
437                 if (gi->table_select[0] == 14)
438                     gi->table_select[0] = 16;
439                 writeheader(gfc, gi->table_select[0], 5);
440                 if (gi->table_select[1] == 14)
441                     gi->table_select[1] = 16;
442                 writeheader(gfc, gi->table_select[1], 5);
443 
444                 writeheader(gfc, gi->subblock_gain[0], 3);
445                 writeheader(gfc, gi->subblock_gain[1], 3);
446                 writeheader(gfc, gi->subblock_gain[2], 3);
447             }
448             else {
449                 writeheader(gfc, 0, 1); /* window_switching_flag */
450                 if (gi->table_select[0] == 14)
451                     gi->table_select[0] = 16;
452                 writeheader(gfc, gi->table_select[0], 5);
453                 if (gi->table_select[1] == 14)
454                     gi->table_select[1] = 16;
455                 writeheader(gfc, gi->table_select[1], 5);
456                 if (gi->table_select[2] == 14)
457                     gi->table_select[2] = 16;
458                 writeheader(gfc, gi->table_select[2], 5);
459 
460                 assert(0 <= gi->region0_count && gi->region0_count < 16);
461                 assert(0 <= gi->region1_count && gi->region1_count < 8);
462                 writeheader(gfc, gi->region0_count, 4);
463                 writeheader(gfc, gi->region1_count, 3);
464             }
465 
466             writeheader(gfc, gi->scalefac_scale, 1);
467             writeheader(gfc, gi->count1table_select, 1);
468         }
469     }
470 
471     if (cfg->error_protection) {
472         /* (jo) error_protection: add crc16 information to header */
473         CRC_writeheader(gfc, esv->header[esv->h_ptr].buf);
474     }
475 
476     {
477         int const old = esv->h_ptr;
478         assert(esv->header[old].ptr == cfg->sideinfo_len * 8);
479 
480         esv->h_ptr = (old + 1) & (MAX_HEADER_BUF - 1);
481         esv->header[esv->h_ptr].write_timing = esv->header[old].write_timing + bitsPerFrame;
482 
483         if (esv->h_ptr == esv->w_ptr) {
484             /* yikes! we are out of header buffer space */
485             ERRORF(gfc, "Error: MAX_HEADER_BUF too small in bitstream.c \n");
486         }
487 
488     }
489 }
490 
491 
492 inline static int
huffman_coder_count1(lame_internal_flags * gfc,gr_info const * gi)493 huffman_coder_count1(lame_internal_flags * gfc, gr_info const *gi)
494 {
495     /* Write count1 area */
496     struct huffcodetab const *const h = &ht[gi->count1table_select + 32];
497     int     i, bits = 0;
498 #ifdef DEBUG
499     int     gegebo = gfc->bs.totbit;
500 #endif
501 
502     int const *ix = &gi->l3_enc[gi->big_values];
503     FLOAT const *xr = &gi->xr[gi->big_values];
504     assert(gi->count1table_select < 2);
505 
506     for (i = (gi->count1 - gi->big_values) / 4; i > 0; --i) {
507         int     huffbits = 0;
508         int     p = 0, v;
509 
510         v = ix[0];
511         if (v) {
512             p += 8;
513             if (xr[0] < 0.0f)
514                 huffbits++;
515             assert(v <= 1);
516         }
517 
518         v = ix[1];
519         if (v) {
520             p += 4;
521             huffbits *= 2;
522             if (xr[1] < 0.0f)
523                 huffbits++;
524             assert(v <= 1);
525         }
526 
527         v = ix[2];
528         if (v) {
529             p += 2;
530             huffbits *= 2;
531             if (xr[2] < 0.0f)
532                 huffbits++;
533             assert(v <= 1);
534         }
535 
536         v = ix[3];
537         if (v) {
538             p++;
539             huffbits *= 2;
540             if (xr[3] < 0.0f)
541                 huffbits++;
542             assert(v <= 1);
543         }
544 
545         ix += 4;
546         xr += 4;
547         putbits2(gfc, huffbits + h->table[p], h->hlen[p]);
548         bits += h->hlen[p];
549     }
550 #ifdef DEBUG
551     DEBUGF(gfc, "count1: real: %ld counted:%d (bigv %d count1len %d)\n",
552            gfc->bs.totbit - gegebo, gi->count1bits, gi->big_values, gi->count1);
553 #endif
554     return bits;
555 }
556 
557 
558 
559 /*
560   Implements the pseudocode of page 98 of the IS
561   */
562 inline static int
Huffmancode(lame_internal_flags * const gfc,const unsigned int tableindex,int start,int end,gr_info const * gi)563 Huffmancode(lame_internal_flags * const gfc, const unsigned int tableindex,
564             int start, int end, gr_info const *gi)
565 {
566     struct huffcodetab const *const h = &ht[tableindex];
567     unsigned int const linbits = h->xlen;
568     int     i, bits = 0;
569 
570     assert(tableindex < 32u);
571     if (!tableindex)
572         return bits;
573 
574     for (i = start; i < end; i += 2) {
575         int16_t  cbits = 0;
576         uint16_t xbits = 0;
577         unsigned int xlen = h->xlen;
578         unsigned int ext = 0;
579         unsigned int x1 = gi->l3_enc[i];
580         unsigned int x2 = gi->l3_enc[i + 1];
581 
582         assert(gi->l3_enc[i] >= 0);
583         assert(gi->l3_enc[i+1] >= 0);
584 
585         if (x1 != 0u) {
586             if (gi->xr[i] < 0.0f)
587                 ext++;
588             cbits--;
589         }
590 
591         if (tableindex > 15u) {
592             /* use ESC-words */
593             if (x1 >= 15u) {
594                 uint16_t const linbits_x1 = x1 - 15u;
595                 assert(linbits_x1 <= h->linmax);
596                 ext |= linbits_x1 << 1u;
597                 xbits = linbits;
598                 x1 = 15u;
599             }
600 
601             if (x2 >= 15u) {
602                 uint16_t const linbits_x2 = x2 - 15u;
603                 assert(linbits_x2 <= h->linmax);
604                 ext <<= linbits;
605                 ext |= linbits_x2;
606                 xbits += linbits;
607                 x2 = 15u;
608             }
609             xlen = 16;
610         }
611 
612         if (x2 != 0u) {
613             ext <<= 1;
614             if (gi->xr[i + 1] < 0.0f)
615                 ext++;
616             cbits--;
617         }
618 
619         assert((x1 | x2) < 16u);
620 
621         x1 = x1 * xlen + x2;
622         xbits -= cbits;
623         cbits += h->hlen[x1];
624 
625         assert(cbits <= MAX_LENGTH);
626         assert(xbits <= MAX_LENGTH);
627 
628         putbits2(gfc, h->table[x1], cbits);
629         putbits2(gfc, (int)ext, xbits);
630         bits += cbits + xbits;
631     }
632     return bits;
633 }
634 
635 /*
636   Note the discussion of huffmancodebits() on pages 28
637   and 29 of the IS, as well as the definitions of the side
638   information on pages 26 and 27.
639   */
640 static int
ShortHuffmancodebits(lame_internal_flags * gfc,gr_info const * gi)641 ShortHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
642 {
643     int     bits;
644     int     region1Start;
645 
646     region1Start = 3 * gfc->scalefac_band.s[3];
647     if (region1Start > gi->big_values)
648         region1Start = gi->big_values;
649 
650     /* short blocks do not have a region2 */
651     bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
652     bits += Huffmancode(gfc, gi->table_select[1], region1Start, gi->big_values, gi);
653     return bits;
654 }
655 
656 static int
LongHuffmancodebits(lame_internal_flags * gfc,gr_info const * gi)657 LongHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
658 {
659     unsigned int i;
660     int     bigvalues, bits;
661     int     region1Start, region2Start;
662 
663     bigvalues = gi->big_values;
664     assert(0 <= bigvalues && bigvalues <= 576);
665 
666     assert(gi->region0_count >= -1);
667     assert(gi->region1_count >= -1);
668     i = gi->region0_count + 1;
669     assert((size_t) i < dimension_of(gfc->scalefac_band.l));
670     region1Start = gfc->scalefac_band.l[i];
671     i += gi->region1_count + 1;
672     assert((size_t) i < dimension_of(gfc->scalefac_band.l));
673     region2Start = gfc->scalefac_band.l[i];
674 
675     if (region1Start > bigvalues)
676         region1Start = bigvalues;
677 
678     if (region2Start > bigvalues)
679         region2Start = bigvalues;
680 
681     bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
682     bits += Huffmancode(gfc, gi->table_select[1], region1Start, region2Start, gi);
683     bits += Huffmancode(gfc, gi->table_select[2], region2Start, bigvalues, gi);
684     return bits;
685 }
686 
687 inline static int
writeMainData(lame_internal_flags * const gfc)688 writeMainData(lame_internal_flags * const gfc)
689 {
690     SessionConfig_t const *const cfg = &gfc->cfg;
691     III_side_info_t const *const l3_side = &gfc->l3_side;
692     int     gr, ch, sfb, data_bits, tot_bits = 0;
693 
694     if (cfg->version == 1) {
695         /* MPEG 1 */
696         for (gr = 0; gr < 2; gr++) {
697             for (ch = 0; ch < cfg->channels_out; ch++) {
698                 gr_info const *const gi = &l3_side->tt[gr][ch];
699                 int const slen1 = slen1_tab[gi->scalefac_compress];
700                 int const slen2 = slen2_tab[gi->scalefac_compress];
701                 data_bits = 0;
702 #ifdef DEBUG
703                 hogege = gfc->bs.totbit;
704 #endif
705                 for (sfb = 0; sfb < gi->sfbdivide; sfb++) {
706                     if (gi->scalefac[sfb] == -1)
707                         continue; /* scfsi is used */
708                     putbits2(gfc, gi->scalefac[sfb], slen1);
709                     data_bits += slen1;
710                 }
711                 for (; sfb < gi->sfbmax; sfb++) {
712                     if (gi->scalefac[sfb] == -1)
713                         continue; /* scfsi is used */
714                     putbits2(gfc, gi->scalefac[sfb], slen2);
715                     data_bits += slen2;
716                 }
717                 assert(data_bits == gi->part2_length);
718 
719                 if (gi->block_type == SHORT_TYPE) {
720                     data_bits += ShortHuffmancodebits(gfc, gi);
721                 }
722                 else {
723                     data_bits += LongHuffmancodebits(gfc, gi);
724                 }
725                 data_bits += huffman_coder_count1(gfc, gi);
726 #ifdef DEBUG
727                 DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
728 #endif
729                 /* does bitcount in quantize.c agree with actual bit count? */
730                 assert(data_bits == gi->part2_3_length + gi->part2_length);
731                 tot_bits += data_bits;
732             }           /* for ch */
733         }               /* for gr */
734     }
735     else {
736         /* MPEG 2 */
737         gr = 0;
738         for (ch = 0; ch < cfg->channels_out; ch++) {
739             gr_info const *const gi = &l3_side->tt[gr][ch];
740             int     i, sfb_partition, scale_bits = 0;
741             assert(gi->sfb_partition_table);
742             data_bits = 0;
743 #ifdef DEBUG
744             hogege = gfc->bs.totbit;
745 #endif
746             sfb = 0;
747             sfb_partition = 0;
748 
749             if (gi->block_type == SHORT_TYPE) {
750                 for (; sfb_partition < 4; sfb_partition++) {
751                     int const sfbs = gi->sfb_partition_table[sfb_partition] / 3;
752                     int const slen = gi->slen[sfb_partition];
753                     for (i = 0; i < sfbs; i++, sfb++) {
754                         putbits2(gfc, Max(gi->scalefac[sfb * 3 + 0], 0), slen);
755                         putbits2(gfc, Max(gi->scalefac[sfb * 3 + 1], 0), slen);
756                         putbits2(gfc, Max(gi->scalefac[sfb * 3 + 2], 0), slen);
757                         scale_bits += 3 * slen;
758                     }
759                 }
760                 data_bits += ShortHuffmancodebits(gfc, gi);
761             }
762             else {
763                 for (; sfb_partition < 4; sfb_partition++) {
764                     int const sfbs = gi->sfb_partition_table[sfb_partition];
765                     int const slen = gi->slen[sfb_partition];
766                     for (i = 0; i < sfbs; i++, sfb++) {
767                         putbits2(gfc, Max(gi->scalefac[sfb], 0), slen);
768                         scale_bits += slen;
769                     }
770                 }
771                 data_bits += LongHuffmancodebits(gfc, gi);
772             }
773             data_bits += huffman_coder_count1(gfc, gi);
774 #ifdef DEBUG
775             DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
776 #endif
777             /* does bitcount in quantize.c agree with actual bit count? */
778             assert(data_bits == gi->part2_3_length);
779             assert(scale_bits == gi->part2_length);
780             tot_bits += scale_bits + data_bits;
781         }               /* for ch */
782     }                   /* for gf */
783     return tot_bits;
784 }                       /* main_data */
785 
786 
787 
788 /* compute the number of bits required to flush all mp3 frames
789    currently in the buffer.  This should be the same as the
790    reservoir size.  Only call this routine between frames - i.e.
791    only after all headers and data have been added to the buffer
792    by format_bitstream().
793 
794    Also compute total_bits_output =
795        size of mp3 buffer (including frame headers which may not
796        have yet been send to the mp3 buffer) +
797        number of bits needed to flush all mp3 frames.
798 
799    total_bytes_output is the size of the mp3 output buffer if
800    lame_encode_flush_nogap() was called right now.
801 
802  */
803 int
compute_flushbits(const lame_internal_flags * gfc,int * total_bytes_output)804 compute_flushbits(const lame_internal_flags * gfc, int *total_bytes_output)
805 {
806     SessionConfig_t const *const cfg = &gfc->cfg;
807     EncStateVar_t const *const esv = &gfc->sv_enc;
808     int     flushbits, remaining_headers;
809     int     bitsPerFrame;
810     int     last_ptr, first_ptr;
811     first_ptr = esv->w_ptr; /* first header to add to bitstream */
812     last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */
813     if (last_ptr == -1)
814         last_ptr = MAX_HEADER_BUF - 1;
815 
816     /* add this many bits to bitstream so we can flush all headers */
817     flushbits = esv->header[last_ptr].write_timing - gfc->bs.totbit;
818     *total_bytes_output = flushbits;
819 
820     if (flushbits >= 0) {
821         /* if flushbits >= 0, some headers have not yet been written */
822         /* reduce flushbits by the size of the headers */
823         remaining_headers = 1 + last_ptr - first_ptr;
824         if (last_ptr < first_ptr)
825             remaining_headers = 1 + last_ptr - first_ptr + MAX_HEADER_BUF;
826         flushbits -= remaining_headers * 8 * cfg->sideinfo_len;
827     }
828 
829 
830     /* finally, add some bits so that the last frame is complete
831      * these bits are not necessary to decode the last frame, but
832      * some decoders will ignore last frame if these bits are missing
833      */
834     bitsPerFrame = getframebits(gfc);
835     flushbits += bitsPerFrame;
836     *total_bytes_output += bitsPerFrame;
837     /* round up:   */
838     if (*total_bytes_output % 8)
839         *total_bytes_output = 1 + (*total_bytes_output / 8);
840     else
841         *total_bytes_output = (*total_bytes_output / 8);
842     *total_bytes_output += gfc->bs.buf_byte_idx + 1;
843 
844 
845     if (flushbits < 0) {
846 #if 0
847         /* if flushbits < 0, this would mean that the buffer looks like:
848          * (data...)  last_header  (data...)  (extra data that should not be here...)
849          */
850         DEBUGF(gfc, "last header write_timing = %i \n", esv->header[last_ptr].write_timing);
851         DEBUGF(gfc, "first header write_timing = %i \n", esv->header[first_ptr].write_timing);
852         DEBUGF(gfc, "bs.totbit:                 %i \n", gfc->bs.totbit);
853         DEBUGF(gfc, "first_ptr, last_ptr        %i %i \n", first_ptr, last_ptr);
854         DEBUGF(gfc, "remaining_headers =        %i \n", remaining_headers);
855         DEBUGF(gfc, "bitsperframe:              %i \n", bitsPerFrame);
856         DEBUGF(gfc, "sidelen:                   %i \n", cfg->sideinfo_len);
857 #endif
858         ERRORF(gfc, "strange error flushing buffer ... \n");
859     }
860     return flushbits;
861 }
862 
863 
864 void
flush_bitstream(lame_internal_flags * gfc)865 flush_bitstream(lame_internal_flags * gfc)
866 {
867     EncStateVar_t *const esv = &gfc->sv_enc;
868     III_side_info_t *l3_side;
869     int     nbytes;
870     int     flushbits;
871     int     last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */
872     if (last_ptr == -1)
873         last_ptr = MAX_HEADER_BUF - 1;
874     l3_side = &gfc->l3_side;
875 
876 
877     if ((flushbits = compute_flushbits(gfc, &nbytes)) < 0)
878         return;
879     drain_into_ancillary(gfc, flushbits);
880 
881     /* check that the 100% of the last frame has been written to bitstream */
882     assert(esv->header[last_ptr].write_timing + getframebits(gfc)
883            == gfc->bs.totbit);
884 
885     /* we have padded out all frames with ancillary data, which is the
886        same as filling the bitreservoir with ancillary data, so : */
887     esv->ResvSize = 0;
888     l3_side->main_data_begin = 0;
889 }
890 
891 
892 
893 
894 void
add_dummy_byte(lame_internal_flags * gfc,unsigned char val,unsigned int n)895 add_dummy_byte(lame_internal_flags * gfc, unsigned char val, unsigned int n)
896 {
897     EncStateVar_t *const esv = &gfc->sv_enc;
898     int     i;
899 
900     while (n-- > 0u) {
901         putbits_noheaders(gfc, val, 8);
902 
903         for (i = 0; i < MAX_HEADER_BUF; ++i)
904             esv->header[i].write_timing += 8;
905     }
906 }
907 
908 
909 /*
910   format_bitstream()
911 
912   This is called after a frame of audio has been quantized and coded.
913   It will write the encoded audio to the bitstream. Note that
914   from a layer3 encoder's perspective the bit stream is primarily
915   a series of main_data() blocks, with header and side information
916   inserted at the proper locations to maintain framing. (See Figure A.7
917   in the IS).
918   */
919 int
format_bitstream(lame_internal_flags * gfc)920 format_bitstream(lame_internal_flags * gfc)
921 {
922     SessionConfig_t const *const cfg = &gfc->cfg;
923     EncStateVar_t *const esv = &gfc->sv_enc;
924     int     bits, nbytes;
925     III_side_info_t *l3_side;
926     int     bitsPerFrame;
927     l3_side = &gfc->l3_side;
928 
929     bitsPerFrame = getframebits(gfc);
930     drain_into_ancillary(gfc, l3_side->resvDrain_pre);
931 
932     encodeSideInfo2(gfc, bitsPerFrame);
933     bits = 8 * cfg->sideinfo_len;
934     bits += writeMainData(gfc);
935     drain_into_ancillary(gfc, l3_side->resvDrain_post);
936     bits += l3_side->resvDrain_post;
937 
938     l3_side->main_data_begin += (bitsPerFrame - bits) / 8;
939 
940     /* compare number of bits needed to clear all buffered mp3 frames
941      * with what we think the resvsize is: */
942     if (compute_flushbits(gfc, &nbytes) != esv->ResvSize) {
943         ERRORF(gfc, "Internal buffer inconsistency. flushbits <> ResvSize");
944     }
945 
946 
947     /* compare main_data_begin for the next frame with what we
948      * think the resvsize is: */
949     if ((l3_side->main_data_begin * 8) != esv->ResvSize) {
950         ERRORF(gfc, "bit reservoir error: \n"
951                "l3_side->main_data_begin: %i \n"
952                "Resvoir size:             %i \n"
953                "resv drain (post)         %i \n"
954                "resv drain (pre)          %i \n"
955                "header and sideinfo:      %i \n"
956                "data bits:                %i \n"
957                "total bits:               %i (remainder: %i) \n"
958                "bitsperframe:             %i \n",
959                8 * l3_side->main_data_begin,
960                esv->ResvSize,
961                l3_side->resvDrain_post,
962                l3_side->resvDrain_pre,
963                8 * cfg->sideinfo_len,
964                bits - l3_side->resvDrain_post - 8 * cfg->sideinfo_len,
965                bits, bits % 8, bitsPerFrame);
966 
967         ERRORF(gfc, "This is a fatal error.  It has several possible causes:");
968         ERRORF(gfc, "90%%  LAME compiled with buggy version of gcc using advanced optimizations");
969         ERRORF(gfc, " 9%%  Your system is overclocked");
970         ERRORF(gfc, " 1%%  bug in LAME encoding library");
971 
972         esv->ResvSize = l3_side->main_data_begin * 8;
973     };
974     assert(gfc->bs.totbit % 8 == 0);
975 
976     if (gfc->bs.totbit > 1000000000) {
977         /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter */
978         int     i;
979         for (i = 0; i < MAX_HEADER_BUF; ++i)
980             esv->header[i].write_timing -= gfc->bs.totbit;
981         gfc->bs.totbit = 0;
982     }
983 
984 
985     return 0;
986 }
987 
988 
989 static int
do_gain_analysis(lame_internal_flags * gfc,unsigned char * buffer,int minimum)990 do_gain_analysis(lame_internal_flags * gfc, unsigned char* buffer, int minimum)
991 {
992     SessionConfig_t const *const cfg = &gfc->cfg;
993     RpgStateVar_t const *const rsv = &gfc->sv_rpg;
994     RpgResult_t *const rov = &gfc->ov_rpg;
995 #ifdef DECODE_ON_THE_FLY
996     if (cfg->decode_on_the_fly) { /* decode the frame */
997         sample_t pcm_buf[2][1152];
998         int     mp3_in = minimum;
999         int     samples_out = -1;
1000 
1001         /* re-synthesis to pcm.  Repeat until we get a samples_out=0 */
1002         while (samples_out != 0) {
1003 
1004             samples_out = hip_decode1_unclipped(gfc->hip, buffer, mp3_in, pcm_buf[0], pcm_buf[1]);
1005             /* samples_out = 0:  need more data to decode
1006              * samples_out = -1:  error.  Lets assume 0 pcm output
1007              * samples_out = number of samples output */
1008 
1009             /* set the lenght of the mp3 input buffer to zero, so that in the
1010              * next iteration of the loop we will be querying mpglib about
1011              * buffered data */
1012             mp3_in = 0;
1013 
1014             if (samples_out == -1) {
1015                 /* error decoding. Not fatal, but might screw up
1016                  * the ReplayGain tag. What should we do? Ignore for now */
1017                 samples_out = 0;
1018             }
1019             if (samples_out > 0) {
1020                 /* process the PCM data */
1021 
1022                 /* this should not be possible, and indicates we have
1023                  * overflown the pcm_buf buffer */
1024                 assert(samples_out <= 1152);
1025 
1026                 if (cfg->findPeakSample) {
1027                     int     i;
1028                     /* FIXME: is this correct? maybe Max(fabs(pcm),PeakSample) */
1029                     for (i = 0; i < samples_out; i++) {
1030                         if (pcm_buf[0][i] > rov->PeakSample)
1031                             rov->PeakSample = pcm_buf[0][i];
1032                         else if (-pcm_buf[0][i] > rov->PeakSample)
1033                             rov->PeakSample = -pcm_buf[0][i];
1034                     }
1035                     if (cfg->channels_out > 1)
1036                         for (i = 0; i < samples_out; i++) {
1037                             if (pcm_buf[1][i] > rov->PeakSample)
1038                                 rov->PeakSample = pcm_buf[1][i];
1039                             else if (-pcm_buf[1][i] > rov->PeakSample)
1040                                 rov->PeakSample = -pcm_buf[1][i];
1041                         }
1042                 }
1043 
1044                 if (cfg->findReplayGain)
1045                     if (AnalyzeSamples
1046                         (rsv->rgdata, pcm_buf[0], pcm_buf[1], samples_out,
1047                          cfg->channels_out) == GAIN_ANALYSIS_ERROR)
1048                         return -6;
1049 
1050             }       /* if (samples_out>0) */
1051         }           /* while (samples_out!=0) */
1052     }               /* if (gfc->decode_on_the_fly) */
1053 #endif
1054     return minimum;
1055 }
1056 
1057 static int
do_copy_buffer(lame_internal_flags * gfc,unsigned char * buffer,int size)1058 do_copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size)
1059 {
1060     Bit_stream_struc *const bs = &gfc->bs;
1061     int const minimum = bs->buf_byte_idx + 1;
1062     if (minimum <= 0)
1063         return 0;
1064     if (size != 0 && minimum > size)
1065         return -1;      /* buffer is too small */
1066     memcpy(buffer, bs->buf, minimum);
1067     bs->buf_byte_idx = -1;
1068     bs->buf_bit_idx = 0;
1069     return minimum;
1070 }
1071 
1072 /* copy data out of the internal MP3 bit buffer into a user supplied
1073    unsigned char buffer.
1074 
1075    mp3data=0      indicates data in buffer is an id3tags and VBR tags
1076    mp3data=1      data is real mp3 frame data.
1077 
1078 
1079 */
1080 int
copy_buffer(lame_internal_flags * gfc,unsigned char * buffer,int size,int mp3data)1081 copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size, int mp3data)
1082 {
1083     int const minimum = do_copy_buffer(gfc, buffer, size);
1084     if (minimum > 0 && mp3data) {
1085         UpdateMusicCRC(&gfc->nMusicCRC, buffer, minimum);
1086 
1087         /** sum number of bytes belonging to the mp3 stream
1088          *  this info will be written into the Xing/LAME header for seeking
1089          */
1090         gfc->VBR_seek_table.nBytesWritten += minimum;
1091 
1092         return do_gain_analysis(gfc, buffer, minimum);
1093     }                   /* if (mp3data) */
1094     return minimum;
1095 }
1096 
1097 
1098 void
init_bit_stream_w(lame_internal_flags * gfc)1099 init_bit_stream_w(lame_internal_flags * gfc)
1100 {
1101     EncStateVar_t *const esv = &gfc->sv_enc;
1102 
1103     esv->h_ptr = esv->w_ptr = 0;
1104     esv->header[esv->h_ptr].write_timing = 0;
1105 
1106     gfc->bs.buf = (unsigned char *) malloc(BUFFER_SIZE);
1107     gfc->bs.buf_size = BUFFER_SIZE;
1108     gfc->bs.buf_byte_idx = -1;
1109     gfc->bs.buf_bit_idx = 0;
1110     gfc->bs.totbit = 0;
1111 }
1112 
1113 /* end of bitstream.c */
1114