]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/mpegaudiodec.c
add proper prefix to extern mpeg audio data tables
[frescor/ffmpeg.git] / libavcodec / mpegaudiodec.c
1 /*
2  * MPEG Audio decoder
3  * Copyright (c) 2001, 2002 Fabrice Bellard.
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file mpegaudiodec.c
24  * MPEG Audio decoder.
25  */
26
27 //#define DEBUG
28 #include "avcodec.h"
29 #include "bitstream.h"
30 #include "dsputil.h"
31
32 /*
33  * TODO:
34  *  - in low precision mode, use more 16 bit multiplies in synth filter
35  *  - test lsf / mpeg25 extensively.
36  */
37
38 /* define USE_HIGHPRECISION to have a bit exact (but slower) mpeg
39    audio decoder */
40 #ifdef CONFIG_MPEGAUDIO_HP
41 #   define USE_HIGHPRECISION
42 #endif
43
44 #include "mpegaudio.h"
45
46 #include "mathops.h"
47
48 #define FRAC_ONE    (1 << FRAC_BITS)
49
50 #define FIX(a)   ((int)((a) * FRAC_ONE))
51 /* WARNING: only correct for posititive numbers */
52 #define FIXR(a)   ((int)((a) * FRAC_ONE + 0.5))
53 #define FRAC_RND(a) (((a) + (FRAC_ONE/2)) >> FRAC_BITS)
54
55 #define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
56
57 /****************/
58
59 #define HEADER_SIZE 4
60 #define BACKSTEP_SIZE 512
61 #define EXTRABYTES 24
62
63 struct GranuleDef;
64
65 typedef struct MPADecodeContext {
66     DECLARE_ALIGNED_8(uint8_t, last_buf[2*BACKSTEP_SIZE + EXTRABYTES]);
67     int last_buf_size;
68     int frame_size;
69     /* next header (used in free format parsing) */
70     uint32_t free_format_next_header;
71     int error_protection;
72     int layer;
73     int sample_rate;
74     int sample_rate_index; /* between 0 and 8 */
75     int bit_rate;
76     GetBitContext gb;
77     GetBitContext in_gb;
78     int nb_channels;
79     int mode;
80     int mode_ext;
81     int lsf;
82     DECLARE_ALIGNED_16(MPA_INT, synth_buf[MPA_MAX_CHANNELS][512 * 2]);
83     int synth_buf_offset[MPA_MAX_CHANNELS];
84     DECLARE_ALIGNED_16(int32_t, sb_samples[MPA_MAX_CHANNELS][36][SBLIMIT]);
85     int32_t mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
86 #ifdef DEBUG
87     int frame_count;
88 #endif
89     void (*compute_antialias)(struct MPADecodeContext *s, struct GranuleDef *g);
90     int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
91     int dither_state;
92     int error_resilience;
93     AVCodecContext* avctx;
94 } MPADecodeContext;
95
96 /**
97  * Context for MP3On4 decoder
98  */
99 typedef struct MP3On4DecodeContext {
100     int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
101     int chan_cfg; ///< channel config number
102     MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
103 } MP3On4DecodeContext;
104
105 /* layer 3 "granule" */
106 typedef struct GranuleDef {
107     uint8_t scfsi;
108     int part2_3_length;
109     int big_values;
110     int global_gain;
111     int scalefac_compress;
112     uint8_t block_type;
113     uint8_t switch_point;
114     int table_select[3];
115     int subblock_gain[3];
116     uint8_t scalefac_scale;
117     uint8_t count1table_select;
118     int region_size[3]; /* number of huffman codes in each region */
119     int preflag;
120     int short_start, long_end; /* long/short band indexes */
121     uint8_t scale_factors[40];
122     int32_t sb_hybrid[SBLIMIT * 18]; /* 576 samples */
123 } GranuleDef;
124
125 #define MODE_EXT_MS_STEREO 2
126 #define MODE_EXT_I_STEREO  1
127
128 /* layer 3 huffman tables */
129 typedef struct HuffTable {
130     int xsize;
131     const uint8_t *bits;
132     const uint16_t *codes;
133 } HuffTable;
134
135 #include "mpegaudiodata.h"
136 #include "mpegaudiodectab.h"
137
138 static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
139 static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
140
141 /* vlc structure for decoding layer 3 huffman tables */
142 static VLC huff_vlc[16];
143 static VLC huff_quad_vlc[2];
144 /* computed from band_size_long */
145 static uint16_t band_index_long[9][23];
146 /* XXX: free when all decoders are closed */
147 #define TABLE_4_3_SIZE (8191 + 16)*4
148 static int8_t  table_4_3_exp[TABLE_4_3_SIZE];
149 static uint32_t table_4_3_value[TABLE_4_3_SIZE];
150 static uint32_t exp_table[512];
151 static uint32_t expval_table[512][16];
152 /* intensity stereo coef table */
153 static int32_t is_table[2][16];
154 static int32_t is_table_lsf[2][2][16];
155 static int32_t csa_table[8][4];
156 static float csa_table_float[8][4];
157 static int32_t mdct_win[8][36];
158
159 /* lower 2 bits: modulo 3, higher bits: shift */
160 static uint16_t scale_factor_modshift[64];
161 /* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
162 static int32_t scale_factor_mult[15][3];
163 /* mult table for layer 2 group quantization */
164
165 #define SCALE_GEN(v) \
166 { FIXR(1.0 * (v)), FIXR(0.7937005259 * (v)), FIXR(0.6299605249 * (v)) }
167
168 static const int32_t scale_factor_mult2[3][3] = {
169     SCALE_GEN(4.0 / 3.0), /* 3 steps */
170     SCALE_GEN(4.0 / 5.0), /* 5 steps */
171     SCALE_GEN(4.0 / 9.0), /* 9 steps */
172 };
173
174 static DECLARE_ALIGNED_16(MPA_INT, window[512]);
175
176 /* layer 1 unscaling */
177 /* n = number of bits of the mantissa minus 1 */
178 static inline int l1_unscale(int n, int mant, int scale_factor)
179 {
180     int shift, mod;
181     int64_t val;
182
183     shift = scale_factor_modshift[scale_factor];
184     mod = shift & 3;
185     shift >>= 2;
186     val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
187     shift += n;
188     /* NOTE: at this point, 1 <= shift >= 21 + 15 */
189     return (int)((val + (1LL << (shift - 1))) >> shift);
190 }
191
192 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
193 {
194     int shift, mod, val;
195
196     shift = scale_factor_modshift[scale_factor];
197     mod = shift & 3;
198     shift >>= 2;
199
200     val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
201     /* NOTE: at this point, 0 <= shift <= 21 */
202     if (shift > 0)
203         val = (val + (1 << (shift - 1))) >> shift;
204     return val;
205 }
206
207 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
208 static inline int l3_unscale(int value, int exponent)
209 {
210     unsigned int m;
211     int e;
212
213     e = table_4_3_exp  [4*value + (exponent&3)];
214     m = table_4_3_value[4*value + (exponent&3)];
215     e -= (exponent >> 2);
216     assert(e>=1);
217     if (e > 31)
218         return 0;
219     m = (m + (1 << (e-1))) >> e;
220
221     return m;
222 }
223
224 /* all integer n^(4/3) computation code */
225 #define DEV_ORDER 13
226
227 #define POW_FRAC_BITS 24
228 #define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
229 #define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
230 #define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
231
232 static int dev_4_3_coefs[DEV_ORDER];
233
234 #if 0 /* unused */
235 static int pow_mult3[3] = {
236     POW_FIX(1.0),
237     POW_FIX(1.25992104989487316476),
238     POW_FIX(1.58740105196819947474),
239 };
240 #endif
241
242 static void int_pow_init(void)
243 {
244     int i, a;
245
246     a = POW_FIX(1.0);
247     for(i=0;i<DEV_ORDER;i++) {
248         a = POW_MULL(a, POW_FIX(4.0 / 3.0) - i * POW_FIX(1.0)) / (i + 1);
249         dev_4_3_coefs[i] = a;
250     }
251 }
252
253 #if 0 /* unused, remove? */
254 /* return the mantissa and the binary exponent */
255 static int int_pow(int i, int *exp_ptr)
256 {
257     int e, er, eq, j;
258     int a, a1;
259
260     /* renormalize */
261     a = i;
262     e = POW_FRAC_BITS;
263     while (a < (1 << (POW_FRAC_BITS - 1))) {
264         a = a << 1;
265         e--;
266     }
267     a -= (1 << POW_FRAC_BITS);
268     a1 = 0;
269     for(j = DEV_ORDER - 1; j >= 0; j--)
270         a1 = POW_MULL(a, dev_4_3_coefs[j] + a1);
271     a = (1 << POW_FRAC_BITS) + a1;
272     /* exponent compute (exact) */
273     e = e * 4;
274     er = e % 3;
275     eq = e / 3;
276     a = POW_MULL(a, pow_mult3[er]);
277     while (a >= 2 * POW_FRAC_ONE) {
278         a = a >> 1;
279         eq++;
280     }
281     /* convert to float */
282     while (a < POW_FRAC_ONE) {
283         a = a << 1;
284         eq--;
285     }
286     /* now POW_FRAC_ONE <= a < 2 * POW_FRAC_ONE */
287 #if POW_FRAC_BITS > FRAC_BITS
288     a = (a + (1 << (POW_FRAC_BITS - FRAC_BITS - 1))) >> (POW_FRAC_BITS - FRAC_BITS);
289     /* correct overflow */
290     if (a >= 2 * (1 << FRAC_BITS)) {
291         a = a >> 1;
292         eq++;
293     }
294 #endif
295     *exp_ptr = eq;
296     return a;
297 }
298 #endif
299
300 static int decode_init(AVCodecContext * avctx)
301 {
302     MPADecodeContext *s = avctx->priv_data;
303     static int init=0;
304     int i, j, k;
305
306     s->avctx = avctx;
307
308 #if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
309     avctx->sample_fmt= SAMPLE_FMT_S32;
310 #else
311     avctx->sample_fmt= SAMPLE_FMT_S16;
312 #endif
313     s->error_resilience= avctx->error_resilience;
314
315     if(avctx->antialias_algo != FF_AA_FLOAT)
316         s->compute_antialias= compute_antialias_integer;
317     else
318         s->compute_antialias= compute_antialias_float;
319
320     if (!init && !avctx->parse_only) {
321         /* scale factors table for layer 1/2 */
322         for(i=0;i<64;i++) {
323             int shift, mod;
324             /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
325             shift = (i / 3);
326             mod = i % 3;
327             scale_factor_modshift[i] = mod | (shift << 2);
328         }
329
330         /* scale factor multiply for layer 1 */
331         for(i=0;i<15;i++) {
332             int n, norm;
333             n = i + 2;
334             norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
335             scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm);
336             scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm);
337             scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm);
338             dprintf(avctx, "%d: norm=%x s=%x %x %x\n",
339                     i, norm,
340                     scale_factor_mult[i][0],
341                     scale_factor_mult[i][1],
342                     scale_factor_mult[i][2]);
343         }
344
345         ff_mpa_synth_init(window);
346
347         /* huffman decode tables */
348         for(i=1;i<16;i++) {
349             const HuffTable *h = &mpa_huff_tables[i];
350             int xsize, x, y;
351             unsigned int n;
352             uint8_t  tmp_bits [512];
353             uint16_t tmp_codes[512];
354
355             memset(tmp_bits , 0, sizeof(tmp_bits ));
356             memset(tmp_codes, 0, sizeof(tmp_codes));
357
358             xsize = h->xsize;
359             n = xsize * xsize;
360
361             j = 0;
362             for(x=0;x<xsize;x++) {
363                 for(y=0;y<xsize;y++){
364                     tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
365                     tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
366                 }
367             }
368
369             /* XXX: fail test */
370             init_vlc(&huff_vlc[i], 7, 512,
371                      tmp_bits, 1, 1, tmp_codes, 2, 2, 1);
372         }
373         for(i=0;i<2;i++) {
374             init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
375                      mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);
376         }
377
378         for(i=0;i<9;i++) {
379             k = 0;
380             for(j=0;j<22;j++) {
381                 band_index_long[i][j] = k;
382                 k += band_size_long[i][j];
383             }
384             band_index_long[i][22] = k;
385         }
386
387         /* compute n ^ (4/3) and store it in mantissa/exp format */
388
389         int_pow_init();
390         for(i=1;i<TABLE_4_3_SIZE;i++) {
391             double f, fm;
392             int e, m;
393             f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);
394             fm = frexp(f, &e);
395             m = (uint32_t)(fm*(1LL<<31) + 0.5);
396             e+= FRAC_BITS - 31 + 5 - 100;
397
398             /* normalized to FRAC_BITS */
399             table_4_3_value[i] = m;
400 //            av_log(NULL, AV_LOG_DEBUG, "%d %d %f\n", i, m, pow((double)i, 4.0 / 3.0));
401             table_4_3_exp[i] = -e;
402         }
403         for(i=0; i<512*16; i++){
404             int exponent= (i>>4);
405             double f= pow(i&15, 4.0 / 3.0) * pow(2, (exponent-400)*0.25 + FRAC_BITS + 5);
406             expval_table[exponent][i&15]= llrint(f);
407             if((i&15)==1)
408                 exp_table[exponent]= llrint(f);
409         }
410
411         for(i=0;i<7;i++) {
412             float f;
413             int v;
414             if (i != 6) {
415                 f = tan((double)i * M_PI / 12.0);
416                 v = FIXR(f / (1.0 + f));
417             } else {
418                 v = FIXR(1.0);
419             }
420             is_table[0][i] = v;
421             is_table[1][6 - i] = v;
422         }
423         /* invalid values */
424         for(i=7;i<16;i++)
425             is_table[0][i] = is_table[1][i] = 0.0;
426
427         for(i=0;i<16;i++) {
428             double f;
429             int e, k;
430
431             for(j=0;j<2;j++) {
432                 e = -(j + 1) * ((i + 1) >> 1);
433                 f = pow(2.0, e / 4.0);
434                 k = i & 1;
435                 is_table_lsf[j][k ^ 1][i] = FIXR(f);
436                 is_table_lsf[j][k][i] = FIXR(1.0);
437                 dprintf(avctx, "is_table_lsf %d %d: %x %x\n",
438                         i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
439             }
440         }
441
442         for(i=0;i<8;i++) {
443             float ci, cs, ca;
444             ci = ci_table[i];
445             cs = 1.0 / sqrt(1.0 + ci * ci);
446             ca = cs * ci;
447             csa_table[i][0] = FIXHR(cs/4);
448             csa_table[i][1] = FIXHR(ca/4);
449             csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
450             csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
451             csa_table_float[i][0] = cs;
452             csa_table_float[i][1] = ca;
453             csa_table_float[i][2] = ca + cs;
454             csa_table_float[i][3] = ca - cs;
455 //            printf("%d %d %d %d\n", FIX(cs), FIX(cs-1), FIX(ca), FIX(cs)-FIX(ca));
456 //            av_log(NULL, AV_LOG_DEBUG,"%f %f %f %f\n", cs, ca, ca+cs, ca-cs);
457         }
458
459         /* compute mdct windows */
460         for(i=0;i<36;i++) {
461             for(j=0; j<4; j++){
462                 double d;
463
464                 if(j==2 && i%3 != 1)
465                     continue;
466
467                 d= sin(M_PI * (i + 0.5) / 36.0);
468                 if(j==1){
469                     if     (i>=30) d= 0;
470                     else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);
471                     else if(i>=18) d= 1;
472                 }else if(j==3){
473                     if     (i<  6) d= 0;
474                     else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);
475                     else if(i< 18) d= 1;
476                 }
477                 //merge last stage of imdct into the window coefficients
478                 d*= 0.5 / cos(M_PI*(2*i + 19)/72);
479
480                 if(j==2)
481                     mdct_win[j][i/3] = FIXHR((d / (1<<5)));
482                 else
483                     mdct_win[j][i  ] = FIXHR((d / (1<<5)));
484 //                av_log(NULL, AV_LOG_DEBUG, "%2d %d %f\n", i,j,d / (1<<5));
485             }
486         }
487
488         /* NOTE: we do frequency inversion adter the MDCT by changing
489            the sign of the right window coefs */
490         for(j=0;j<4;j++) {
491             for(i=0;i<36;i+=2) {
492                 mdct_win[j + 4][i] = mdct_win[j][i];
493                 mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
494             }
495         }
496
497 #if defined(DEBUG)
498         for(j=0;j<8;j++) {
499             av_log(avctx, AV_LOG_DEBUG, "win%d=\n", j);
500             for(i=0;i<36;i++)
501                 av_log(avctx, AV_LOG_DEBUG, "%f, ", (double)mdct_win[j][i] / FRAC_ONE);
502             av_log(avctx, AV_LOG_DEBUG, "\n");
503         }
504 #endif
505         init = 1;
506     }
507
508 #ifdef DEBUG
509     s->frame_count = 0;
510 #endif
511     if (avctx->codec_id == CODEC_ID_MP3ADU)
512         s->adu_mode = 1;
513     return 0;
514 }
515
516 /* tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j))) */
517
518 /* cos(i*pi/64) */
519
520 #define COS0_0  FIXHR(0.50060299823519630134/2)
521 #define COS0_1  FIXHR(0.50547095989754365998/2)
522 #define COS0_2  FIXHR(0.51544730992262454697/2)
523 #define COS0_3  FIXHR(0.53104259108978417447/2)
524 #define COS0_4  FIXHR(0.55310389603444452782/2)
525 #define COS0_5  FIXHR(0.58293496820613387367/2)
526 #define COS0_6  FIXHR(0.62250412303566481615/2)
527 #define COS0_7  FIXHR(0.67480834145500574602/2)
528 #define COS0_8  FIXHR(0.74453627100229844977/2)
529 #define COS0_9  FIXHR(0.83934964541552703873/2)
530 #define COS0_10 FIXHR(0.97256823786196069369/2)
531 #define COS0_11 FIXHR(1.16943993343288495515/4)
532 #define COS0_12 FIXHR(1.48416461631416627724/4)
533 #define COS0_13 FIXHR(2.05778100995341155085/8)
534 #define COS0_14 FIXHR(3.40760841846871878570/8)
535 #define COS0_15 FIXHR(10.19000812354805681150/32)
536
537 #define COS1_0 FIXHR(0.50241928618815570551/2)
538 #define COS1_1 FIXHR(0.52249861493968888062/2)
539 #define COS1_2 FIXHR(0.56694403481635770368/2)
540 #define COS1_3 FIXHR(0.64682178335999012954/2)
541 #define COS1_4 FIXHR(0.78815462345125022473/2)
542 #define COS1_5 FIXHR(1.06067768599034747134/4)
543 #define COS1_6 FIXHR(1.72244709823833392782/4)
544 #define COS1_7 FIXHR(5.10114861868916385802/16)
545
546 #define COS2_0 FIXHR(0.50979557910415916894/2)
547 #define COS2_1 FIXHR(0.60134488693504528054/2)
548 #define COS2_2 FIXHR(0.89997622313641570463/2)
549 #define COS2_3 FIXHR(2.56291544774150617881/8)
550
551 #define COS3_0 FIXHR(0.54119610014619698439/2)
552 #define COS3_1 FIXHR(1.30656296487637652785/4)
553
554 #define COS4_0 FIXHR(0.70710678118654752439/2)
555
556 /* butterfly operator */
557 #define BF(a, b, c, s)\
558 {\
559     tmp0 = tab[a] + tab[b];\
560     tmp1 = tab[a] - tab[b];\
561     tab[a] = tmp0;\
562     tab[b] = MULH(tmp1<<(s), c);\
563 }
564
565 #define BF1(a, b, c, d)\
566 {\
567     BF(a, b, COS4_0, 1);\
568     BF(c, d,-COS4_0, 1);\
569     tab[c] += tab[d];\
570 }
571
572 #define BF2(a, b, c, d)\
573 {\
574     BF(a, b, COS4_0, 1);\
575     BF(c, d,-COS4_0, 1);\
576     tab[c] += tab[d];\
577     tab[a] += tab[c];\
578     tab[c] += tab[b];\
579     tab[b] += tab[d];\
580 }
581
582 #define ADD(a, b) tab[a] += tab[b]
583
584 /* DCT32 without 1/sqrt(2) coef zero scaling. */
585 static void dct32(int32_t *out, int32_t *tab)
586 {
587     int tmp0, tmp1;
588
589     /* pass 1 */
590     BF( 0, 31, COS0_0 , 1);
591     BF(15, 16, COS0_15, 5);
592     /* pass 2 */
593     BF( 0, 15, COS1_0 , 1);
594     BF(16, 31,-COS1_0 , 1);
595     /* pass 1 */
596     BF( 7, 24, COS0_7 , 1);
597     BF( 8, 23, COS0_8 , 1);
598     /* pass 2 */
599     BF( 7,  8, COS1_7 , 4);
600     BF(23, 24,-COS1_7 , 4);
601     /* pass 3 */
602     BF( 0,  7, COS2_0 , 1);
603     BF( 8, 15,-COS2_0 , 1);
604     BF(16, 23, COS2_0 , 1);
605     BF(24, 31,-COS2_0 , 1);
606     /* pass 1 */
607     BF( 3, 28, COS0_3 , 1);
608     BF(12, 19, COS0_12, 2);
609     /* pass 2 */
610     BF( 3, 12, COS1_3 , 1);
611     BF(19, 28,-COS1_3 , 1);
612     /* pass 1 */
613     BF( 4, 27, COS0_4 , 1);
614     BF(11, 20, COS0_11, 2);
615     /* pass 2 */
616     BF( 4, 11, COS1_4 , 1);
617     BF(20, 27,-COS1_4 , 1);
618     /* pass 3 */
619     BF( 3,  4, COS2_3 , 3);
620     BF(11, 12,-COS2_3 , 3);
621     BF(19, 20, COS2_3 , 3);
622     BF(27, 28,-COS2_3 , 3);
623     /* pass 4 */
624     BF( 0,  3, COS3_0 , 1);
625     BF( 4,  7,-COS3_0 , 1);
626     BF( 8, 11, COS3_0 , 1);
627     BF(12, 15,-COS3_0 , 1);
628     BF(16, 19, COS3_0 , 1);
629     BF(20, 23,-COS3_0 , 1);
630     BF(24, 27, COS3_0 , 1);
631     BF(28, 31,-COS3_0 , 1);
632
633
634
635     /* pass 1 */
636     BF( 1, 30, COS0_1 , 1);
637     BF(14, 17, COS0_14, 3);
638     /* pass 2 */
639     BF( 1, 14, COS1_1 , 1);
640     BF(17, 30,-COS1_1 , 1);
641     /* pass 1 */
642     BF( 6, 25, COS0_6 , 1);
643     BF( 9, 22, COS0_9 , 1);
644     /* pass 2 */
645     BF( 6,  9, COS1_6 , 2);
646     BF(22, 25,-COS1_6 , 2);
647     /* pass 3 */
648     BF( 1,  6, COS2_1 , 1);
649     BF( 9, 14,-COS2_1 , 1);
650     BF(17, 22, COS2_1 , 1);
651     BF(25, 30,-COS2_1 , 1);
652
653     /* pass 1 */
654     BF( 2, 29, COS0_2 , 1);
655     BF(13, 18, COS0_13, 3);
656     /* pass 2 */
657     BF( 2, 13, COS1_2 , 1);
658     BF(18, 29,-COS1_2 , 1);
659     /* pass 1 */
660     BF( 5, 26, COS0_5 , 1);
661     BF(10, 21, COS0_10, 1);
662     /* pass 2 */
663     BF( 5, 10, COS1_5 , 2);
664     BF(21, 26,-COS1_5 , 2);
665     /* pass 3 */
666     BF( 2,  5, COS2_2 , 1);
667     BF(10, 13,-COS2_2 , 1);
668     BF(18, 21, COS2_2 , 1);
669     BF(26, 29,-COS2_2 , 1);
670     /* pass 4 */
671     BF( 1,  2, COS3_1 , 2);
672     BF( 5,  6,-COS3_1 , 2);
673     BF( 9, 10, COS3_1 , 2);
674     BF(13, 14,-COS3_1 , 2);
675     BF(17, 18, COS3_1 , 2);
676     BF(21, 22,-COS3_1 , 2);
677     BF(25, 26, COS3_1 , 2);
678     BF(29, 30,-COS3_1 , 2);
679
680     /* pass 5 */
681     BF1( 0,  1,  2,  3);
682     BF2( 4,  5,  6,  7);
683     BF1( 8,  9, 10, 11);
684     BF2(12, 13, 14, 15);
685     BF1(16, 17, 18, 19);
686     BF2(20, 21, 22, 23);
687     BF1(24, 25, 26, 27);
688     BF2(28, 29, 30, 31);
689
690     /* pass 6 */
691
692     ADD( 8, 12);
693     ADD(12, 10);
694     ADD(10, 14);
695     ADD(14,  9);
696     ADD( 9, 13);
697     ADD(13, 11);
698     ADD(11, 15);
699
700     out[ 0] = tab[0];
701     out[16] = tab[1];
702     out[ 8] = tab[2];
703     out[24] = tab[3];
704     out[ 4] = tab[4];
705     out[20] = tab[5];
706     out[12] = tab[6];
707     out[28] = tab[7];
708     out[ 2] = tab[8];
709     out[18] = tab[9];
710     out[10] = tab[10];
711     out[26] = tab[11];
712     out[ 6] = tab[12];
713     out[22] = tab[13];
714     out[14] = tab[14];
715     out[30] = tab[15];
716
717     ADD(24, 28);
718     ADD(28, 26);
719     ADD(26, 30);
720     ADD(30, 25);
721     ADD(25, 29);
722     ADD(29, 27);
723     ADD(27, 31);
724
725     out[ 1] = tab[16] + tab[24];
726     out[17] = tab[17] + tab[25];
727     out[ 9] = tab[18] + tab[26];
728     out[25] = tab[19] + tab[27];
729     out[ 5] = tab[20] + tab[28];
730     out[21] = tab[21] + tab[29];
731     out[13] = tab[22] + tab[30];
732     out[29] = tab[23] + tab[31];
733     out[ 3] = tab[24] + tab[20];
734     out[19] = tab[25] + tab[21];
735     out[11] = tab[26] + tab[22];
736     out[27] = tab[27] + tab[23];
737     out[ 7] = tab[28] + tab[18];
738     out[23] = tab[29] + tab[19];
739     out[15] = tab[30] + tab[17];
740     out[31] = tab[31];
741 }
742
743 #if FRAC_BITS <= 15
744
745 static inline int round_sample(int *sum)
746 {
747     int sum1;
748     sum1 = (*sum) >> OUT_SHIFT;
749     *sum &= (1<<OUT_SHIFT)-1;
750     if (sum1 < OUT_MIN)
751         sum1 = OUT_MIN;
752     else if (sum1 > OUT_MAX)
753         sum1 = OUT_MAX;
754     return sum1;
755 }
756
757 /* signed 16x16 -> 32 multiply add accumulate */
758 #define MACS(rt, ra, rb) MAC16(rt, ra, rb)
759
760 /* signed 16x16 -> 32 multiply */
761 #define MULS(ra, rb) MUL16(ra, rb)
762
763 #else
764
765 static inline int round_sample(int64_t *sum)
766 {
767     int sum1;
768     sum1 = (int)((*sum) >> OUT_SHIFT);
769     *sum &= (1<<OUT_SHIFT)-1;
770     if (sum1 < OUT_MIN)
771         sum1 = OUT_MIN;
772     else if (sum1 > OUT_MAX)
773         sum1 = OUT_MAX;
774     return sum1;
775 }
776
777 #   define MULS(ra, rb) MUL64(ra, rb)
778 #endif
779
780 #define SUM8(sum, op, w, p) \
781 {                                               \
782     sum op MULS((w)[0 * 64], p[0 * 64]);\
783     sum op MULS((w)[1 * 64], p[1 * 64]);\
784     sum op MULS((w)[2 * 64], p[2 * 64]);\
785     sum op MULS((w)[3 * 64], p[3 * 64]);\
786     sum op MULS((w)[4 * 64], p[4 * 64]);\
787     sum op MULS((w)[5 * 64], p[5 * 64]);\
788     sum op MULS((w)[6 * 64], p[6 * 64]);\
789     sum op MULS((w)[7 * 64], p[7 * 64]);\
790 }
791
792 #define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
793 {                                               \
794     int tmp;\
795     tmp = p[0 * 64];\
796     sum1 op1 MULS((w1)[0 * 64], tmp);\
797     sum2 op2 MULS((w2)[0 * 64], tmp);\
798     tmp = p[1 * 64];\
799     sum1 op1 MULS((w1)[1 * 64], tmp);\
800     sum2 op2 MULS((w2)[1 * 64], tmp);\
801     tmp = p[2 * 64];\
802     sum1 op1 MULS((w1)[2 * 64], tmp);\
803     sum2 op2 MULS((w2)[2 * 64], tmp);\
804     tmp = p[3 * 64];\
805     sum1 op1 MULS((w1)[3 * 64], tmp);\
806     sum2 op2 MULS((w2)[3 * 64], tmp);\
807     tmp = p[4 * 64];\
808     sum1 op1 MULS((w1)[4 * 64], tmp);\
809     sum2 op2 MULS((w2)[4 * 64], tmp);\
810     tmp = p[5 * 64];\
811     sum1 op1 MULS((w1)[5 * 64], tmp);\
812     sum2 op2 MULS((w2)[5 * 64], tmp);\
813     tmp = p[6 * 64];\
814     sum1 op1 MULS((w1)[6 * 64], tmp);\
815     sum2 op2 MULS((w2)[6 * 64], tmp);\
816     tmp = p[7 * 64];\
817     sum1 op1 MULS((w1)[7 * 64], tmp);\
818     sum2 op2 MULS((w2)[7 * 64], tmp);\
819 }
820
821 void ff_mpa_synth_init(MPA_INT *window)
822 {
823     int i;
824
825     /* max = 18760, max sum over all 16 coefs : 44736 */
826     for(i=0;i<257;i++) {
827         int v;
828         v = ff_mpa_enwindow[i];
829 #if WFRAC_BITS < 16
830         v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
831 #endif
832         window[i] = v;
833         if ((i & 63) != 0)
834             v = -v;
835         if (i != 0)
836             window[512 - i] = v;
837     }
838 }
839
840 /* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
841    32 samples. */
842 /* XXX: optimize by avoiding ring buffer usage */
843 void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
844                          MPA_INT *window, int *dither_state,
845                          OUT_INT *samples, int incr,
846                          int32_t sb_samples[SBLIMIT])
847 {
848     int32_t tmp[32];
849     register MPA_INT *synth_buf;
850     register const MPA_INT *w, *w2, *p;
851     int j, offset, v;
852     OUT_INT *samples2;
853 #if FRAC_BITS <= 15
854     int sum, sum2;
855 #else
856     int64_t sum, sum2;
857 #endif
858
859     dct32(tmp, sb_samples);
860
861     offset = *synth_buf_offset;
862     synth_buf = synth_buf_ptr + offset;
863
864     for(j=0;j<32;j++) {
865         v = tmp[j];
866 #if FRAC_BITS <= 15
867         /* NOTE: can cause a loss in precision if very high amplitude
868            sound */
869         if (v > 32767)
870             v = 32767;
871         else if (v < -32768)
872             v = -32768;
873 #endif
874         synth_buf[j] = v;
875     }
876     /* copy to avoid wrap */
877     memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
878
879     samples2 = samples + 31 * incr;
880     w = window;
881     w2 = window + 31;
882
883     sum = *dither_state;
884     p = synth_buf + 16;
885     SUM8(sum, +=, w, p);
886     p = synth_buf + 48;
887     SUM8(sum, -=, w + 32, p);
888     *samples = round_sample(&sum);
889     samples += incr;
890     w++;
891
892     /* we calculate two samples at the same time to avoid one memory
893        access per two sample */
894     for(j=1;j<16;j++) {
895         sum2 = 0;
896         p = synth_buf + 16 + j;
897         SUM8P2(sum, +=, sum2, -=, w, w2, p);
898         p = synth_buf + 48 - j;
899         SUM8P2(sum, -=, sum2, -=, w + 32, w2 + 32, p);
900
901         *samples = round_sample(&sum);
902         samples += incr;
903         sum += sum2;
904         *samples2 = round_sample(&sum);
905         samples2 -= incr;
906         w++;
907         w2--;
908     }
909
910     p = synth_buf + 32;
911     SUM8(sum, -=, w + 32, p);
912     *samples = round_sample(&sum);
913     *dither_state= sum;
914
915     offset = (offset - 32) & 511;
916     *synth_buf_offset = offset;
917 }
918
919 #define C3 FIXHR(0.86602540378443864676/2)
920
921 /* 0.5 / cos(pi*(2*i+1)/36) */
922 static const int icos36[9] = {
923     FIXR(0.50190991877167369479),
924     FIXR(0.51763809020504152469), //0
925     FIXR(0.55168895948124587824),
926     FIXR(0.61038729438072803416),
927     FIXR(0.70710678118654752439), //1
928     FIXR(0.87172339781054900991),
929     FIXR(1.18310079157624925896),
930     FIXR(1.93185165257813657349), //2
931     FIXR(5.73685662283492756461),
932 };
933
934 /* 0.5 / cos(pi*(2*i+1)/36) */
935 static const int icos36h[9] = {
936     FIXHR(0.50190991877167369479/2),
937     FIXHR(0.51763809020504152469/2), //0
938     FIXHR(0.55168895948124587824/2),
939     FIXHR(0.61038729438072803416/2),
940     FIXHR(0.70710678118654752439/2), //1
941     FIXHR(0.87172339781054900991/2),
942     FIXHR(1.18310079157624925896/4),
943     FIXHR(1.93185165257813657349/4), //2
944 //    FIXHR(5.73685662283492756461),
945 };
946
947 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
948    cases. */
949 static void imdct12(int *out, int *in)
950 {
951     int in0, in1, in2, in3, in4, in5, t1, t2;
952
953     in0= in[0*3];
954     in1= in[1*3] + in[0*3];
955     in2= in[2*3] + in[1*3];
956     in3= in[3*3] + in[2*3];
957     in4= in[4*3] + in[3*3];
958     in5= in[5*3] + in[4*3];
959     in5 += in3;
960     in3 += in1;
961
962     in2= MULH(2*in2, C3);
963     in3= MULH(4*in3, C3);
964
965     t1 = in0 - in4;
966     t2 = MULH(2*(in1 - in5), icos36h[4]);
967
968     out[ 7]=
969     out[10]= t1 + t2;
970     out[ 1]=
971     out[ 4]= t1 - t2;
972
973     in0 += in4>>1;
974     in4 = in0 + in2;
975     in5 += 2*in1;
976     in1 = MULH(in5 + in3, icos36h[1]);
977     out[ 8]=
978     out[ 9]= in4 + in1;
979     out[ 2]=
980     out[ 3]= in4 - in1;
981
982     in0 -= in2;
983     in5 = MULH(2*(in5 - in3), icos36h[7]);
984     out[ 0]=
985     out[ 5]= in0 - in5;
986     out[ 6]=
987     out[11]= in0 + in5;
988 }
989
990 /* cos(pi*i/18) */
991 #define C1 FIXHR(0.98480775301220805936/2)
992 #define C2 FIXHR(0.93969262078590838405/2)
993 #define C3 FIXHR(0.86602540378443864676/2)
994 #define C4 FIXHR(0.76604444311897803520/2)
995 #define C5 FIXHR(0.64278760968653932632/2)
996 #define C6 FIXHR(0.5/2)
997 #define C7 FIXHR(0.34202014332566873304/2)
998 #define C8 FIXHR(0.17364817766693034885/2)
999
1000
1001 /* using Lee like decomposition followed by hand coded 9 points DCT */
1002 static void imdct36(int *out, int *buf, int *in, int *win)
1003 {
1004     int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
1005     int tmp[18], *tmp1, *in1;
1006
1007     for(i=17;i>=1;i--)
1008         in[i] += in[i-1];
1009     for(i=17;i>=3;i-=2)
1010         in[i] += in[i-2];
1011
1012     for(j=0;j<2;j++) {
1013         tmp1 = tmp + j;
1014         in1 = in + j;
1015 #if 0
1016 //more accurate but slower
1017         int64_t t0, t1, t2, t3;
1018         t2 = in1[2*4] + in1[2*8] - in1[2*2];
1019
1020         t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
1021         t1 = in1[2*0] - in1[2*6];
1022         tmp1[ 6] = t1 - (t2>>1);
1023         tmp1[16] = t1 + t2;
1024
1025         t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
1026         t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
1027         t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
1028
1029         tmp1[10] = (t3 - t0 - t2) >> 32;
1030         tmp1[ 2] = (t3 + t0 + t1) >> 32;
1031         tmp1[14] = (t3 + t2 - t1) >> 32;
1032
1033         tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1034         t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
1035         t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
1036         t0 = MUL64(2*in1[2*3], C3);
1037
1038         t1 = MUL64(2*(in1[2*1] + in1[2*7]),   -C5);
1039
1040         tmp1[ 0] = (t2 + t3 + t0) >> 32;
1041         tmp1[12] = (t2 + t1 - t0) >> 32;
1042         tmp1[ 8] = (t3 - t1 - t0) >> 32;
1043 #else
1044         t2 = in1[2*4] + in1[2*8] - in1[2*2];
1045
1046         t3 = in1[2*0] + (in1[2*6]>>1);
1047         t1 = in1[2*0] - in1[2*6];
1048         tmp1[ 6] = t1 - (t2>>1);
1049         tmp1[16] = t1 + t2;
1050
1051         t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1052         t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1053         t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1054
1055         tmp1[10] = t3 - t0 - t2;
1056         tmp1[ 2] = t3 + t0 + t1;
1057         tmp1[14] = t3 + t2 - t1;
1058
1059         tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1060         t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1061         t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1062         t0 = MULH(2*in1[2*3], C3);
1063
1064         t1 = MULH(2*(in1[2*1] + in1[2*7]),   -C5);
1065
1066         tmp1[ 0] = t2 + t3 + t0;
1067         tmp1[12] = t2 + t1 - t0;
1068         tmp1[ 8] = t3 - t1 - t0;
1069 #endif
1070     }
1071
1072     i = 0;
1073     for(j=0;j<4;j++) {
1074         t0 = tmp[i];
1075         t1 = tmp[i + 2];
1076         s0 = t1 + t0;
1077         s2 = t1 - t0;
1078
1079         t2 = tmp[i + 1];
1080         t3 = tmp[i + 3];
1081         s1 = MULH(2*(t3 + t2), icos36h[j]);
1082         s3 = MULL(t3 - t2, icos36[8 - j]);
1083
1084         t0 = s0 + s1;
1085         t1 = s0 - s1;
1086         out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1087         out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1088         buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1089         buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1090
1091         t0 = s2 + s3;
1092         t1 = s2 - s3;
1093         out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1094         out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1095         buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1096         buf[      + j] = MULH(t0, win[18         + j]);
1097         i += 4;
1098     }
1099
1100     s0 = tmp[16];
1101     s1 = MULH(2*tmp[17], icos36h[4]);
1102     t0 = s0 + s1;
1103     t1 = s0 - s1;
1104     out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
1105     out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
1106     buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
1107     buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
1108 }
1109
1110 /* header decoding. MUST check the header before because no
1111    consistency check is done there. Return 1 if free format found and
1112    that the frame size must be computed externally */
1113 static int decode_header(MPADecodeContext *s, uint32_t header)
1114 {
1115     int sample_rate, frame_size, mpeg25, padding;
1116     int sample_rate_index, bitrate_index;
1117     if (header & (1<<20)) {
1118         s->lsf = (header & (1<<19)) ? 0 : 1;
1119         mpeg25 = 0;
1120     } else {
1121         s->lsf = 1;
1122         mpeg25 = 1;
1123     }
1124
1125     s->layer = 4 - ((header >> 17) & 3);
1126     /* extract frequency */
1127     sample_rate_index = (header >> 10) & 3;
1128     sample_rate = ff_mpa_freq_tab[sample_rate_index] >> (s->lsf + mpeg25);
1129     sample_rate_index += 3 * (s->lsf + mpeg25);
1130     s->sample_rate_index = sample_rate_index;
1131     s->error_protection = ((header >> 16) & 1) ^ 1;
1132     s->sample_rate = sample_rate;
1133
1134     bitrate_index = (header >> 12) & 0xf;
1135     padding = (header >> 9) & 1;
1136     //extension = (header >> 8) & 1;
1137     s->mode = (header >> 6) & 3;
1138     s->mode_ext = (header >> 4) & 3;
1139     //copyright = (header >> 3) & 1;
1140     //original = (header >> 2) & 1;
1141     //emphasis = header & 3;
1142
1143     if (s->mode == MPA_MONO)
1144         s->nb_channels = 1;
1145     else
1146         s->nb_channels = 2;
1147
1148     if (bitrate_index != 0) {
1149         frame_size = ff_mpa_bitrate_tab[s->lsf][s->layer - 1][bitrate_index];
1150         s->bit_rate = frame_size * 1000;
1151         switch(s->layer) {
1152         case 1:
1153             frame_size = (frame_size * 12000) / sample_rate;
1154             frame_size = (frame_size + padding) * 4;
1155             break;
1156         case 2:
1157             frame_size = (frame_size * 144000) / sample_rate;
1158             frame_size += padding;
1159             break;
1160         default:
1161         case 3:
1162             frame_size = (frame_size * 144000) / (sample_rate << s->lsf);
1163             frame_size += padding;
1164             break;
1165         }
1166         s->frame_size = frame_size;
1167     } else {
1168         /* if no frame size computed, signal it */
1169         return 1;
1170     }
1171
1172 #if defined(DEBUG)
1173     dprintf(s->avctx, "layer%d, %d Hz, %d kbits/s, ",
1174            s->layer, s->sample_rate, s->bit_rate);
1175     if (s->nb_channels == 2) {
1176         if (s->layer == 3) {
1177             if (s->mode_ext & MODE_EXT_MS_STEREO)
1178                 dprintf(s->avctx, "ms-");
1179             if (s->mode_ext & MODE_EXT_I_STEREO)
1180                 dprintf(s->avctx, "i-");
1181         }
1182         dprintf(s->avctx, "stereo");
1183     } else {
1184         dprintf(s->avctx, "mono");
1185     }
1186     dprintf(s->avctx, "\n");
1187 #endif
1188     return 0;
1189 }
1190
1191 /* useful helper to get mpeg audio stream infos. Return -1 if error in
1192    header, otherwise the coded frame size in bytes */
1193 int mpa_decode_header(AVCodecContext *avctx, uint32_t head, int *sample_rate)
1194 {
1195     MPADecodeContext s1, *s = &s1;
1196     s1.avctx = avctx;
1197
1198     if (ff_mpa_check_header(head) != 0)
1199         return -1;
1200
1201     if (decode_header(s, head) != 0) {
1202         return -1;
1203     }
1204
1205     switch(s->layer) {
1206     case 1:
1207         avctx->frame_size = 384;
1208         break;
1209     case 2:
1210         avctx->frame_size = 1152;
1211         break;
1212     default:
1213     case 3:
1214         if (s->lsf)
1215             avctx->frame_size = 576;
1216         else
1217             avctx->frame_size = 1152;
1218         break;
1219     }
1220
1221     *sample_rate = s->sample_rate;
1222     avctx->channels = s->nb_channels;
1223     avctx->bit_rate = s->bit_rate;
1224     avctx->sub_id = s->layer;
1225     return s->frame_size;
1226 }
1227
1228 /* return the number of decoded frames */
1229 static int mp_decode_layer1(MPADecodeContext *s)
1230 {
1231     int bound, i, v, n, ch, j, mant;
1232     uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1233     uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1234
1235     if (s->mode == MPA_JSTEREO)
1236         bound = (s->mode_ext + 1) * 4;
1237     else
1238         bound = SBLIMIT;
1239
1240     /* allocation bits */
1241     for(i=0;i<bound;i++) {
1242         for(ch=0;ch<s->nb_channels;ch++) {
1243             allocation[ch][i] = get_bits(&s->gb, 4);
1244         }
1245     }
1246     for(i=bound;i<SBLIMIT;i++) {
1247         allocation[0][i] = get_bits(&s->gb, 4);
1248     }
1249
1250     /* scale factors */
1251     for(i=0;i<bound;i++) {
1252         for(ch=0;ch<s->nb_channels;ch++) {
1253             if (allocation[ch][i])
1254                 scale_factors[ch][i] = get_bits(&s->gb, 6);
1255         }
1256     }
1257     for(i=bound;i<SBLIMIT;i++) {
1258         if (allocation[0][i]) {
1259             scale_factors[0][i] = get_bits(&s->gb, 6);
1260             scale_factors[1][i] = get_bits(&s->gb, 6);
1261         }
1262     }
1263
1264     /* compute samples */
1265     for(j=0;j<12;j++) {
1266         for(i=0;i<bound;i++) {
1267             for(ch=0;ch<s->nb_channels;ch++) {
1268                 n = allocation[ch][i];
1269                 if (n) {
1270                     mant = get_bits(&s->gb, n + 1);
1271                     v = l1_unscale(n, mant, scale_factors[ch][i]);
1272                 } else {
1273                     v = 0;
1274                 }
1275                 s->sb_samples[ch][j][i] = v;
1276             }
1277         }
1278         for(i=bound;i<SBLIMIT;i++) {
1279             n = allocation[0][i];
1280             if (n) {
1281                 mant = get_bits(&s->gb, n + 1);
1282                 v = l1_unscale(n, mant, scale_factors[0][i]);
1283                 s->sb_samples[0][j][i] = v;
1284                 v = l1_unscale(n, mant, scale_factors[1][i]);
1285                 s->sb_samples[1][j][i] = v;
1286             } else {
1287                 s->sb_samples[0][j][i] = 0;
1288                 s->sb_samples[1][j][i] = 0;
1289             }
1290         }
1291     }
1292     return 12;
1293 }
1294
1295 /* bitrate is in kb/s */
1296 int l2_select_table(int bitrate, int nb_channels, int freq, int lsf)
1297 {
1298     int ch_bitrate, table;
1299
1300     ch_bitrate = bitrate / nb_channels;
1301     if (!lsf) {
1302         if ((freq == 48000 && ch_bitrate >= 56) ||
1303             (ch_bitrate >= 56 && ch_bitrate <= 80))
1304             table = 0;
1305         else if (freq != 48000 && ch_bitrate >= 96)
1306             table = 1;
1307         else if (freq != 32000 && ch_bitrate <= 48)
1308             table = 2;
1309         else
1310             table = 3;
1311     } else {
1312         table = 4;
1313     }
1314     return table;
1315 }
1316
1317 static int mp_decode_layer2(MPADecodeContext *s)
1318 {
1319     int sblimit; /* number of used subbands */
1320     const unsigned char *alloc_table;
1321     int table, bit_alloc_bits, i, j, ch, bound, v;
1322     unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1323     unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1324     unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1325     int scale, qindex, bits, steps, k, l, m, b;
1326
1327     /* select decoding table */
1328     table = l2_select_table(s->bit_rate / 1000, s->nb_channels,
1329                             s->sample_rate, s->lsf);
1330     sblimit = ff_mpa_sblimit_table[table];
1331     alloc_table = ff_mpa_alloc_tables[table];
1332
1333     if (s->mode == MPA_JSTEREO)
1334         bound = (s->mode_ext + 1) * 4;
1335     else
1336         bound = sblimit;
1337
1338     dprintf(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
1339
1340     /* sanity check */
1341     if( bound > sblimit ) bound = sblimit;
1342
1343     /* parse bit allocation */
1344     j = 0;
1345     for(i=0;i<bound;i++) {
1346         bit_alloc_bits = alloc_table[j];
1347         for(ch=0;ch<s->nb_channels;ch++) {
1348             bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1349         }
1350         j += 1 << bit_alloc_bits;
1351     }
1352     for(i=bound;i<sblimit;i++) {
1353         bit_alloc_bits = alloc_table[j];
1354         v = get_bits(&s->gb, bit_alloc_bits);
1355         bit_alloc[0][i] = v;
1356         bit_alloc[1][i] = v;
1357         j += 1 << bit_alloc_bits;
1358     }
1359
1360 #ifdef DEBUG
1361     {
1362         for(ch=0;ch<s->nb_channels;ch++) {
1363             for(i=0;i<sblimit;i++)
1364                 dprintf(s->avctx, " %d", bit_alloc[ch][i]);
1365             dprintf(s->avctx, "\n");
1366         }
1367     }
1368 #endif
1369
1370     /* scale codes */
1371     for(i=0;i<sblimit;i++) {
1372         for(ch=0;ch<s->nb_channels;ch++) {
1373             if (bit_alloc[ch][i])
1374                 scale_code[ch][i] = get_bits(&s->gb, 2);
1375         }
1376     }
1377
1378     /* scale factors */
1379     for(i=0;i<sblimit;i++) {
1380         for(ch=0;ch<s->nb_channels;ch++) {
1381             if (bit_alloc[ch][i]) {
1382                 sf = scale_factors[ch][i];
1383                 switch(scale_code[ch][i]) {
1384                 default:
1385                 case 0:
1386                     sf[0] = get_bits(&s->gb, 6);
1387                     sf[1] = get_bits(&s->gb, 6);
1388                     sf[2] = get_bits(&s->gb, 6);
1389                     break;
1390                 case 2:
1391                     sf[0] = get_bits(&s->gb, 6);
1392                     sf[1] = sf[0];
1393                     sf[2] = sf[0];
1394                     break;
1395                 case 1:
1396                     sf[0] = get_bits(&s->gb, 6);
1397                     sf[2] = get_bits(&s->gb, 6);
1398                     sf[1] = sf[0];
1399                     break;
1400                 case 3:
1401                     sf[0] = get_bits(&s->gb, 6);
1402                     sf[2] = get_bits(&s->gb, 6);
1403                     sf[1] = sf[2];
1404                     break;
1405                 }
1406             }
1407         }
1408     }
1409
1410 #ifdef DEBUG
1411     for(ch=0;ch<s->nb_channels;ch++) {
1412         for(i=0;i<sblimit;i++) {
1413             if (bit_alloc[ch][i]) {
1414                 sf = scale_factors[ch][i];
1415                 dprintf(s->avctx, " %d %d %d", sf[0], sf[1], sf[2]);
1416             } else {
1417                 dprintf(s->avctx, " -");
1418             }
1419         }
1420         dprintf(s->avctx, "\n");
1421     }
1422 #endif
1423
1424     /* samples */
1425     for(k=0;k<3;k++) {
1426         for(l=0;l<12;l+=3) {
1427             j = 0;
1428             for(i=0;i<bound;i++) {
1429                 bit_alloc_bits = alloc_table[j];
1430                 for(ch=0;ch<s->nb_channels;ch++) {
1431                     b = bit_alloc[ch][i];
1432                     if (b) {
1433                         scale = scale_factors[ch][i][k];
1434                         qindex = alloc_table[j+b];
1435                         bits = ff_mpa_quant_bits[qindex];
1436                         if (bits < 0) {
1437                             /* 3 values at the same time */
1438                             v = get_bits(&s->gb, -bits);
1439                             steps = ff_mpa_quant_steps[qindex];
1440                             s->sb_samples[ch][k * 12 + l + 0][i] =
1441                                 l2_unscale_group(steps, v % steps, scale);
1442                             v = v / steps;
1443                             s->sb_samples[ch][k * 12 + l + 1][i] =
1444                                 l2_unscale_group(steps, v % steps, scale);
1445                             v = v / steps;
1446                             s->sb_samples[ch][k * 12 + l + 2][i] =
1447                                 l2_unscale_group(steps, v, scale);
1448                         } else {
1449                             for(m=0;m<3;m++) {
1450                                 v = get_bits(&s->gb, bits);
1451                                 v = l1_unscale(bits - 1, v, scale);
1452                                 s->sb_samples[ch][k * 12 + l + m][i] = v;
1453                             }
1454                         }
1455                     } else {
1456                         s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1457                         s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1458                         s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1459                     }
1460                 }
1461                 /* next subband in alloc table */
1462                 j += 1 << bit_alloc_bits;
1463             }
1464             /* XXX: find a way to avoid this duplication of code */
1465             for(i=bound;i<sblimit;i++) {
1466                 bit_alloc_bits = alloc_table[j];
1467                 b = bit_alloc[0][i];
1468                 if (b) {
1469                     int mant, scale0, scale1;
1470                     scale0 = scale_factors[0][i][k];
1471                     scale1 = scale_factors[1][i][k];
1472                     qindex = alloc_table[j+b];
1473                     bits = ff_mpa_quant_bits[qindex];
1474                     if (bits < 0) {
1475                         /* 3 values at the same time */
1476                         v = get_bits(&s->gb, -bits);
1477                         steps = ff_mpa_quant_steps[qindex];
1478                         mant = v % steps;
1479                         v = v / steps;
1480                         s->sb_samples[0][k * 12 + l + 0][i] =
1481                             l2_unscale_group(steps, mant, scale0);
1482                         s->sb_samples[1][k * 12 + l + 0][i] =
1483                             l2_unscale_group(steps, mant, scale1);
1484                         mant = v % steps;
1485                         v = v / steps;
1486                         s->sb_samples[0][k * 12 + l + 1][i] =
1487                             l2_unscale_group(steps, mant, scale0);
1488                         s->sb_samples[1][k * 12 + l + 1][i] =
1489                             l2_unscale_group(steps, mant, scale1);
1490                         s->sb_samples[0][k * 12 + l + 2][i] =
1491                             l2_unscale_group(steps, v, scale0);
1492                         s->sb_samples[1][k * 12 + l + 2][i] =
1493                             l2_unscale_group(steps, v, scale1);
1494                     } else {
1495                         for(m=0;m<3;m++) {
1496                             mant = get_bits(&s->gb, bits);
1497                             s->sb_samples[0][k * 12 + l + m][i] =
1498                                 l1_unscale(bits - 1, mant, scale0);
1499                             s->sb_samples[1][k * 12 + l + m][i] =
1500                                 l1_unscale(bits - 1, mant, scale1);
1501                         }
1502                     }
1503                 } else {
1504                     s->sb_samples[0][k * 12 + l + 0][i] = 0;
1505                     s->sb_samples[0][k * 12 + l + 1][i] = 0;
1506                     s->sb_samples[0][k * 12 + l + 2][i] = 0;
1507                     s->sb_samples[1][k * 12 + l + 0][i] = 0;
1508                     s->sb_samples[1][k * 12 + l + 1][i] = 0;
1509                     s->sb_samples[1][k * 12 + l + 2][i] = 0;
1510                 }
1511                 /* next subband in alloc table */
1512                 j += 1 << bit_alloc_bits;
1513             }
1514             /* fill remaining samples to zero */
1515             for(i=sblimit;i<SBLIMIT;i++) {
1516                 for(ch=0;ch<s->nb_channels;ch++) {
1517                     s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1518                     s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1519                     s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1520                 }
1521             }
1522         }
1523     }
1524     return 3 * 12;
1525 }
1526
1527 static inline void lsf_sf_expand(int *slen,
1528                                  int sf, int n1, int n2, int n3)
1529 {
1530     if (n3) {
1531         slen[3] = sf % n3;
1532         sf /= n3;
1533     } else {
1534         slen[3] = 0;
1535     }
1536     if (n2) {
1537         slen[2] = sf % n2;
1538         sf /= n2;
1539     } else {
1540         slen[2] = 0;
1541     }
1542     slen[1] = sf % n1;
1543     sf /= n1;
1544     slen[0] = sf;
1545 }
1546
1547 static void exponents_from_scale_factors(MPADecodeContext *s,
1548                                          GranuleDef *g,
1549                                          int16_t *exponents)
1550 {
1551     const uint8_t *bstab, *pretab;
1552     int len, i, j, k, l, v0, shift, gain, gains[3];
1553     int16_t *exp_ptr;
1554
1555     exp_ptr = exponents;
1556     gain = g->global_gain - 210;
1557     shift = g->scalefac_scale + 1;
1558
1559     bstab = band_size_long[s->sample_rate_index];
1560     pretab = mpa_pretab[g->preflag];
1561     for(i=0;i<g->long_end;i++) {
1562         v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1563         len = bstab[i];
1564         for(j=len;j>0;j--)
1565             *exp_ptr++ = v0;
1566     }
1567
1568     if (g->short_start < 13) {
1569         bstab = band_size_short[s->sample_rate_index];
1570         gains[0] = gain - (g->subblock_gain[0] << 3);
1571         gains[1] = gain - (g->subblock_gain[1] << 3);
1572         gains[2] = gain - (g->subblock_gain[2] << 3);
1573         k = g->long_end;
1574         for(i=g->short_start;i<13;i++) {
1575             len = bstab[i];
1576             for(l=0;l<3;l++) {
1577                 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1578                 for(j=len;j>0;j--)
1579                 *exp_ptr++ = v0;
1580             }
1581         }
1582     }
1583 }
1584
1585 /* handle n = 0 too */
1586 static inline int get_bitsz(GetBitContext *s, int n)
1587 {
1588     if (n == 0)
1589         return 0;
1590     else
1591         return get_bits(s, n);
1592 }
1593
1594
1595 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos, int *end_pos2){
1596     if(s->in_gb.buffer && *pos >= s->gb.size_in_bits){
1597         s->gb= s->in_gb;
1598         s->in_gb.buffer=NULL;
1599         assert((get_bits_count(&s->gb) & 7) == 0);
1600         skip_bits_long(&s->gb, *pos - *end_pos);
1601         *end_pos2=
1602         *end_pos= *end_pos2 + get_bits_count(&s->gb) - *pos;
1603         *pos= get_bits_count(&s->gb);
1604     }
1605 }
1606
1607 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1608                           int16_t *exponents, int end_pos2)
1609 {
1610     int s_index;
1611     int i;
1612     int last_pos, bits_left;
1613     VLC *vlc;
1614     int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1615
1616     /* low frequencies (called big values) */
1617     s_index = 0;
1618     for(i=0;i<3;i++) {
1619         int j, k, l, linbits;
1620         j = g->region_size[i];
1621         if (j == 0)
1622             continue;
1623         /* select vlc table */
1624         k = g->table_select[i];
1625         l = mpa_huff_data[k][0];
1626         linbits = mpa_huff_data[k][1];
1627         vlc = &huff_vlc[l];
1628
1629         if(!l){
1630             memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1631             s_index += 2*j;
1632             continue;
1633         }
1634
1635         /* read huffcode and compute each couple */
1636         for(;j>0;j--) {
1637             int exponent, x, y, v;
1638             int pos= get_bits_count(&s->gb);
1639
1640             if (pos >= end_pos){
1641 //                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1642                 switch_buffer(s, &pos, &end_pos, &end_pos2);
1643 //                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1644                 if(pos >= end_pos)
1645                     break;
1646             }
1647             y = get_vlc2(&s->gb, vlc->table, 7, 3);
1648
1649             if(!y){
1650                 g->sb_hybrid[s_index  ] =
1651                 g->sb_hybrid[s_index+1] = 0;
1652                 s_index += 2;
1653                 continue;
1654             }
1655
1656             exponent= exponents[s_index];
1657
1658             dprintf(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
1659                     i, g->region_size[i] - j, x, y, exponent);
1660             if(y&16){
1661                 x = y >> 5;
1662                 y = y & 0x0f;
1663                 if (x < 15){
1664                     v = expval_table[ exponent ][ x ];
1665 //                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
1666                 }else{
1667                     x += get_bitsz(&s->gb, linbits);
1668                     v = l3_unscale(x, exponent);
1669                 }
1670                 if (get_bits1(&s->gb))
1671                     v = -v;
1672                 g->sb_hybrid[s_index] = v;
1673                 if (y < 15){
1674                     v = expval_table[ exponent ][ y ];
1675                 }else{
1676                     y += get_bitsz(&s->gb, linbits);
1677                     v = l3_unscale(y, exponent);
1678                 }
1679                 if (get_bits1(&s->gb))
1680                     v = -v;
1681                 g->sb_hybrid[s_index+1] = v;
1682             }else{
1683                 x = y >> 5;
1684                 y = y & 0x0f;
1685                 x += y;
1686                 if (x < 15){
1687                     v = expval_table[ exponent ][ x ];
1688                 }else{
1689                     x += get_bitsz(&s->gb, linbits);
1690                     v = l3_unscale(x, exponent);
1691                 }
1692                 if (get_bits1(&s->gb))
1693                     v = -v;
1694                 g->sb_hybrid[s_index+!!y] = v;
1695                 g->sb_hybrid[s_index+ !y] = 0;
1696             }
1697             s_index+=2;
1698         }
1699     }
1700
1701     /* high frequencies */
1702     vlc = &huff_quad_vlc[g->count1table_select];
1703     last_pos=0;
1704     while (s_index <= 572) {
1705         int pos, code;
1706         pos = get_bits_count(&s->gb);
1707         if (pos >= end_pos) {
1708             if (pos > end_pos2 && last_pos){
1709                 /* some encoders generate an incorrect size for this
1710                    part. We must go back into the data */
1711                 s_index -= 4;
1712                 skip_bits_long(&s->gb, last_pos - pos);
1713                 av_log(NULL, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1714                 if(s->error_resilience >= FF_ER_COMPLIANT)
1715                     s_index=0;
1716                 break;
1717             }
1718 //                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1719             switch_buffer(s, &pos, &end_pos, &end_pos2);
1720 //                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1721             if(pos >= end_pos)
1722                 break;
1723         }
1724         last_pos= pos;
1725
1726         code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1727         dprintf(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1728         g->sb_hybrid[s_index+0]=
1729         g->sb_hybrid[s_index+1]=
1730         g->sb_hybrid[s_index+2]=
1731         g->sb_hybrid[s_index+3]= 0;
1732         while(code){
1733             static const int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1734             int v;
1735             int pos= s_index+idxtab[code];
1736             code ^= 8>>idxtab[code];
1737             v = exp_table[ exponents[pos] ];
1738 //            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1739             if(get_bits1(&s->gb))
1740                 v = -v;
1741             g->sb_hybrid[pos] = v;
1742         }
1743         s_index+=4;
1744     }
1745     /* skip extension bits */
1746     bits_left = end_pos2 - get_bits_count(&s->gb);
1747 //av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1748     if (bits_left < 0/* || bits_left > 500*/) {
1749         av_log(NULL, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1750         s_index=0;
1751     }else if(bits_left > 0 && s->error_resilience >= FF_ER_AGGRESSIVE){
1752         av_log(NULL, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1753         s_index=0;
1754     }
1755     memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1756     skip_bits_long(&s->gb, bits_left);
1757
1758     i= get_bits_count(&s->gb);
1759     switch_buffer(s, &i, &end_pos, &end_pos2);
1760
1761     return 0;
1762 }
1763
1764 /* Reorder short blocks from bitstream order to interleaved order. It
1765    would be faster to do it in parsing, but the code would be far more
1766    complicated */
1767 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1768 {
1769     int i, j, len;
1770     int32_t *ptr, *dst, *ptr1;
1771     int32_t tmp[576];
1772
1773     if (g->block_type != 2)
1774         return;
1775
1776     if (g->switch_point) {
1777         if (s->sample_rate_index != 8) {
1778             ptr = g->sb_hybrid + 36;
1779         } else {
1780             ptr = g->sb_hybrid + 48;
1781         }
1782     } else {
1783         ptr = g->sb_hybrid;
1784     }
1785
1786     for(i=g->short_start;i<13;i++) {
1787         len = band_size_short[s->sample_rate_index][i];
1788         ptr1 = ptr;
1789         dst = tmp;
1790         for(j=len;j>0;j--) {
1791             *dst++ = ptr[0*len];
1792             *dst++ = ptr[1*len];
1793             *dst++ = ptr[2*len];
1794             ptr++;
1795         }
1796         ptr+=2*len;
1797         memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1798     }
1799 }
1800
1801 #define ISQRT2 FIXR(0.70710678118654752440)
1802
1803 static void compute_stereo(MPADecodeContext *s,
1804                            GranuleDef *g0, GranuleDef *g1)
1805 {
1806     int i, j, k, l;
1807     int32_t v1, v2;
1808     int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1809     int32_t (*is_tab)[16];
1810     int32_t *tab0, *tab1;
1811     int non_zero_found_short[3];
1812
1813     /* intensity stereo */
1814     if (s->mode_ext & MODE_EXT_I_STEREO) {
1815         if (!s->lsf) {
1816             is_tab = is_table;
1817             sf_max = 7;
1818         } else {
1819             is_tab = is_table_lsf[g1->scalefac_compress & 1];
1820             sf_max = 16;
1821         }
1822
1823         tab0 = g0->sb_hybrid + 576;
1824         tab1 = g1->sb_hybrid + 576;
1825
1826         non_zero_found_short[0] = 0;
1827         non_zero_found_short[1] = 0;
1828         non_zero_found_short[2] = 0;
1829         k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1830         for(i = 12;i >= g1->short_start;i--) {
1831             /* for last band, use previous scale factor */
1832             if (i != 11)
1833                 k -= 3;
1834             len = band_size_short[s->sample_rate_index][i];
1835             for(l=2;l>=0;l--) {
1836                 tab0 -= len;
1837                 tab1 -= len;
1838                 if (!non_zero_found_short[l]) {
1839                     /* test if non zero band. if so, stop doing i-stereo */
1840                     for(j=0;j<len;j++) {
1841                         if (tab1[j] != 0) {
1842                             non_zero_found_short[l] = 1;
1843                             goto found1;
1844                         }
1845                     }
1846                     sf = g1->scale_factors[k + l];
1847                     if (sf >= sf_max)
1848                         goto found1;
1849
1850                     v1 = is_tab[0][sf];
1851                     v2 = is_tab[1][sf];
1852                     for(j=0;j<len;j++) {
1853                         tmp0 = tab0[j];
1854                         tab0[j] = MULL(tmp0, v1);
1855                         tab1[j] = MULL(tmp0, v2);
1856                     }
1857                 } else {
1858                 found1:
1859                     if (s->mode_ext & MODE_EXT_MS_STEREO) {
1860                         /* lower part of the spectrum : do ms stereo
1861                            if enabled */
1862                         for(j=0;j<len;j++) {
1863                             tmp0 = tab0[j];
1864                             tmp1 = tab1[j];
1865                             tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1866                             tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1867                         }
1868                     }
1869                 }
1870             }
1871         }
1872
1873         non_zero_found = non_zero_found_short[0] |
1874             non_zero_found_short[1] |
1875             non_zero_found_short[2];
1876
1877         for(i = g1->long_end - 1;i >= 0;i--) {
1878             len = band_size_long[s->sample_rate_index][i];
1879             tab0 -= len;
1880             tab1 -= len;
1881             /* test if non zero band. if so, stop doing i-stereo */
1882             if (!non_zero_found) {
1883                 for(j=0;j<len;j++) {
1884                     if (tab1[j] != 0) {
1885                         non_zero_found = 1;
1886                         goto found2;
1887                     }
1888                 }
1889                 /* for last band, use previous scale factor */
1890                 k = (i == 21) ? 20 : i;
1891                 sf = g1->scale_factors[k];
1892                 if (sf >= sf_max)
1893                     goto found2;
1894                 v1 = is_tab[0][sf];
1895                 v2 = is_tab[1][sf];
1896                 for(j=0;j<len;j++) {
1897                     tmp0 = tab0[j];
1898                     tab0[j] = MULL(tmp0, v1);
1899                     tab1[j] = MULL(tmp0, v2);
1900                 }
1901             } else {
1902             found2:
1903                 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1904                     /* lower part of the spectrum : do ms stereo
1905                        if enabled */
1906                     for(j=0;j<len;j++) {
1907                         tmp0 = tab0[j];
1908                         tmp1 = tab1[j];
1909                         tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1910                         tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1911                     }
1912                 }
1913             }
1914         }
1915     } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1916         /* ms stereo ONLY */
1917         /* NOTE: the 1/sqrt(2) normalization factor is included in the
1918            global gain */
1919         tab0 = g0->sb_hybrid;
1920         tab1 = g1->sb_hybrid;
1921         for(i=0;i<576;i++) {
1922             tmp0 = tab0[i];
1923             tmp1 = tab1[i];
1924             tab0[i] = tmp0 + tmp1;
1925             tab1[i] = tmp0 - tmp1;
1926         }
1927     }
1928 }
1929
1930 static void compute_antialias_integer(MPADecodeContext *s,
1931                               GranuleDef *g)
1932 {
1933     int32_t *ptr, *csa;
1934     int n, i;
1935
1936     /* we antialias only "long" bands */
1937     if (g->block_type == 2) {
1938         if (!g->switch_point)
1939             return;
1940         /* XXX: check this for 8000Hz case */
1941         n = 1;
1942     } else {
1943         n = SBLIMIT - 1;
1944     }
1945
1946     ptr = g->sb_hybrid + 18;
1947     for(i = n;i > 0;i--) {
1948         int tmp0, tmp1, tmp2;
1949         csa = &csa_table[0][0];
1950 #define INT_AA(j) \
1951             tmp0 = ptr[-1-j];\
1952             tmp1 = ptr[   j];\
1953             tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1954             ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1955             ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1956
1957         INT_AA(0)
1958         INT_AA(1)
1959         INT_AA(2)
1960         INT_AA(3)
1961         INT_AA(4)
1962         INT_AA(5)
1963         INT_AA(6)
1964         INT_AA(7)
1965
1966         ptr += 18;
1967     }
1968 }
1969
1970 static void compute_antialias_float(MPADecodeContext *s,
1971                               GranuleDef *g)
1972 {
1973     int32_t *ptr;
1974     int n, i;
1975
1976     /* we antialias only "long" bands */
1977     if (g->block_type == 2) {
1978         if (!g->switch_point)
1979             return;
1980         /* XXX: check this for 8000Hz case */
1981         n = 1;
1982     } else {
1983         n = SBLIMIT - 1;
1984     }
1985
1986     ptr = g->sb_hybrid + 18;
1987     for(i = n;i > 0;i--) {
1988         float tmp0, tmp1;
1989         float *csa = &csa_table_float[0][0];
1990 #define FLOAT_AA(j)\
1991         tmp0= ptr[-1-j];\
1992         tmp1= ptr[   j];\
1993         ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1994         ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1995
1996         FLOAT_AA(0)
1997         FLOAT_AA(1)
1998         FLOAT_AA(2)
1999         FLOAT_AA(3)
2000         FLOAT_AA(4)
2001         FLOAT_AA(5)
2002         FLOAT_AA(6)
2003         FLOAT_AA(7)
2004
2005         ptr += 18;
2006     }
2007 }
2008
2009 static void compute_imdct(MPADecodeContext *s,
2010                           GranuleDef *g,
2011                           int32_t *sb_samples,
2012                           int32_t *mdct_buf)
2013 {
2014     int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
2015     int32_t out2[12];
2016     int i, j, mdct_long_end, v, sblimit;
2017
2018     /* find last non zero block */
2019     ptr = g->sb_hybrid + 576;
2020     ptr1 = g->sb_hybrid + 2 * 18;
2021     while (ptr >= ptr1) {
2022         ptr -= 6;
2023         v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
2024         if (v != 0)
2025             break;
2026     }
2027     sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
2028
2029     if (g->block_type == 2) {
2030         /* XXX: check for 8000 Hz */
2031         if (g->switch_point)
2032             mdct_long_end = 2;
2033         else
2034             mdct_long_end = 0;
2035     } else {
2036         mdct_long_end = sblimit;
2037     }
2038
2039     buf = mdct_buf;
2040     ptr = g->sb_hybrid;
2041     for(j=0;j<mdct_long_end;j++) {
2042         /* apply window & overlap with previous buffer */
2043         out_ptr = sb_samples + j;
2044         /* select window */
2045         if (g->switch_point && j < 2)
2046             win1 = mdct_win[0];
2047         else
2048             win1 = mdct_win[g->block_type];
2049         /* select frequency inversion */
2050         win = win1 + ((4 * 36) & -(j & 1));
2051         imdct36(out_ptr, buf, ptr, win);
2052         out_ptr += 18*SBLIMIT;
2053         ptr += 18;
2054         buf += 18;
2055     }
2056     for(j=mdct_long_end;j<sblimit;j++) {
2057         /* select frequency inversion */
2058         win = mdct_win[2] + ((4 * 36) & -(j & 1));
2059         out_ptr = sb_samples + j;
2060
2061         for(i=0; i<6; i++){
2062             *out_ptr = buf[i];
2063             out_ptr += SBLIMIT;
2064         }
2065         imdct12(out2, ptr + 0);
2066         for(i=0;i<6;i++) {
2067             *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
2068             buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
2069             out_ptr += SBLIMIT;
2070         }
2071         imdct12(out2, ptr + 1);
2072         for(i=0;i<6;i++) {
2073             *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
2074             buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
2075             out_ptr += SBLIMIT;
2076         }
2077         imdct12(out2, ptr + 2);
2078         for(i=0;i<6;i++) {
2079             buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
2080             buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
2081             buf[i + 6*2] = 0;
2082         }
2083         ptr += 18;
2084         buf += 18;
2085     }
2086     /* zero bands */
2087     for(j=sblimit;j<SBLIMIT;j++) {
2088         /* overlap */
2089         out_ptr = sb_samples + j;
2090         for(i=0;i<18;i++) {
2091             *out_ptr = buf[i];
2092             buf[i] = 0;
2093             out_ptr += SBLIMIT;
2094         }
2095         buf += 18;
2096     }
2097 }
2098
2099 #if defined(DEBUG)
2100 void sample_dump(int fnum, int32_t *tab, int n)
2101 {
2102     static FILE *files[16], *f;
2103     char buf[512];
2104     int i;
2105     int32_t v;
2106
2107     f = files[fnum];
2108     if (!f) {
2109         snprintf(buf, sizeof(buf), "/tmp/out%d.%s.pcm",
2110                 fnum,
2111 #ifdef USE_HIGHPRECISION
2112                 "hp"
2113 #else
2114                 "lp"
2115 #endif
2116                 );
2117         f = fopen(buf, "w");
2118         if (!f)
2119             return;
2120         files[fnum] = f;
2121     }
2122
2123     if (fnum == 0) {
2124         static int pos = 0;
2125         av_log(NULL, AV_LOG_DEBUG, "pos=%d\n", pos);
2126         for(i=0;i<n;i++) {
2127             av_log(NULL, AV_LOG_DEBUG, " %0.4f", (double)tab[i] / FRAC_ONE);
2128             if ((i % 18) == 17)
2129                 av_log(NULL, AV_LOG_DEBUG, "\n");
2130         }
2131         pos += n;
2132     }
2133     for(i=0;i<n;i++) {
2134         /* normalize to 23 frac bits */
2135         v = tab[i] << (23 - FRAC_BITS);
2136         fwrite(&v, 1, sizeof(int32_t), f);
2137     }
2138 }
2139 #endif
2140
2141
2142 /* main layer3 decoding function */
2143 static int mp_decode_layer3(MPADecodeContext *s)
2144 {
2145     int nb_granules, main_data_begin, private_bits;
2146     int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
2147     GranuleDef granules[2][2], *g;
2148     int16_t exponents[576];
2149
2150     /* read side info */
2151     if (s->lsf) {
2152         main_data_begin = get_bits(&s->gb, 8);
2153         private_bits = get_bits(&s->gb, s->nb_channels);
2154         nb_granules = 1;
2155     } else {
2156         main_data_begin = get_bits(&s->gb, 9);
2157         if (s->nb_channels == 2)
2158             private_bits = get_bits(&s->gb, 3);
2159         else
2160             private_bits = get_bits(&s->gb, 5);
2161         nb_granules = 2;
2162         for(ch=0;ch<s->nb_channels;ch++) {
2163             granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
2164             granules[ch][1].scfsi = get_bits(&s->gb, 4);
2165         }
2166     }
2167
2168     for(gr=0;gr<nb_granules;gr++) {
2169         for(ch=0;ch<s->nb_channels;ch++) {
2170             dprintf(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
2171             g = &granules[ch][gr];
2172             g->part2_3_length = get_bits(&s->gb, 12);
2173             g->big_values = get_bits(&s->gb, 9);
2174             if(g->big_values > 288){
2175                 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
2176                 return -1;
2177             }
2178
2179             g->global_gain = get_bits(&s->gb, 8);
2180             /* if MS stereo only is selected, we precompute the
2181                1/sqrt(2) renormalization factor */
2182             if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
2183                 MODE_EXT_MS_STEREO)
2184                 g->global_gain -= 2;
2185             if (s->lsf)
2186                 g->scalefac_compress = get_bits(&s->gb, 9);
2187             else
2188                 g->scalefac_compress = get_bits(&s->gb, 4);
2189             blocksplit_flag = get_bits(&s->gb, 1);
2190             if (blocksplit_flag) {
2191                 g->block_type = get_bits(&s->gb, 2);
2192                 if (g->block_type == 0){
2193                     av_log(NULL, AV_LOG_ERROR, "invalid block type\n");
2194                     return -1;
2195                 }
2196                 g->switch_point = get_bits(&s->gb, 1);
2197                 for(i=0;i<2;i++)
2198                     g->table_select[i] = get_bits(&s->gb, 5);
2199                 for(i=0;i<3;i++)
2200                     g->subblock_gain[i] = get_bits(&s->gb, 3);
2201                 /* compute huffman coded region sizes */
2202                 if (g->block_type == 2)
2203                     g->region_size[0] = (36 / 2);
2204                 else {
2205                     if (s->sample_rate_index <= 2)
2206                         g->region_size[0] = (36 / 2);
2207                     else if (s->sample_rate_index != 8)
2208                         g->region_size[0] = (54 / 2);
2209                     else
2210                         g->region_size[0] = (108 / 2);
2211                 }
2212                 g->region_size[1] = (576 / 2);
2213             } else {
2214                 int region_address1, region_address2, l;
2215                 g->block_type = 0;
2216                 g->switch_point = 0;
2217                 for(i=0;i<3;i++)
2218                     g->table_select[i] = get_bits(&s->gb, 5);
2219                 /* compute huffman coded region sizes */
2220                 region_address1 = get_bits(&s->gb, 4);
2221                 region_address2 = get_bits(&s->gb, 3);
2222                 dprintf(s->avctx, "region1=%d region2=%d\n",
2223                         region_address1, region_address2);
2224                 g->region_size[0] =
2225                     band_index_long[s->sample_rate_index][region_address1 + 1] >> 1;
2226                 l = region_address1 + region_address2 + 2;
2227                 /* should not overflow */
2228                 if (l > 22)
2229                     l = 22;
2230                 g->region_size[1] =
2231                     band_index_long[s->sample_rate_index][l] >> 1;
2232             }
2233             /* convert region offsets to region sizes and truncate
2234                size to big_values */
2235             g->region_size[2] = (576 / 2);
2236             j = 0;
2237             for(i=0;i<3;i++) {
2238                 k = FFMIN(g->region_size[i], g->big_values);
2239                 g->region_size[i] = k - j;
2240                 j = k;
2241             }
2242
2243             /* compute band indexes */
2244             if (g->block_type == 2) {
2245                 if (g->switch_point) {
2246                     /* if switched mode, we handle the 36 first samples as
2247                        long blocks.  For 8000Hz, we handle the 48 first
2248                        exponents as long blocks (XXX: check this!) */
2249                     if (s->sample_rate_index <= 2)
2250                         g->long_end = 8;
2251                     else if (s->sample_rate_index != 8)
2252                         g->long_end = 6;
2253                     else
2254                         g->long_end = 4; /* 8000 Hz */
2255
2256                     g->short_start = 2 + (s->sample_rate_index != 8);
2257                 } else {
2258                     g->long_end = 0;
2259                     g->short_start = 0;
2260                 }
2261             } else {
2262                 g->short_start = 13;
2263                 g->long_end = 22;
2264             }
2265
2266             g->preflag = 0;
2267             if (!s->lsf)
2268                 g->preflag = get_bits(&s->gb, 1);
2269             g->scalefac_scale = get_bits(&s->gb, 1);
2270             g->count1table_select = get_bits(&s->gb, 1);
2271             dprintf(s->avctx, "block_type=%d switch_point=%d\n",
2272                     g->block_type, g->switch_point);
2273         }
2274     }
2275
2276   if (!s->adu_mode) {
2277     const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2278     assert((get_bits_count(&s->gb) & 7) == 0);
2279     /* now we get bits from the main_data_begin offset */
2280     dprintf(s->avctx, "seekback: %d\n", main_data_begin);
2281 //av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2282
2283     memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2284     s->in_gb= s->gb;
2285         init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
2286         skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
2287   }
2288
2289     for(gr=0;gr<nb_granules;gr++) {
2290         for(ch=0;ch<s->nb_channels;ch++) {
2291             g = &granules[ch][gr];
2292             if(get_bits_count(&s->gb)<0){
2293                 av_log(NULL, AV_LOG_ERROR, "mdb:%d, lastbuf:%d skipping granule %d\n",
2294                                             main_data_begin, s->last_buf_size, gr);
2295                 skip_bits_long(&s->gb, g->part2_3_length);
2296                 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
2297                 if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer){
2298                     skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
2299                     s->gb= s->in_gb;
2300                     s->in_gb.buffer=NULL;
2301                 }
2302                 continue;
2303             }
2304
2305             bits_pos = get_bits_count(&s->gb);
2306
2307             if (!s->lsf) {
2308                 uint8_t *sc;
2309                 int slen, slen1, slen2;
2310
2311                 /* MPEG1 scale factors */
2312                 slen1 = slen_table[0][g->scalefac_compress];
2313                 slen2 = slen_table[1][g->scalefac_compress];
2314                 dprintf(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
2315                 if (g->block_type == 2) {
2316                     n = g->switch_point ? 17 : 18;
2317                     j = 0;
2318                     if(slen1){
2319                         for(i=0;i<n;i++)
2320                             g->scale_factors[j++] = get_bits(&s->gb, slen1);
2321                     }else{
2322                         for(i=0;i<n;i++)
2323                             g->scale_factors[j++] = 0;
2324                     }
2325                     if(slen2){
2326                         for(i=0;i<18;i++)
2327                             g->scale_factors[j++] = get_bits(&s->gb, slen2);
2328                         for(i=0;i<3;i++)
2329                             g->scale_factors[j++] = 0;
2330                     }else{
2331                         for(i=0;i<21;i++)
2332                             g->scale_factors[j++] = 0;
2333                     }
2334                 } else {
2335                     sc = granules[ch][0].scale_factors;
2336                     j = 0;
2337                     for(k=0;k<4;k++) {
2338                         n = (k == 0 ? 6 : 5);
2339                         if ((g->scfsi & (0x8 >> k)) == 0) {
2340                             slen = (k < 2) ? slen1 : slen2;
2341                             if(slen){
2342                                 for(i=0;i<n;i++)
2343                                     g->scale_factors[j++] = get_bits(&s->gb, slen);
2344                             }else{
2345                                 for(i=0;i<n;i++)
2346                                     g->scale_factors[j++] = 0;
2347                             }
2348                         } else {
2349                             /* simply copy from last granule */
2350                             for(i=0;i<n;i++) {
2351                                 g->scale_factors[j] = sc[j];
2352                                 j++;
2353                             }
2354                         }
2355                     }
2356                     g->scale_factors[j++] = 0;
2357                 }
2358 #if defined(DEBUG)
2359                 {
2360                     dprintf(s->avctx, "scfsi=%x gr=%d ch=%d scale_factors:\n",
2361                            g->scfsi, gr, ch);
2362                     for(i=0;i<j;i++)
2363                         dprintf(s->avctx, " %d", g->scale_factors[i]);
2364                     dprintf(s->avctx, "\n");
2365                 }
2366 #endif
2367             } else {
2368                 int tindex, tindex2, slen[4], sl, sf;
2369
2370                 /* LSF scale factors */
2371                 if (g->block_type == 2) {
2372                     tindex = g->switch_point ? 2 : 1;
2373                 } else {
2374                     tindex = 0;
2375                 }
2376                 sf = g->scalefac_compress;
2377                 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2378                     /* intensity stereo case */
2379                     sf >>= 1;
2380                     if (sf < 180) {
2381                         lsf_sf_expand(slen, sf, 6, 6, 0);
2382                         tindex2 = 3;
2383                     } else if (sf < 244) {
2384                         lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2385                         tindex2 = 4;
2386                     } else {
2387                         lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2388                         tindex2 = 5;
2389                     }
2390                 } else {
2391                     /* normal case */
2392                     if (sf < 400) {
2393                         lsf_sf_expand(slen, sf, 5, 4, 4);
2394                         tindex2 = 0;
2395                     } else if (sf < 500) {
2396                         lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2397                         tindex2 = 1;
2398                     } else {
2399                         lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2400                         tindex2 = 2;
2401                         g->preflag = 1;
2402                     }
2403                 }
2404
2405                 j = 0;
2406                 for(k=0;k<4;k++) {
2407                     n = lsf_nsf_table[tindex2][tindex][k];
2408                     sl = slen[k];
2409                     if(sl){
2410                         for(i=0;i<n;i++)
2411                             g->scale_factors[j++] = get_bits(&s->gb, sl);
2412                     }else{
2413                         for(i=0;i<n;i++)
2414                             g->scale_factors[j++] = 0;
2415                     }
2416                 }
2417                 /* XXX: should compute exact size */
2418                 for(;j<40;j++)
2419                     g->scale_factors[j] = 0;
2420 #if defined(DEBUG)
2421                 {
2422                     dprintf(s->avctx, "gr=%d ch=%d scale_factors:\n",
2423                            gr, ch);
2424                     for(i=0;i<40;i++)
2425                         dprintf(s->avctx, " %d", g->scale_factors[i]);
2426                     dprintf(s->avctx, "\n");
2427                 }
2428 #endif
2429             }
2430
2431             exponents_from_scale_factors(s, g, exponents);
2432
2433             /* read Huffman coded residue */
2434             huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
2435 #if defined(DEBUG)
2436             sample_dump(0, g->sb_hybrid, 576);
2437 #endif
2438         } /* ch */
2439
2440         if (s->nb_channels == 2)
2441             compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2442
2443         for(ch=0;ch<s->nb_channels;ch++) {
2444             g = &granules[ch][gr];
2445
2446             reorder_block(s, g);
2447 #if defined(DEBUG)
2448             sample_dump(0, g->sb_hybrid, 576);
2449 #endif
2450             s->compute_antialias(s, g);
2451 #if defined(DEBUG)
2452             sample_dump(1, g->sb_hybrid, 576);
2453 #endif
2454             compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2455 #if defined(DEBUG)
2456             sample_dump(2, &s->sb_samples[ch][18 * gr][0], 576);
2457 #endif
2458         }
2459     } /* gr */
2460     if(get_bits_count(&s->gb)<0)
2461         skip_bits_long(&s->gb, -get_bits_count(&s->gb));
2462     return nb_granules * 18;
2463 }
2464
2465 static int mp_decode_frame(MPADecodeContext *s,
2466                            OUT_INT *samples, const uint8_t *buf, int buf_size)
2467 {
2468     int i, nb_frames, ch;
2469     OUT_INT *samples_ptr;
2470
2471     init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE)*8);
2472
2473     /* skip error protection field */
2474     if (s->error_protection)
2475         get_bits(&s->gb, 16);
2476
2477     dprintf(s->avctx, "frame %d:\n", s->frame_count);
2478     switch(s->layer) {
2479     case 1:
2480         nb_frames = mp_decode_layer1(s);
2481         break;
2482     case 2:
2483         nb_frames = mp_decode_layer2(s);
2484         break;
2485     case 3:
2486     default:
2487         nb_frames = mp_decode_layer3(s);
2488
2489         s->last_buf_size=0;
2490         if(s->in_gb.buffer){
2491             align_get_bits(&s->gb);
2492             i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2493             if(i >= 0 && i <= BACKSTEP_SIZE){
2494                 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
2495                 s->last_buf_size=i;
2496             }else
2497                 av_log(NULL, AV_LOG_ERROR, "invalid old backstep %d\n", i);
2498             s->gb= s->in_gb;
2499             s->in_gb.buffer= NULL;
2500         }
2501
2502         align_get_bits(&s->gb);
2503         assert((get_bits_count(&s->gb) & 7) == 0);
2504         i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2505
2506         if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
2507             av_log(NULL, AV_LOG_ERROR, "invalid new backstep %d\n", i);
2508             i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
2509         }
2510         assert(i <= buf_size - HEADER_SIZE && i>= 0);
2511         memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
2512         s->last_buf_size += i;
2513
2514         break;
2515     }
2516 #if defined(DEBUG)
2517     for(i=0;i<nb_frames;i++) {
2518         for(ch=0;ch<s->nb_channels;ch++) {
2519             int j;
2520             dprintf(s->avctx, "%d-%d:", i, ch);
2521             for(j=0;j<SBLIMIT;j++)
2522                 dprintf(s->avctx, " %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);
2523             dprintf(s->avctx, "\n");
2524         }
2525     }
2526 #endif
2527     /* apply the synthesis filter */
2528     for(ch=0;ch<s->nb_channels;ch++) {
2529         samples_ptr = samples + ch;
2530         for(i=0;i<nb_frames;i++) {
2531             ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2532                          window, &s->dither_state,
2533                          samples_ptr, s->nb_channels,
2534                          s->sb_samples[ch][i]);
2535             samples_ptr += 32 * s->nb_channels;
2536         }
2537     }
2538 #ifdef DEBUG
2539     s->frame_count++;
2540 #endif
2541     return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2542 }
2543
2544 static int decode_frame(AVCodecContext * avctx,
2545                         void *data, int *data_size,
2546                         uint8_t * buf, int buf_size)
2547 {
2548     MPADecodeContext *s = avctx->priv_data;
2549     uint32_t header;
2550     int out_size;
2551     OUT_INT *out_samples = data;
2552
2553 retry:
2554     if(buf_size < HEADER_SIZE)
2555         return -1;
2556
2557     header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
2558     if(ff_mpa_check_header(header) < 0){
2559         buf++;
2560 //        buf_size--;
2561         av_log(avctx, AV_LOG_ERROR, "Header missing skipping one byte.\n");
2562         goto retry;
2563     }
2564
2565     if (decode_header(s, header) == 1) {
2566         /* free format: prepare to compute frame size */
2567         s->frame_size = -1;
2568         return -1;
2569     }
2570     /* update codec info */
2571     avctx->channels = s->nb_channels;
2572     avctx->bit_rate = s->bit_rate;
2573     avctx->sub_id = s->layer;
2574     switch(s->layer) {
2575     case 1:
2576         avctx->frame_size = 384;
2577         break;
2578     case 2:
2579         avctx->frame_size = 1152;
2580         break;
2581     case 3:
2582         if (s->lsf)
2583             avctx->frame_size = 576;
2584         else
2585             avctx->frame_size = 1152;
2586         break;
2587     }
2588
2589     if(s->frame_size<=0 || s->frame_size > buf_size){
2590         av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2591         return -1;
2592     }else if(s->frame_size < buf_size){
2593         av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
2594     }
2595
2596     out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2597     if(out_size>=0){
2598         *data_size = out_size;
2599         avctx->sample_rate = s->sample_rate;
2600         //FIXME maybe move the other codec info stuff from above here too
2601     }else
2602         av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed
2603     s->frame_size = 0;
2604     return buf_size;
2605 }
2606
2607 static void flush(AVCodecContext *avctx){
2608     MPADecodeContext *s = avctx->priv_data;
2609     s->last_buf_size= 0;
2610 }
2611
2612 #ifdef CONFIG_MP3ADU_DECODER
2613 static int decode_frame_adu(AVCodecContext * avctx,
2614                         void *data, int *data_size,
2615                         uint8_t * buf, int buf_size)
2616 {
2617     MPADecodeContext *s = avctx->priv_data;
2618     uint32_t header;
2619     int len, out_size;
2620     OUT_INT *out_samples = data;
2621
2622     len = buf_size;
2623
2624     // Discard too short frames
2625     if (buf_size < HEADER_SIZE) {
2626         *data_size = 0;
2627         return buf_size;
2628     }
2629
2630
2631     if (len > MPA_MAX_CODED_FRAME_SIZE)
2632         len = MPA_MAX_CODED_FRAME_SIZE;
2633
2634     // Get header and restore sync word
2635     header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3] | 0xffe00000;
2636
2637     if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2638         *data_size = 0;
2639         return buf_size;
2640     }
2641
2642     decode_header(s, header);
2643     /* update codec info */
2644     avctx->sample_rate = s->sample_rate;
2645     avctx->channels = s->nb_channels;
2646     avctx->bit_rate = s->bit_rate;
2647     avctx->sub_id = s->layer;
2648
2649     avctx->frame_size=s->frame_size = len;
2650
2651     if (avctx->parse_only) {
2652         out_size = buf_size;
2653     } else {
2654         out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2655     }
2656
2657     *data_size = out_size;
2658     return buf_size;
2659 }
2660 #endif /* CONFIG_MP3ADU_DECODER */
2661
2662 #ifdef CONFIG_MP3ON4_DECODER
2663 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2664 static int mp3Frames[16] = {0,1,1,2,3,3,4,5,2};   /* number of mp3 decoder instances */
2665 static int mp3Channels[16] = {0,1,2,3,4,5,6,8,4}; /* total output channels */
2666 /* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2667 static int chan_offset[9][5] = {
2668     {0},
2669     {0},            // C
2670     {0},            // FLR
2671     {2,0},          // C FLR
2672     {2,0,3},        // C FLR BS
2673     {4,0,2},        // C FLR BLRS
2674     {4,0,2,5},      // C FLR BLRS LFE
2675     {4,0,2,6,5},    // C FLR BLRS BLR LFE
2676     {0,2}           // FLR BLRS
2677 };
2678
2679
2680 static int decode_init_mp3on4(AVCodecContext * avctx)
2681 {
2682     MP3On4DecodeContext *s = avctx->priv_data;
2683     int i;
2684
2685     if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2686         av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2687         return -1;
2688     }
2689
2690     s->chan_cfg = (((unsigned char *)avctx->extradata)[1] >> 3) & 0x0f;
2691     s->frames = mp3Frames[s->chan_cfg];
2692     if(!s->frames) {
2693         av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2694         return -1;
2695     }
2696     avctx->channels = mp3Channels[s->chan_cfg];
2697
2698     /* Init the first mp3 decoder in standard way, so that all tables get builded
2699      * We replace avctx->priv_data with the context of the first decoder so that
2700      * decode_init() does not have to be changed.
2701      * Other decoders will be inited here copying data from the first context
2702      */
2703     // Allocate zeroed memory for the first decoder context
2704     s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2705     // Put decoder context in place to make init_decode() happy
2706     avctx->priv_data = s->mp3decctx[0];
2707     decode_init(avctx);
2708     // Restore mp3on4 context pointer
2709     avctx->priv_data = s;
2710     s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2711
2712     /* Create a separate codec/context for each frame (first is already ok).
2713      * Each frame is 1 or 2 channels - up to 5 frames allowed
2714      */
2715     for (i = 1; i < s->frames; i++) {
2716         s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2717         s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2718         s->mp3decctx[i]->adu_mode = 1;
2719         s->mp3decctx[i]->avctx = avctx;
2720     }
2721
2722     return 0;
2723 }
2724
2725
2726 static int decode_close_mp3on4(AVCodecContext * avctx)
2727 {
2728     MP3On4DecodeContext *s = avctx->priv_data;
2729     int i;
2730
2731     for (i = 0; i < s->frames; i++)
2732         if (s->mp3decctx[i])
2733             av_free(s->mp3decctx[i]);
2734
2735     return 0;
2736 }
2737
2738
2739 static int decode_frame_mp3on4(AVCodecContext * avctx,
2740                         void *data, int *data_size,
2741                         uint8_t * buf, int buf_size)
2742 {
2743     MP3On4DecodeContext *s = avctx->priv_data;
2744     MPADecodeContext *m;
2745     int len, out_size = 0;
2746     uint32_t header;
2747     OUT_INT *out_samples = data;
2748     OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2749     OUT_INT *outptr, *bp;
2750     int fsize;
2751     unsigned char *start2 = buf, *start;
2752     int fr, i, j, n;
2753     int off = avctx->channels;
2754     int *coff = chan_offset[s->chan_cfg];
2755
2756     len = buf_size;
2757
2758     // Discard too short frames
2759     if (buf_size < HEADER_SIZE) {
2760         *data_size = 0;
2761         return buf_size;
2762     }
2763
2764     // If only one decoder interleave is not needed
2765     outptr = s->frames == 1 ? out_samples : decoded_buf;
2766
2767     for (fr = 0; fr < s->frames; fr++) {
2768         start = start2;
2769         fsize = (start[0] << 4) | (start[1] >> 4);
2770         start2 += fsize;
2771         if (fsize > len)
2772             fsize = len;
2773         len -= fsize;
2774         if (fsize > MPA_MAX_CODED_FRAME_SIZE)
2775             fsize = MPA_MAX_CODED_FRAME_SIZE;
2776         m = s->mp3decctx[fr];
2777         assert (m != NULL);
2778
2779         // Get header
2780         header = (start[0] << 24) | (start[1] << 16) | (start[2] << 8) | start[3] | 0xfff00000;
2781
2782         if (ff_mpa_check_header(header) < 0) { // Bad header, discard block
2783             *data_size = 0;
2784             return buf_size;
2785         }
2786
2787         decode_header(m, header);
2788         mp_decode_frame(m, decoded_buf, start, fsize);
2789
2790         n = MPA_FRAME_SIZE * m->nb_channels;
2791         out_size += n * sizeof(OUT_INT);
2792         if(s->frames > 1) {
2793             /* interleave output data */
2794             bp = out_samples + coff[fr];
2795             if(m->nb_channels == 1) {
2796                 for(j = 0; j < n; j++) {
2797                     *bp = decoded_buf[j];
2798                     bp += off;
2799                 }
2800             } else {
2801                 for(j = 0; j < n; j++) {
2802                     bp[0] = decoded_buf[j++];
2803                     bp[1] = decoded_buf[j];
2804                     bp += off;
2805                 }
2806             }
2807         }
2808     }
2809
2810     /* update codec info */
2811     avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2812     avctx->frame_size= buf_size;
2813     avctx->bit_rate = 0;
2814     for (i = 0; i < s->frames; i++)
2815         avctx->bit_rate += s->mp3decctx[i]->bit_rate;
2816
2817     *data_size = out_size;
2818     return buf_size;
2819 }
2820 #endif /* CONFIG_MP3ON4_DECODER */
2821
2822 #ifdef CONFIG_MP2_DECODER
2823 AVCodec mp2_decoder =
2824 {
2825     "mp2",
2826     CODEC_TYPE_AUDIO,
2827     CODEC_ID_MP2,
2828     sizeof(MPADecodeContext),
2829     decode_init,
2830     NULL,
2831     NULL,
2832     decode_frame,
2833     CODEC_CAP_PARSE_ONLY,
2834 };
2835 #endif
2836 #ifdef CONFIG_MP3_DECODER
2837 AVCodec mp3_decoder =
2838 {
2839     "mp3",
2840     CODEC_TYPE_AUDIO,
2841     CODEC_ID_MP3,
2842     sizeof(MPADecodeContext),
2843     decode_init,
2844     NULL,
2845     NULL,
2846     decode_frame,
2847     CODEC_CAP_PARSE_ONLY,
2848     .flush= flush,
2849 };
2850 #endif
2851 #ifdef CONFIG_MP3ADU_DECODER
2852 AVCodec mp3adu_decoder =
2853 {
2854     "mp3adu",
2855     CODEC_TYPE_AUDIO,
2856     CODEC_ID_MP3ADU,
2857     sizeof(MPADecodeContext),
2858     decode_init,
2859     NULL,
2860     NULL,
2861     decode_frame_adu,
2862     CODEC_CAP_PARSE_ONLY,
2863     .flush= flush,
2864 };
2865 #endif
2866 #ifdef CONFIG_MP3ON4_DECODER
2867 AVCodec mp3on4_decoder =
2868 {
2869     "mp3on4",
2870     CODEC_TYPE_AUDIO,
2871     CODEC_ID_MP3ON4,
2872     sizeof(MP3On4DecodeContext),
2873     decode_init_mp3on4,
2874     NULL,
2875     decode_close_mp3on4,
2876     decode_frame_mp3on4,
2877     .flush= flush,
2878 };
2879 #endif