]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegaudiodec_template.c
avcodec/atrac9dec: Don't create VLCs that are never used
[ffmpeg] / libavcodec / mpegaudiodec_template.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
24  * MPEG Audio decoder
25  */
26
27 #include "libavutil/attributes.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/crc.h"
31 #include "libavutil/float_dsp.h"
32 #include "libavutil/libm.h"
33 #include "avcodec.h"
34 #include "get_bits.h"
35 #include "internal.h"
36 #include "mathops.h"
37 #include "mpegaudiodsp.h"
38
39 /*
40  * TODO:
41  *  - test lsf / mpeg25 extensively.
42  */
43
44 #include "mpegaudio.h"
45 #include "mpegaudiodecheader.h"
46
47 #define BACKSTEP_SIZE 512
48 #define EXTRABYTES 24
49 #define LAST_BUF_SIZE 2 * BACKSTEP_SIZE + EXTRABYTES
50
51 /* layer 3 "granule" */
52 typedef struct GranuleDef {
53     uint8_t scfsi;
54     int part2_3_length;
55     int big_values;
56     int global_gain;
57     int scalefac_compress;
58     uint8_t block_type;
59     uint8_t switch_point;
60     int table_select[3];
61     int subblock_gain[3];
62     uint8_t scalefac_scale;
63     uint8_t count1table_select;
64     int region_size[3]; /* number of huffman codes in each region */
65     int preflag;
66     int short_start, long_end; /* long/short band indexes */
67     uint8_t scale_factors[40];
68     DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
69 } GranuleDef;
70
71 typedef struct MPADecodeContext {
72     MPA_DECODE_HEADER
73     uint8_t last_buf[LAST_BUF_SIZE];
74     int last_buf_size;
75     int extrasize;
76     /* next header (used in free format parsing) */
77     uint32_t free_format_next_header;
78     GetBitContext gb;
79     GetBitContext in_gb;
80     DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
81     int synth_buf_offset[MPA_MAX_CHANNELS];
82     DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
83     INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
84     GranuleDef granules[2][2]; /* Used in Layer 3 */
85     int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
86     int dither_state;
87     int err_recognition;
88     AVCodecContext* avctx;
89     MPADSPContext mpadsp;
90     void (*butterflies_float)(float *av_restrict v1, float *av_restrict v2, int len);
91     AVFrame *frame;
92     uint32_t crc;
93 } MPADecodeContext;
94
95 #define HEADER_SIZE 4
96
97 #include "mpegaudiodata.h"
98 #include "mpegaudiodectab.h"
99
100 /* vlc structure for decoding layer 3 huffman tables */
101 static VLC huff_vlc[16];
102 static VLC_TYPE huff_vlc_tables[
103     0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
104   142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
105   ][2];
106 static const int huff_vlc_tables_sizes[16] = {
107     0,  128,  128,  128,  130,  128,  154,  166,
108   142,  204,  190,  170,  542,  460,  662,  414
109 };
110 static VLC huff_quad_vlc[2];
111 static VLC_TYPE  huff_quad_vlc_tables[64+16][2];
112 static const int huff_quad_vlc_tables_sizes[2] = { 64, 16 };
113 /* computed from band_size_long */
114 static uint16_t band_index_long[9][23];
115 #include "mpegaudio_tablegen.h"
116 /* intensity stereo coef table */
117 static INTFLOAT is_table[2][16];
118 static INTFLOAT is_table_lsf[2][2][16];
119 static INTFLOAT csa_table[8][4];
120
121 static int16_t division_tab3[1 << 6 ];
122 static int16_t division_tab5[1 << 8 ];
123 static int16_t division_tab9[1 << 11];
124
125 static int16_t * const division_tabs[4] = {
126     division_tab3, division_tab5, NULL, division_tab9
127 };
128
129 /* lower 2 bits: modulo 3, higher bits: shift */
130 static uint16_t scale_factor_modshift[64];
131 /* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
132 static int32_t scale_factor_mult[15][3];
133 /* mult table for layer 2 group quantization */
134
135 #define SCALE_GEN(v) \
136 { FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
137
138 static const int32_t scale_factor_mult2[3][3] = {
139     SCALE_GEN(4.0 / 3.0), /* 3 steps */
140     SCALE_GEN(4.0 / 5.0), /* 5 steps */
141     SCALE_GEN(4.0 / 9.0), /* 9 steps */
142 };
143
144 /**
145  * Convert region offsets to region sizes and truncate
146  * size to big_values.
147  */
148 static void region_offset2size(GranuleDef *g)
149 {
150     int i, k, j = 0;
151     g->region_size[2] = 576 / 2;
152     for (i = 0; i < 3; i++) {
153         k = FFMIN(g->region_size[i], g->big_values);
154         g->region_size[i] = k - j;
155         j = k;
156     }
157 }
158
159 static void init_short_region(MPADecodeContext *s, GranuleDef *g)
160 {
161     if (g->block_type == 2) {
162         if (s->sample_rate_index != 8)
163             g->region_size[0] = (36 / 2);
164         else
165             g->region_size[0] = (72 / 2);
166     } else {
167         if (s->sample_rate_index <= 2)
168             g->region_size[0] = (36 / 2);
169         else if (s->sample_rate_index != 8)
170             g->region_size[0] = (54 / 2);
171         else
172             g->region_size[0] = (108 / 2);
173     }
174     g->region_size[1] = (576 / 2);
175 }
176
177 static void init_long_region(MPADecodeContext *s, GranuleDef *g,
178                              int ra1, int ra2)
179 {
180     int l;
181     g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
182     /* should not overflow */
183     l = FFMIN(ra1 + ra2 + 2, 22);
184     g->region_size[1] = band_index_long[s->sample_rate_index][      l] >> 1;
185 }
186
187 static void compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
188 {
189     if (g->block_type == 2) {
190         if (g->switch_point) {
191             if(s->sample_rate_index == 8)
192                 avpriv_request_sample(s->avctx, "switch point in 8khz");
193             /* if switched mode, we handle the 36 first samples as
194                 long blocks.  For 8000Hz, we handle the 72 first
195                 exponents as long blocks */
196             if (s->sample_rate_index <= 2)
197                 g->long_end = 8;
198             else
199                 g->long_end = 6;
200
201             g->short_start = 3;
202         } else {
203             g->long_end    = 0;
204             g->short_start = 0;
205         }
206     } else {
207         g->short_start = 13;
208         g->long_end    = 22;
209     }
210 }
211
212 /* layer 1 unscaling */
213 /* n = number of bits of the mantissa minus 1 */
214 static inline int l1_unscale(int n, int mant, int scale_factor)
215 {
216     int shift, mod;
217     int64_t val;
218
219     shift   = scale_factor_modshift[scale_factor];
220     mod     = shift & 3;
221     shift >>= 2;
222     val     = MUL64((int)(mant + (-1U << n) + 1), scale_factor_mult[n-1][mod]);
223     shift  += n;
224     /* NOTE: at this point, 1 <= shift >= 21 + 15 */
225     return (int)((val + (1LL << (shift - 1))) >> shift);
226 }
227
228 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
229 {
230     int shift, mod, val;
231
232     shift   = scale_factor_modshift[scale_factor];
233     mod     = shift & 3;
234     shift >>= 2;
235
236     val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
237     /* NOTE: at this point, 0 <= shift <= 21 */
238     if (shift > 0)
239         val = (val + (1 << (shift - 1))) >> shift;
240     return val;
241 }
242
243 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
244 static inline int l3_unscale(int value, int exponent)
245 {
246     unsigned int m;
247     int e;
248
249     e  = table_4_3_exp  [4 * value + (exponent & 3)];
250     m  = table_4_3_value[4 * value + (exponent & 3)];
251     e -= exponent >> 2;
252 #ifdef DEBUG
253     if(e < 1)
254         av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
255 #endif
256     if (e > (SUINT)31)
257         return 0;
258     m = (m + ((1U << e) >> 1)) >> e;
259
260     return m;
261 }
262
263 static av_cold void decode_init_static(void)
264 {
265     int i, j, k;
266     int offset;
267
268     /* scale factors table for layer 1/2 */
269     for (i = 0; i < 64; i++) {
270         int shift, mod;
271         /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
272         shift = i / 3;
273         mod   = i % 3;
274         scale_factor_modshift[i] = mod | (shift << 2);
275     }
276
277     /* scale factor multiply for layer 1 */
278     for (i = 0; i < 15; i++) {
279         int n, norm;
280         n = i + 2;
281         norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
282         scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);
283         scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
284         scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
285         ff_dlog(NULL, "%d: norm=%x s=%"PRIx32" %"PRIx32" %"PRIx32"\n", i,
286                 (unsigned)norm,
287                 scale_factor_mult[i][0],
288                 scale_factor_mult[i][1],
289                 scale_factor_mult[i][2]);
290     }
291
292     /* huffman decode tables */
293     offset = 0;
294     for (i = 1; i < 16; i++) {
295         const HuffTable *h = &mpa_huff_tables[i];
296         int xsize, x, y;
297         uint8_t  tmp_bits [512] = { 0 };
298         uint16_t tmp_codes[512] = { 0 };
299
300         xsize = h->xsize;
301
302         j = 0;
303         for (x = 0; x < xsize; x++) {
304             for (y = 0; y < xsize; y++) {
305                 tmp_bits [(x << 5) | y | ((x && y) << 4)]= h->bits [j  ];
306                 tmp_codes[(x << 5) | y | ((x && y) << 4)]= h->codes[j++];
307             }
308         }
309
310         /* XXX: fail test */
311         huff_vlc[i].table = huff_vlc_tables+offset;
312         huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
313         init_vlc(&huff_vlc[i], 7, 512,
314                  tmp_bits, 1, 1, tmp_codes, 2, 2,
315                  INIT_VLC_USE_NEW_STATIC);
316         offset += huff_vlc_tables_sizes[i];
317     }
318     av_assert0(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
319
320     offset = 0;
321     for (i = 0; i < 2; i++) {
322         huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
323         huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
324         init_vlc(&huff_quad_vlc[i], i == 0 ? 6 : 4, 16,
325                  mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
326                  INIT_VLC_USE_NEW_STATIC);
327         offset += huff_quad_vlc_tables_sizes[i];
328     }
329     av_assert0(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
330
331     for (i = 0; i < 9; i++) {
332         k = 0;
333         for (j = 0; j < 22; j++) {
334             band_index_long[i][j] = k;
335             k += band_size_long[i][j];
336         }
337         band_index_long[i][22] = k;
338     }
339
340     /* compute n ^ (4/3) and store it in mantissa/exp format */
341
342     mpegaudio_tableinit();
343
344     for (i = 0; i < 4; i++) {
345         if (ff_mpa_quant_bits[i] < 0) {
346             for (j = 0; j < (1 << (-ff_mpa_quant_bits[i] + 1)); j++) {
347                 int val1, val2, val3, steps;
348                 int val = j;
349                 steps   = ff_mpa_quant_steps[i];
350                 val1    = val % steps;
351                 val    /= steps;
352                 val2    = val % steps;
353                 val3    = val / steps;
354                 division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
355             }
356         }
357     }
358
359
360     for (i = 0; i < 7; i++) {
361         float f;
362         INTFLOAT v;
363         if (i != 6) {
364             f = tan((double)i * M_PI / 12.0);
365             v = FIXR(f / (1.0 + f));
366         } else {
367             v = FIXR(1.0);
368         }
369         is_table[0][    i] = v;
370         is_table[1][6 - i] = v;
371     }
372     /* invalid values */
373     for (i = 7; i < 16; i++)
374         is_table[0][i] = is_table[1][i] = 0.0;
375
376     for (i = 0; i < 16; i++) {
377         double f;
378         int e, k;
379
380         for (j = 0; j < 2; j++) {
381             e = -(j + 1) * ((i + 1) >> 1);
382             f = exp2(e / 4.0);
383             k = i & 1;
384             is_table_lsf[j][k ^ 1][i] = FIXR(f);
385             is_table_lsf[j][k    ][i] = FIXR(1.0);
386             ff_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
387                     i, j, (float) is_table_lsf[j][0][i],
388                     (float) is_table_lsf[j][1][i]);
389         }
390     }
391
392     for (i = 0; i < 8; i++) {
393         double ci, cs, ca;
394         ci = ci_table[i];
395         cs = 1.0 / sqrt(1.0 + ci * ci);
396         ca = cs * ci;
397 #if !USE_FLOATS
398         csa_table[i][0] = FIXHR(cs/4);
399         csa_table[i][1] = FIXHR(ca/4);
400         csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
401         csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
402 #else
403         csa_table[i][0] = cs;
404         csa_table[i][1] = ca;
405         csa_table[i][2] = ca + cs;
406         csa_table[i][3] = ca - cs;
407 #endif
408     }
409     RENAME(ff_mpa_synth_init)();
410 }
411
412 static av_cold int decode_init(AVCodecContext * avctx)
413 {
414     static int initialized_tables = 0;
415     MPADecodeContext *s = avctx->priv_data;
416
417     if (!initialized_tables) {
418         decode_init_static();
419         initialized_tables = 1;
420     }
421
422     s->avctx = avctx;
423
424 #if USE_FLOATS
425     {
426         AVFloatDSPContext *fdsp;
427         fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
428         if (!fdsp)
429             return AVERROR(ENOMEM);
430         s->butterflies_float = fdsp->butterflies_float;
431         av_free(fdsp);
432     }
433 #endif
434
435     ff_mpadsp_init(&s->mpadsp);
436
437     if (avctx->request_sample_fmt == OUT_FMT &&
438         avctx->codec_id != AV_CODEC_ID_MP3ON4)
439         avctx->sample_fmt = OUT_FMT;
440     else
441         avctx->sample_fmt = OUT_FMT_P;
442     s->err_recognition = avctx->err_recognition;
443
444     if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
445         s->adu_mode = 1;
446
447     return 0;
448 }
449
450 #define C3 FIXHR(0.86602540378443864676/2)
451 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
452 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
453 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
454
455 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
456    cases. */
457 static void imdct12(INTFLOAT *out, SUINTFLOAT *in)
458 {
459     SUINTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
460
461     in0  = in[0*3];
462     in1  = in[1*3] + in[0*3];
463     in2  = in[2*3] + in[1*3];
464     in3  = in[3*3] + in[2*3];
465     in4  = in[4*3] + in[3*3];
466     in5  = in[5*3] + in[4*3];
467     in5 += in3;
468     in3 += in1;
469
470     in2  = MULH3(in2, C3, 2);
471     in3  = MULH3(in3, C3, 4);
472
473     t1   = in0 - in4;
474     t2   = MULH3(in1 - in5, C4, 2);
475
476     out[ 7] =
477     out[10] = t1 + t2;
478     out[ 1] =
479     out[ 4] = t1 - t2;
480
481     in0    += SHR(in4, 1);
482     in4     = in0 + in2;
483     in5    += 2*in1;
484     in1     = MULH3(in5 + in3, C5, 1);
485     out[ 8] =
486     out[ 9] = in4 + in1;
487     out[ 2] =
488     out[ 3] = in4 - in1;
489
490     in0    -= in2;
491     in5     = MULH3(in5 - in3, C6, 2);
492     out[ 0] =
493     out[ 5] = in0 - in5;
494     out[ 6] =
495     out[11] = in0 + in5;
496 }
497
498 static int handle_crc(MPADecodeContext *s, int sec_len)
499 {
500     if (s->error_protection && (s->err_recognition & AV_EF_CRCCHECK)) {
501         const uint8_t *buf = s->gb.buffer - HEADER_SIZE;
502         int sec_byte_len  = sec_len >> 3;
503         int sec_rem_bits  = sec_len & 7;
504         const AVCRC *crc_tab = av_crc_get_table(AV_CRC_16_ANSI);
505         uint8_t tmp_buf[4];
506         uint32_t crc_val = av_crc(crc_tab, UINT16_MAX, &buf[2], 2);
507         crc_val = av_crc(crc_tab, crc_val, &buf[6], sec_byte_len);
508
509         AV_WB32(tmp_buf,
510                 ((buf[6 + sec_byte_len] & (0xFF00 >> sec_rem_bits)) << 24) +
511                 ((s->crc << 16) >> sec_rem_bits));
512
513         crc_val = av_crc(crc_tab, crc_val, tmp_buf, 3);
514
515         if (crc_val) {
516             av_log(s->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", crc_val);
517             if (s->err_recognition & AV_EF_EXPLODE)
518                 return AVERROR_INVALIDDATA;
519         }
520     }
521     return 0;
522 }
523
524 /* return the number of decoded frames */
525 static int mp_decode_layer1(MPADecodeContext *s)
526 {
527     int bound, i, v, n, ch, j, mant;
528     uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
529     uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
530     int ret;
531
532     ret = handle_crc(s, (s->nb_channels == 1) ? 8*16  : 8*32);
533     if (ret < 0)
534         return ret;
535
536     if (s->mode == MPA_JSTEREO)
537         bound = (s->mode_ext + 1) * 4;
538     else
539         bound = SBLIMIT;
540
541     /* allocation bits */
542     for (i = 0; i < bound; i++) {
543         for (ch = 0; ch < s->nb_channels; ch++) {
544             allocation[ch][i] = get_bits(&s->gb, 4);
545         }
546     }
547     for (i = bound; i < SBLIMIT; i++)
548         allocation[0][i] = get_bits(&s->gb, 4);
549
550     /* scale factors */
551     for (i = 0; i < bound; i++) {
552         for (ch = 0; ch < s->nb_channels; ch++) {
553             if (allocation[ch][i])
554                 scale_factors[ch][i] = get_bits(&s->gb, 6);
555         }
556     }
557     for (i = bound; i < SBLIMIT; i++) {
558         if (allocation[0][i]) {
559             scale_factors[0][i] = get_bits(&s->gb, 6);
560             scale_factors[1][i] = get_bits(&s->gb, 6);
561         }
562     }
563
564     /* compute samples */
565     for (j = 0; j < 12; j++) {
566         for (i = 0; i < bound; i++) {
567             for (ch = 0; ch < s->nb_channels; ch++) {
568                 n = allocation[ch][i];
569                 if (n) {
570                     mant = get_bits(&s->gb, n + 1);
571                     v = l1_unscale(n, mant, scale_factors[ch][i]);
572                 } else {
573                     v = 0;
574                 }
575                 s->sb_samples[ch][j][i] = v;
576             }
577         }
578         for (i = bound; i < SBLIMIT; i++) {
579             n = allocation[0][i];
580             if (n) {
581                 mant = get_bits(&s->gb, n + 1);
582                 v = l1_unscale(n, mant, scale_factors[0][i]);
583                 s->sb_samples[0][j][i] = v;
584                 v = l1_unscale(n, mant, scale_factors[1][i]);
585                 s->sb_samples[1][j][i] = v;
586             } else {
587                 s->sb_samples[0][j][i] = 0;
588                 s->sb_samples[1][j][i] = 0;
589             }
590         }
591     }
592     return 12;
593 }
594
595 static int mp_decode_layer2(MPADecodeContext *s)
596 {
597     int sblimit; /* number of used subbands */
598     const unsigned char *alloc_table;
599     int table, bit_alloc_bits, i, j, ch, bound, v;
600     unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
601     unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
602     unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
603     int scale, qindex, bits, steps, k, l, m, b;
604     int ret;
605
606     /* select decoding table */
607     table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
608                                    s->sample_rate, s->lsf);
609     sblimit     = ff_mpa_sblimit_table[table];
610     alloc_table = ff_mpa_alloc_tables[table];
611
612     if (s->mode == MPA_JSTEREO)
613         bound = (s->mode_ext + 1) * 4;
614     else
615         bound = sblimit;
616
617     ff_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
618
619     /* sanity check */
620     if (bound > sblimit)
621         bound = sblimit;
622
623     /* parse bit allocation */
624     j = 0;
625     for (i = 0; i < bound; i++) {
626         bit_alloc_bits = alloc_table[j];
627         for (ch = 0; ch < s->nb_channels; ch++)
628             bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
629         j += 1 << bit_alloc_bits;
630     }
631     for (i = bound; i < sblimit; i++) {
632         bit_alloc_bits = alloc_table[j];
633         v = get_bits(&s->gb, bit_alloc_bits);
634         bit_alloc[0][i] = v;
635         bit_alloc[1][i] = v;
636         j += 1 << bit_alloc_bits;
637     }
638
639     /* scale codes */
640     for (i = 0; i < sblimit; i++) {
641         for (ch = 0; ch < s->nb_channels; ch++) {
642             if (bit_alloc[ch][i])
643                 scale_code[ch][i] = get_bits(&s->gb, 2);
644         }
645     }
646
647     ret = handle_crc(s, get_bits_count(&s->gb) - 16);
648     if (ret < 0)
649         return ret;
650
651     /* scale factors */
652     for (i = 0; i < sblimit; i++) {
653         for (ch = 0; ch < s->nb_channels; ch++) {
654             if (bit_alloc[ch][i]) {
655                 sf = scale_factors[ch][i];
656                 switch (scale_code[ch][i]) {
657                 default:
658                 case 0:
659                     sf[0] = get_bits(&s->gb, 6);
660                     sf[1] = get_bits(&s->gb, 6);
661                     sf[2] = get_bits(&s->gb, 6);
662                     break;
663                 case 2:
664                     sf[0] = get_bits(&s->gb, 6);
665                     sf[1] = sf[0];
666                     sf[2] = sf[0];
667                     break;
668                 case 1:
669                     sf[0] = get_bits(&s->gb, 6);
670                     sf[2] = get_bits(&s->gb, 6);
671                     sf[1] = sf[0];
672                     break;
673                 case 3:
674                     sf[0] = get_bits(&s->gb, 6);
675                     sf[2] = get_bits(&s->gb, 6);
676                     sf[1] = sf[2];
677                     break;
678                 }
679             }
680         }
681     }
682
683     /* samples */
684     for (k = 0; k < 3; k++) {
685         for (l = 0; l < 12; l += 3) {
686             j = 0;
687             for (i = 0; i < bound; i++) {
688                 bit_alloc_bits = alloc_table[j];
689                 for (ch = 0; ch < s->nb_channels; ch++) {
690                     b = bit_alloc[ch][i];
691                     if (b) {
692                         scale = scale_factors[ch][i][k];
693                         qindex = alloc_table[j+b];
694                         bits = ff_mpa_quant_bits[qindex];
695                         if (bits < 0) {
696                             int v2;
697                             /* 3 values at the same time */
698                             v = get_bits(&s->gb, -bits);
699                             v2 = division_tabs[qindex][v];
700                             steps  = ff_mpa_quant_steps[qindex];
701
702                             s->sb_samples[ch][k * 12 + l + 0][i] =
703                                 l2_unscale_group(steps,  v2       & 15, scale);
704                             s->sb_samples[ch][k * 12 + l + 1][i] =
705                                 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
706                             s->sb_samples[ch][k * 12 + l + 2][i] =
707                                 l2_unscale_group(steps,  v2 >> 8      , scale);
708                         } else {
709                             for (m = 0; m < 3; m++) {
710                                 v = get_bits(&s->gb, bits);
711                                 v = l1_unscale(bits - 1, v, scale);
712                                 s->sb_samples[ch][k * 12 + l + m][i] = v;
713                             }
714                         }
715                     } else {
716                         s->sb_samples[ch][k * 12 + l + 0][i] = 0;
717                         s->sb_samples[ch][k * 12 + l + 1][i] = 0;
718                         s->sb_samples[ch][k * 12 + l + 2][i] = 0;
719                     }
720                 }
721                 /* next subband in alloc table */
722                 j += 1 << bit_alloc_bits;
723             }
724             /* XXX: find a way to avoid this duplication of code */
725             for (i = bound; i < sblimit; i++) {
726                 bit_alloc_bits = alloc_table[j];
727                 b = bit_alloc[0][i];
728                 if (b) {
729                     int mant, scale0, scale1;
730                     scale0 = scale_factors[0][i][k];
731                     scale1 = scale_factors[1][i][k];
732                     qindex = alloc_table[j + b];
733                     bits = ff_mpa_quant_bits[qindex];
734                     if (bits < 0) {
735                         /* 3 values at the same time */
736                         v = get_bits(&s->gb, -bits);
737                         steps = ff_mpa_quant_steps[qindex];
738                         mant = v % steps;
739                         v = v / steps;
740                         s->sb_samples[0][k * 12 + l + 0][i] =
741                             l2_unscale_group(steps, mant, scale0);
742                         s->sb_samples[1][k * 12 + l + 0][i] =
743                             l2_unscale_group(steps, mant, scale1);
744                         mant = v % steps;
745                         v = v / steps;
746                         s->sb_samples[0][k * 12 + l + 1][i] =
747                             l2_unscale_group(steps, mant, scale0);
748                         s->sb_samples[1][k * 12 + l + 1][i] =
749                             l2_unscale_group(steps, mant, scale1);
750                         s->sb_samples[0][k * 12 + l + 2][i] =
751                             l2_unscale_group(steps, v, scale0);
752                         s->sb_samples[1][k * 12 + l + 2][i] =
753                             l2_unscale_group(steps, v, scale1);
754                     } else {
755                         for (m = 0; m < 3; m++) {
756                             mant = get_bits(&s->gb, bits);
757                             s->sb_samples[0][k * 12 + l + m][i] =
758                                 l1_unscale(bits - 1, mant, scale0);
759                             s->sb_samples[1][k * 12 + l + m][i] =
760                                 l1_unscale(bits - 1, mant, scale1);
761                         }
762                     }
763                 } else {
764                     s->sb_samples[0][k * 12 + l + 0][i] = 0;
765                     s->sb_samples[0][k * 12 + l + 1][i] = 0;
766                     s->sb_samples[0][k * 12 + l + 2][i] = 0;
767                     s->sb_samples[1][k * 12 + l + 0][i] = 0;
768                     s->sb_samples[1][k * 12 + l + 1][i] = 0;
769                     s->sb_samples[1][k * 12 + l + 2][i] = 0;
770                 }
771                 /* next subband in alloc table */
772                 j += 1 << bit_alloc_bits;
773             }
774             /* fill remaining samples to zero */
775             for (i = sblimit; i < SBLIMIT; i++) {
776                 for (ch = 0; ch < s->nb_channels; ch++) {
777                     s->sb_samples[ch][k * 12 + l + 0][i] = 0;
778                     s->sb_samples[ch][k * 12 + l + 1][i] = 0;
779                     s->sb_samples[ch][k * 12 + l + 2][i] = 0;
780                 }
781             }
782         }
783     }
784     return 3 * 12;
785 }
786
787 #define SPLIT(dst,sf,n)             \
788     if (n == 3) {                   \
789         int m = (sf * 171) >> 9;    \
790         dst   = sf - 3 * m;         \
791         sf    = m;                  \
792     } else if (n == 4) {            \
793         dst  = sf & 3;              \
794         sf >>= 2;                   \
795     } else if (n == 5) {            \
796         int m = (sf * 205) >> 10;   \
797         dst   = sf - 5 * m;         \
798         sf    = m;                  \
799     } else if (n == 6) {            \
800         int m = (sf * 171) >> 10;   \
801         dst   = sf - 6 * m;         \
802         sf    = m;                  \
803     } else {                        \
804         dst = 0;                    \
805     }
806
807 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
808                                            int n3)
809 {
810     SPLIT(slen[3], sf, n3)
811     SPLIT(slen[2], sf, n2)
812     SPLIT(slen[1], sf, n1)
813     slen[0] = sf;
814 }
815
816 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
817                                          int16_t *exponents)
818 {
819     const uint8_t *bstab, *pretab;
820     int len, i, j, k, l, v0, shift, gain, gains[3];
821     int16_t *exp_ptr;
822
823     exp_ptr = exponents;
824     gain    = g->global_gain - 210;
825     shift   = g->scalefac_scale + 1;
826
827     bstab  = band_size_long[s->sample_rate_index];
828     pretab = mpa_pretab[g->preflag];
829     for (i = 0; i < g->long_end; i++) {
830         v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
831         len = bstab[i];
832         for (j = len; j > 0; j--)
833             *exp_ptr++ = v0;
834     }
835
836     if (g->short_start < 13) {
837         bstab    = band_size_short[s->sample_rate_index];
838         gains[0] = gain - (g->subblock_gain[0] << 3);
839         gains[1] = gain - (g->subblock_gain[1] << 3);
840         gains[2] = gain - (g->subblock_gain[2] << 3);
841         k        = g->long_end;
842         for (i = g->short_start; i < 13; i++) {
843             len = bstab[i];
844             for (l = 0; l < 3; l++) {
845                 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
846                 for (j = len; j > 0; j--)
847                     *exp_ptr++ = v0;
848             }
849         }
850     }
851 }
852
853 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
854                           int *end_pos2)
855 {
856     if (s->in_gb.buffer && *pos >= s->gb.size_in_bits - s->extrasize * 8) {
857         s->gb           = s->in_gb;
858         s->in_gb.buffer = NULL;
859         s->extrasize    = 0;
860         av_assert2((get_bits_count(&s->gb) & 7) == 0);
861         skip_bits_long(&s->gb, *pos - *end_pos);
862         *end_pos2 =
863         *end_pos  = *end_pos2 + get_bits_count(&s->gb) - *pos;
864         *pos      = get_bits_count(&s->gb);
865     }
866 }
867
868 /* Following is an optimized code for
869             INTFLOAT v = *src
870             if(get_bits1(&s->gb))
871                 v = -v;
872             *dst = v;
873 */
874 #if USE_FLOATS
875 #define READ_FLIP_SIGN(dst,src)                     \
876     v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31);  \
877     AV_WN32A(dst, v);
878 #else
879 #define READ_FLIP_SIGN(dst,src)     \
880     v      = -get_bits1(&s->gb);    \
881     *(dst) = (*(src) ^ v) - v;
882 #endif
883
884 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
885                           int16_t *exponents, int end_pos2)
886 {
887     int s_index;
888     int i;
889     int last_pos, bits_left;
890     VLC *vlc;
891     int end_pos = FFMIN(end_pos2, s->gb.size_in_bits - s->extrasize * 8);
892
893     /* low frequencies (called big values) */
894     s_index = 0;
895     for (i = 0; i < 3; i++) {
896         int j, k, l, linbits;
897         j = g->region_size[i];
898         if (j == 0)
899             continue;
900         /* select vlc table */
901         k       = g->table_select[i];
902         l       = mpa_huff_data[k][0];
903         linbits = mpa_huff_data[k][1];
904         vlc     = &huff_vlc[l];
905
906         if (!l) {
907             memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
908             s_index += 2 * j;
909             continue;
910         }
911
912         /* read huffcode and compute each couple */
913         for (; j > 0; j--) {
914             int exponent, x, y;
915             int v;
916             int pos = get_bits_count(&s->gb);
917
918             if (pos >= end_pos){
919                 switch_buffer(s, &pos, &end_pos, &end_pos2);
920                 if (pos >= end_pos)
921                     break;
922             }
923             y = get_vlc2(&s->gb, vlc->table, 7, 3);
924
925             if (!y) {
926                 g->sb_hybrid[s_index    ] =
927                 g->sb_hybrid[s_index + 1] = 0;
928                 s_index += 2;
929                 continue;
930             }
931
932             exponent= exponents[s_index];
933
934             ff_dlog(s->avctx, "region=%d n=%d y=%d exp=%d\n",
935                     i, g->region_size[i] - j, y, exponent);
936             if (y & 16) {
937                 x = y >> 5;
938                 y = y & 0x0f;
939                 if (x < 15) {
940                     READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
941                 } else {
942                     x += get_bitsz(&s->gb, linbits);
943                     v  = l3_unscale(x, exponent);
944                     if (get_bits1(&s->gb))
945                         v = -v;
946                     g->sb_hybrid[s_index] = v;
947                 }
948                 if (y < 15) {
949                     READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
950                 } else {
951                     y += get_bitsz(&s->gb, linbits);
952                     v  = l3_unscale(y, exponent);
953                     if (get_bits1(&s->gb))
954                         v = -v;
955                     g->sb_hybrid[s_index + 1] = v;
956                 }
957             } else {
958                 x = y >> 5;
959                 y = y & 0x0f;
960                 x += y;
961                 if (x < 15) {
962                     READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
963                 } else {
964                     x += get_bitsz(&s->gb, linbits);
965                     v  = l3_unscale(x, exponent);
966                     if (get_bits1(&s->gb))
967                         v = -v;
968                     g->sb_hybrid[s_index+!!y] = v;
969                 }
970                 g->sb_hybrid[s_index + !y] = 0;
971             }
972             s_index += 2;
973         }
974     }
975
976     /* high frequencies */
977     vlc = &huff_quad_vlc[g->count1table_select];
978     last_pos = 0;
979     while (s_index <= 572) {
980         int pos, code;
981         pos = get_bits_count(&s->gb);
982         if (pos >= end_pos) {
983             if (pos > end_pos2 && last_pos) {
984                 /* some encoders generate an incorrect size for this
985                    part. We must go back into the data */
986                 s_index -= 4;
987                 skip_bits_long(&s->gb, last_pos - pos);
988                 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
989                 if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
990                     s_index=0;
991                 break;
992             }
993             switch_buffer(s, &pos, &end_pos, &end_pos2);
994             if (pos >= end_pos)
995                 break;
996         }
997         last_pos = pos;
998
999         code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1000         ff_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1001         g->sb_hybrid[s_index + 0] =
1002         g->sb_hybrid[s_index + 1] =
1003         g->sb_hybrid[s_index + 2] =
1004         g->sb_hybrid[s_index + 3] = 0;
1005         while (code) {
1006             static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
1007             int v;
1008             int pos = s_index + idxtab[code];
1009             code   ^= 8 >> idxtab[code];
1010             READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
1011         }
1012         s_index += 4;
1013     }
1014     /* skip extension bits */
1015     bits_left = end_pos2 - get_bits_count(&s->gb);
1016     if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
1017         av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1018         s_index=0;
1019     } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
1020         av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1021         s_index = 0;
1022     }
1023     memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1024     skip_bits_long(&s->gb, bits_left);
1025
1026     i = get_bits_count(&s->gb);
1027     switch_buffer(s, &i, &end_pos, &end_pos2);
1028
1029     return 0;
1030 }
1031
1032 /* Reorder short blocks from bitstream order to interleaved order. It
1033    would be faster to do it in parsing, but the code would be far more
1034    complicated */
1035 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1036 {
1037     int i, j, len;
1038     INTFLOAT *ptr, *dst, *ptr1;
1039     INTFLOAT tmp[576];
1040
1041     if (g->block_type != 2)
1042         return;
1043
1044     if (g->switch_point) {
1045         if (s->sample_rate_index != 8)
1046             ptr = g->sb_hybrid + 36;
1047         else
1048             ptr = g->sb_hybrid + 72;
1049     } else {
1050         ptr = g->sb_hybrid;
1051     }
1052
1053     for (i = g->short_start; i < 13; i++) {
1054         len  = band_size_short[s->sample_rate_index][i];
1055         ptr1 = ptr;
1056         dst  = tmp;
1057         for (j = len; j > 0; j--) {
1058             *dst++ = ptr[0*len];
1059             *dst++ = ptr[1*len];
1060             *dst++ = ptr[2*len];
1061             ptr++;
1062         }
1063         ptr += 2 * len;
1064         memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1065     }
1066 }
1067
1068 #define ISQRT2 FIXR(0.70710678118654752440)
1069
1070 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1071 {
1072     int i, j, k, l;
1073     int sf_max, sf, len, non_zero_found;
1074     INTFLOAT (*is_tab)[16], *tab0, *tab1, v1, v2;
1075     SUINTFLOAT tmp0, tmp1;
1076     int non_zero_found_short[3];
1077
1078     /* intensity stereo */
1079     if (s->mode_ext & MODE_EXT_I_STEREO) {
1080         if (!s->lsf) {
1081             is_tab = is_table;
1082             sf_max = 7;
1083         } else {
1084             is_tab = is_table_lsf[g1->scalefac_compress & 1];
1085             sf_max = 16;
1086         }
1087
1088         tab0 = g0->sb_hybrid + 576;
1089         tab1 = g1->sb_hybrid + 576;
1090
1091         non_zero_found_short[0] = 0;
1092         non_zero_found_short[1] = 0;
1093         non_zero_found_short[2] = 0;
1094         k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1095         for (i = 12; i >= g1->short_start; i--) {
1096             /* for last band, use previous scale factor */
1097             if (i != 11)
1098                 k -= 3;
1099             len = band_size_short[s->sample_rate_index][i];
1100             for (l = 2; l >= 0; l--) {
1101                 tab0 -= len;
1102                 tab1 -= len;
1103                 if (!non_zero_found_short[l]) {
1104                     /* test if non zero band. if so, stop doing i-stereo */
1105                     for (j = 0; j < len; j++) {
1106                         if (tab1[j] != 0) {
1107                             non_zero_found_short[l] = 1;
1108                             goto found1;
1109                         }
1110                     }
1111                     sf = g1->scale_factors[k + l];
1112                     if (sf >= sf_max)
1113                         goto found1;
1114
1115                     v1 = is_tab[0][sf];
1116                     v2 = is_tab[1][sf];
1117                     for (j = 0; j < len; j++) {
1118                         tmp0    = tab0[j];
1119                         tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1120                         tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1121                     }
1122                 } else {
1123 found1:
1124                     if (s->mode_ext & MODE_EXT_MS_STEREO) {
1125                         /* lower part of the spectrum : do ms stereo
1126                            if enabled */
1127                         for (j = 0; j < len; j++) {
1128                             tmp0    = tab0[j];
1129                             tmp1    = tab1[j];
1130                             tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1131                             tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1132                         }
1133                     }
1134                 }
1135             }
1136         }
1137
1138         non_zero_found = non_zero_found_short[0] |
1139                          non_zero_found_short[1] |
1140                          non_zero_found_short[2];
1141
1142         for (i = g1->long_end - 1;i >= 0;i--) {
1143             len   = band_size_long[s->sample_rate_index][i];
1144             tab0 -= len;
1145             tab1 -= len;
1146             /* test if non zero band. if so, stop doing i-stereo */
1147             if (!non_zero_found) {
1148                 for (j = 0; j < len; j++) {
1149                     if (tab1[j] != 0) {
1150                         non_zero_found = 1;
1151                         goto found2;
1152                     }
1153                 }
1154                 /* for last band, use previous scale factor */
1155                 k  = (i == 21) ? 20 : i;
1156                 sf = g1->scale_factors[k];
1157                 if (sf >= sf_max)
1158                     goto found2;
1159                 v1 = is_tab[0][sf];
1160                 v2 = is_tab[1][sf];
1161                 for (j = 0; j < len; j++) {
1162                     tmp0    = tab0[j];
1163                     tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1164                     tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1165                 }
1166             } else {
1167 found2:
1168                 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1169                     /* lower part of the spectrum : do ms stereo
1170                        if enabled */
1171                     for (j = 0; j < len; j++) {
1172                         tmp0    = tab0[j];
1173                         tmp1    = tab1[j];
1174                         tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1175                         tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1176                     }
1177                 }
1178             }
1179         }
1180     } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1181         /* ms stereo ONLY */
1182         /* NOTE: the 1/sqrt(2) normalization factor is included in the
1183            global gain */
1184 #if USE_FLOATS
1185        s->butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1186 #else
1187         tab0 = g0->sb_hybrid;
1188         tab1 = g1->sb_hybrid;
1189         for (i = 0; i < 576; i++) {
1190             tmp0    = tab0[i];
1191             tmp1    = tab1[i];
1192             tab0[i] = tmp0 + tmp1;
1193             tab1[i] = tmp0 - tmp1;
1194         }
1195 #endif
1196     }
1197 }
1198
1199 #if USE_FLOATS
1200 #if HAVE_MIPSFPU
1201 #   include "mips/compute_antialias_float.h"
1202 #endif /* HAVE_MIPSFPU */
1203 #else
1204 #if HAVE_MIPSDSP
1205 #   include "mips/compute_antialias_fixed.h"
1206 #endif /* HAVE_MIPSDSP */
1207 #endif /* USE_FLOATS */
1208
1209 #ifndef compute_antialias
1210 #if USE_FLOATS
1211 #define AA(j) do {                                                      \
1212         float tmp0 = ptr[-1-j];                                         \
1213         float tmp1 = ptr[   j];                                         \
1214         ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1];    \
1215         ptr[   j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0];    \
1216     } while (0)
1217 #else
1218 #define AA(j) do {                                              \
1219         SUINT tmp0 = ptr[-1-j];                                   \
1220         SUINT tmp1 = ptr[   j];                                   \
1221         SUINT tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]);          \
1222         ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2]));   \
1223         ptr[   j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3]));   \
1224     } while (0)
1225 #endif
1226
1227 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1228 {
1229     INTFLOAT *ptr;
1230     int n, i;
1231
1232     /* we antialias only "long" bands */
1233     if (g->block_type == 2) {
1234         if (!g->switch_point)
1235             return;
1236         /* XXX: check this for 8000Hz case */
1237         n = 1;
1238     } else {
1239         n = SBLIMIT - 1;
1240     }
1241
1242     ptr = g->sb_hybrid + 18;
1243     for (i = n; i > 0; i--) {
1244         AA(0);
1245         AA(1);
1246         AA(2);
1247         AA(3);
1248         AA(4);
1249         AA(5);
1250         AA(6);
1251         AA(7);
1252
1253         ptr += 18;
1254     }
1255 }
1256 #endif /* compute_antialias */
1257
1258 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1259                           INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1260 {
1261     INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1262     INTFLOAT out2[12];
1263     int i, j, mdct_long_end, sblimit;
1264
1265     /* find last non zero block */
1266     ptr  = g->sb_hybrid + 576;
1267     ptr1 = g->sb_hybrid + 2 * 18;
1268     while (ptr >= ptr1) {
1269         int32_t *p;
1270         ptr -= 6;
1271         p    = (int32_t*)ptr;
1272         if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1273             break;
1274     }
1275     sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1276
1277     if (g->block_type == 2) {
1278         /* XXX: check for 8000 Hz */
1279         if (g->switch_point)
1280             mdct_long_end = 2;
1281         else
1282             mdct_long_end = 0;
1283     } else {
1284         mdct_long_end = sblimit;
1285     }
1286
1287     s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1288                                      mdct_long_end, g->switch_point,
1289                                      g->block_type);
1290
1291     buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1292     ptr = g->sb_hybrid + 18 * mdct_long_end;
1293
1294     for (j = mdct_long_end; j < sblimit; j++) {
1295         /* select frequency inversion */
1296         win     = RENAME(ff_mdct_win)[2 + (4  & -(j & 1))];
1297         out_ptr = sb_samples + j;
1298
1299         for (i = 0; i < 6; i++) {
1300             *out_ptr = buf[4*i];
1301             out_ptr += SBLIMIT;
1302         }
1303         imdct12(out2, ptr + 0);
1304         for (i = 0; i < 6; i++) {
1305             *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*1)];
1306             buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1307             out_ptr += SBLIMIT;
1308         }
1309         imdct12(out2, ptr + 1);
1310         for (i = 0; i < 6; i++) {
1311             *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*2)];
1312             buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1313             out_ptr += SBLIMIT;
1314         }
1315         imdct12(out2, ptr + 2);
1316         for (i = 0; i < 6; i++) {
1317             buf[4*(i + 6*0)] = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*0)];
1318             buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1319             buf[4*(i + 6*2)] = 0;
1320         }
1321         ptr += 18;
1322         buf += (j&3) != 3 ? 1 : (4*18-3);
1323     }
1324     /* zero bands */
1325     for (j = sblimit; j < SBLIMIT; j++) {
1326         /* overlap */
1327         out_ptr = sb_samples + j;
1328         for (i = 0; i < 18; i++) {
1329             *out_ptr = buf[4*i];
1330             buf[4*i]   = 0;
1331             out_ptr += SBLIMIT;
1332         }
1333         buf += (j&3) != 3 ? 1 : (4*18-3);
1334     }
1335 }
1336
1337 /* main layer3 decoding function */
1338 static int mp_decode_layer3(MPADecodeContext *s)
1339 {
1340     int nb_granules, main_data_begin;
1341     int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1342     GranuleDef *g;
1343     int16_t exponents[576]; //FIXME try INTFLOAT
1344     int ret;
1345
1346     /* read side info */
1347     if (s->lsf) {
1348         ret = handle_crc(s, ((s->nb_channels == 1) ? 8*9  : 8*17));
1349         main_data_begin = get_bits(&s->gb, 8);
1350         skip_bits(&s->gb, s->nb_channels);
1351         nb_granules = 1;
1352     } else {
1353         ret = handle_crc(s, ((s->nb_channels == 1) ? 8*17 : 8*32));
1354         main_data_begin = get_bits(&s->gb, 9);
1355         if (s->nb_channels == 2)
1356             skip_bits(&s->gb, 3);
1357         else
1358             skip_bits(&s->gb, 5);
1359         nb_granules = 2;
1360         for (ch = 0; ch < s->nb_channels; ch++) {
1361             s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1362             s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1363         }
1364     }
1365     if (ret < 0)
1366         return ret;
1367
1368     for (gr = 0; gr < nb_granules; gr++) {
1369         for (ch = 0; ch < s->nb_channels; ch++) {
1370             ff_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1371             g = &s->granules[ch][gr];
1372             g->part2_3_length = get_bits(&s->gb, 12);
1373             g->big_values     = get_bits(&s->gb,  9);
1374             if (g->big_values > 288) {
1375                 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1376                 return AVERROR_INVALIDDATA;
1377             }
1378
1379             g->global_gain = get_bits(&s->gb, 8);
1380             /* if MS stereo only is selected, we precompute the
1381                1/sqrt(2) renormalization factor */
1382             if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1383                 MODE_EXT_MS_STEREO)
1384                 g->global_gain -= 2;
1385             if (s->lsf)
1386                 g->scalefac_compress = get_bits(&s->gb, 9);
1387             else
1388                 g->scalefac_compress = get_bits(&s->gb, 4);
1389             blocksplit_flag = get_bits1(&s->gb);
1390             if (blocksplit_flag) {
1391                 g->block_type = get_bits(&s->gb, 2);
1392                 if (g->block_type == 0) {
1393                     av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1394                     return AVERROR_INVALIDDATA;
1395                 }
1396                 g->switch_point = get_bits1(&s->gb);
1397                 for (i = 0; i < 2; i++)
1398                     g->table_select[i] = get_bits(&s->gb, 5);
1399                 for (i = 0; i < 3; i++)
1400                     g->subblock_gain[i] = get_bits(&s->gb, 3);
1401                 init_short_region(s, g);
1402             } else {
1403                 int region_address1, region_address2;
1404                 g->block_type = 0;
1405                 g->switch_point = 0;
1406                 for (i = 0; i < 3; i++)
1407                     g->table_select[i] = get_bits(&s->gb, 5);
1408                 /* compute huffman coded region sizes */
1409                 region_address1 = get_bits(&s->gb, 4);
1410                 region_address2 = get_bits(&s->gb, 3);
1411                 ff_dlog(s->avctx, "region1=%d region2=%d\n",
1412                         region_address1, region_address2);
1413                 init_long_region(s, g, region_address1, region_address2);
1414             }
1415             region_offset2size(g);
1416             compute_band_indexes(s, g);
1417
1418             g->preflag = 0;
1419             if (!s->lsf)
1420                 g->preflag = get_bits1(&s->gb);
1421             g->scalefac_scale     = get_bits1(&s->gb);
1422             g->count1table_select = get_bits1(&s->gb);
1423             ff_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1424                     g->block_type, g->switch_point);
1425         }
1426     }
1427
1428     if (!s->adu_mode) {
1429         int skip;
1430         const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb) >> 3);
1431         s->extrasize = av_clip((get_bits_left(&s->gb) >> 3) - s->extrasize, 0,
1432                                FFMAX(0, LAST_BUF_SIZE - s->last_buf_size));
1433         av_assert1((get_bits_count(&s->gb) & 7) == 0);
1434         /* now we get bits from the main_data_begin offset */
1435         ff_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1436                 main_data_begin, s->last_buf_size);
1437
1438         memcpy(s->last_buf + s->last_buf_size, ptr, s->extrasize);
1439         s->in_gb = s->gb;
1440         init_get_bits(&s->gb, s->last_buf, (s->last_buf_size + s->extrasize) * 8);
1441         s->last_buf_size <<= 3;
1442         for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1443             for (ch = 0; ch < s->nb_channels; ch++) {
1444                 g = &s->granules[ch][gr];
1445                 s->last_buf_size += g->part2_3_length;
1446                 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1447                 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1448             }
1449         }
1450         skip = s->last_buf_size - 8 * main_data_begin;
1451         if (skip >= s->gb.size_in_bits - s->extrasize * 8 && s->in_gb.buffer) {
1452             skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits + s->extrasize * 8);
1453             s->gb           = s->in_gb;
1454             s->in_gb.buffer = NULL;
1455             s->extrasize    = 0;
1456         } else {
1457             skip_bits_long(&s->gb, skip);
1458         }
1459     } else {
1460         gr = 0;
1461         s->extrasize = 0;
1462     }
1463
1464     for (; gr < nb_granules; gr++) {
1465         for (ch = 0; ch < s->nb_channels; ch++) {
1466             g = &s->granules[ch][gr];
1467             bits_pos = get_bits_count(&s->gb);
1468
1469             if (!s->lsf) {
1470                 uint8_t *sc;
1471                 int slen, slen1, slen2;
1472
1473                 /* MPEG-1 scale factors */
1474                 slen1 = slen_table[0][g->scalefac_compress];
1475                 slen2 = slen_table[1][g->scalefac_compress];
1476                 ff_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1477                 if (g->block_type == 2) {
1478                     n = g->switch_point ? 17 : 18;
1479                     j = 0;
1480                     if (slen1) {
1481                         for (i = 0; i < n; i++)
1482                             g->scale_factors[j++] = get_bits(&s->gb, slen1);
1483                     } else {
1484                         for (i = 0; i < n; i++)
1485                             g->scale_factors[j++] = 0;
1486                     }
1487                     if (slen2) {
1488                         for (i = 0; i < 18; i++)
1489                             g->scale_factors[j++] = get_bits(&s->gb, slen2);
1490                         for (i = 0; i < 3; i++)
1491                             g->scale_factors[j++] = 0;
1492                     } else {
1493                         for (i = 0; i < 21; i++)
1494                             g->scale_factors[j++] = 0;
1495                     }
1496                 } else {
1497                     sc = s->granules[ch][0].scale_factors;
1498                     j = 0;
1499                     for (k = 0; k < 4; k++) {
1500                         n = k == 0 ? 6 : 5;
1501                         if ((g->scfsi & (0x8 >> k)) == 0) {
1502                             slen = (k < 2) ? slen1 : slen2;
1503                             if (slen) {
1504                                 for (i = 0; i < n; i++)
1505                                     g->scale_factors[j++] = get_bits(&s->gb, slen);
1506                             } else {
1507                                 for (i = 0; i < n; i++)
1508                                     g->scale_factors[j++] = 0;
1509                             }
1510                         } else {
1511                             /* simply copy from last granule */
1512                             for (i = 0; i < n; i++) {
1513                                 g->scale_factors[j] = sc[j];
1514                                 j++;
1515                             }
1516                         }
1517                     }
1518                     g->scale_factors[j++] = 0;
1519                 }
1520             } else {
1521                 int tindex, tindex2, slen[4], sl, sf;
1522
1523                 /* LSF scale factors */
1524                 if (g->block_type == 2)
1525                     tindex = g->switch_point ? 2 : 1;
1526                 else
1527                     tindex = 0;
1528
1529                 sf = g->scalefac_compress;
1530                 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1531                     /* intensity stereo case */
1532                     sf >>= 1;
1533                     if (sf < 180) {
1534                         lsf_sf_expand(slen, sf, 6, 6, 0);
1535                         tindex2 = 3;
1536                     } else if (sf < 244) {
1537                         lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1538                         tindex2 = 4;
1539                     } else {
1540                         lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1541                         tindex2 = 5;
1542                     }
1543                 } else {
1544                     /* normal case */
1545                     if (sf < 400) {
1546                         lsf_sf_expand(slen, sf, 5, 4, 4);
1547                         tindex2 = 0;
1548                     } else if (sf < 500) {
1549                         lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1550                         tindex2 = 1;
1551                     } else {
1552                         lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1553                         tindex2 = 2;
1554                         g->preflag = 1;
1555                     }
1556                 }
1557
1558                 j = 0;
1559                 for (k = 0; k < 4; k++) {
1560                     n  = lsf_nsf_table[tindex2][tindex][k];
1561                     sl = slen[k];
1562                     if (sl) {
1563                         for (i = 0; i < n; i++)
1564                             g->scale_factors[j++] = get_bits(&s->gb, sl);
1565                     } else {
1566                         for (i = 0; i < n; i++)
1567                             g->scale_factors[j++] = 0;
1568                     }
1569                 }
1570                 /* XXX: should compute exact size */
1571                 for (; j < 40; j++)
1572                     g->scale_factors[j] = 0;
1573             }
1574
1575             exponents_from_scale_factors(s, g, exponents);
1576
1577             /* read Huffman coded residue */
1578             huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1579         } /* ch */
1580
1581         if (s->mode == MPA_JSTEREO)
1582             compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1583
1584         for (ch = 0; ch < s->nb_channels; ch++) {
1585             g = &s->granules[ch][gr];
1586
1587             reorder_block(s, g);
1588             compute_antialias(s, g);
1589             compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1590         }
1591     } /* gr */
1592     if (get_bits_count(&s->gb) < 0)
1593         skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1594     return nb_granules * 18;
1595 }
1596
1597 static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1598                            const uint8_t *buf, int buf_size)
1599 {
1600     int i, nb_frames, ch, ret;
1601     OUT_INT *samples_ptr;
1602
1603     init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1604     if (s->error_protection)
1605         s->crc = get_bits(&s->gb, 16);
1606
1607     switch(s->layer) {
1608     case 1:
1609         s->avctx->frame_size = 384;
1610         nb_frames = mp_decode_layer1(s);
1611         break;
1612     case 2:
1613         s->avctx->frame_size = 1152;
1614         nb_frames = mp_decode_layer2(s);
1615         break;
1616     case 3:
1617         s->avctx->frame_size = s->lsf ? 576 : 1152;
1618     default:
1619         nb_frames = mp_decode_layer3(s);
1620
1621         s->last_buf_size=0;
1622         if (s->in_gb.buffer) {
1623             align_get_bits(&s->gb);
1624             i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1625             if (i >= 0 && i <= BACKSTEP_SIZE) {
1626                 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb) >> 3), i);
1627                 s->last_buf_size=i;
1628             } else
1629                 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1630             s->gb           = s->in_gb;
1631             s->in_gb.buffer = NULL;
1632             s->extrasize    = 0;
1633         }
1634
1635         align_get_bits(&s->gb);
1636         av_assert1((get_bits_count(&s->gb) & 7) == 0);
1637         i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1638         if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1639             if (i < 0)
1640                 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1641             i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1642         }
1643         av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1644         memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1645         s->last_buf_size += i;
1646     }
1647
1648     if(nb_frames < 0)
1649         return nb_frames;
1650
1651     /* get output buffer */
1652     if (!samples) {
1653         av_assert0(s->frame);
1654         s->frame->nb_samples = s->avctx->frame_size;
1655         if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0)
1656             return ret;
1657         samples = (OUT_INT **)s->frame->extended_data;
1658     }
1659
1660     /* apply the synthesis filter */
1661     for (ch = 0; ch < s->nb_channels; ch++) {
1662         int sample_stride;
1663         if (s->avctx->sample_fmt == OUT_FMT_P) {
1664             samples_ptr   = samples[ch];
1665             sample_stride = 1;
1666         } else {
1667             samples_ptr   = samples[0] + ch;
1668             sample_stride = s->nb_channels;
1669         }
1670         for (i = 0; i < nb_frames; i++) {
1671             RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1672                                         &(s->synth_buf_offset[ch]),
1673                                         RENAME(ff_mpa_synth_window),
1674                                         &s->dither_state, samples_ptr,
1675                                         sample_stride, s->sb_samples[ch][i]);
1676             samples_ptr += 32 * sample_stride;
1677         }
1678     }
1679
1680     return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1681 }
1682
1683 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1684                         AVPacket *avpkt)
1685 {
1686     const uint8_t *buf  = avpkt->data;
1687     int buf_size        = avpkt->size;
1688     MPADecodeContext *s = avctx->priv_data;
1689     uint32_t header;
1690     int ret;
1691
1692     int skipped = 0;
1693     while(buf_size && !*buf){
1694         buf++;
1695         buf_size--;
1696         skipped++;
1697     }
1698
1699     if (buf_size < HEADER_SIZE)
1700         return AVERROR_INVALIDDATA;
1701
1702     header = AV_RB32(buf);
1703     if (header >> 8 == AV_RB32("TAG") >> 8) {
1704         av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
1705         return buf_size + skipped;
1706     }
1707     ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1708     if (ret < 0) {
1709         av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1710         return AVERROR_INVALIDDATA;
1711     } else if (ret == 1) {
1712         /* free format: prepare to compute frame size */
1713         s->frame_size = -1;
1714         return AVERROR_INVALIDDATA;
1715     }
1716     /* update codec info */
1717     avctx->channels       = s->nb_channels;
1718     avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1719     if (!avctx->bit_rate)
1720         avctx->bit_rate = s->bit_rate;
1721
1722     if (s->frame_size <= 0) {
1723         av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1724         return AVERROR_INVALIDDATA;
1725     } else if (s->frame_size < buf_size) {
1726         av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1727         buf_size= s->frame_size;
1728     }
1729
1730     s->frame = data;
1731
1732     ret = mp_decode_frame(s, NULL, buf, buf_size);
1733     if (ret >= 0) {
1734         s->frame->nb_samples = avctx->frame_size;
1735         *got_frame_ptr       = 1;
1736         avctx->sample_rate   = s->sample_rate;
1737         //FIXME maybe move the other codec info stuff from above here too
1738     } else {
1739         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1740         /* Only return an error if the bad frame makes up the whole packet or
1741          * the error is related to buffer management.
1742          * If there is more data in the packet, just consume the bad frame
1743          * instead of returning an error, which would discard the whole
1744          * packet. */
1745         *got_frame_ptr = 0;
1746         if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1747             return ret;
1748     }
1749     s->frame_size = 0;
1750     return buf_size + skipped;
1751 }
1752
1753 static void mp_flush(MPADecodeContext *ctx)
1754 {
1755     memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1756     memset(ctx->mdct_buf, 0, sizeof(ctx->mdct_buf));
1757     ctx->last_buf_size = 0;
1758     ctx->dither_state = 0;
1759 }
1760
1761 static void flush(AVCodecContext *avctx)
1762 {
1763     mp_flush(avctx->priv_data);
1764 }
1765
1766 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1767 static int decode_frame_adu(AVCodecContext *avctx, void *data,
1768                             int *got_frame_ptr, AVPacket *avpkt)
1769 {
1770     const uint8_t *buf  = avpkt->data;
1771     int buf_size        = avpkt->size;
1772     MPADecodeContext *s = avctx->priv_data;
1773     uint32_t header;
1774     int len, ret;
1775     int av_unused out_size;
1776
1777     len = buf_size;
1778
1779     // Discard too short frames
1780     if (buf_size < HEADER_SIZE) {
1781         av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1782         return AVERROR_INVALIDDATA;
1783     }
1784
1785
1786     if (len > MPA_MAX_CODED_FRAME_SIZE)
1787         len = MPA_MAX_CODED_FRAME_SIZE;
1788
1789     // Get header and restore sync word
1790     header = AV_RB32(buf) | 0xffe00000;
1791
1792     ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1793     if (ret < 0) {
1794         av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1795         return ret;
1796     }
1797     /* update codec info */
1798     avctx->sample_rate = s->sample_rate;
1799     avctx->channels    = s->nb_channels;
1800     avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1801     if (!avctx->bit_rate)
1802         avctx->bit_rate = s->bit_rate;
1803
1804     s->frame_size = len;
1805
1806     s->frame = data;
1807
1808     ret = mp_decode_frame(s, NULL, buf, buf_size);
1809     if (ret < 0) {
1810         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1811         return ret;
1812     }
1813
1814     *got_frame_ptr = 1;
1815
1816     return buf_size;
1817 }
1818 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1819
1820 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1821
1822 /**
1823  * Context for MP3On4 decoder
1824  */
1825 typedef struct MP3On4DecodeContext {
1826     int frames;                     ///< number of mp3 frames per block (number of mp3 decoder instances)
1827     int syncword;                   ///< syncword patch
1828     const uint8_t *coff;            ///< channel offsets in output buffer
1829     MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1830 } MP3On4DecodeContext;
1831
1832 #include "mpeg4audio.h"
1833
1834 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1835
1836 /* number of mp3 decoder instances */
1837 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1838
1839 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1840 static const uint8_t chan_offset[8][5] = {
1841     { 0             },
1842     { 0             },  // C
1843     { 0             },  // FLR
1844     { 2, 0          },  // C FLR
1845     { 2, 0, 3       },  // C FLR BS
1846     { 2, 0, 3       },  // C FLR BLRS
1847     { 2, 0, 4, 3    },  // C FLR BLRS LFE
1848     { 2, 0, 6, 4, 3 },  // C FLR BLRS BLR LFE
1849 };
1850
1851 /* mp3on4 channel layouts */
1852 static const int16_t chan_layout[8] = {
1853     0,
1854     AV_CH_LAYOUT_MONO,
1855     AV_CH_LAYOUT_STEREO,
1856     AV_CH_LAYOUT_SURROUND,
1857     AV_CH_LAYOUT_4POINT0,
1858     AV_CH_LAYOUT_5POINT0,
1859     AV_CH_LAYOUT_5POINT1,
1860     AV_CH_LAYOUT_7POINT1
1861 };
1862
1863 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1864 {
1865     MP3On4DecodeContext *s = avctx->priv_data;
1866     int i;
1867
1868     for (i = 0; i < s->frames; i++)
1869         av_freep(&s->mp3decctx[i]);
1870
1871     return 0;
1872 }
1873
1874
1875 static av_cold int decode_init_mp3on4(AVCodecContext * avctx)
1876 {
1877     MP3On4DecodeContext *s = avctx->priv_data;
1878     MPEG4AudioConfig cfg;
1879     int i, ret;
1880
1881     if ((avctx->extradata_size < 2) || !avctx->extradata) {
1882         av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1883         return AVERROR_INVALIDDATA;
1884     }
1885
1886     avpriv_mpeg4audio_get_config2(&cfg, avctx->extradata,
1887                                   avctx->extradata_size, 1, avctx);
1888     if (!cfg.chan_config || cfg.chan_config > 7) {
1889         av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1890         return AVERROR_INVALIDDATA;
1891     }
1892     s->frames             = mp3Frames[cfg.chan_config];
1893     s->coff               = chan_offset[cfg.chan_config];
1894     avctx->channels       = ff_mpeg4audio_channels[cfg.chan_config];
1895     avctx->channel_layout = chan_layout[cfg.chan_config];
1896
1897     if (cfg.sample_rate < 16000)
1898         s->syncword = 0xffe00000;
1899     else
1900         s->syncword = 0xfff00000;
1901
1902     /* Init the first mp3 decoder in standard way, so that all tables get builded
1903      * We replace avctx->priv_data with the context of the first decoder so that
1904      * decode_init() does not have to be changed.
1905      * Other decoders will be initialized here copying data from the first context
1906      */
1907     // Allocate zeroed memory for the first decoder context
1908     s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1909     if (!s->mp3decctx[0])
1910         return AVERROR(ENOMEM);
1911     // Put decoder context in place to make init_decode() happy
1912     avctx->priv_data = s->mp3decctx[0];
1913     ret = decode_init(avctx);
1914     // Restore mp3on4 context pointer
1915     avctx->priv_data = s;
1916     if (ret < 0)
1917         return ret;
1918     s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1919
1920     /* Create a separate codec/context for each frame (first is already ok).
1921      * Each frame is 1 or 2 channels - up to 5 frames allowed
1922      */
1923     for (i = 1; i < s->frames; i++) {
1924         s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1925         if (!s->mp3decctx[i])
1926             return AVERROR(ENOMEM);
1927         s->mp3decctx[i]->adu_mode = 1;
1928         s->mp3decctx[i]->avctx = avctx;
1929         s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1930         s->mp3decctx[i]->butterflies_float = s->mp3decctx[0]->butterflies_float;
1931     }
1932
1933     return 0;
1934 }
1935
1936
1937 static void flush_mp3on4(AVCodecContext *avctx)
1938 {
1939     int i;
1940     MP3On4DecodeContext *s = avctx->priv_data;
1941
1942     for (i = 0; i < s->frames; i++)
1943         mp_flush(s->mp3decctx[i]);
1944 }
1945
1946
1947 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1948                                int *got_frame_ptr, AVPacket *avpkt)
1949 {
1950     AVFrame *frame         = data;
1951     const uint8_t *buf     = avpkt->data;
1952     int buf_size           = avpkt->size;
1953     MP3On4DecodeContext *s = avctx->priv_data;
1954     MPADecodeContext *m;
1955     int fsize, len = buf_size, out_size = 0;
1956     uint32_t header;
1957     OUT_INT **out_samples;
1958     OUT_INT *outptr[2];
1959     int fr, ch, ret;
1960
1961     /* get output buffer */
1962     frame->nb_samples = MPA_FRAME_SIZE;
1963     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1964         return ret;
1965     out_samples = (OUT_INT **)frame->extended_data;
1966
1967     // Discard too short frames
1968     if (buf_size < HEADER_SIZE)
1969         return AVERROR_INVALIDDATA;
1970
1971     avctx->bit_rate = 0;
1972
1973     ch = 0;
1974     for (fr = 0; fr < s->frames; fr++) {
1975         fsize = AV_RB16(buf) >> 4;
1976         fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1977         m     = s->mp3decctx[fr];
1978         av_assert1(m);
1979
1980         if (fsize < HEADER_SIZE) {
1981             av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1982             return AVERROR_INVALIDDATA;
1983         }
1984         header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1985
1986         ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1987         if (ret < 0) {
1988             av_log(avctx, AV_LOG_ERROR, "Bad header, discard block\n");
1989             return AVERROR_INVALIDDATA;
1990         }
1991
1992         if (ch + m->nb_channels > avctx->channels ||
1993             s->coff[fr] + m->nb_channels > avctx->channels) {
1994             av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1995                                         "channel count\n");
1996             return AVERROR_INVALIDDATA;
1997         }
1998         ch += m->nb_channels;
1999
2000         outptr[0] = out_samples[s->coff[fr]];
2001         if (m->nb_channels > 1)
2002             outptr[1] = out_samples[s->coff[fr] + 1];
2003
2004         if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0) {
2005             av_log(avctx, AV_LOG_ERROR, "failed to decode channel %d\n", ch);
2006             memset(outptr[0], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2007             if (m->nb_channels > 1)
2008                 memset(outptr[1], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2009             ret = m->nb_channels * MPA_FRAME_SIZE*sizeof(OUT_INT);
2010         }
2011
2012         out_size += ret;
2013         buf      += fsize;
2014         len      -= fsize;
2015
2016         avctx->bit_rate += m->bit_rate;
2017     }
2018     if (ch != avctx->channels) {
2019         av_log(avctx, AV_LOG_ERROR, "failed to decode all channels\n");
2020         return AVERROR_INVALIDDATA;
2021     }
2022
2023     /* update codec info */
2024     avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2025
2026     frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
2027     *got_frame_ptr    = 1;
2028
2029     return buf_size;
2030 }
2031 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */