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