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