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