b0eb290976dd8009cf7913798e37c8c1ac35d2c7
[goodguy/cinelerra.git] / cinelerra-5.1 / libzmpeg3 / audio / layer3.C
1 #include "../libzmpeg3.h"
2
3 int zaudio_decoder_layer_t::
4 get_scale_factors_1(int *scf, l3_info_t *l3_info, int ch, int gr)
5 {
6   static uint8_t slen[2][16] = 
7     {{0, 0, 0, 0, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4},
8      {0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 3}};
9   int i, numbits;
10   int num0 = slen[0][l3_info->scalefac_compress];
11   int num1 = slen[1][l3_info->scalefac_compress];
12   if( l3_info->block_type == 2 ) {
13     i = 18;
14     numbits = (num0 + num1) * 18;
15
16     if( l3_info->mixed_block_flag ) {
17       for( ; --i>9; ) *scf++ = stream->get_bits(num0);
18       /* num0*17 + num1*18 */
19       numbits -= num0; 
20     }
21     while( --i >= 0 ) *scf++ = stream->get_bits(num0);
22     for( i=18; --i>=0; ) *scf++ = stream->get_bits(num1);
23     /* short[13][0..2] = 0 */
24     *scf++ = 0; *scf++ = 0; *scf++ = 0; 
25   }
26   else {
27     int scfsi = l3_info->scfsi;
28     if( scfsi < 0 ) { 
29       /* scfsi < 0 => granule == 0 */
30       for( i=11; --i>=0; ) *scf++ = stream->get_bits(num0);
31       for( i=10; --i>=0; ) *scf++ = stream->get_bits(num1);
32       numbits = (num0 + num1) * 10 + num0;
33       *scf++ = 0;
34     }
35     else {
36       numbits = 0;
37       if( !(scfsi & 0x8) ) {
38         for( i=6; --i>=0; ) *scf++ = stream->get_bits(num0);
39         numbits += num0 * 6;
40       }
41       else
42         scf += 6; 
43       if( !(scfsi & 0x4) ) {
44         for( i=5; --i>=0; ) *scf++ = stream->get_bits(num0);
45         numbits += num0 * 5;
46       }
47       else 
48         scf += 5;
49       if(!(scfsi & 0x2)) {
50         for( i=5; --i>=0; ) *scf++ = stream->get_bits(num1);
51         numbits += num1 * 5;
52       }
53       else
54         scf += 5; 
55       if( !(scfsi & 0x1) ) {
56         for( i=5; --i>=0; ) *scf++ = stream->get_bits(num1);
57         numbits += num1 * 5;
58       }
59       else
60         scf += 5;
61       *scf++ = 0;  /* no l[21] in original sources */
62     }
63   }
64   return numbits;
65 }
66
67 int zaudio_decoder_layer_t::
68 get_scale_factors_2(int *scf, l3_info_t *l3_info, int i_stereo)
69 {
70   int i, j;
71   static uint8_t stab[3][6][4] = 
72     {{{ 6, 5, 5,5 }, { 6, 5, 7,3 }, { 11,10,0,0},
73       { 7, 7, 7,0 }, { 6, 6, 6,3 }, {  8, 8,5,0}},
74      {{ 9, 9, 9,9 }, { 9, 9,12,6 }, { 18,18,0,0},
75       {12,12,12,0 }, {12, 9, 9,6 }, { 15,12,9,0}},
76      {{ 6, 9, 9,9 }, { 6, 9,12,6 }, { 15,18,0,0},
77       { 6,15,12,0 }, { 6,12, 9,6 }, {  6,18,9,0}}}; 
78
79   /* i_stereo AND second channel -> do_layer3() checks this */
80   unsigned int slen = i_stereo ?
81     i_slen2[l3_info->scalefac_compress >> 1] :
82     n_slen2[l3_info->scalefac_compress];
83
84   l3_info->preflag = (slen >> 15) & 0x1;
85   int n = 0;
86   if( l3_info->block_type == 2 ) {
87     ++n;
88     if( l3_info->mixed_block_flag ) ++n ;
89   }
90   uint8_t *pnt = stab[n][(slen >> 12) & 0x7];
91   int numbits = 0;
92   for( i=0; i<4; ++i ) {
93     int num = slen & 0x7;
94     slen >>= 3;
95     if( num ) {
96       for( j=(int)pnt[i]; --j>=0; ) *scf++ = stream->get_bits(num);
97       numbits += pnt[i] * num;
98     }
99     else
100       for( j=(int)pnt[i]; --j>=0; ) *scf++ = 0;
101   }
102   
103   n = (n << 1) + 1;
104   for( i=0; i<n; ++i )
105     *scf++ = 0;
106
107   return numbits;
108 }
109
110 static int pretab1[22] = {0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,2,0};
111 static int pretab2[22] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
112
113 /*
114  * Dequantize samples (includes huffman decoding)
115  *
116  * 24 is enough because tab13 has max. a 19 bit huffvector
117  */
118
119 #define BITSHIFT ((int)(sizeof(int32_t)-1) * 8)
120 #define REFRESH_MASK if( num < BITSHIFT ) { \
121   if( -part2remain >= num ) break; \
122   do { \
123     mask |= stream->get_bits(8) << (BITSHIFT-num); \
124     num += 8; part2remain -= 8; \
125 } while( num < BITSHIFT ); }
126
127 int zaudio_decoder_layer_t::
128 dequantize_sample(float xr[SBLIMIT][SSLIMIT], int *scf,
129        l3_info_t *l3_info, int sfreq, int part2bits)
130 {
131   short a, *val;
132   float v, vv;
133   int i, l[3], cb, mc, *m, *me;
134   int shift = 1 + l3_info->scalefac_scale;
135   float *xrpnt = (float*)xr;
136   int part2remain = l3_info->part2_3_length - part2bits;
137   int num = stream->get_bit_offset();
138   int32_t mask = stream->get_bits(num);
139
140 //zmsgs("1 %08x %d\n", mask, num);
141   mask = mask << (BITSHIFT + 8 - num);
142   part2remain -= num;
143
144   int bv       = l3_info->big_values;
145   int region1  = l3_info->region1start;
146   int region2  = l3_info->region2start;
147   int l3 = ((576 >> 1) - bv) >> 1;   
148   /* we may lose the 'odd' bit here !!, check this later again */
149   if( bv <= region1 ) {
150     l[0] = bv; 
151     l[1] = l[2] = 0;
152   }
153   else {
154     l[0] = region1;
155     if( bv <= region2 ) {
156       l[1] = bv - l[0];  l[2] = 0;
157     }
158     else {
159       l[1] = region2 - l[0]; 
160       l[2] = bv - region2;
161     }
162   }
163  
164   if( l3_info->block_type == 2 ) {
165     /* decoding with short or mixed mode BandIndex table */
166     int max[4];
167     int step = 0;
168     int lwin = 3;
169     cb = 0;
170     v = 0.0;
171     if( l3_info->mixed_block_flag ) {
172       max[0] = max[1] = max[2] = 2;
173       max[3] = -1;
174       m = map[sfreq][0];
175       me = mapend[sfreq][0];
176     }
177     else {
178       /* max[3] not floatly needed in this case */
179       max[0] = max[1] = max[2] = max[3] = -1;
180       m = map[sfreq][1];
181       me = mapend[sfreq][1];
182     }
183
184     for( mc=i=0; i<2; ++i ) {
185       int lp = l[i];
186       huffman_t *h = ht + l3_info->table_select[i];
187       for( ; lp>0; --lp, --mc ) {
188         int x, y;
189         if( !mc ) {
190           mc    = *m++;
191           xrpnt = ((float*)xr) + (*m++);
192           lwin  = *m++;
193           cb    = *m++;
194           if( lwin == 3 ) {
195             v = l3_info->pow2gain[(*scf++) << shift];
196             step = 1;
197           }
198           else {
199             v = l3_info->full_gain[lwin][(*scf++) << shift];
200             step = 3;
201           }
202         }
203
204         val = h->table;
205         REFRESH_MASK;
206         while( (y=*val++) < 0) {
207           if( mask < 0 ) val -= y;
208           --num;
209           mask <<= 1;
210         }
211         x = y >> 4;
212         y &= 0xf;
213
214         if( x == 15 && h->linbits ) {
215           max[lwin] = cb;
216           REFRESH_MASK;
217           x += ((uint32_t)mask) >> (BITSHIFT + 8 - h->linbits);
218           num -= h->linbits + 1;
219           mask <<= h->linbits;
220           vv = ispow[x]*v;
221           *xrpnt = mask < 0 ? -vv : vv;
222           mask <<= 1;
223         }
224         else if( x != 0 ) {
225           max[lwin] = cb;
226           if( -part2remain >= num ) break;
227           vv = ispow[x]*v;
228           *xrpnt = mask < 0 ? -vv : vv;
229           --num;
230           mask <<= 1;
231         }
232         else
233           *xrpnt = 0.0;
234
235         xrpnt += step;
236         if( y == 15 && h->linbits ) {
237           max[lwin] = cb;
238           REFRESH_MASK;
239           y += ((uint32_t) mask) >> (BITSHIFT + 8 - h->linbits);
240           num -= h->linbits + 1;
241           mask <<= h->linbits;
242           vv = ispow[y]*v;
243           *xrpnt = mask < 0 ? -vv : vv;
244           mask <<= 1;
245         }
246         else if( y != 0 ) {
247           max[lwin] = cb;
248           if( -part2remain >= num ) break;
249           vv = ispow[y]*v;
250           *xrpnt = mask < 0 ? -vv : vv;
251           --num;
252           mask <<= 1;
253         }
254         else
255           *xrpnt = 0.0;
256         xrpnt += step;
257       }
258     }
259
260     for( ;l3 && -part2remain < num; l3--) {
261       huffman_t *h = htc + l3_info->count1table_select;
262       val = h->table;
263
264       REFRESH_MASK;
265       while( (a=*val++) < 0) {
266         if( mask < 0 ) val -= a;
267         --num;
268         mask <<= 1;
269       }
270
271       for( i=0; i<4; ++i ) {
272         if( !(i & 1) ) {
273           if( !mc ) {
274             mc = *m++;
275             xrpnt = ((float*)xr) + (*m++);
276             lwin = *m++;
277             cb = *m++;
278             if( lwin == 3 ) {
279               v = l3_info->pow2gain[(*scf++) << shift];
280               step = 1;
281             }
282             else {
283               v = l3_info->full_gain[lwin][(*scf++) << shift];
284               step = 3;
285             }
286           }
287           --mc;
288         }
289         if( (a & (0x8 >> i)) ) {
290           max[lwin] = cb;
291           if( -part2remain >= num ) break;
292           *xrpnt = mask < 0 ?  -v : v;
293           --num;
294           mask <<= 1;
295         }
296         else
297           *xrpnt = 0.0;
298         xrpnt += step;
299       }
300     }
301
302     if( lwin < 3 ) { /* short band? */
303       for(;;) {
304         while( --mc >= 0 ) {
305           /* short band -> step=3 */
306           *xrpnt = 0.0; xrpnt += 3; 
307           *xrpnt = 0.0; xrpnt += 3;
308         }
309         if( m >= me ) break;
310         mc = *m++;
311         xrpnt = ((float*)xr) + *m++;
312         /* optimize: field will be set to zero at the end of the function */
313         if( *m++ == 0 ) break; 
314         /* cb */
315         ++m; 
316       }
317     }
318
319     l3_info->maxband[0] = max[0] + 1;
320     l3_info->maxband[1] = max[1] + 1;
321     l3_info->maxband[2] = max[2] + 1;
322     l3_info->maxbandl = max[3] + 1;
323     int rmax = max[0] > max[1] ? max[0] : max[1];
324     rmax = (rmax > max[2] ? rmax : max[2]) + 1;
325     l3_info->maxb = rmax ?
326       shortLimit[sfreq][rmax] :
327       longLimit[sfreq][max[3] + 1];
328   }
329   else {
330     /* decoding with 'long' BandIndex table (block_type != 2) */
331     int *pretab = l3_info->preflag ? pretab1 : pretab2;
332     int max = -1;
333     cb = 0;
334     m = map[sfreq][2];
335     v = 0.0;
336     mc = 0;
337     /* long hash table values */
338     for( i=0; i<3; ++i ) {
339       int lp = l[i];
340       huffman_t *h = ht + l3_info->table_select[i];
341       for( ; lp>0; --lp, --mc ) {
342         int x, y;
343         if( !mc ) {
344           mc = *m++;
345           cb = *m++;
346           v = cb != 21 ?
347             l3_info->pow2gain[(*scf++ + *pretab++) << shift] : 0.0;
348         }
349         val = h->table;
350         REFRESH_MASK;
351         while( (y=*val++) < 0 ) {
352           if( mask < 0 ) val -= y;
353           --num;
354           mask <<= 1;
355         }
356         x = y >> 4;
357         y &= 0x0f;
358
359         if( x == 15 && h->linbits ) {
360           max = cb;
361           REFRESH_MASK;
362           x += ((uint32_t) mask) >> (BITSHIFT + 8 - h->linbits);
363           num -= h->linbits + 1;
364           mask <<= h->linbits;
365           vv = ispow[x]*v;
366           *xrpnt++ = mask < 0 ? -vv : vv;
367           mask <<= 1;
368         }
369         else if( x ) {
370           max = cb;
371           if( -part2remain >= num ) break;
372           vv = ispow[x]*v;
373           *xrpnt++ = mask < 0 ? -vv : vv;
374           --num;
375           mask <<= 1;
376         }
377         else
378           *xrpnt++ = 0.0;
379
380         if( y == 15 && h->linbits ) {
381           max = cb;
382           REFRESH_MASK;
383           y += ((uint32_t) mask) >> (BITSHIFT + 8 - h->linbits);
384           num -= h->linbits + 1;
385           mask <<= h->linbits;
386           vv = ispow[y]*v;
387           *xrpnt++ = mask < 0 ? -vv : vv;
388           mask <<= 1;
389         }
390         else if( y != 0 ) {
391           max = cb;
392           if( -part2remain >= num ) break;
393           vv = ispow[y]*v;
394           *xrpnt++ = mask < 0 ? -vv : vv;
395           --num;
396           mask <<= 1;
397         }
398         else
399           *xrpnt++ = 0.0;
400       }
401     }
402
403     /* short (count1table) values */
404     for( ; l3 && -part2remain < num; l3-- ) {
405       huffman_t *h = htc + l3_info->count1table_select;
406       val = h->table;
407       REFRESH_MASK;
408       while( (a=*val++) < 0) {
409         if( mask < 0 ) val -= a;
410         --num;
411         mask <<= 1;
412       }
413
414       for( i=0; i<4; ++i ) {
415         if( !(i & 1) ) {
416           if( !mc ) {
417             mc = *m++;
418             cb = *m++;
419             v =  cb != 21 ?
420               l3_info->pow2gain[((*scf++) + (*pretab++)) << shift] : 0.0;
421           }
422           --mc;
423         }
424         if( (a & (0x8 >> i)) ) {
425           max = cb;
426           if( -part2remain >= num ) break;
427           *xrpnt++ = mask < 0 ? -v : v;
428           --num;
429           mask <<= 1;
430         }
431         else
432           *xrpnt++ = 0.0;
433       }
434     }
435
436     l3_info->maxbandl = max + 1;
437     l3_info->maxb = longLimit[sfreq][l3_info->maxbandl];
438   }
439
440   while( xrpnt < &xr[SBLIMIT][0] ) *xrpnt++ = 0.0;
441
442   if( -part2remain > num )
443     num = -part2remain;
444   part2remain += num;
445
446   if( num > 0 ) {
447     stream->start_reverse();
448     stream->get_bits_reverse(num);
449     stream->start_forward();
450   }
451
452 //zmsgs("3 %d %04x\n", stream->bit_number, stream->show_bits(16));
453   while( part2remain > 16 ) {
454     stream->get_bits(16); /* Dismiss stuffing Bits */
455     part2remain -= 16;
456   }
457
458   if( part2remain > 0 )
459     stream->get_bits(part2remain);
460   else if( part2remain < 0 ) {
461     zmsgs("can't rewind stream %d bits! data=%02x%02x%02x%02x\n", -part2remain,
462       (uint8_t)stream->input_ptr[-3], (uint8_t)stream->input_ptr[-2], 
463       (uint8_t)stream->input_ptr[-1], (uint8_t)stream->input_ptr[0]);
464     return 1; /* -> error */
465   }
466   return 0;
467 }
468
469 int zaudio_decoder_layer_t::
470 get_side_info(l3_sideinfo_t *si, int channels, int ms_stereo,
471     long sfreq, int single, int lsf)
472 {
473   int i, ch, gr;
474   int powdiff = (single == 3) ? 4 : 0;
475   static const int tabs[2][5] = { { 2,9,5,3,4 } , { 1,8,1,2,9 } };
476   const int *tab = tabs[lsf];
477
478   si->main_data_begin = stream->get_bits(tab[1]);
479   si->private_bits = stream->get_bits(channels == 1 ? tab[2] : tab[3]);
480   if( !lsf ) {
481     for( ch=0; ch<channels; ++ch ) {
482       si->ch[ch].gr[0].scfsi = -1;
483       si->ch[ch].gr[1].scfsi = stream->get_bits(4);
484     }
485   }
486
487   for( gr=0; gr<tab[0]; ++gr ) {
488     for( ch=0; ch<channels; ++ch ) {
489       l3_info_t *l3_info = &(si->ch[ch].gr[gr]);
490       l3_info->part2_3_length = stream->get_bits(12);
491       l3_info->big_values = stream->get_bits(9);
492       if( l3_info->big_values > 288 ) {
493         zerrs(" big_values too large! %d\n",l3_info->big_values);
494         l3_info->big_values = 288;
495       }
496       l3_info->pow2gain = gainpow2 + 256 - stream->get_bits(8) + powdiff;
497       if( ms_stereo ) l3_info->pow2gain += 2;
498       l3_info->scalefac_compress = stream->get_bits(tab[4]);
499
500       if(stream->get_bits(1)) {
501         /* window switch flag  */
502         l3_info->block_type       = stream->get_bits(2);
503         l3_info->mixed_block_flag = stream->get_bits(1);
504         l3_info->table_select[0]  = stream->get_bits(5);
505         l3_info->table_select[1]  = stream->get_bits(5);
506         /* table_select[2] not needed, because there is no region2, */
507         /* but to satisfy some verifications tools we set it either. */
508         l3_info->table_select[2] = 0;
509         for( i=0; i<3; ++i )
510           l3_info->full_gain[i] = l3_info->pow2gain + (stream->get_bits(3) << 3);
511
512         if( l3_info->block_type == 0 ) {
513           zerr("Blocktype == 0 and window-switching == 1 not allowed.\n");
514           return 1;
515         }
516         /* region_count/start parameters are implicit in this case. */       
517         if( !lsf || l3_info->block_type == 2 )
518           l3_info->region1start = 36 >> 1;
519         else {
520           /* check this again for 2.5 and sfreq=8 */
521           l3_info->region1start =  sfreq == 8 ? 108 >> 1 : 54 >> 1;
522         }
523         l3_info->region2start = 576 >> 1;
524       }
525       else {
526         int r0c, r1c;
527         for( i=0; i<3; ++i )
528           l3_info->table_select[i] = stream->get_bits(5);
529         r0c = stream->get_bits(4);
530         r1c = stream->get_bits(3);
531         l3_info->region1start = bandInfo[sfreq].longIdx[r0c + 1] >> 1 ;
532         l3_info->region2start = bandInfo[sfreq].longIdx[r0c + 1 + r1c + 1] >> 1;
533         l3_info->block_type = 0;
534         l3_info->mixed_block_flag = 0;
535       }
536       if( !lsf ) l3_info->preflag = stream->get_bits(1);
537       l3_info->scalefac_scale = stream->get_bits(1);
538       l3_info->count1table_select = stream->get_bits(1);
539     }
540   }
541   return 0;
542 }
543
544 int zaudio_decoder_layer_t::
545 hybrid( float fsIn[SBLIMIT][SSLIMIT], float tsOut[SSLIMIT][SBLIMIT],
546      int ch, l3_info_t *l3_info)
547 {
548   float *tspnt = (float *) tsOut;
549   float *rawout1,*rawout2;
550   int i, b, bt, sb;
551   int (*zdct)(float *inbuf, float *o1, float *o2, float *wintab, float *tsbuf);
552   
553   b = mp3_blc[ch];
554   rawout1 = mp3_block[b][ch];
555   b = -b + 1;
556   rawout2 = mp3_block[b][ch];
557   mp3_blc[ch] = b;
558   
559   sb = 0;
560   if( l3_info->mixed_block_flag ) {
561     sb = 2;
562     dct36(fsIn[0], rawout1, rawout2, win[0], tspnt);
563     dct36(fsIn[1], rawout1 + 18, rawout2 + 18, win1[0], tspnt + 1);
564     rawout1 += 36; rawout2 += 36; 
565     tspnt += 2;
566   }
567
568   bt = l3_info->block_type;
569   zdct = bt == 2 ? dct12 : dct36;
570   for( ; sb <(int)l3_info->maxb; sb+=2, tspnt+=2, rawout1+=36, rawout2+=36 ) {
571     zdct(fsIn[sb], rawout1, rawout2, win[bt], tspnt);
572     zdct(fsIn[sb + 1], rawout1 + 18, rawout2 + 18, win1[bt], tspnt + 1);
573   }
574
575   for( ; sb < (int)SBLIMIT; ++sb, ++tspnt ) {
576     for( i=0; i<(int)SSLIMIT; ++i ) {
577       tspnt[i * SBLIMIT] = *rawout1++;
578       *rawout2++ = 0.0;
579     }
580   }
581   return 0;
582 }
583
584 int zaudio_decoder_layer_t::
585 antialias(float xr[SBLIMIT][SSLIMIT], l3_info_t *l3_info)
586 {
587   int sblim;
588   if( l3_info->block_type == 2 ) {
589     if( !l3_info->mixed_block_flag ) return 0;
590     sblim = 1; 
591   }
592   else
593     sblim = l3_info->maxb-1;
594
595   /* 31 alias-reduction operations between each pair of sub-bands */
596   /* with 8 butterflies between each pair                         */
597
598   float *xr1 = (float*)xr[1];
599   for( int sb=sblim; sb > 0; --sb, xr1+=10 ) {
600     float *cs = aa_cs;
601     float *ca = aa_ca;
602     float *xr2 = xr1;
603     for( int ss=8; --ss>=0;) {
604       /* upper and lower butterfly inputs */
605       float bu = *--xr2;
606       float bd = *xr1;
607       *xr2   = (bu * (*cs)   ) - (bd * (*ca)   );
608       *xr1++ = (bd * (*cs++) ) + (bu * (*ca++) );
609     }
610   }
611   return 0;
612 }
613
614 /* 
615  * calculate float channel values for Joint-I-Stereo-mode
616  */
617 int zaudio_decoder_layer_t::
618 calc_i_stereo(float xr_buf[2][SBLIMIT][SSLIMIT], int *scalefac,
619        l3_info_t *l3_info, int sfreq, int ms_stereo, int lsf)
620 {
621   float (*xr)[SBLIMIT*SSLIMIT] = (float (*)[SBLIMIT*SSLIMIT])xr_buf;
622   struct bandInfoStruct *bi = &bandInfo[sfreq];
623   static const float *tabs[3][2][2] = { /* TODO: optimize as static */
624     { { tan1_1, tan2_1 }       , { tan1_2, tan2_2 } },
625     { { pow1_1[0], pow2_1[0] } , { pow1_2[0], pow2_2[0] } } ,
626     { { pow1_1[1], pow2_1[1] } , { pow1_2[1], pow2_2[1] } } 
627   };
628
629   int tab = lsf + (l3_info->scalefac_compress & lsf);
630   const float *tab1 = tabs[tab][ms_stereo][0];
631   const float *tab2 = tabs[tab][ms_stereo][1];
632   if( l3_info->block_type == 2 ) {
633     int lwin,do_l = 0;
634     if( l3_info->mixed_block_flag ) do_l = 1;
635     for(lwin = 0; lwin < 3; lwin++) { 
636       /* process each window */
637       /* get first band with zero values */
638       /* sfb is minimal 3 for mixed mode */
639       int is_p, sb, idx, sfb = l3_info->maxband[lwin];  
640       if(sfb > 3) do_l = 0;
641
642       for( ; sfb < 12 ; ++sfb ) {
643         /* scale: 0-15 */ 
644         is_p = scalefac[sfb * 3 + lwin - l3_info->mixed_block_flag]; 
645         if( is_p != 7 ) {
646           sb  = bi->shortDiff[sfb];
647           idx = bi->shortIdx[sfb] + lwin;
648           float t1  = tab1[is_p]; 
649           float t2 = tab2[is_p];
650           for( ; sb > 0; --sb, idx+=3 ) {
651             float v = xr[0][idx];
652             xr[0][idx] = v * t1;
653             xr[1][idx] = v * t2;
654           }
655         }
656       }
657
658       /* in the original: copy 10 to 11, */
659       /*  here: copy 11 to 12 maybe still wrong??? (copy 12 to 13?) */
660       /* scale: 0-15 */
661       is_p = scalefac[11 * 3 + lwin - l3_info->mixed_block_flag]; 
662       sb   = bi->shortDiff[12];
663       idx  = bi->shortIdx[12] + lwin;
664       if( is_p != 7 ) {
665         float t1, t2;
666         t1 = tab1[is_p]; 
667         t2 = tab2[is_p];
668         for( ; sb > 0; --sb, idx+=3 ) {  
669           float v = xr[0][idx];
670           xr[0][idx] = v * t1;
671           xr[1][idx] = v * t2;
672         }
673       }
674     } /* end for(lwin; .. ; . ) */
675
676     /* also check l-part, if ALL bands in the three windows are 'empty' */
677     /*  and mode = mixed_mode */
678     if( do_l ) {
679       int sfb = l3_info->maxbandl;
680       int idx = bi->longIdx[sfb];
681
682       for ( ; sfb < 8; ++sfb ) {
683         int sb = bi->longDiff[sfb];
684         /* scale: 0-15 */
685         int is_p = scalefac[sfb]; 
686         if( is_p != 7 ) {
687           float t1, t2;
688           t1 = tab1[is_p]; 
689           t2 = tab2[is_p];
690           for( ; sb > 0; sb--, idx++) {
691             float v = xr[0][idx];
692             xr[0][idx] = v * t1;
693             xr[1][idx] = v * t2;
694           }
695         }
696         else 
697           idx += sb;
698       }
699     }     
700   } 
701   else { /* ((l3_info->block_type != 2)) */
702     int sfb = l3_info->maxbandl;
703     int is_p, idx = bi->longIdx[sfb];
704     for( ; sfb < 21; sfb++) {
705       int sb = bi->longDiff[sfb];
706       /* scale: 0-15 */
707       is_p = scalefac[sfb]; 
708       if( is_p != 7 ) {
709         float t1 = tab1[is_p]; 
710         float t2 = tab2[is_p];
711         for( ; sb > 0; --sb, ++idx ) {
712           float v = xr[0][idx];
713           xr[0][idx] = v * t1;
714           xr[1][idx] = v * t2;
715         }
716       }
717       else
718         idx += sb;
719     }
720
721     is_p = scalefac[20];
722     if(is_p != 7) {  
723       /* copy l-band 20 to l-band 21 */
724       float t1 = tab1[is_p];
725       float t2 = tab2[is_p]; 
726       for( int sb=bi->longDiff[21]; sb > 0; --sb, ++idx ) {
727         float v = xr[0][idx];
728         xr[0][idx] = v * t1;
729         xr[1][idx] = v * t2;
730       }
731     }
732   } /* ... */
733
734   return 0;
735 }
736
737 int zaudio_decoder_layer_t::
738 do_layer3(uint8_t *zframe, int zframe_size, float **zoutput, int render)
739 {
740   float *in0, *in1;
741   int i, n, gr, ch, ss;
742   /* max 39 for short[13][3] mode, mixed: 38, long: 22 */
743   int scalefacs[2][39]; 
744   l3_sideinfo_t sideinfo;
745   int ms_stereo, i_stereo;
746   int sfreq = sampling_frequency_code;
747   int stereo1, granules;
748   int output_offset = 0;
749
750 //zmsg("1\n");
751   zframe += 4; /* Skip header */
752   zframe_size -= 4;
753
754   /* flip/init buffer */
755   bsbuf = &bsspace[bsnum][512];
756   bsnum ^= 1;
757   /* Copy frame into history buffer */
758   memcpy(bsbuf, zframe, zframe_size);
759 //zmsgs(" %d %02x%02x%02x%02x\n", first_frame, 
760 // (uint8_t)bsbuf[0], (uint8_t)bsbuf[1], (uint8_t)bsbuf[2], (uint8_t)bsbuf[3]);
761
762   int prev_len = -1;
763   uint8_t *ptr = 0;
764   if( !first_frame ) {
765     /* Set up bitstream to use buffer */
766     stream->use_ptr(bsbuf);
767 //zmsgs(" 7 %x\n", stream->show_bits(16));
768     /* CRC must be skipped here for proper alignment with the backstep */
769     if( error_protection ) stream->get_bits(16);
770 //zmsgs(" 8 %x\n", stream->show_bits(16));
771     if( channels == 1 ) { /* stream is mono */
772       stereo1 = 1;
773       single = 0;
774     }
775     else { /* Stereo */
776       stereo1 = 2;
777     }
778
779     if( mode == md_JOINT_STEREO ) {
780       ms_stereo = (mode_ext & 0x2) >> 1;
781       i_stereo  = mode_ext & 0x1;
782     }
783     else
784       ms_stereo = i_stereo = 0;
785     granules = lsf ? 1 : 2;
786 //zmsg(" 6\n");
787     if( get_side_info(&sideinfo, channels, ms_stereo, sfreq, single, lsf) ) {
788       layer_reset();
789       return output_offset;
790     }
791 //zmsg(" 7\n");
792     /* Step back */
793     if( sideinfo.main_data_begin >= 512 ) return output_offset;
794 //  if( sideinfo.main_data_begin ) {  /* apparently, zero is legal */
795       prev_len = sideinfo.main_data_begin;
796       uint8_t *prev = prev_bsbuf + prev_framesize - prev_len;
797 //zmsgs(" 7 %ld %d %ld\n", ssize, sideinfo.main_data_begin, prev_framesize);
798       ptr = bsbuf + ssize - prev_len;
799       memcpy(ptr, prev, prev_len);
800       past_framesize += prev_framesize;
801     }
802 //}
803   if( ptr && past_framesize >= prev_len ) {
804     stream->use_ptr(ptr);
805     for( gr=0; gr<granules; ++gr ) {
806       float hybridIn [2][SBLIMIT][SSLIMIT];
807       float hybridOut[2][SSLIMIT][SBLIMIT];
808
809       l3_info_t *l3_info = &(sideinfo.ch[0].gr[gr]);
810       int32_t part2bits;
811       part2bits = lsf ?
812         get_scale_factors_2(scalefacs[0], l3_info, 0) :
813         get_scale_factors_1(scalefacs[0], l3_info, 0, gr);
814 //zmsgs("4 %04x\n", stream->show_bits(16));
815       if( dequantize_sample(hybridIn[0], scalefacs[0],
816                l3_info, sfreq, part2bits) ) {
817           layer_reset();
818           return output_offset;
819       }
820 //zmsgs("5 %04x\n", stream->show_bits(16));
821       if( channels == 2 ) {
822         l3_info_t *l3_info = &(sideinfo.ch[1].gr[gr]);
823         int32_t part2bits = lsf ? 
824           get_scale_factors_2(scalefacs[1], l3_info, i_stereo) :
825           get_scale_factors_1(scalefacs[1], l3_info, 1, gr);
826
827        if( dequantize_sample(hybridIn[1], scalefacs[1], 
828                l3_info, sfreq, part2bits) ) {
829           layer_reset();
830           return output_offset;
831         }
832
833         if( ms_stereo ) {
834           int maxb = sideinfo.ch[0].gr[gr].maxb;
835           if( (int)sideinfo.ch[1].gr[gr].maxb > maxb )
836             maxb = sideinfo.ch[1].gr[gr].maxb;
837           for( i=0; i<(int)SSLIMIT * maxb; ++i ) {
838             float tmp0 = ((float*)hybridIn[0])[i];
839             float tmp1 = ((float*)hybridIn[1])[i];
840             ((float*)hybridIn[0])[i] = tmp0 + tmp1;
841             ((float*)hybridIn[1])[i] = tmp0 - tmp1;
842           }
843         }
844
845           if( i_stereo )
846             calc_i_stereo(hybridIn, scalefacs[1], l3_info, sfreq, ms_stereo, lsf);
847         if( ms_stereo || i_stereo || (single == 3)) {
848           if( l3_info->maxb > sideinfo.ch[0].gr[gr].maxb )
849             sideinfo.ch[0].gr[gr].maxb = l3_info->maxb;
850           else
851             l3_info->maxb = sideinfo.ch[0].gr[gr].maxb;
852         }
853         in0 = (float*)hybridIn[0];
854         in1 = (float*)hybridIn[1];
855         n = SSLIMIT*l3_info->maxb; 
856         switch( single ) {
857         case 3:
858           /* *0.5 done by pow-scale */
859           for( i=0; i<n; ++i, ++in0 ) *in0 += *in1++; 
860           break;
861         case 1:
862           for( i=0; i<n; ++i ) *in0++ = *in1++;
863           break;
864         }
865       }
866
867 //zmsg(" 9\n");
868       for(ch = 0; ch < stereo1; ch++) {
869         l3_info_t *l3_info = &sideinfo.ch[ch].gr[gr];
870 //zmsg(" 9.1\n");
871         antialias(hybridIn[ch], l3_info);
872 //zmsg(" 9.2\n");
873         hybrid(hybridIn[ch], hybridOut[ch], ch, l3_info);
874 //zmsg(" 9.3\n");
875       }
876 //zmsg(" 10\n");
877       if( render && (zoutput[0] || (single < 0 && zoutput[1])) ) {
878         int offset0 = output_offset;
879         if( single >= 0 ) {
880           for( ss=0; ss<(int)SSLIMIT; ++ss )
881             synth_stereo(hybridOut[0][ss], 0, zoutput[0], &output_offset);
882         }
883         else {
884           for( ss=0; ss<(int)SSLIMIT; ++ss ) {
885             int offset1 = offset0;
886             if( zoutput[0] )
887               synth_stereo(hybridOut[0][ss], 0, zoutput[0], &offset0);
888             if( zoutput[1] ) {
889               synth_stereo(hybridOut[1][ss], 1, zoutput[1], &offset1);
890               offset0 = offset1;
891             }
892           }
893         }
894       }
895       output_offset += 32 * SSLIMIT;
896     }
897   }
898
899 //zmsg(" 12\n");
900   first_frame = 0;
901   prev_bsbuf = bsbuf;
902   prev_framesize = zframe_size;
903   return output_offset;
904 }
905
906 void zaudio_decoder_layer_t::
907 layer_reset()
908 {
909 //zmsg("1\n");
910   first_frame = 1;
911   past_framesize = 0;
912   bsnum = 0;
913   bsbuf = &bsspace[1][512];
914   prev_bsbuf = 0;
915 /*  prev_framesize = 0; */
916 /*  memset(bsspace, 0, sizeof(bsspace)); */
917   memset(mp3_block, 0, sizeof(mp3_block));
918   memset(mp3_blc, 0, sizeof(mp3_blc));
919   synths_reset();
920 }
921
922 /* Return 1 if the head check doesn't find a header. */
923 int zaudio_decoder_layer_t::
924 layer_check(uint8_t *data)
925 {
926   uint32_t head =
927     ((uint32_t)data[0] << 24) | ((uint32_t)data[1] << 16) | 
928     ((uint32_t)data[2] <<  8) | ((uint32_t)data[3]);
929   if( (head & 0xffe00000) != 0xffe00000 ) return 1;
930   if( !((head >> 17) & 3) ) return 1;
931   if( ((head >> 12) & 0xf) == 0xf ) return 1;
932   if( !((head >> 12) & 0xf) ) return 1;
933   if( ((head >> 10) & 0x3) == 0x3 ) return 1;
934   if( ((head >> 19) & 1) == 1 &&
935       ((head >> 17) & 3) == 3 &&
936       ((head >> 16) & 1) == 1 ) return 1;
937   if( (head & 0xffff0000) == 0xfffe0000 ) return 1;
938   if( (head & 0xffff0000) == 0xffed0000 ) return 1; /* JPEG header */
939   return 0;
940 }
941
942 int zaudio_decoder_layer_t::
943 id3_check(uint8_t *data)
944 {
945   return data[0]=='I' && data[1]=='D' && data[2]=='3' ? 1 : 0;
946 }
947
948 /* Decode layer header */
949 int zaudio_decoder_layer_t::
950 layer3_header(uint8_t *data)
951 {
952   int zlsf, zmpeg35;
953   int zlayer, zchannels, zmode;
954   int zsampling_frequency_code;
955   uint32_t zheader;
956   switch( id3_state ) { /* ID3 tag */
957   case id3_IDLE:
958     /* Read header */
959     if( id3_check(data) ) {
960       id3_state = id3_HEADER;
961       id3_current_byte = 0;
962       return 0;
963     }
964     break;
965
966     case id3_HEADER:
967       if( ++id3_current_byte >= 6 ) {
968         id3_size =
969           ((uint32_t)data[0] << 21) | ((uint32_t)data[1] << 14) |
970           ((uint32_t)data[2] << 7)  | ((uint32_t)data[3]);
971         id3_current_byte = 0;
972         id3_state = id3_SKIP;
973 //zmsgs("%d %02x%02x%02x%02x size=0x%x layer=%d\n", __LINE__,
974 //  data[0], data[1], data[2], data[3], id3_size, layer);
975       }
976       return 0;
977
978     case id3_SKIP:
979 //zmsgs("%d id3_current_byte=0x%x %02x%02x%02x%02x\n", __LINE__,
980 // id3_current_byte, data[0], data[1], data[2], data[3]);
981       if( ++id3_current_byte >= id3_size )
982         id3_state = id3_IDLE;
983       return 0;
984   }
985
986   if( layer_check(data) ) return 0;
987 //zmsgs("%d id3_state=%d %02x%02x%02x%02x\n", __LINE__,
988 // id3_state, data[0], data[1], data[2], data[3]);
989   zheader =
990     ((uint32_t)data[0] << 24) | ((uint32_t)data[1] << 16) | 
991     ((uint32_t)data[2] <<  8) | ((uint32_t)data[3]);
992   if( zheader & (1 << 20) ) {
993     zlsf = (zheader & (1 << 19)) ? 0x0 : 0x1;
994     zmpeg35 = 0;
995   }
996   else {
997     zlsf = 1;
998     zmpeg35 = 1;
999   }
1000
1001   zlayer = 4 - ((zheader >> 17) & 3);
1002 //zmsgs("1 %d zheader=%08x zlayer=%d layer=%d\n", __LINE__,
1003 //   zheader, zlayer, layer);
1004   if( layer != 0 && zlayer != layer ) return 0;
1005   zsampling_frequency_code =  zmpeg35 ?
1006     6 + ((zheader >> 10) & 0x3) : ((zheader >> 10) & 0x3) + (zlsf * 3);
1007
1008   if( samplerate != 0 &&
1009       zsampling_frequency_code != sampling_frequency_code ) return 0;
1010   zmode = ((zheader >> 6) & 0x3);
1011   zchannels = (zmode == md_MONO) ? 1 : 2;
1012 /*  if( channels >= 0 && zchannels != channels ) return 0; */
1013 /*  if( zchannels > channels ) channels = zchannels; */
1014   channels = zchannels;
1015   layer = zlayer;
1016   lsf = zlsf;
1017   mpeg35 = zmpeg35;
1018   mode = zmode;
1019   sampling_frequency_code = zsampling_frequency_code;
1020   samplerate = freqs[sampling_frequency_code];
1021   error_protection = ((zheader >> 16) & 0x1) ^ 0x1;
1022   bitrate_index = ((zheader >> 12) & 0xf);
1023   padding   = ((zheader >> 9) & 0x1);
1024   extension = ((zheader >> 8) & 0x1);
1025   mode_ext  = ((zheader >> 4) & 0x3);
1026   copyright = ((zheader >> 3) & 0x1);
1027   original  = ((zheader >> 2) & 0x1);
1028   emphasis  = zheader & 0x3;
1029   single = channels > 1 ? -1 : 3;
1030   if( !bitrate_index ) return 0;
1031   bitrate = 1000 * tabsel_123[lsf][layer-1][bitrate_index];
1032   switch( layer ) {
1033   case 1:
1034     framesize  = (long)tabsel_123[lsf][0][bitrate_index] * 12000;
1035     framesize /= freqs[sampling_frequency_code];
1036     framesize  = ((framesize + padding) << 2);
1037     break;
1038   case 2:
1039     framesize = (long)tabsel_123[lsf][1][bitrate_index] * 144000;
1040     framesize /= freqs[sampling_frequency_code];
1041     framesize += padding;
1042     break;
1043   case 3:
1044     ssize =  lsf ?
1045       ((channels == 1) ? 9 : 17) :
1046       ((channels == 1) ? 17 : 32);
1047     if( error_protection ) ssize += 2;
1048     framesize  = (long)tabsel_123[lsf][2][bitrate_index] * 144000;
1049     framesize /= freqs[sampling_frequency_code] << lsf;
1050     framesize += padding;
1051     break; 
1052   default:
1053     return 0;
1054   }
1055 //zmsgs("%d bitrate=%d framesize=%ld samplerate=%d channels=%d layer=%d\n", 
1056 // __LINE__, bitrate, framesize, samplerate, channels, layer);
1057   if( bitrate < 64000 && layer != 3 ) return 0;
1058   if( framesize > (int)MAXFRAMESIZE ) return 0;
1059 //zmsgs("10 %d\n", layer);
1060   return framesize;
1061 }
1062
1063 zaudio_decoder_layer_t::
1064 audio_decoder_layer_t()
1065 {
1066   bo = 1;
1067   channels = -1;
1068   stream = new bits_t(0, 0);
1069   init_decode_tables();
1070   layer_reset();
1071 }
1072
1073 zaudio_decoder_layer_t::
1074 ~audio_decoder_layer_t()
1075 {
1076   delete stream;
1077 }
1078