replaced libart with new polygon code
[swftools.git] / lib / bladeenc / l3bitstream.c
1 /*
2                         (c) Copyright 1998-2000 - Tord Jansson
3                         ======================================
4
5                 This file is part of the BladeEnc MP3 Encoder, based on
6                 ISO's reference code for MPEG Layer 3 compression, and might
7                 contain smaller or larger sections that are directly taken
8                 from ISO's reference code.
9
10                 All changes to the ISO reference code herein are either
11                 copyrighted by Tord Jansson (tord.jansson@swipnet.se)
12                 or sublicensed to Tord Jansson by a third party.
13
14         BladeEnc is free software; you can redistribute this file
15         and/or modify it under the terms of the GNU Lesser General Public
16         License as published by the Free Software Foundation; either
17         version 2.1 of the License, or (at your option) any later version.
18
19
20
21         ------------    Changes    ------------
22
23         2000-12-04  Andre Piotrowski
24
25         -       redesigned, reformatted, slightly optimized
26 */
27
28 #include        <stdlib.h>
29 #include        <assert.h>
30
31 #include        "system.h"
32 #include        "common.h"
33
34 #include        "l3psy.h"
35 #include        "loop.h"
36 #include        "formatbitstream2.h"
37 #include        "huffman.h"
38
39 #include        "l3bitstream.h" /* the public interface */
40 #include        "l3bitstream-pvt.h"
41
42
43
44
45
46 static  int                             stereo = 1;
47 static  frame_params    *fr_ps  = NULL;
48
49 static  int                             PartHoldersInitialized = 0;
50
51
52
53 static  BitHolder                      *headerPH;
54 static  BitHolder                     *frameSIPH;
55 static  BitHolder                   *channelSIPH[MAX_CHANNELS];
56 static  BitHolder                  *spectrumSIPH[MAX_GRANULES][MAX_CHANNELS];
57 static  BitHolder                *scaleFactorsPH[MAX_GRANULES][MAX_CHANNELS];
58 static  BitHolder                   *codedDataPH[MAX_GRANULES][MAX_CHANNELS];
59 static  BitHolder                *userSpectrumPH[MAX_GRANULES][MAX_CHANNELS];
60 static  BitHolder               *userFrameDataPH;
61
62
63
64 static  BF_FrameData    sFrameData;
65 static  BF_FrameResults sFrameResults;
66
67
68
69
70
71 /*
72         III_format_bitstream()
73
74         This is called after a frame of audio has been quantized and coded.
75         It will write the encoded audio to the bitstream. Note that
76         from a layer3 encoder's perspective the bit stream is primarily
77         a series of main_data() blocks, with header and side information
78         inserted at the proper locations to maintain framing. (See Figure A.7
79         in the IS).
80 */
81
82 void                                    III_format_bitstream
83 (
84         int                                             bitsPerFrame,
85         frame_params                    *in_fr_ps,
86         int                                             l3_enc[2][2][576],
87         III_side_info_t                 *l3_side,
88         III_scalefac_t                  *scalefac,
89         double                                  (*xr)[2][576],
90         char                                    *ancillary,
91         int                                             ancillary_bits
92 )
93 {
94         int                                             gr, ch, i, mode_gr;
95
96         fr_ps = in_fr_ps;
97         stereo = fr_ps->stereo;
98         mode_gr = 2;
99
100         if (!PartHoldersInitialized)
101         {
102                  headerPH = initBitHolder (&sFrameData.header, 16*2);
103                 frameSIPH = initBitHolder (&sFrameData.frameSI, 4*2);
104
105                 for (ch = 0;  ch < MAX_CHANNELS;  ch++)
106                         channelSIPH[ch] = initBitHolder (&sFrameData.channelSI[ch], 8*2);
107
108                 for (gr = 0;  gr < MAX_GRANULES;  gr++)
109                 {
110                         for (ch = 0;  ch < MAX_CHANNELS;  ch++)
111                         {
112                                   spectrumSIPH[gr][ch] = initBitHolder (&sFrameData.  spectrumSI[gr][ch],  32*2);
113                                 scaleFactorsPH[gr][ch] = initBitHolder (&sFrameData.scaleFactors[gr][ch],  64*2);
114                                    codedDataPH[gr][ch] = initBitHolder (&sFrameData.   codedData[gr][ch], 576*2);
115                                 userSpectrumPH[gr][ch] = initBitHolder (&sFrameData.userSpectrum[gr][ch],   4*2);
116                         }
117                 }
118                 userFrameDataPH = initBitHolder (&sFrameData.userFrameData, 8*2);
119
120                 PartHoldersInitialized = 1;
121         }
122
123 #if 1
124         for (gr = 0;  gr < mode_gr;  gr++)
125         {
126                 for (ch = 0;  ch < stereo;  ch++)
127                 {
128                         int                                             *pi = &l3_enc[gr][ch][0];
129                         double                                  *pr =     &xr[gr][ch][0];
130
131                         for (i = 0;  i < 576;  i++, pr++, pi++)
132                                 if (*pr < 0  &&  *pi > 0)
133                                         *pi *= -1;
134                 }
135         }
136 #endif
137
138         encodeSideInfo (l3_side);
139         encodeMainData (l3_enc, l3_side, scalefac);
140         write_ancillary_data (ancillary, ancillary_bits);
141
142         if (l3_side->resvDrain)
143                 drain_into_ancillary_data (l3_side->resvDrain);
144
145         sFrameData.frameLength = bitsPerFrame;
146         sFrameData.nGranules   = mode_gr;
147         sFrameData.nChannels   = stereo;
148
149         writeFrame (&sFrameData, &sFrameResults);
150
151         /* we set this here -- it will be tested in the next loops iteration */
152         l3_side->main_data_begin = sFrameResults.nextBackPtr;
153 }
154
155
156
157
158
159 void                                    III_FlushBitstream (void)
160 {
161         int                                             gr, ch;
162
163         if (PartHoldersInitialized)
164         {
165                 exitBitHolder (&sFrameData.header);
166                 exitBitHolder (&sFrameData.frameSI);
167
168                 for (ch = 0;  ch < MAX_CHANNELS;  ch++)
169                         exitBitHolder (&sFrameData.channelSI[ch]);
170
171
172                 for (gr = 0;  gr < MAX_GRANULES;  gr++)
173                 {
174                         for (ch = 0;  ch < MAX_CHANNELS;  ch++)
175                         {
176                                 exitBitHolder (&sFrameData.  spectrumSI[gr][ch]);
177                                 exitBitHolder (&sFrameData.scaleFactors[gr][ch]);
178                                 exitBitHolder (&sFrameData.   codedData[gr][ch]);
179                                 exitBitHolder (&sFrameData.userSpectrum[gr][ch]);
180                         }
181                 }
182                 exitBitHolder (&sFrameData.userFrameData);
183
184                 PartHoldersInitialized = 0;
185         }
186
187         /* BF_FlushBitstream (frameData, frameResults); */
188 }
189
190
191
192
193
194 static  unsigned                slen1_tab[16] = { 0, 0, 0, 0, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4 };
195 static  unsigned                slen2_tab[16] = { 0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 3 };
196
197
198
199
200
201 static  void                    encodeMainData
202 (
203         int                                             l3_enc[2][2][576],
204         III_side_info_t                 *side_info,
205         III_scalefac_t                  *scalefac
206 )
207 {
208         int                                             gr, ch, sfb, b, mode_gr;
209
210         mode_gr = 2;
211
212
213         for (gr = 0;  gr < mode_gr;  gr++)
214                 for (ch = 0;  ch < stereo;  ch++)
215                         scaleFactorsPH[gr][ch]->nrEntries = 0;
216
217
218         for (gr = 0;  gr < mode_gr;  gr++)
219                 for (ch = 0;  ch < stereo;  ch++)
220                         codedDataPH[gr][ch]->nrEntries = 0;
221
222
223         for (gr = 0;  gr < 2;  gr++)
224         {
225                 for (ch = 0;  ch < stereo;  ch++)
226                 {
227                         BitHolder                               *ph = scaleFactorsPH[gr][ch];           
228                         gr_info                                 *cod_info = &side_info->gr[gr].ch[ch].tt;
229                         unsigned                                slen1 = slen1_tab[cod_info->scalefac_compress];
230                         unsigned                                slen2 = slen2_tab[cod_info->scalefac_compress];
231                         int                                             *ix = &l3_enc[gr][ch][0];
232
233                         if (cod_info->window_switching_flag  &&  cod_info->block_type == SHORT_TYPE)
234                         {
235                                 if (cod_info->mixed_block_flag)
236                                 {
237                                         for (sfb = 0;  sfb < 8;  sfb++)
238                                                 addBits (ph, scalefac->l[gr][ch][sfb], slen1);
239
240                                         for (sfb = 3;  sfb < 6;  sfb++)
241                                                 for (b = 0;  b < 3;  b++)
242                                                         addBits (ph, scalefac->s[gr][ch][sfb][b], slen1);
243                                 }
244                                 else
245                                 {
246                                         for (sfb = 0;  sfb < 6;  sfb++)
247                                                 for (b = 0;  b < 3;  b++)
248                                                         addBits (ph, scalefac->s[gr][ch][sfb][b], slen1);
249                                 }
250
251                                 for (sfb = 6;  sfb < 12;  sfb++)
252                                         for (b = 0;  b < 3;  b++)
253                                                 addBits (ph, scalefac->s[gr][ch][sfb][b], slen2);
254                         }
255                         else if (gr == 0)
256                         {
257                                 for (sfb = 0;  sfb < 11;  sfb++)
258                                         addBits (ph, scalefac->l[gr][ch][sfb], slen1);
259
260                                 for (sfb = 11;  sfb < 21;  sfb++)
261                                         addBits (ph, scalefac->l[gr][ch][sfb], slen2);
262                         }
263                         else
264                         {
265                                 if (!side_info->scfsi[ch][0])
266                                         for (sfb = 0;  sfb < 6;  sfb++)
267                                                 addBits (ph, scalefac->l[gr][ch][sfb], slen1);
268
269                                 if (!side_info->scfsi[ch][1])
270                                         for (sfb = 6;  sfb < 11;  sfb++)
271                                                 addBits (ph, scalefac->l[gr][ch][sfb], slen1);
272
273                                 if (!side_info->scfsi[ch][2])
274                                         for (sfb = 11;  sfb < 16;  sfb++)
275                                                 addBits (ph, scalefac->l[gr][ch][sfb], slen2);
276
277                                 if (!side_info->scfsi[ch][3])
278                                         for (sfb = 16;  sfb < 21;  sfb++)
279                                                 addBits (ph, scalefac->l[gr][ch][sfb], slen2);
280                         }
281
282                         Huffmancodebits (codedDataPH[gr][ch], ix, cod_info);
283                 } /* for ch */
284         } /* for gr */
285 } /* main_data */
286
287
288
289
290
291 /*____ encodeSideInfo() _____________________________________________________*/
292
293 static  int                             encodeSideInfo (III_side_info_t *side_info)
294 {
295         int                                             gr, ch, scfsi_band, region, b, bits_sent, mode_gr;
296         layer                                   *info = fr_ps->header;
297
298         mode_gr =  2;
299
300
301         headerPH->nrEntries = 0;
302
303         addBits (headerPH, 0xfff                   , 12);
304         addBits (headerPH, 1                       ,  1);
305         addBits (headerPH, 4 - 3                   ,  2);   /* 4 - Layer */
306         addBits (headerPH, !info->error_protection ,  1);
307         addBits (headerPH, info->bitrate_index     ,  4);
308         addBits (headerPH, info->sampling_frequency,  2);
309         addBits (headerPH, info->padding           ,  1);
310         addBits (headerPH, info->extension         ,  1);
311         addBits (headerPH, info->mode              ,  2);
312         addBits (headerPH, info->mode_ext          ,  2);
313         addBits (headerPH, info->copyright         ,  1);
314         addBits (headerPH, info->original          ,  1);
315         addBits (headerPH, info->emphasis          ,  2);
316
317         bits_sent = 32;
318
319         if (info->error_protection)
320         {
321                 addBits (headerPH, 0, 16);   /* Just a dummy add. Real CRC calculated & inserted in writeSideInfo() */
322                 bits_sent += 16;
323         }
324
325
326         frameSIPH->nrEntries = 0;
327
328         addBits (frameSIPH, side_info->main_data_begin, 9);
329
330         if (stereo == 2)
331                 addBits (frameSIPH, side_info->private_bits, 3);
332         else
333                 addBits (frameSIPH, side_info->private_bits, 5);
334
335
336         for (ch = 0;  ch < stereo;  ch++)
337         {
338                 BitHolder                               *ph = channelSIPH[ch];
339
340                 ph->nrEntries = 0;
341
342                 for (scfsi_band = 0;  scfsi_band < 4;  scfsi_band++)
343                         addBits (ph, side_info->scfsi[ch][scfsi_band], 1);
344         }
345
346
347         for (gr = 0;  gr < 2;  gr++)
348         {
349                 for (ch = 0;  ch < stereo;  ch++)
350                 {
351                         BitHolder                               *ph = spectrumSIPH[gr][ch];
352                         gr_info                                 *cod_info = &side_info->gr[gr].ch[ch].tt;
353
354                         ph->nrEntries = 0;
355
356                         addBits (ph, cod_info->part2_3_length       , 12);
357                         addBits (ph, cod_info->big_values           ,  9);
358                         addBits (ph, cod_info->global_gain          ,  8);
359                         addBits (ph, cod_info->scalefac_compress    ,  4);
360                         addBits (ph, cod_info->window_switching_flag,  1);
361
362                         if (cod_info->window_switching_flag)
363                         {   
364                                 addBits (ph, cod_info->block_type      , 2);
365                                 addBits (ph, cod_info->mixed_block_flag, 1);
366
367                                 for (region = 0; region < 2; region++)
368                                         addBits (ph, cod_info->table_select[region], 5);
369
370                                 for (b = 0;  b < 3;  b++)
371                                         addBits (ph, cod_info->subblock_gain[b], 3);
372                         }
373                         else
374                         {
375                                 for (region = 0; region < 3; region++)
376                                         addBits (ph, cod_info->table_select[region], 5);
377
378                                 addBits (ph, cod_info->region0_count, 4);
379                                 addBits (ph, cod_info->region1_count, 3);
380                         }
381
382                         addBits (ph, cod_info->preflag           , 1);
383                         addBits (ph, cod_info->scalefac_scale    , 1);
384                         addBits (ph, cod_info->count1table_select, 1);
385                 }
386         }
387
388
389         if (stereo == 2)
390                 bits_sent += 256;
391         else
392                 bits_sent += 136;
393
394
395         return bits_sent;
396 }
397
398
399
400
401
402 /*____ write_ancillary_data() _______________________________________________*/
403
404 static  void                    write_ancillary_data
405 (
406         char                                    *theData,
407         int                                             lengthInBits
408 )
409 {
410         int                                             bytesToSend   = lengthInBits / 8;
411         int                                             remainingBits = lengthInBits % 8;
412         unsigned                                wrd;
413
414         userFrameDataPH->nrEntries = 0;
415
416         while (bytesToSend--)
417         {
418                 wrd = *theData++;
419                 addBits (userFrameDataPH, wrd, 8);
420         }
421         if (remainingBits)
422         {
423                 /* right-justify remaining bits */
424                 wrd = *theData >> (8 - remainingBits);
425                 addBits (userFrameDataPH, wrd, remainingBits);
426         }
427 }
428
429
430
431
432
433 /*
434         Some combinations of bitrate, Fs, and stereo make it impossible to stuff
435         out a frame using just main_data, due to the limited number of bits to
436         indicate main_data_length. In these situations, we put stuffing bits into
437         the ancillary data...
438 */
439 static  void                    drain_into_ancillary_data (int lengthInBits)
440 {
441         int                                             wordsToSend   = lengthInBits / 32;
442         int                                             remainingBits = lengthInBits % 32;
443
444         /*
445                 userFrameDataPH->part->nrEntries set by call to write_ancillary_data()
446         */
447
448         while (wordsToSend--)
449                 addBits (userFrameDataPH, 0, 32);
450         if (remainingBits)
451                 addBits (userFrameDataPH, 0, remainingBits); 
452 }
453
454
455
456
457
458 /*
459         Note the discussion of huffmancodebits() on pages 28
460         and 29 of the IS, as well as the definitions of the side
461         information on pages 26 and 27.
462 */
463 static  void                    Huffmancodebits
464 (
465         BitHolder                               *ph,
466         int                                             *ix,
467         gr_info                                 *cod_info
468 )
469 {
470         int                                             sfb, window, line, start, end;
471         int                                             stuffingBits, table;
472
473         int                                             bitsWritten = 0;
474         int                                             bigvalues   = cod_info->big_values * 2;
475
476
477         /*
478                 Within each scalefactor band, data is given for successive time windows,
479                 beginning with window 0 and ending with window 2 (in case of short blocks!
480                 --- there is only one long block window). Within each window, the quantized
481                 values are then arranged in order of increasing frequency...
482         */
483
484         /* 1: Write the bigvalues */
485         if (bigvalues)
486         {
487                 if (cod_info->window_switching_flag  &&  (cod_info->block_type == SHORT_TYPE))
488                 {
489                         int                                                     (*ix_s)[3] = (int (*)[3]) ix;
490                         int                                                     *scalefac = &sfBandIndex[fr_ps->header->sampling_frequency].s[0];
491
492                         table = cod_info->table_select[0];
493                         if (table)
494                         {
495                                 if (cod_info->mixed_block_flag)  /* Mixed blocks long, short */
496                                 {
497                                         for (line=0; line<36; line+=2)   /* cod_info->address1 = 36 */
498                                                 bitsWritten += writeHuffmanCode (ph, table, ix[line], ix[line+1]);
499                                 }
500                                 else
501                                 {
502                                         for (sfb=0; sfb<3; sfb++)   /* (cod_info->region0_count + 1) / 3 = 3 */
503                                         {
504                                                 start = scalefac[sfb];
505                                                 end   = scalefac[sfb+1];
506
507                                                 for (window=0; window<3; window++)
508                                                         for (line=start; line<end; line+=2)
509                                                                 bitsWritten += writeHuffmanCode (ph, table, ix_s[line][window], ix_s[line+1][window]);
510                                         }
511                                 }
512                         }
513
514                         table = cod_info->table_select[1];
515                         if (table)
516                         {
517                                 for (sfb=3; sfb<SFB_SMAX; sfb++)   /* scalefac[3] = 12 --- 12*3 = 36 */
518                                 {
519                                         start = scalefac[sfb];
520                                         end   = scalefac[sfb+1]; 
521
522                                         for (window=0; window<3; window++)
523                                                 for (line=start; line<end; line+=2)
524                                                         bitsWritten += writeHuffmanCode (ph, table, ix_s[line][window], ix_s[line+1][window]);
525                                 }
526                         }
527                 }
528                 else   /* Long blocks */
529                 {
530                         int                                                     region1Start = (cod_info->address1 > bigvalues) ? bigvalues : cod_info->address1;
531                         int                                                     region2Start = (cod_info->address2 > bigvalues) ? bigvalues : cod_info->address2;
532
533                         table = cod_info->table_select[0];
534                         if (table)
535                                 for (line=0; line<region1Start; line+=2)
536                                         bitsWritten += writeHuffmanCode (ph, table, ix[line], ix[line+1]);
537
538                         table = cod_info->table_select[1];
539                         if (table)
540                                 for (line=region1Start; line<region2Start; line+=2)
541                                         bitsWritten += writeHuffmanCode (ph, table, ix[line], ix[line+1]);
542
543                         table = cod_info->table_select[2];
544                         if (table)
545                                 for (line=region2Start; line<bigvalues; line+=2)
546                                         bitsWritten += writeHuffmanCode (ph, table, ix[line], ix[line+1]);
547                 }
548         }
549
550         /* 2: Write count1 area */
551         if (cod_info->count1)
552         {
553                 struct huffcodetab              *h = ht + (cod_info->count1table_select + 32);
554
555                 int                                             *pos = ix + bigvalues;
556                 int                                             *end = ix + bigvalues + (cod_info->count1 * 4);
557
558                 while (pos < end)
559                 {
560                         int                                             len, v, w, x, y;
561                         int                                             bits = 0;
562                         int                                             p    = 0;
563
564                         v = *pos++;  if (v)  bits++, p |= 1;
565                         w = *pos++;  if (w)  bits++, p |= 2;
566                         x = *pos++;  if (x)  bits++, p |= 4;
567                         y = *pos++;  if (y)  bits++, p |= 8;
568
569                         addBits (ph, h->table[p], len = h->hlen[p]);
570
571                         if (v)  addBits (ph, v<0, 1);
572                         if (w)  addBits (ph, w<0, 1);
573                         if (x)  addBits (ph, x<0, 1);
574                         if (y)  addBits (ph, y<0, 1);
575
576                         bitsWritten += bits+len;
577                 }
578         }
579
580
581         stuffingBits = cod_info->part2_3_length - cod_info->part2_length - bitsWritten;
582         if (stuffingBits)
583         {
584                 int                                             stuffingWords = stuffingBits / 32;
585                 int                                             remainingBits = stuffingBits % 32;
586
587                 /*
588                         Due to the nature of the Huffman code
589                         tables, we will pad with ones
590                 */
591                 while (stuffingWords--)
592                         addBits (ph, ~0, 32);
593                 if (remainingBits)
594                         addBits (ph, ~0, remainingBits);
595
596                 bitsWritten += stuffingBits;
597         }
598 }
599
600
601
602
603
604 /*
605         Implements the pseudocode of page 98 of the IS
606
607         aaaaaaaaaaaaaaargh --- why don«t write the code immediately?
608 */
609
610 static  int                             writeHuffmanCode
611 (
612         BitHolder                               *ph,
613         int                                             table,
614         int                                             x,
615         int                                             y
616 )
617 {
618         struct huffcodetab              *h = ht + table;
619
620         unsigned                                signx = (x <= 0) ? (x = -x, 1) : 0;
621         unsigned                                signy = (y <= 0) ? (y = -y, 1) : 0;
622
623         unsigned                                code, cbits, idx;
624
625 assert (table);
626 /*
627         if (table == 0)
628                 return 0;
629 */
630
631         if (table > 15)   /* ESC-table is used */
632         {
633                 unsigned                                linbits = h->linbits;
634                 unsigned                                ext     = 0;
635                 unsigned                                xbits   = 0;
636
637                 if (x)  {if (x > 14)  {ext =                    (x-15);  xbits += linbits;  x = 15;}  ext = (ext << 1) | signx;  xbits++;}
638                 if (y)  {if (y > 14)  {ext = (ext << linbits) | (y-15);  xbits += linbits;  y = 15;}  ext = (ext << 1) | signy;  xbits++;}
639
640                 idx   = x * h->ylen + y;
641                 code  = h->table[idx];
642                 cbits = h->hlen[idx];
643
644                 addBits (ph, code, cbits);
645                 addBits (ph, ext , xbits);
646
647                 return cbits + xbits;
648         }
649         else   /* No ESC-words */
650         {
651                 idx   = x * h->ylen + y;
652                 code  = h->table[idx];
653                 cbits = h->hlen[idx];
654
655                 if (x)  {code = (code << 1) | signx;  cbits++;}
656                 if (y)  {code = (code << 1) | signy;  cbits++;}
657
658                 addBits (ph, code, cbits);
659
660                 return cbits;
661         }
662 }
663
664
665