add bluray support, add dialog close fixes, scale fix
[goodguy/history.git] / cinelerra-5.0 / 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   part2remain += num;
443   stream->start_reverse();
444   stream->get_bits_reverse(num);
445   stream->start_forward();
446
447 //zmsgs("3 %d %04x\n", stream->bit_number, stream->show_bits(16));
448   while( part2remain > 16 ) {
449     stream->get_bits(16); /* Dismiss stuffing Bits */
450     part2remain -= 16;
451   }
452
453   if( part2remain > 0 )
454     stream->get_bits(part2remain);
455   else if( part2remain < 0 ) {
456     zmsgs("can't rewind stream %d bits! data=%02x%02x%02x%02x\n", -part2remain,
457       (uint8_t)stream->input_ptr[-3], (uint8_t)stream->input_ptr[-2], 
458       (uint8_t)stream->input_ptr[-1], (uint8_t)stream->input_ptr[0]);
459     return 1; /* -> error */
460   }
461   return 0;
462 }
463
464 int zaudio_decoder_layer_t::
465 get_side_info(l3_sideinfo_t *si, int channels, int ms_stereo,
466     long sfreq, int single, int lsf)
467 {
468   int i, ch, gr;
469   int powdiff = (single == 3) ? 4 : 0;
470   static const int tabs[2][5] = { { 2,9,5,3,4 } , { 1,8,1,2,9 } };
471   const int *tab = tabs[lsf];
472
473   si->main_data_begin = stream->get_bits(tab[1]);
474   si->private_bits = stream->get_bits(channels == 1 ? tab[2] : tab[3]);
475   if( !lsf ) {
476     for( ch=0; ch<channels; ++ch ) {
477       si->ch[ch].gr[0].scfsi = -1;
478       si->ch[ch].gr[1].scfsi = stream->get_bits(4);
479     }
480   }
481
482   for( gr=0; gr<tab[0]; ++gr ) {
483     for( ch=0; ch<channels; ++ch ) {
484       l3_info_t *l3_info = &(si->ch[ch].gr[gr]);
485       l3_info->part2_3_length = stream->get_bits(12);
486       l3_info->big_values = stream->get_bits(9);
487       if( l3_info->big_values > 288 ) {
488         zerrs(" big_values too large! %d\n",l3_info->big_values);
489         l3_info->big_values = 288;
490       }
491       l3_info->pow2gain = gainpow2 + 256 - stream->get_bits(8) + powdiff;
492       if( ms_stereo ) l3_info->pow2gain += 2;
493       l3_info->scalefac_compress = stream->get_bits(tab[4]);
494
495       if(stream->get_bits(1)) {
496         /* window switch flag  */
497         l3_info->block_type       = stream->get_bits(2);
498         l3_info->mixed_block_flag = stream->get_bits(1);
499         l3_info->table_select[0]  = stream->get_bits(5);
500         l3_info->table_select[1]  = stream->get_bits(5);
501         /* table_select[2] not needed, because there is no region2, */
502         /* but to satisfy some verifications tools we set it either. */
503         l3_info->table_select[2] = 0;
504         for( i=0; i<3; ++i )
505           l3_info->full_gain[i] = l3_info->pow2gain + (stream->get_bits(3) << 3);
506
507         if( l3_info->block_type == 0 ) {
508           zerr("Blocktype == 0 and window-switching == 1 not allowed.\n");
509           return 1;
510         }
511         /* region_count/start parameters are implicit in this case. */       
512         if( !lsf || l3_info->block_type == 2 )
513           l3_info->region1start = 36 >> 1;
514         else {
515           /* check this again for 2.5 and sfreq=8 */
516           l3_info->region1start =  sfreq == 8 ? 108 >> 1 : 54 >> 1;
517         }
518         l3_info->region2start = 576 >> 1;
519       }
520       else {
521         int r0c, r1c;
522         for( i=0; i<3; ++i )
523           l3_info->table_select[i] = stream->get_bits(5);
524         r0c = stream->get_bits(4);
525         r1c = stream->get_bits(3);
526         l3_info->region1start = bandInfo[sfreq].longIdx[r0c + 1] >> 1 ;
527         l3_info->region2start = bandInfo[sfreq].longIdx[r0c + 1 + r1c + 1] >> 1;
528         l3_info->block_type = 0;
529         l3_info->mixed_block_flag = 0;
530       }
531       if( !lsf ) l3_info->preflag = stream->get_bits(1);
532       l3_info->scalefac_scale = stream->get_bits(1);
533       l3_info->count1table_select = stream->get_bits(1);
534     }
535   }
536   return 0;
537 }
538
539 int zaudio_decoder_layer_t::
540 hybrid( float fsIn[SBLIMIT][SSLIMIT], float tsOut[SSLIMIT][SBLIMIT],
541      int ch, l3_info_t *l3_info)
542 {
543   float *tspnt = (float *) tsOut;
544   float *rawout1,*rawout2;
545   int i, b, bt, sb;
546   int (*zdct)(float *inbuf, float *o1, float *o2, float *wintab, float *tsbuf);
547   
548   b = mp3_blc[ch];
549   rawout1 = mp3_block[b][ch];
550   b = -b + 1;
551   rawout2 = mp3_block[b][ch];
552   mp3_blc[ch] = b;
553   
554   sb = 0;
555   if( l3_info->mixed_block_flag ) {
556     sb = 2;
557     dct36(fsIn[0], rawout1, rawout2, win[0], tspnt);
558     dct36(fsIn[1], rawout1 + 18, rawout2 + 18, win1[0], tspnt + 1);
559     rawout1 += 36; rawout2 += 36; 
560     tspnt += 2;
561   }
562
563   bt = l3_info->block_type;
564   zdct = bt == 2 ? dct12 : dct36;
565   for( ; sb <(int)l3_info->maxb; sb+=2, tspnt+=2, rawout1+=36, rawout2+=36 ) {
566     zdct(fsIn[sb], rawout1, rawout2, win[bt], tspnt);
567     zdct(fsIn[sb + 1], rawout1 + 18, rawout2 + 18, win1[bt], tspnt + 1);
568   }
569
570   for( ; sb < (int)SBLIMIT; ++sb, ++tspnt ) {
571     for( i=0; i<(int)SSLIMIT; ++i ) {
572       tspnt[i * SBLIMIT] = *rawout1++;
573       *rawout2++ = 0.0;
574     }
575   }
576   return 0;
577 }
578
579 int zaudio_decoder_layer_t::
580 antialias(float xr[SBLIMIT][SSLIMIT], l3_info_t *l3_info)
581 {
582   int sblim;
583   if( l3_info->block_type == 2 ) {
584     if( !l3_info->mixed_block_flag ) return 0;
585     sblim = 1; 
586   }
587   else
588     sblim = l3_info->maxb-1;
589
590   /* 31 alias-reduction operations between each pair of sub-bands */
591   /* with 8 butterflies between each pair                         */
592
593   float *xr1 = (float*)xr[1];
594   for( int sb=sblim; sb > 0; --sb, xr1+=10 ) {
595     float *cs = aa_cs;
596     float *ca = aa_ca;
597     float *xr2 = xr1;
598     for( int ss=8; --ss>=0;) {
599       /* upper and lower butterfly inputs */
600       float bu = *--xr2;
601       float bd = *xr1;
602       *xr2   = (bu * (*cs)   ) - (bd * (*ca)   );
603       *xr1++ = (bd * (*cs++) ) + (bu * (*ca++) );
604     }
605   }
606   return 0;
607 }
608
609 /* 
610  * calculate float channel values for Joint-I-Stereo-mode
611  */
612 int zaudio_decoder_layer_t::
613 calc_i_stereo(float xr_buf[2][SBLIMIT][SSLIMIT], int *scalefac,
614        l3_info_t *l3_info, int sfreq, int ms_stereo, int lsf)
615 {
616   float (*xr)[SBLIMIT*SSLIMIT] = (float (*)[SBLIMIT*SSLIMIT])xr_buf;
617   struct bandInfoStruct *bi = &bandInfo[sfreq];
618   static const float *tabs[3][2][2] = { /* TODO: optimize as static */
619     { { tan1_1, tan2_1 }       , { tan1_2, tan2_2 } },
620     { { pow1_1[0], pow2_1[0] } , { pow1_2[0], pow2_2[0] } } ,
621     { { pow1_1[1], pow2_1[1] } , { pow1_2[1], pow2_2[1] } } 
622   };
623
624   int tab = lsf + (l3_info->scalefac_compress & lsf);
625   const float *tab1 = tabs[tab][ms_stereo][0];
626   const float *tab2 = tabs[tab][ms_stereo][1];
627   if( l3_info->block_type == 2 ) {
628     int lwin,do_l = 0;
629     if( l3_info->mixed_block_flag ) do_l = 1;
630     for(lwin = 0; lwin < 3; lwin++) { 
631       /* process each window */
632       /* get first band with zero values */
633       /* sfb is minimal 3 for mixed mode */
634       int is_p, sb, idx, sfb = l3_info->maxband[lwin];  
635       if(sfb > 3) do_l = 0;
636
637       for( ; sfb < 12 ; ++sfb ) {
638         /* scale: 0-15 */ 
639         is_p = scalefac[sfb * 3 + lwin - l3_info->mixed_block_flag]; 
640         if( is_p != 7 ) {
641           sb  = bi->shortDiff[sfb];
642           idx = bi->shortIdx[sfb] + lwin;
643           float t1  = tab1[is_p]; 
644           float t2 = tab2[is_p];
645           for( ; sb > 0; --sb, idx+=3 ) {
646             float v = xr[0][idx];
647             xr[0][idx] = v * t1;
648             xr[1][idx] = v * t2;
649           }
650         }
651       }
652
653       /* in the original: copy 10 to 11, */
654       /*  here: copy 11 to 12 maybe still wrong??? (copy 12 to 13?) */
655       /* scale: 0-15 */
656       is_p = scalefac[11 * 3 + lwin - l3_info->mixed_block_flag]; 
657       sb   = bi->shortDiff[12];
658       idx  = bi->shortIdx[12] + lwin;
659       if( is_p != 7 ) {
660         float t1, t2;
661         t1 = tab1[is_p]; 
662         t2 = tab2[is_p];
663         for( ; sb > 0; --sb, idx+=3 ) {  
664           float v = xr[0][idx];
665           xr[0][idx] = v * t1;
666           xr[1][idx] = v * t2;
667         }
668       }
669     } /* end for(lwin; .. ; . ) */
670
671     /* also check l-part, if ALL bands in the three windows are 'empty' */
672     /*  and mode = mixed_mode */
673     if( do_l ) {
674       int sfb = l3_info->maxbandl;
675       int idx = bi->longIdx[sfb];
676
677       for ( ; sfb < 8; ++sfb ) {
678         int sb = bi->longDiff[sfb];
679         /* scale: 0-15 */
680         int is_p = scalefac[sfb]; 
681         if( is_p != 7 ) {
682           float t1, t2;
683           t1 = tab1[is_p]; 
684           t2 = tab2[is_p];
685           for( ; sb > 0; sb--, idx++) {
686             float v = xr[0][idx];
687             xr[0][idx] = v * t1;
688             xr[1][idx] = v * t2;
689           }
690         }
691         else 
692           idx += sb;
693       }
694     }     
695   } 
696   else { /* ((l3_info->block_type != 2)) */
697     int sfb = l3_info->maxbandl;
698     int is_p, idx = bi->longIdx[sfb];
699     for( ; sfb < 21; sfb++) {
700       int sb = bi->longDiff[sfb];
701       /* scale: 0-15 */
702       is_p = scalefac[sfb]; 
703       if( is_p != 7 ) {
704         float t1 = tab1[is_p]; 
705         float t2 = tab2[is_p];
706         for( ; sb > 0; --sb, ++idx ) {
707           float v = xr[0][idx];
708           xr[0][idx] = v * t1;
709           xr[1][idx] = v * t2;
710         }
711       }
712       else
713         idx += sb;
714     }
715
716     is_p = scalefac[20];
717     if(is_p != 7) {  
718       /* copy l-band 20 to l-band 21 */
719       float t1 = tab1[is_p];
720       float t2 = tab2[is_p]; 
721       for( int sb=bi->longDiff[21]; sb > 0; --sb, ++idx ) {
722         float v = xr[0][idx];
723         xr[0][idx] = v * t1;
724         xr[1][idx] = v * t2;
725       }
726     }
727   } /* ... */
728
729   return 0;
730 }
731
732 int zaudio_decoder_layer_t::
733 do_layer3(uint8_t *zframe, int zframe_size, float **zoutput, int render)
734 {
735   float *in0, *in1;
736   int i, n, gr, ch, ss;
737   /* max 39 for short[13][3] mode, mixed: 38, long: 22 */
738   int scalefacs[2][39]; 
739   l3_sideinfo_t sideinfo;
740   int ms_stereo, i_stereo;
741   int sfreq = sampling_frequency_code;
742   int stereo1, granules;
743   int output_offset = 0;
744
745 //zmsg("1\n");
746   zframe += 4; /* Skip header */
747   zframe_size -= 4;
748
749   /* flip/init buffer */
750   bsbuf = &bsspace[bsnum][512];
751   bsnum ^= 1;
752   /* Copy frame into history buffer */
753   memcpy(bsbuf, zframe, zframe_size);
754 //zmsgs(" %d %02x%02x%02x%02x\n", first_frame, 
755 // (uint8_t)bsbuf[0], (uint8_t)bsbuf[1], (uint8_t)bsbuf[2], (uint8_t)bsbuf[3]);
756
757   int prev_len = -1;
758   uint8_t *ptr = 0;
759   if( !first_frame ) {
760     /* Set up bitstream to use buffer */
761     stream->use_ptr(bsbuf);
762 //zmsgs(" 7 %x\n", stream->show_bits(16));
763     /* CRC must be skipped here for proper alignment with the backstep */
764     if( error_protection ) stream->get_bits(16);
765 //zmsgs(" 8 %x\n", stream->show_bits(16));
766     if( channels == 1 ) { /* stream is mono */
767       stereo1 = 1;
768       single = 0;
769     }
770     else { /* Stereo */
771       stereo1 = 2;
772     }
773
774     if( mode == md_JOINT_STEREO ) {
775       ms_stereo = (mode_ext & 0x2) >> 1;
776       i_stereo  = mode_ext & 0x1;
777     }
778     else
779       ms_stereo = i_stereo = 0;
780     granules = lsf ? 1 : 2;
781 //zmsg(" 6\n");
782     if( get_side_info(&sideinfo, channels, ms_stereo, sfreq, single, lsf) ) {
783       layer_reset();
784       return output_offset;
785     }
786 //zmsg(" 7\n");
787     /* Step back */
788     if( sideinfo.main_data_begin >= 512 ) return output_offset;
789     if( sideinfo.main_data_begin ) {
790       prev_len = sideinfo.main_data_begin;
791       uint8_t *prev = prev_bsbuf + prev_framesize - prev_len;
792 //zmsgs(" 7 %ld %d %ld\n", ssize, sideinfo.main_data_begin, prev_framesize);
793       ptr = bsbuf + ssize - prev_len;
794       memcpy(ptr, prev, prev_len);
795       past_framesize += prev_framesize;
796     }
797   }
798   if( ptr && past_framesize >= prev_len ) {
799     stream->use_ptr(ptr);
800     for( gr=0; gr<granules; ++gr ) {
801       float hybridIn [2][SBLIMIT][SSLIMIT];
802       float hybridOut[2][SSLIMIT][SBLIMIT];
803
804       l3_info_t *l3_info = &(sideinfo.ch[0].gr[gr]);
805       int32_t part2bits;
806       part2bits = lsf ?
807         get_scale_factors_2(scalefacs[0], l3_info, 0) :
808         get_scale_factors_1(scalefacs[0], l3_info, 0, gr);
809 //zmsgs("4 %04x\n", stream->show_bits(16));
810       if( dequantize_sample(hybridIn[0], scalefacs[0],
811                l3_info, sfreq, part2bits) ) {
812           layer_reset();
813           return output_offset;
814       }
815 //zmsgs("5 %04x\n", stream->show_bits(16));
816       if( channels == 2 ) {
817         l3_info_t *l3_info = &(sideinfo.ch[1].gr[gr]);
818         int32_t part2bits = lsf ? 
819           get_scale_factors_2(scalefacs[1], l3_info, i_stereo) :
820           get_scale_factors_1(scalefacs[1], l3_info, 1, gr);
821
822        if( dequantize_sample(hybridIn[1], scalefacs[1], 
823                l3_info, sfreq, part2bits) ) {
824           layer_reset();
825           return output_offset;
826         }
827
828         if( ms_stereo ) {
829           int maxb = sideinfo.ch[0].gr[gr].maxb;
830           if( (int)sideinfo.ch[1].gr[gr].maxb > maxb )
831             maxb = sideinfo.ch[1].gr[gr].maxb;
832           for( i=0; i<(int)SSLIMIT * maxb; ++i ) {
833             float tmp0 = ((float*)hybridIn[0])[i];
834             float tmp1 = ((float*)hybridIn[1])[i];
835             ((float*)hybridIn[0])[i] = tmp0 + tmp1;
836             ((float*)hybridIn[1])[i] = tmp0 - tmp1;
837           }
838         }
839
840           if( i_stereo )
841             calc_i_stereo(hybridIn, scalefacs[1], l3_info, sfreq, ms_stereo, lsf);
842         if( ms_stereo || i_stereo || (single == 3)) {
843           if( l3_info->maxb > sideinfo.ch[0].gr[gr].maxb )
844             sideinfo.ch[0].gr[gr].maxb = l3_info->maxb;
845           else
846             l3_info->maxb = sideinfo.ch[0].gr[gr].maxb;
847         }
848         in0 = (float*)hybridIn[0];
849         in1 = (float*)hybridIn[1];
850         n = SSLIMIT*l3_info->maxb; 
851         switch( single ) {
852         case 3:
853           /* *0.5 done by pow-scale */
854           for( i=0; i<n; ++i, ++in0 ) *in0 += *in1++; 
855           break;
856         case 1:
857           for( i=0; i<n; ++i ) *in0++ = *in1++;
858           break;
859         }
860       }
861
862 //zmsg(" 9\n");
863       for(ch = 0; ch < stereo1; ch++) {
864         l3_info_t *l3_info = &sideinfo.ch[ch].gr[gr];
865 //zmsg(" 9.1\n");
866         antialias(hybridIn[ch], l3_info);
867 //zmsg(" 9.2\n");
868         hybrid(hybridIn[ch], hybridOut[ch], ch, l3_info);
869 //zmsg(" 9.3\n");
870       }
871 //zmsg(" 10\n");
872       if( render && (zoutput[0] || (single < 0 && zoutput[1])) ) {
873         int offset0 = output_offset;
874         if( single >= 0 ) {
875           for( ss=0; ss<(int)SSLIMIT; ++ss )
876             synth_stereo(hybridOut[0][ss], 0, zoutput[0], &output_offset);
877         }
878         else {
879           for( ss=0; ss<(int)SSLIMIT; ++ss ) {
880             int offset1 = offset0;
881             if( zoutput[0] )
882               synth_stereo(hybridOut[0][ss], 0, zoutput[0], &offset0);
883             if( zoutput[1] ) {
884               synth_stereo(hybridOut[1][ss], 1, zoutput[1], &offset1);
885               offset0 = offset1;
886             }
887           }
888         }
889       }
890       output_offset += 32 * SSLIMIT;
891     }
892   }
893
894 //zmsg(" 12\n");
895   first_frame = 0;
896   prev_bsbuf = bsbuf;
897   prev_framesize = zframe_size;
898   return output_offset;
899 }
900
901 void zaudio_decoder_layer_t::
902 layer_reset()
903 {
904 //zmsg("1\n");
905   first_frame = 1;
906   past_framesize = 0;
907   bsnum = 0;
908   bsbuf = &bsspace[1][512];
909   prev_bsbuf = 0;
910 /*  prev_framesize = 0; */
911 /*  memset(bsspace, 0, sizeof(bsspace)); */
912   memset(mp3_block, 0, sizeof(mp3_block));
913   memset(mp3_blc, 0, sizeof(mp3_blc));
914   synths_reset();
915 }
916
917 /* Return 1 if the head check doesn't find a header. */
918 int zaudio_decoder_layer_t::
919 layer_check(uint8_t *data)
920 {
921   uint32_t head =
922     ((uint32_t)data[0] << 24) | ((uint32_t)data[1] << 16) | 
923     ((uint32_t)data[2] <<  8) | ((uint32_t)data[3]);
924   if( (head & 0xffe00000) != 0xffe00000 ) return 1;
925   if( !((head >> 17) & 3) ) return 1;
926   if( ((head >> 12) & 0xf) == 0xf ) return 1;
927   if( !((head >> 12) & 0xf) ) return 1;
928   if( ((head >> 10) & 0x3) == 0x3 ) return 1;
929   if( ((head >> 19) & 1) == 1 &&
930       ((head >> 17) & 3) == 3 &&
931       ((head >> 16) & 1) == 1 ) return 1;
932   if( (head & 0xffff0000) == 0xfffe0000 ) return 1;
933   if( (head & 0xffff0000) == 0xffed0000 ) return 1; /* JPEG header */
934   return 0;
935 }
936
937 int zaudio_decoder_layer_t::
938 id3_check(uint8_t *data)
939 {
940   return data[0]=='I' && data[1]=='D' && data[2]=='3' ? 1 : 0;
941 }
942
943 /* Decode layer header */
944 int zaudio_decoder_layer_t::
945 layer3_header(uint8_t *data)
946 {
947   int zlsf, zmpeg35;
948   int zlayer, zchannels, zmode;
949   int zsampling_frequency_code;
950   uint32_t zheader;
951   switch( id3_state ) { /* ID3 tag */
952   case id3_IDLE:
953     /* Read header */
954     if( id3_check(data) ) {
955       id3_state = id3_HEADER;
956       id3_current_byte = 0;
957       return 0;
958     }
959     break;
960
961     case id3_HEADER:
962       if( ++id3_current_byte >= 6 ) {
963         id3_size =
964           ((uint32_t)data[0] << 21) | ((uint32_t)data[1] << 14) |
965           ((uint32_t)data[2] << 7)  | ((uint32_t)data[3]);
966         id3_current_byte = 0;
967         id3_state = id3_SKIP;
968 //zmsgs("%d %02x%02x%02x%02x size=0x%x layer=%d\n", __LINE__,
969 //  data[0], data[1], data[2], data[3], id3_size, layer);
970       }
971       return 0;
972
973     case id3_SKIP:
974 //zmsgs("%d id3_current_byte=0x%x %02x%02x%02x%02x\n", __LINE__,
975 // id3_current_byte, data[0], data[1], data[2], data[3]);
976       if( ++id3_current_byte >= id3_size )
977         id3_state = id3_IDLE;
978       return 0;
979   }
980
981   if( layer_check(data) ) return 0;
982 //zmsgs("%d id3_state=%d %02x%02x%02x%02x\n", __LINE__,
983 // id3_state, data[0], data[1], data[2], data[3]);
984   zheader =
985     ((uint32_t)data[0] << 24) | ((uint32_t)data[1] << 16) | 
986     ((uint32_t)data[2] <<  8) | ((uint32_t)data[3]);
987   if( zheader & (1 << 20) ) {
988     zlsf = (zheader & (1 << 19)) ? 0x0 : 0x1;
989     zmpeg35 = 0;
990   }
991   else {
992     zlsf = 1;
993     zmpeg35 = 1;
994   }
995
996   zlayer = 4 - ((zheader >> 17) & 3);
997 //zmsgs("1 %d zheader=%08x zlayer=%d layer=%d\n", __LINE__,
998 //   zheader, zlayer, layer);
999   if( layer != 0 && zlayer != layer ) return 0;
1000   zsampling_frequency_code =  zmpeg35 ?
1001     6 + ((zheader >> 10) & 0x3) : ((zheader >> 10) & 0x3) + (zlsf * 3);
1002
1003   if( samplerate != 0 &&
1004       zsampling_frequency_code != sampling_frequency_code ) return 0;
1005   zmode = ((zheader >> 6) & 0x3);
1006   zchannels = (zmode == md_MONO) ? 1 : 2;
1007 /*  if( channels >= 0 && zchannels != channels ) return 0; */
1008 /*  if( zchannels > channels ) channels = zchannels; */
1009   channels = zchannels;
1010   layer = zlayer;
1011   lsf = zlsf;
1012   mpeg35 = zmpeg35;
1013   mode = zmode;
1014   sampling_frequency_code = zsampling_frequency_code;
1015   samplerate = freqs[sampling_frequency_code];
1016   error_protection = ((zheader >> 16) & 0x1) ^ 0x1;
1017   bitrate_index = ((zheader >> 12) & 0xf);
1018   padding   = ((zheader >> 9) & 0x1);
1019   extension = ((zheader >> 8) & 0x1);
1020   mode_ext  = ((zheader >> 4) & 0x3);
1021   copyright = ((zheader >> 3) & 0x1);
1022   original  = ((zheader >> 2) & 0x1);
1023   emphasis  = zheader & 0x3;
1024   single = channels > 1 ? -1 : 3;
1025   if( !bitrate_index ) return 0;
1026   bitrate = 1000 * tabsel_123[lsf][layer-1][bitrate_index];
1027   switch( layer ) {
1028   case 1:
1029     framesize  = (long)tabsel_123[lsf][0][bitrate_index] * 12000;
1030     framesize /= freqs[sampling_frequency_code];
1031     framesize  = ((framesize + padding) << 2);
1032     break;
1033   case 2:
1034     framesize = (long)tabsel_123[lsf][1][bitrate_index] * 144000;
1035     framesize /= freqs[sampling_frequency_code];
1036     framesize += padding;
1037     break;
1038   case 3:
1039     ssize =  lsf ?
1040       ((channels == 1) ? 9 : 17) :
1041       ((channels == 1) ? 17 : 32);
1042     if( error_protection ) ssize += 2;
1043     framesize  = (long)tabsel_123[lsf][2][bitrate_index] * 144000;
1044     framesize /= freqs[sampling_frequency_code] << lsf;
1045     framesize += padding;
1046     break; 
1047   default:
1048     return 0;
1049   }
1050 //zmsgs("%d bitrate=%d framesize=%ld samplerate=%d channels=%d layer=%d\n", 
1051 // __LINE__, bitrate, framesize, samplerate, channels, layer);
1052   if( bitrate < 64000 && layer != 3 ) return 0;
1053   if( framesize > (int)MAXFRAMESIZE ) return 0;
1054 //zmsgs("10 %d\n", layer);
1055   return framesize;
1056 }
1057
1058 zaudio_decoder_layer_t::
1059 audio_decoder_layer_t()
1060 {
1061   bo = 1;
1062   channels = -1;
1063   stream = new bits_t(0, 0);
1064   init_decode_tables();
1065   layer_reset();
1066 }
1067
1068 zaudio_decoder_layer_t::
1069 ~audio_decoder_layer_t()
1070 {
1071   delete stream;
1072 }
1073