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