Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 83614f2d

History | View | Annotate | Download (77.8 KB)

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 libavcodec/mpegaudiodec.c
24
 * MPEG Audio decoder.
25
 */
26

    
27
#include "avcodec.h"
28
#include "get_bits.h"
29
#include "dsputil.h"
30

    
31
/*
32
 * TODO:
33
 *  - in low precision mode, use more 16 bit multiplies in synth filter
34
 *  - test lsf / mpeg25 extensively.
35
 */
36

    
37
#include "mpegaudio.h"
38
#include "mpegaudiodecheader.h"
39

    
40
#include "mathops.h"
41

    
42
/* WARNING: only correct for posititive numbers */
43
#define FIXR(a)   ((int)((a) * FRAC_ONE + 0.5))
44
#define FRAC_RND(a) (((a) + (FRAC_ONE/2)) >> FRAC_BITS)
45

    
46
#define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
47

    
48
/****************/
49

    
50
#define HEADER_SIZE 4
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
    int32_t sb_hybrid[SBLIMIT * 18]; /* 576 samples */
70
} GranuleDef;
71

    
72
#include "mpegaudiodata.h"
73
#include "mpegaudiodectab.h"
74

    
75
static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
76
static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
77

    
78
/* vlc structure for decoding layer 3 huffman tables */
79
static VLC huff_vlc[16];
80
static VLC_TYPE huff_vlc_tables[
81
  0+128+128+128+130+128+154+166+
82
  142+204+190+170+542+460+662+414
83
  ][2];
84
static const int huff_vlc_tables_sizes[16] = {
85
  0, 128, 128, 128, 130, 128, 154, 166,
86
  142, 204, 190, 170, 542, 460, 662, 414
87
};
88
static VLC huff_quad_vlc[2];
89
static VLC_TYPE huff_quad_vlc_tables[128+16][2];
90
static const int huff_quad_vlc_tables_sizes[2] = {
91
  128, 16
92
};
93
/* computed from band_size_long */
94
static uint16_t band_index_long[9][23];
95
/* XXX: free when all decoders are closed */
96
#define TABLE_4_3_SIZE (8191 + 16)*4
97
static int8_t  table_4_3_exp[TABLE_4_3_SIZE];
98
static uint32_t table_4_3_value[TABLE_4_3_SIZE];
99
static uint32_t exp_table[512];
100
static uint32_t expval_table[512][16];
101
/* intensity stereo coef table */
102
static int32_t is_table[2][16];
103
static int32_t is_table_lsf[2][2][16];
104
static int32_t csa_table[8][4];
105
static float csa_table_float[8][4];
106
static int32_t mdct_win[8][36];
107

    
108
/* lower 2 bits: modulo 3, higher bits: shift */
109
static uint16_t scale_factor_modshift[64];
110
/* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
111
static int32_t scale_factor_mult[15][3];
112
/* mult table for layer 2 group quantization */
113

    
114
#define SCALE_GEN(v) \
115
{ FIXR(1.0 * (v)), FIXR(0.7937005259 * (v)), FIXR(0.6299605249 * (v)) }
116

    
117
static const int32_t scale_factor_mult2[3][3] = {
118
    SCALE_GEN(4.0 / 3.0), /* 3 steps */
119
    SCALE_GEN(4.0 / 5.0), /* 5 steps */
120
    SCALE_GEN(4.0 / 9.0), /* 9 steps */
121
};
122

    
123
static DECLARE_ALIGNED_16(MPA_INT, window[512]);
124

    
125
/**
126
 * Convert region offsets to region sizes and truncate
127
 * size to big_values.
128
 */
129
void ff_region_offset2size(GranuleDef *g){
130
    int i, k, j=0;
131
    g->region_size[2] = (576 / 2);
132
    for(i=0;i<3;i++) {
133
        k = FFMIN(g->region_size[i], g->big_values);
134
        g->region_size[i] = k - j;
135
        j = k;
136
    }
137
}
138

    
139
void ff_init_short_region(MPADecodeContext *s, GranuleDef *g){
140
    if (g->block_type == 2)
141
        g->region_size[0] = (36 / 2);
142
    else {
143
        if (s->sample_rate_index <= 2)
144
            g->region_size[0] = (36 / 2);
145
        else if (s->sample_rate_index != 8)
146
            g->region_size[0] = (54 / 2);
147
        else
148
            g->region_size[0] = (108 / 2);
149
    }
150
    g->region_size[1] = (576 / 2);
151
}
152

    
153
void ff_init_long_region(MPADecodeContext *s, GranuleDef *g, int ra1, int ra2){
154
    int l;
155
    g->region_size[0] =
156
        band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
157
    /* should not overflow */
158
    l = FFMIN(ra1 + ra2 + 2, 22);
159
    g->region_size[1] =
160
        band_index_long[s->sample_rate_index][l] >> 1;
161
}
162

    
163
void ff_compute_band_indexes(MPADecodeContext *s, GranuleDef *g){
164
    if (g->block_type == 2) {
165
        if (g->switch_point) {
166
            /* if switched mode, we handle the 36 first samples as
167
                long blocks.  For 8000Hz, we handle the 48 first
168
                exponents as long blocks (XXX: check this!) */
169
            if (s->sample_rate_index <= 2)
170
                g->long_end = 8;
171
            else if (s->sample_rate_index != 8)
172
                g->long_end = 6;
173
            else
174
                g->long_end = 4; /* 8000 Hz */
175

    
176
            g->short_start = 2 + (s->sample_rate_index != 8);
177
        } else {
178
            g->long_end = 0;
179
            g->short_start = 0;
180
        }
181
    } else {
182
        g->short_start = 13;
183
        g->long_end = 22;
184
    }
185
}
186

    
187
/* layer 1 unscaling */
188
/* n = number of bits of the mantissa minus 1 */
189
static inline int l1_unscale(int n, int mant, int scale_factor)
190
{
191
    int shift, mod;
192
    int64_t val;
193

    
194
    shift = scale_factor_modshift[scale_factor];
195
    mod = shift & 3;
196
    shift >>= 2;
197
    val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
198
    shift += n;
199
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
200
    return (int)((val + (1LL << (shift - 1))) >> shift);
201
}
202

    
203
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
204
{
205
    int shift, mod, val;
206

    
207
    shift = scale_factor_modshift[scale_factor];
208
    mod = shift & 3;
209
    shift >>= 2;
210

    
211
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
212
    /* NOTE: at this point, 0 <= shift <= 21 */
213
    if (shift > 0)
214
        val = (val + (1 << (shift - 1))) >> shift;
215
    return val;
216
}
217

    
218
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
219
static inline int l3_unscale(int value, int exponent)
220
{
221
    unsigned int m;
222
    int e;
223

    
224
    e = table_4_3_exp  [4*value + (exponent&3)];
225
    m = table_4_3_value[4*value + (exponent&3)];
226
    e -= (exponent >> 2);
227
    assert(e>=1);
228
    if (e > 31)
229
        return 0;
230
    m = (m + (1 << (e-1))) >> e;
231

    
232
    return m;
233
}
234

    
235
/* all integer n^(4/3) computation code */
236
#define DEV_ORDER 13
237

    
238
#define POW_FRAC_BITS 24
239
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
240
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
241
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
242

    
243
static int dev_4_3_coefs[DEV_ORDER];
244

    
245
#if 0 /* unused */
246
static int pow_mult3[3] = {
247
    POW_FIX(1.0),
248
    POW_FIX(1.25992104989487316476),
249
    POW_FIX(1.58740105196819947474),
250
};
251
#endif
252

    
253
static av_cold void int_pow_init(void)
254
{
255
    int i, a;
256

    
257
    a = POW_FIX(1.0);
258
    for(i=0;i<DEV_ORDER;i++) {
259
        a = POW_MULL(a, POW_FIX(4.0 / 3.0) - i * POW_FIX(1.0)) / (i + 1);
260
        dev_4_3_coefs[i] = a;
261
    }
262
}
263

    
264
#if 0 /* unused, remove? */
265
/* return the mantissa and the binary exponent */
266
static int int_pow(int i, int *exp_ptr)
267
{
268
    int e, er, eq, j;
269
    int a, a1;
270

271
    /* renormalize */
272
    a = i;
273
    e = POW_FRAC_BITS;
274
    while (a < (1 << (POW_FRAC_BITS - 1))) {
275
        a = a << 1;
276
        e--;
277
    }
278
    a -= (1 << POW_FRAC_BITS);
279
    a1 = 0;
280
    for(j = DEV_ORDER - 1; j >= 0; j--)
281
        a1 = POW_MULL(a, dev_4_3_coefs[j] + a1);
282
    a = (1 << POW_FRAC_BITS) + a1;
283
    /* exponent compute (exact) */
284
    e = e * 4;
285
    er = e % 3;
286
    eq = e / 3;
287
    a = POW_MULL(a, pow_mult3[er]);
288
    while (a >= 2 * POW_FRAC_ONE) {
289
        a = a >> 1;
290
        eq++;
291
    }
292
    /* convert to float */
293
    while (a < POW_FRAC_ONE) {
294
        a = a << 1;
295
        eq--;
296
    }
297
    /* now POW_FRAC_ONE <= a < 2 * POW_FRAC_ONE */
298
#if POW_FRAC_BITS > FRAC_BITS
299
    a = (a + (1 << (POW_FRAC_BITS - FRAC_BITS - 1))) >> (POW_FRAC_BITS - FRAC_BITS);
300
    /* correct overflow */
301
    if (a >= 2 * (1 << FRAC_BITS)) {
302
        a = a >> 1;
303
        eq++;
304
    }
305
#endif
306
    *exp_ptr = eq;
307
    return a;
308
}
309
#endif
310

    
311
static av_cold int decode_init(AVCodecContext * avctx)
312
{
313
    MPADecodeContext *s = avctx->priv_data;
314
    static int init=0;
315
    int i, j, k;
316

    
317
    s->avctx = avctx;
318

    
319
    avctx->sample_fmt= OUT_FMT;
320
    s->error_recognition= avctx->error_recognition;
321

    
322
    if(avctx->antialias_algo != FF_AA_FLOAT)
323
        s->compute_antialias= compute_antialias_integer;
324
    else
325
        s->compute_antialias= compute_antialias_float;
326

    
327
    if (!init && !avctx->parse_only) {
328
        int offset;
329

    
330
        /* scale factors table for layer 1/2 */
331
        for(i=0;i<64;i++) {
332
            int shift, mod;
333
            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
334
            shift = (i / 3);
335
            mod = i % 3;
336
            scale_factor_modshift[i] = mod | (shift << 2);
337
        }
338

    
339
        /* scale factor multiply for layer 1 */
340
        for(i=0;i<15;i++) {
341
            int n, norm;
342
            n = i + 2;
343
            norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
344
            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm, FRAC_BITS);
345
            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm, FRAC_BITS);
346
            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm, FRAC_BITS);
347
            dprintf(avctx, "%d: norm=%x s=%x %x %x\n",
348
                    i, norm,
349
                    scale_factor_mult[i][0],
350
                    scale_factor_mult[i][1],
351
                    scale_factor_mult[i][2]);
352
        }
353

    
354
        ff_mpa_synth_init(window);
355

    
356
        /* huffman decode tables */
357
        offset = 0;
358
        for(i=1;i<16;i++) {
359
            const HuffTable *h = &mpa_huff_tables[i];
360
            int xsize, x, y;
361
            uint8_t  tmp_bits [512];
362
            uint16_t tmp_codes[512];
363

    
364
            memset(tmp_bits , 0, sizeof(tmp_bits ));
365
            memset(tmp_codes, 0, sizeof(tmp_codes));
366

    
367
            xsize = h->xsize;
368

    
369
            j = 0;
370
            for(x=0;x<xsize;x++) {
371
                for(y=0;y<xsize;y++){
372
                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
373
                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
374
                }
375
            }
376

    
377
            /* XXX: fail test */
378
            huff_vlc[i].table = huff_vlc_tables+offset;
379
            huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
380
            init_vlc(&huff_vlc[i], 7, 512,
381
                     tmp_bits, 1, 1, tmp_codes, 2, 2,
382
                     INIT_VLC_USE_NEW_STATIC);
383
            offset += huff_vlc_tables_sizes[i];
384
        }
385
        assert(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
386

    
387
        offset = 0;
388
        for(i=0;i<2;i++) {
389
            huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
390
            huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
391
            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
392
                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
393
                     INIT_VLC_USE_NEW_STATIC);
394
            offset += huff_quad_vlc_tables_sizes[i];
395
        }
396
        assert(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
397

    
398
        for(i=0;i<9;i++) {
399
            k = 0;
400
            for(j=0;j<22;j++) {
401
                band_index_long[i][j] = k;
402
                k += band_size_long[i][j];
403
            }
404
            band_index_long[i][22] = k;
405
        }
406

    
407
        /* compute n ^ (4/3) and store it in mantissa/exp format */
408

    
409
        int_pow_init();
410
        for(i=1;i<TABLE_4_3_SIZE;i++) {
411
            double f, fm;
412
            int e, m;
413
            f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);
414
            fm = frexp(f, &e);
415
            m = (uint32_t)(fm*(1LL<<31) + 0.5);
416
            e+= FRAC_BITS - 31 + 5 - 100;
417

    
418
            /* normalized to FRAC_BITS */
419
            table_4_3_value[i] = m;
420
            table_4_3_exp[i] = -e;
421
        }
422
        for(i=0; i<512*16; i++){
423
            int exponent= (i>>4);
424
            double f= pow(i&15, 4.0 / 3.0) * pow(2, (exponent-400)*0.25 + FRAC_BITS + 5);
425
            expval_table[exponent][i&15]= llrint(f);
426
            if((i&15)==1)
427
                exp_table[exponent]= llrint(f);
428
        }
429

    
430
        for(i=0;i<7;i++) {
431
            float f;
432
            int v;
433
            if (i != 6) {
434
                f = tan((double)i * M_PI / 12.0);
435
                v = FIXR(f / (1.0 + f));
436
            } else {
437
                v = FIXR(1.0);
438
            }
439
            is_table[0][i] = v;
440
            is_table[1][6 - i] = v;
441
        }
442
        /* invalid values */
443
        for(i=7;i<16;i++)
444
            is_table[0][i] = is_table[1][i] = 0.0;
445

    
446
        for(i=0;i<16;i++) {
447
            double f;
448
            int e, k;
449

    
450
            for(j=0;j<2;j++) {
451
                e = -(j + 1) * ((i + 1) >> 1);
452
                f = pow(2.0, e / 4.0);
453
                k = i & 1;
454
                is_table_lsf[j][k ^ 1][i] = FIXR(f);
455
                is_table_lsf[j][k][i] = FIXR(1.0);
456
                dprintf(avctx, "is_table_lsf %d %d: %x %x\n",
457
                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
458
            }
459
        }
460

    
461
        for(i=0;i<8;i++) {
462
            float ci, cs, ca;
463
            ci = ci_table[i];
464
            cs = 1.0 / sqrt(1.0 + ci * ci);
465
            ca = cs * ci;
466
            csa_table[i][0] = FIXHR(cs/4);
467
            csa_table[i][1] = FIXHR(ca/4);
468
            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
469
            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
470
            csa_table_float[i][0] = cs;
471
            csa_table_float[i][1] = ca;
472
            csa_table_float[i][2] = ca + cs;
473
            csa_table_float[i][3] = ca - cs;
474
        }
475

    
476
        /* compute mdct windows */
477
        for(i=0;i<36;i++) {
478
            for(j=0; j<4; j++){
479
                double d;
480

    
481
                if(j==2 && i%3 != 1)
482
                    continue;
483

    
484
                d= sin(M_PI * (i + 0.5) / 36.0);
485
                if(j==1){
486
                    if     (i>=30) d= 0;
487
                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);
488
                    else if(i>=18) d= 1;
489
                }else if(j==3){
490
                    if     (i<  6) d= 0;
491
                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);
492
                    else if(i< 18) d= 1;
493
                }
494
                //merge last stage of imdct into the window coefficients
495
                d*= 0.5 / cos(M_PI*(2*i + 19)/72);
496

    
497
                if(j==2)
498
                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));
499
                else
500
                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));
501
            }
502
        }
503

    
504
        /* NOTE: we do frequency inversion adter the MDCT by changing
505
           the sign of the right window coefs */
506
        for(j=0;j<4;j++) {
507
            for(i=0;i<36;i+=2) {
508
                mdct_win[j + 4][i] = mdct_win[j][i];
509
                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
510
            }
511
        }
512

    
513
        init = 1;
514
    }
515

    
516
    if (avctx->codec_id == CODEC_ID_MP3ADU)
517
        s->adu_mode = 1;
518
    return 0;
519
}
520

    
521
/* tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j))) */
522

    
523
/* cos(i*pi/64) */
524

    
525
#define COS0_0  FIXHR(0.50060299823519630134/2)
526
#define COS0_1  FIXHR(0.50547095989754365998/2)
527
#define COS0_2  FIXHR(0.51544730992262454697/2)
528
#define COS0_3  FIXHR(0.53104259108978417447/2)
529
#define COS0_4  FIXHR(0.55310389603444452782/2)
530
#define COS0_5  FIXHR(0.58293496820613387367/2)
531
#define COS0_6  FIXHR(0.62250412303566481615/2)
532
#define COS0_7  FIXHR(0.67480834145500574602/2)
533
#define COS0_8  FIXHR(0.74453627100229844977/2)
534
#define COS0_9  FIXHR(0.83934964541552703873/2)
535
#define COS0_10 FIXHR(0.97256823786196069369/2)
536
#define COS0_11 FIXHR(1.16943993343288495515/4)
537
#define COS0_12 FIXHR(1.48416461631416627724/4)
538
#define COS0_13 FIXHR(2.05778100995341155085/8)
539
#define COS0_14 FIXHR(3.40760841846871878570/8)
540
#define COS0_15 FIXHR(10.19000812354805681150/32)
541

    
542
#define COS1_0 FIXHR(0.50241928618815570551/2)
543
#define COS1_1 FIXHR(0.52249861493968888062/2)
544
#define COS1_2 FIXHR(0.56694403481635770368/2)
545
#define COS1_3 FIXHR(0.64682178335999012954/2)
546
#define COS1_4 FIXHR(0.78815462345125022473/2)
547
#define COS1_5 FIXHR(1.06067768599034747134/4)
548
#define COS1_6 FIXHR(1.72244709823833392782/4)
549
#define COS1_7 FIXHR(5.10114861868916385802/16)
550

    
551
#define COS2_0 FIXHR(0.50979557910415916894/2)
552
#define COS2_1 FIXHR(0.60134488693504528054/2)
553
#define COS2_2 FIXHR(0.89997622313641570463/2)
554
#define COS2_3 FIXHR(2.56291544774150617881/8)
555

    
556
#define COS3_0 FIXHR(0.54119610014619698439/2)
557
#define COS3_1 FIXHR(1.30656296487637652785/4)
558

    
559
#define COS4_0 FIXHR(0.70710678118654752439/2)
560

    
561
/* butterfly operator */
562
#define BF(a, b, c, s)\
563
{\
564
    tmp0 = tab[a] + tab[b];\
565
    tmp1 = tab[a] - tab[b];\
566
    tab[a] = tmp0;\
567
    tab[b] = MULH(tmp1<<(s), c);\
568
}
569

    
570
#define BF1(a, b, c, d)\
571
{\
572
    BF(a, b, COS4_0, 1);\
573
    BF(c, d,-COS4_0, 1);\
574
    tab[c] += tab[d];\
575
}
576

    
577
#define BF2(a, b, c, d)\
578
{\
579
    BF(a, b, COS4_0, 1);\
580
    BF(c, d,-COS4_0, 1);\
581
    tab[c] += tab[d];\
582
    tab[a] += tab[c];\
583
    tab[c] += tab[b];\
584
    tab[b] += tab[d];\
585
}
586

    
587
#define ADD(a, b) tab[a] += tab[b]
588

    
589
/* DCT32 without 1/sqrt(2) coef zero scaling. */
590
static void dct32(int32_t *out, int32_t *tab)
591
{
592
    int tmp0, tmp1;
593

    
594
    /* pass 1 */
595
    BF( 0, 31, COS0_0 , 1);
596
    BF(15, 16, COS0_15, 5);
597
    /* pass 2 */
598
    BF( 0, 15, COS1_0 , 1);
599
    BF(16, 31,-COS1_0 , 1);
600
    /* pass 1 */
601
    BF( 7, 24, COS0_7 , 1);
602
    BF( 8, 23, COS0_8 , 1);
603
    /* pass 2 */
604
    BF( 7,  8, COS1_7 , 4);
605
    BF(23, 24,-COS1_7 , 4);
606
    /* pass 3 */
607
    BF( 0,  7, COS2_0 , 1);
608
    BF( 8, 15,-COS2_0 , 1);
609
    BF(16, 23, COS2_0 , 1);
610
    BF(24, 31,-COS2_0 , 1);
611
    /* pass 1 */
612
    BF( 3, 28, COS0_3 , 1);
613
    BF(12, 19, COS0_12, 2);
614
    /* pass 2 */
615
    BF( 3, 12, COS1_3 , 1);
616
    BF(19, 28,-COS1_3 , 1);
617
    /* pass 1 */
618
    BF( 4, 27, COS0_4 , 1);
619
    BF(11, 20, COS0_11, 2);
620
    /* pass 2 */
621
    BF( 4, 11, COS1_4 , 1);
622
    BF(20, 27,-COS1_4 , 1);
623
    /* pass 3 */
624
    BF( 3,  4, COS2_3 , 3);
625
    BF(11, 12,-COS2_3 , 3);
626
    BF(19, 20, COS2_3 , 3);
627
    BF(27, 28,-COS2_3 , 3);
628
    /* pass 4 */
629
    BF( 0,  3, COS3_0 , 1);
630
    BF( 4,  7,-COS3_0 , 1);
631
    BF( 8, 11, COS3_0 , 1);
632
    BF(12, 15,-COS3_0 , 1);
633
    BF(16, 19, COS3_0 , 1);
634
    BF(20, 23,-COS3_0 , 1);
635
    BF(24, 27, COS3_0 , 1);
636
    BF(28, 31,-COS3_0 , 1);
637

    
638

    
639

    
640
    /* pass 1 */
641
    BF( 1, 30, COS0_1 , 1);
642
    BF(14, 17, COS0_14, 3);
643
    /* pass 2 */
644
    BF( 1, 14, COS1_1 , 1);
645
    BF(17, 30,-COS1_1 , 1);
646
    /* pass 1 */
647
    BF( 6, 25, COS0_6 , 1);
648
    BF( 9, 22, COS0_9 , 1);
649
    /* pass 2 */
650
    BF( 6,  9, COS1_6 , 2);
651
    BF(22, 25,-COS1_6 , 2);
652
    /* pass 3 */
653
    BF( 1,  6, COS2_1 , 1);
654
    BF( 9, 14,-COS2_1 , 1);
655
    BF(17, 22, COS2_1 , 1);
656
    BF(25, 30,-COS2_1 , 1);
657

    
658
    /* pass 1 */
659
    BF( 2, 29, COS0_2 , 1);
660
    BF(13, 18, COS0_13, 3);
661
    /* pass 2 */
662
    BF( 2, 13, COS1_2 , 1);
663
    BF(18, 29,-COS1_2 , 1);
664
    /* pass 1 */
665
    BF( 5, 26, COS0_5 , 1);
666
    BF(10, 21, COS0_10, 1);
667
    /* pass 2 */
668
    BF( 5, 10, COS1_5 , 2);
669
    BF(21, 26,-COS1_5 , 2);
670
    /* pass 3 */
671
    BF( 2,  5, COS2_2 , 1);
672
    BF(10, 13,-COS2_2 , 1);
673
    BF(18, 21, COS2_2 , 1);
674
    BF(26, 29,-COS2_2 , 1);
675
    /* pass 4 */
676
    BF( 1,  2, COS3_1 , 2);
677
    BF( 5,  6,-COS3_1 , 2);
678
    BF( 9, 10, COS3_1 , 2);
679
    BF(13, 14,-COS3_1 , 2);
680
    BF(17, 18, COS3_1 , 2);
681
    BF(21, 22,-COS3_1 , 2);
682
    BF(25, 26, COS3_1 , 2);
683
    BF(29, 30,-COS3_1 , 2);
684

    
685
    /* pass 5 */
686
    BF1( 0,  1,  2,  3);
687
    BF2( 4,  5,  6,  7);
688
    BF1( 8,  9, 10, 11);
689
    BF2(12, 13, 14, 15);
690
    BF1(16, 17, 18, 19);
691
    BF2(20, 21, 22, 23);
692
    BF1(24, 25, 26, 27);
693
    BF2(28, 29, 30, 31);
694

    
695
    /* pass 6 */
696

    
697
    ADD( 8, 12);
698
    ADD(12, 10);
699
    ADD(10, 14);
700
    ADD(14,  9);
701
    ADD( 9, 13);
702
    ADD(13, 11);
703
    ADD(11, 15);
704

    
705
    out[ 0] = tab[0];
706
    out[16] = tab[1];
707
    out[ 8] = tab[2];
708
    out[24] = tab[3];
709
    out[ 4] = tab[4];
710
    out[20] = tab[5];
711
    out[12] = tab[6];
712
    out[28] = tab[7];
713
    out[ 2] = tab[8];
714
    out[18] = tab[9];
715
    out[10] = tab[10];
716
    out[26] = tab[11];
717
    out[ 6] = tab[12];
718
    out[22] = tab[13];
719
    out[14] = tab[14];
720
    out[30] = tab[15];
721

    
722
    ADD(24, 28);
723
    ADD(28, 26);
724
    ADD(26, 30);
725
    ADD(30, 25);
726
    ADD(25, 29);
727
    ADD(29, 27);
728
    ADD(27, 31);
729

    
730
    out[ 1] = tab[16] + tab[24];
731
    out[17] = tab[17] + tab[25];
732
    out[ 9] = tab[18] + tab[26];
733
    out[25] = tab[19] + tab[27];
734
    out[ 5] = tab[20] + tab[28];
735
    out[21] = tab[21] + tab[29];
736
    out[13] = tab[22] + tab[30];
737
    out[29] = tab[23] + tab[31];
738
    out[ 3] = tab[24] + tab[20];
739
    out[19] = tab[25] + tab[21];
740
    out[11] = tab[26] + tab[22];
741
    out[27] = tab[27] + tab[23];
742
    out[ 7] = tab[28] + tab[18];
743
    out[23] = tab[29] + tab[19];
744
    out[15] = tab[30] + tab[17];
745
    out[31] = tab[31];
746
}
747

    
748
#if FRAC_BITS <= 15
749

    
750
static inline int round_sample(int *sum)
751
{
752
    int sum1;
753
    sum1 = (*sum) >> OUT_SHIFT;
754
    *sum &= (1<<OUT_SHIFT)-1;
755
    return av_clip(sum1, OUT_MIN, OUT_MAX);
756
}
757

    
758
/* signed 16x16 -> 32 multiply add accumulate */
759
#define MACS(rt, ra, rb) MAC16(rt, ra, rb)
760

    
761
/* signed 16x16 -> 32 multiply */
762
#define MULS(ra, rb) MUL16(ra, rb)
763

    
764
#define MLSS(rt, ra, rb) MLS16(rt, ra, rb)
765

    
766
#else
767

    
768
static inline int round_sample(int64_t *sum)
769
{
770
    int sum1;
771
    sum1 = (int)((*sum) >> OUT_SHIFT);
772
    *sum &= (1<<OUT_SHIFT)-1;
773
    return av_clip(sum1, OUT_MIN, OUT_MAX);
774
}
775

    
776
#   define MULS(ra, rb) MUL64(ra, rb)
777
#   define MACS(rt, ra, rb) MAC64(rt, ra, rb)
778
#   define MLSS(rt, ra, rb) MLS64(rt, ra, rb)
779
#endif
780

    
781
#define SUM8(op, sum, w, p)               \
782
{                                         \
783
    op(sum, (w)[0 * 64], (p)[0 * 64]);    \
784
    op(sum, (w)[1 * 64], (p)[1 * 64]);    \
785
    op(sum, (w)[2 * 64], (p)[2 * 64]);    \
786
    op(sum, (w)[3 * 64], (p)[3 * 64]);    \
787
    op(sum, (w)[4 * 64], (p)[4 * 64]);    \
788
    op(sum, (w)[5 * 64], (p)[5 * 64]);    \
789
    op(sum, (w)[6 * 64], (p)[6 * 64]);    \
790
    op(sum, (w)[7 * 64], (p)[7 * 64]);    \
791
}
792

    
793
#define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
794
{                                               \
795
    int tmp;\
796
    tmp = p[0 * 64];\
797
    op1(sum1, (w1)[0 * 64], tmp);\
798
    op2(sum2, (w2)[0 * 64], tmp);\
799
    tmp = p[1 * 64];\
800
    op1(sum1, (w1)[1 * 64], tmp);\
801
    op2(sum2, (w2)[1 * 64], tmp);\
802
    tmp = p[2 * 64];\
803
    op1(sum1, (w1)[2 * 64], tmp);\
804
    op2(sum2, (w2)[2 * 64], tmp);\
805
    tmp = p[3 * 64];\
806
    op1(sum1, (w1)[3 * 64], tmp);\
807
    op2(sum2, (w2)[3 * 64], tmp);\
808
    tmp = p[4 * 64];\
809
    op1(sum1, (w1)[4 * 64], tmp);\
810
    op2(sum2, (w2)[4 * 64], tmp);\
811
    tmp = p[5 * 64];\
812
    op1(sum1, (w1)[5 * 64], tmp);\
813
    op2(sum2, (w2)[5 * 64], tmp);\
814
    tmp = p[6 * 64];\
815
    op1(sum1, (w1)[6 * 64], tmp);\
816
    op2(sum2, (w2)[6 * 64], tmp);\
817
    tmp = p[7 * 64];\
818
    op1(sum1, (w1)[7 * 64], tmp);\
819
    op2(sum2, (w2)[7 * 64], tmp);\
820
}
821

    
822
void av_cold ff_mpa_synth_init(MPA_INT *window)
823
{
824
    int i;
825

    
826
    /* max = 18760, max sum over all 16 coefs : 44736 */
827
    for(i=0;i<257;i++) {
828
        int v;
829
        v = ff_mpa_enwindow[i];
830
#if WFRAC_BITS < 16
831
        v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
832
#endif
833
        window[i] = v;
834
        if ((i & 63) != 0)
835
            v = -v;
836
        if (i != 0)
837
            window[512 - i] = v;
838
    }
839
}
840

    
841
/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
842
   32 samples. */
843
/* XXX: optimize by avoiding ring buffer usage */
844
void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
845
                         MPA_INT *window, int *dither_state,
846
                         OUT_INT *samples, int incr,
847
                         int32_t sb_samples[SBLIMIT])
848
{
849
    register MPA_INT *synth_buf;
850
    register const MPA_INT *w, *w2, *p;
851
    int j, offset;
852
    OUT_INT *samples2;
853
#if FRAC_BITS <= 15
854
    int32_t tmp[32];
855
    int sum, sum2;
856
#else
857
    int64_t sum, sum2;
858
#endif
859

    
860
    offset = *synth_buf_offset;
861
    synth_buf = synth_buf_ptr + offset;
862

    
863
#if FRAC_BITS <= 15
864
    dct32(tmp, sb_samples);
865
    for(j=0;j<32;j++) {
866
        /* NOTE: can cause a loss in precision if very high amplitude
867
           sound */
868
        synth_buf[j] = av_clip_int16(tmp[j]);
869
    }
870
#else
871
    dct32(synth_buf, sb_samples);
872
#endif
873

    
874
    /* copy to avoid wrap */
875
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
876

    
877
    samples2 = samples + 31 * incr;
878
    w = window;
879
    w2 = window + 31;
880

    
881
    sum = *dither_state;
882
    p = synth_buf + 16;
883
    SUM8(MACS, sum, w, p);
884
    p = synth_buf + 48;
885
    SUM8(MLSS, sum, w + 32, p);
886
    *samples = round_sample(&sum);
887
    samples += incr;
888
    w++;
889

    
890
    /* we calculate two samples at the same time to avoid one memory
891
       access per two sample */
892
    for(j=1;j<16;j++) {
893
        sum2 = 0;
894
        p = synth_buf + 16 + j;
895
        SUM8P2(sum, MACS, sum2, MLSS, w, w2, p);
896
        p = synth_buf + 48 - j;
897
        SUM8P2(sum, MLSS, sum2, MLSS, w + 32, w2 + 32, p);
898

    
899
        *samples = round_sample(&sum);
900
        samples += incr;
901
        sum += sum2;
902
        *samples2 = round_sample(&sum);
903
        samples2 -= incr;
904
        w++;
905
        w2--;
906
    }
907

    
908
    p = synth_buf + 32;
909
    SUM8(MLSS, sum, w + 32, p);
910
    *samples = round_sample(&sum);
911
    *dither_state= sum;
912

    
913
    offset = (offset - 32) & 511;
914
    *synth_buf_offset = offset;
915
}
916

    
917
#define C3 FIXHR(0.86602540378443864676/2)
918

    
919
/* 0.5 / cos(pi*(2*i+1)/36) */
920
static const int icos36[9] = {
921
    FIXR(0.50190991877167369479),
922
    FIXR(0.51763809020504152469), //0
923
    FIXR(0.55168895948124587824),
924
    FIXR(0.61038729438072803416),
925
    FIXR(0.70710678118654752439), //1
926
    FIXR(0.87172339781054900991),
927
    FIXR(1.18310079157624925896),
928
    FIXR(1.93185165257813657349), //2
929
    FIXR(5.73685662283492756461),
930
};
931

    
932
/* 0.5 / cos(pi*(2*i+1)/36) */
933
static const int icos36h[9] = {
934
    FIXHR(0.50190991877167369479/2),
935
    FIXHR(0.51763809020504152469/2), //0
936
    FIXHR(0.55168895948124587824/2),
937
    FIXHR(0.61038729438072803416/2),
938
    FIXHR(0.70710678118654752439/2), //1
939
    FIXHR(0.87172339781054900991/2),
940
    FIXHR(1.18310079157624925896/4),
941
    FIXHR(1.93185165257813657349/4), //2
942
//    FIXHR(5.73685662283492756461),
943
};
944

    
945
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
946
   cases. */
947
static void imdct12(int *out, int *in)
948
{
949
    int in0, in1, in2, in3, in4, in5, t1, t2;
950

    
951
    in0= in[0*3];
952
    in1= in[1*3] + in[0*3];
953
    in2= in[2*3] + in[1*3];
954
    in3= in[3*3] + in[2*3];
955
    in4= in[4*3] + in[3*3];
956
    in5= in[5*3] + in[4*3];
957
    in5 += in3;
958
    in3 += in1;
959

    
960
    in2= MULH(2*in2, C3);
961
    in3= MULH(4*in3, C3);
962

    
963
    t1 = in0 - in4;
964
    t2 = MULH(2*(in1 - in5), icos36h[4]);
965

    
966
    out[ 7]=
967
    out[10]= t1 + t2;
968
    out[ 1]=
969
    out[ 4]= t1 - t2;
970

    
971
    in0 += in4>>1;
972
    in4 = in0 + in2;
973
    in5 += 2*in1;
974
    in1 = MULH(in5 + in3, icos36h[1]);
975
    out[ 8]=
976
    out[ 9]= in4 + in1;
977
    out[ 2]=
978
    out[ 3]= in4 - in1;
979

    
980
    in0 -= in2;
981
    in5 = MULH(2*(in5 - in3), icos36h[7]);
982
    out[ 0]=
983
    out[ 5]= in0 - in5;
984
    out[ 6]=
985
    out[11]= in0 + in5;
986
}
987

    
988
/* cos(pi*i/18) */
989
#define C1 FIXHR(0.98480775301220805936/2)
990
#define C2 FIXHR(0.93969262078590838405/2)
991
#define C3 FIXHR(0.86602540378443864676/2)
992
#define C4 FIXHR(0.76604444311897803520/2)
993
#define C5 FIXHR(0.64278760968653932632/2)
994
#define C6 FIXHR(0.5/2)
995
#define C7 FIXHR(0.34202014332566873304/2)
996
#define C8 FIXHR(0.17364817766693034885/2)
997

    
998

    
999
/* using Lee like decomposition followed by hand coded 9 points DCT */
1000
static void imdct36(int *out, int *buf, int *in, int *win)
1001
{
1002
    int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
1003
    int tmp[18], *tmp1, *in1;
1004

    
1005
    for(i=17;i>=1;i--)
1006
        in[i] += in[i-1];
1007
    for(i=17;i>=3;i-=2)
1008
        in[i] += in[i-2];
1009

    
1010
    for(j=0;j<2;j++) {
1011
        tmp1 = tmp + j;
1012
        in1 = in + j;
1013
#if 0
1014
//more accurate but slower
1015
        int64_t t0, t1, t2, t3;
1016
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1017

1018
        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
1019
        t1 = in1[2*0] - in1[2*6];
1020
        tmp1[ 6] = t1 - (t2>>1);
1021
        tmp1[16] = t1 + t2;
1022

1023
        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
1024
        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
1025
        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
1026

1027
        tmp1[10] = (t3 - t0 - t2) >> 32;
1028
        tmp1[ 2] = (t3 + t0 + t1) >> 32;
1029
        tmp1[14] = (t3 + t2 - t1) >> 32;
1030

1031
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1032
        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
1033
        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
1034
        t0 = MUL64(2*in1[2*3], C3);
1035

1036
        t1 = MUL64(2*(in1[2*1] + in1[2*7]),   -C5);
1037

1038
        tmp1[ 0] = (t2 + t3 + t0) >> 32;
1039
        tmp1[12] = (t2 + t1 - t0) >> 32;
1040
        tmp1[ 8] = (t3 - t1 - t0) >> 32;
1041
#else
1042
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1043

    
1044
        t3 = in1[2*0] + (in1[2*6]>>1);
1045
        t1 = in1[2*0] - in1[2*6];
1046
        tmp1[ 6] = t1 - (t2>>1);
1047
        tmp1[16] = t1 + t2;
1048

    
1049
        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1050
        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1051
        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1052

    
1053
        tmp1[10] = t3 - t0 - t2;
1054
        tmp1[ 2] = t3 + t0 + t1;
1055
        tmp1[14] = t3 + t2 - t1;
1056

    
1057
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1058
        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1059
        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1060
        t0 = MULH(2*in1[2*3], C3);
1061

    
1062
        t1 = MULH(2*(in1[2*1] + in1[2*7]),   -C5);
1063

    
1064
        tmp1[ 0] = t2 + t3 + t0;
1065
        tmp1[12] = t2 + t1 - t0;
1066
        tmp1[ 8] = t3 - t1 - t0;
1067
#endif
1068
    }
1069

    
1070
    i = 0;
1071
    for(j=0;j<4;j++) {
1072
        t0 = tmp[i];
1073
        t1 = tmp[i + 2];
1074
        s0 = t1 + t0;
1075
        s2 = t1 - t0;
1076

    
1077
        t2 = tmp[i + 1];
1078
        t3 = tmp[i + 3];
1079
        s1 = MULH(2*(t3 + t2), icos36h[j]);
1080
        s3 = MULL(t3 - t2, icos36[8 - j], FRAC_BITS);
1081

    
1082
        t0 = s0 + s1;
1083
        t1 = s0 - s1;
1084
        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1085
        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1086
        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1087
        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1088

    
1089
        t0 = s2 + s3;
1090
        t1 = s2 - s3;
1091
        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1092
        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1093
        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1094
        buf[      + j] = MULH(t0, win[18         + j]);
1095
        i += 4;
1096
    }
1097

    
1098
    s0 = tmp[16];
1099
    s1 = MULH(2*tmp[17], icos36h[4]);
1100
    t0 = s0 + s1;
1101
    t1 = s0 - s1;
1102
    out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
1103
    out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
1104
    buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
1105
    buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
1106
}
1107

    
1108
/* return the number of decoded frames */
1109
static int mp_decode_layer1(MPADecodeContext *s)
1110
{
1111
    int bound, i, v, n, ch, j, mant;
1112
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1113
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1114

    
1115
    if (s->mode == MPA_JSTEREO)
1116
        bound = (s->mode_ext + 1) * 4;
1117
    else
1118
        bound = SBLIMIT;
1119

    
1120
    /* allocation bits */
1121
    for(i=0;i<bound;i++) {
1122
        for(ch=0;ch<s->nb_channels;ch++) {
1123
            allocation[ch][i] = get_bits(&s->gb, 4);
1124
        }
1125
    }
1126
    for(i=bound;i<SBLIMIT;i++) {
1127
        allocation[0][i] = get_bits(&s->gb, 4);
1128
    }
1129

    
1130
    /* scale factors */
1131
    for(i=0;i<bound;i++) {
1132
        for(ch=0;ch<s->nb_channels;ch++) {
1133
            if (allocation[ch][i])
1134
                scale_factors[ch][i] = get_bits(&s->gb, 6);
1135
        }
1136
    }
1137
    for(i=bound;i<SBLIMIT;i++) {
1138
        if (allocation[0][i]) {
1139
            scale_factors[0][i] = get_bits(&s->gb, 6);
1140
            scale_factors[1][i] = get_bits(&s->gb, 6);
1141
        }
1142
    }
1143

    
1144
    /* compute samples */
1145
    for(j=0;j<12;j++) {
1146
        for(i=0;i<bound;i++) {
1147
            for(ch=0;ch<s->nb_channels;ch++) {
1148
                n = allocation[ch][i];
1149
                if (n) {
1150
                    mant = get_bits(&s->gb, n + 1);
1151
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
1152
                } else {
1153
                    v = 0;
1154
                }
1155
                s->sb_samples[ch][j][i] = v;
1156
            }
1157
        }
1158
        for(i=bound;i<SBLIMIT;i++) {
1159
            n = allocation[0][i];
1160
            if (n) {
1161
                mant = get_bits(&s->gb, n + 1);
1162
                v = l1_unscale(n, mant, scale_factors[0][i]);
1163
                s->sb_samples[0][j][i] = v;
1164
                v = l1_unscale(n, mant, scale_factors[1][i]);
1165
                s->sb_samples[1][j][i] = v;
1166
            } else {
1167
                s->sb_samples[0][j][i] = 0;
1168
                s->sb_samples[1][j][i] = 0;
1169
            }
1170
        }
1171
    }
1172
    return 12;
1173
}
1174

    
1175
static int mp_decode_layer2(MPADecodeContext *s)
1176
{
1177
    int sblimit; /* number of used subbands */
1178
    const unsigned char *alloc_table;
1179
    int table, bit_alloc_bits, i, j, ch, bound, v;
1180
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1181
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1182
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1183
    int scale, qindex, bits, steps, k, l, m, b;
1184

    
1185
    /* select decoding table */
1186
    table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
1187
                            s->sample_rate, s->lsf);
1188
    sblimit = ff_mpa_sblimit_table[table];
1189
    alloc_table = ff_mpa_alloc_tables[table];
1190

    
1191
    if (s->mode == MPA_JSTEREO)
1192
        bound = (s->mode_ext + 1) * 4;
1193
    else
1194
        bound = sblimit;
1195

    
1196
    dprintf(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
1197

    
1198
    /* sanity check */
1199
    if( bound > sblimit ) bound = sblimit;
1200

    
1201
    /* parse bit allocation */
1202
    j = 0;
1203
    for(i=0;i<bound;i++) {
1204
        bit_alloc_bits = alloc_table[j];
1205
        for(ch=0;ch<s->nb_channels;ch++) {
1206
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1207
        }
1208
        j += 1 << bit_alloc_bits;
1209
    }
1210
    for(i=bound;i<sblimit;i++) {
1211
        bit_alloc_bits = alloc_table[j];
1212
        v = get_bits(&s->gb, bit_alloc_bits);
1213
        bit_alloc[0][i] = v;
1214
        bit_alloc[1][i] = v;
1215
        j += 1 << bit_alloc_bits;
1216
    }
1217

    
1218
    /* scale codes */
1219
    for(i=0;i<sblimit;i++) {
1220
        for(ch=0;ch<s->nb_channels;ch++) {
1221
            if (bit_alloc[ch][i])
1222
                scale_code[ch][i] = get_bits(&s->gb, 2);
1223
        }
1224
    }
1225

    
1226
    /* scale factors */
1227
    for(i=0;i<sblimit;i++) {
1228
        for(ch=0;ch<s->nb_channels;ch++) {
1229
            if (bit_alloc[ch][i]) {
1230
                sf = scale_factors[ch][i];
1231
                switch(scale_code[ch][i]) {
1232
                default:
1233
                case 0:
1234
                    sf[0] = get_bits(&s->gb, 6);
1235
                    sf[1] = get_bits(&s->gb, 6);
1236
                    sf[2] = get_bits(&s->gb, 6);
1237
                    break;
1238
                case 2:
1239
                    sf[0] = get_bits(&s->gb, 6);
1240
                    sf[1] = sf[0];
1241
                    sf[2] = sf[0];
1242
                    break;
1243
                case 1:
1244
                    sf[0] = get_bits(&s->gb, 6);
1245
                    sf[2] = get_bits(&s->gb, 6);
1246
                    sf[1] = sf[0];
1247
                    break;
1248
                case 3:
1249
                    sf[0] = get_bits(&s->gb, 6);
1250
                    sf[2] = get_bits(&s->gb, 6);
1251
                    sf[1] = sf[2];
1252
                    break;
1253
                }
1254
            }
1255
        }
1256
    }
1257

    
1258
    /* samples */
1259
    for(k=0;k<3;k++) {
1260
        for(l=0;l<12;l+=3) {
1261
            j = 0;
1262
            for(i=0;i<bound;i++) {
1263
                bit_alloc_bits = alloc_table[j];
1264
                for(ch=0;ch<s->nb_channels;ch++) {
1265
                    b = bit_alloc[ch][i];
1266
                    if (b) {
1267
                        scale = scale_factors[ch][i][k];
1268
                        qindex = alloc_table[j+b];
1269
                        bits = ff_mpa_quant_bits[qindex];
1270
                        if (bits < 0) {
1271
                            /* 3 values at the same time */
1272
                            v = get_bits(&s->gb, -bits);
1273
                            steps = ff_mpa_quant_steps[qindex];
1274
                            s->sb_samples[ch][k * 12 + l + 0][i] =
1275
                                l2_unscale_group(steps, v % steps, scale);
1276
                            v = v / steps;
1277
                            s->sb_samples[ch][k * 12 + l + 1][i] =
1278
                                l2_unscale_group(steps, v % steps, scale);
1279
                            v = v / steps;
1280
                            s->sb_samples[ch][k * 12 + l + 2][i] =
1281
                                l2_unscale_group(steps, v, scale);
1282
                        } else {
1283
                            for(m=0;m<3;m++) {
1284
                                v = get_bits(&s->gb, bits);
1285
                                v = l1_unscale(bits - 1, v, scale);
1286
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
1287
                            }
1288
                        }
1289
                    } else {
1290
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1291
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1292
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1293
                    }
1294
                }
1295
                /* next subband in alloc table */
1296
                j += 1 << bit_alloc_bits;
1297
            }
1298
            /* XXX: find a way to avoid this duplication of code */
1299
            for(i=bound;i<sblimit;i++) {
1300
                bit_alloc_bits = alloc_table[j];
1301
                b = bit_alloc[0][i];
1302
                if (b) {
1303
                    int mant, scale0, scale1;
1304
                    scale0 = scale_factors[0][i][k];
1305
                    scale1 = scale_factors[1][i][k];
1306
                    qindex = alloc_table[j+b];
1307
                    bits = ff_mpa_quant_bits[qindex];
1308
                    if (bits < 0) {
1309
                        /* 3 values at the same time */
1310
                        v = get_bits(&s->gb, -bits);
1311
                        steps = ff_mpa_quant_steps[qindex];
1312
                        mant = v % steps;
1313
                        v = v / steps;
1314
                        s->sb_samples[0][k * 12 + l + 0][i] =
1315
                            l2_unscale_group(steps, mant, scale0);
1316
                        s->sb_samples[1][k * 12 + l + 0][i] =
1317
                            l2_unscale_group(steps, mant, scale1);
1318
                        mant = v % steps;
1319
                        v = v / steps;
1320
                        s->sb_samples[0][k * 12 + l + 1][i] =
1321
                            l2_unscale_group(steps, mant, scale0);
1322
                        s->sb_samples[1][k * 12 + l + 1][i] =
1323
                            l2_unscale_group(steps, mant, scale1);
1324
                        s->sb_samples[0][k * 12 + l + 2][i] =
1325
                            l2_unscale_group(steps, v, scale0);
1326
                        s->sb_samples[1][k * 12 + l + 2][i] =
1327
                            l2_unscale_group(steps, v, scale1);
1328
                    } else {
1329
                        for(m=0;m<3;m++) {
1330
                            mant = get_bits(&s->gb, bits);
1331
                            s->sb_samples[0][k * 12 + l + m][i] =
1332
                                l1_unscale(bits - 1, mant, scale0);
1333
                            s->sb_samples[1][k * 12 + l + m][i] =
1334
                                l1_unscale(bits - 1, mant, scale1);
1335
                        }
1336
                    }
1337
                } else {
1338
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
1339
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
1340
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
1341
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
1342
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
1343
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
1344
                }
1345
                /* next subband in alloc table */
1346
                j += 1 << bit_alloc_bits;
1347
            }
1348
            /* fill remaining samples to zero */
1349
            for(i=sblimit;i<SBLIMIT;i++) {
1350
                for(ch=0;ch<s->nb_channels;ch++) {
1351
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1352
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1353
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1354
                }
1355
            }
1356
        }
1357
    }
1358
    return 3 * 12;
1359
}
1360

    
1361
static inline void lsf_sf_expand(int *slen,
1362
                                 int sf, int n1, int n2, int n3)
1363
{
1364
    if (n3) {
1365
        slen[3] = sf % n3;
1366
        sf /= n3;
1367
    } else {
1368
        slen[3] = 0;
1369
    }
1370
    if (n2) {
1371
        slen[2] = sf % n2;
1372
        sf /= n2;
1373
    } else {
1374
        slen[2] = 0;
1375
    }
1376
    slen[1] = sf % n1;
1377
    sf /= n1;
1378
    slen[0] = sf;
1379
}
1380

    
1381
static void exponents_from_scale_factors(MPADecodeContext *s,
1382
                                         GranuleDef *g,
1383
                                         int16_t *exponents)
1384
{
1385
    const uint8_t *bstab, *pretab;
1386
    int len, i, j, k, l, v0, shift, gain, gains[3];
1387
    int16_t *exp_ptr;
1388

    
1389
    exp_ptr = exponents;
1390
    gain = g->global_gain - 210;
1391
    shift = g->scalefac_scale + 1;
1392

    
1393
    bstab = band_size_long[s->sample_rate_index];
1394
    pretab = mpa_pretab[g->preflag];
1395
    for(i=0;i<g->long_end;i++) {
1396
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1397
        len = bstab[i];
1398
        for(j=len;j>0;j--)
1399
            *exp_ptr++ = v0;
1400
    }
1401

    
1402
    if (g->short_start < 13) {
1403
        bstab = band_size_short[s->sample_rate_index];
1404
        gains[0] = gain - (g->subblock_gain[0] << 3);
1405
        gains[1] = gain - (g->subblock_gain[1] << 3);
1406
        gains[2] = gain - (g->subblock_gain[2] << 3);
1407
        k = g->long_end;
1408
        for(i=g->short_start;i<13;i++) {
1409
            len = bstab[i];
1410
            for(l=0;l<3;l++) {
1411
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1412
                for(j=len;j>0;j--)
1413
                *exp_ptr++ = v0;
1414
            }
1415
        }
1416
    }
1417
}
1418

    
1419
/* handle n = 0 too */
1420
static inline int get_bitsz(GetBitContext *s, int n)
1421
{
1422
    if (n == 0)
1423
        return 0;
1424
    else
1425
        return get_bits(s, n);
1426
}
1427

    
1428

    
1429
static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos, int *end_pos2){
1430
    if(s->in_gb.buffer && *pos >= s->gb.size_in_bits){
1431
        s->gb= s->in_gb;
1432
        s->in_gb.buffer=NULL;
1433
        assert((get_bits_count(&s->gb) & 7) == 0);
1434
        skip_bits_long(&s->gb, *pos - *end_pos);
1435
        *end_pos2=
1436
        *end_pos= *end_pos2 + get_bits_count(&s->gb) - *pos;
1437
        *pos= get_bits_count(&s->gb);
1438
    }
1439
}
1440

    
1441
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1442
                          int16_t *exponents, int end_pos2)
1443
{
1444
    int s_index;
1445
    int i;
1446
    int last_pos, bits_left;
1447
    VLC *vlc;
1448
    int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1449

    
1450
    /* low frequencies (called big values) */
1451
    s_index = 0;
1452
    for(i=0;i<3;i++) {
1453
        int j, k, l, linbits;
1454
        j = g->region_size[i];
1455
        if (j == 0)
1456
            continue;
1457
        /* select vlc table */
1458
        k = g->table_select[i];
1459
        l = mpa_huff_data[k][0];
1460
        linbits = mpa_huff_data[k][1];
1461
        vlc = &huff_vlc[l];
1462

    
1463
        if(!l){
1464
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1465
            s_index += 2*j;
1466
            continue;
1467
        }
1468

    
1469
        /* read huffcode and compute each couple */
1470
        for(;j>0;j--) {
1471
            int exponent, x, y, v;
1472
            int pos= get_bits_count(&s->gb);
1473

    
1474
            if (pos >= end_pos){
1475
//                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1476
                switch_buffer(s, &pos, &end_pos, &end_pos2);
1477
//                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1478
                if(pos >= end_pos)
1479
                    break;
1480
            }
1481
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
1482

    
1483
            if(!y){
1484
                g->sb_hybrid[s_index  ] =
1485
                g->sb_hybrid[s_index+1] = 0;
1486
                s_index += 2;
1487
                continue;
1488
            }
1489

    
1490
            exponent= exponents[s_index];
1491

    
1492
            dprintf(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
1493
                    i, g->region_size[i] - j, x, y, exponent);
1494
            if(y&16){
1495
                x = y >> 5;
1496
                y = y & 0x0f;
1497
                if (x < 15){
1498
                    v = expval_table[ exponent ][ x ];
1499
//                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
1500
                }else{
1501
                    x += get_bitsz(&s->gb, linbits);
1502
                    v = l3_unscale(x, exponent);
1503
                }
1504
                if (get_bits1(&s->gb))
1505
                    v = -v;
1506
                g->sb_hybrid[s_index] = v;
1507
                if (y < 15){
1508
                    v = expval_table[ exponent ][ y ];
1509
                }else{
1510
                    y += get_bitsz(&s->gb, linbits);
1511
                    v = l3_unscale(y, exponent);
1512
                }
1513
                if (get_bits1(&s->gb))
1514
                    v = -v;
1515
                g->sb_hybrid[s_index+1] = v;
1516
            }else{
1517
                x = y >> 5;
1518
                y = y & 0x0f;
1519
                x += y;
1520
                if (x < 15){
1521
                    v = expval_table[ exponent ][ x ];
1522
                }else{
1523
                    x += get_bitsz(&s->gb, linbits);
1524
                    v = l3_unscale(x, exponent);
1525
                }
1526
                if (get_bits1(&s->gb))
1527
                    v = -v;
1528
                g->sb_hybrid[s_index+!!y] = v;
1529
                g->sb_hybrid[s_index+ !y] = 0;
1530
            }
1531
            s_index+=2;
1532
        }
1533
    }
1534

    
1535
    /* high frequencies */
1536
    vlc = &huff_quad_vlc[g->count1table_select];
1537
    last_pos=0;
1538
    while (s_index <= 572) {
1539
        int pos, code;
1540
        pos = get_bits_count(&s->gb);
1541
        if (pos >= end_pos) {
1542
            if (pos > end_pos2 && last_pos){
1543
                /* some encoders generate an incorrect size for this
1544
                   part. We must go back into the data */
1545
                s_index -= 4;
1546
                skip_bits_long(&s->gb, last_pos - pos);
1547
                av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1548
                if(s->error_recognition >= FF_ER_COMPLIANT)
1549
                    s_index=0;
1550
                break;
1551
            }
1552
//                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1553
            switch_buffer(s, &pos, &end_pos, &end_pos2);
1554
//                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1555
            if(pos >= end_pos)
1556
                break;
1557
        }
1558
        last_pos= pos;
1559

    
1560
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1561
        dprintf(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1562
        g->sb_hybrid[s_index+0]=
1563
        g->sb_hybrid[s_index+1]=
1564
        g->sb_hybrid[s_index+2]=
1565
        g->sb_hybrid[s_index+3]= 0;
1566
        while(code){
1567
            static const int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1568
            int v;
1569
            int pos= s_index+idxtab[code];
1570
            code ^= 8>>idxtab[code];
1571
            v = exp_table[ exponents[pos] ];
1572
//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1573
            if(get_bits1(&s->gb))
1574
                v = -v;
1575
            g->sb_hybrid[pos] = v;
1576
        }
1577
        s_index+=4;
1578
    }
1579
    /* skip extension bits */
1580
    bits_left = end_pos2 - get_bits_count(&s->gb);
1581
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1582
    if (bits_left < 0 && s->error_recognition >= FF_ER_COMPLIANT) {
1583
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1584
        s_index=0;
1585
    }else if(bits_left > 0 && s->error_recognition >= FF_ER_AGGRESSIVE){
1586
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1587
        s_index=0;
1588
    }
1589
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1590
    skip_bits_long(&s->gb, bits_left);
1591

    
1592
    i= get_bits_count(&s->gb);
1593
    switch_buffer(s, &i, &end_pos, &end_pos2);
1594

    
1595
    return 0;
1596
}
1597

    
1598
/* Reorder short blocks from bitstream order to interleaved order. It
1599
   would be faster to do it in parsing, but the code would be far more
1600
   complicated */
1601
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1602
{
1603
    int i, j, len;
1604
    int32_t *ptr, *dst, *ptr1;
1605
    int32_t tmp[576];
1606

    
1607
    if (g->block_type != 2)
1608
        return;
1609

    
1610
    if (g->switch_point) {
1611
        if (s->sample_rate_index != 8) {
1612
            ptr = g->sb_hybrid + 36;
1613
        } else {
1614
            ptr = g->sb_hybrid + 48;
1615
        }
1616
    } else {
1617
        ptr = g->sb_hybrid;
1618
    }
1619

    
1620
    for(i=g->short_start;i<13;i++) {
1621
        len = band_size_short[s->sample_rate_index][i];
1622
        ptr1 = ptr;
1623
        dst = tmp;
1624
        for(j=len;j>0;j--) {
1625
            *dst++ = ptr[0*len];
1626
            *dst++ = ptr[1*len];
1627
            *dst++ = ptr[2*len];
1628
            ptr++;
1629
        }
1630
        ptr+=2*len;
1631
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1632
    }
1633
}
1634

    
1635
#define ISQRT2 FIXR(0.70710678118654752440)
1636

    
1637
static void compute_stereo(MPADecodeContext *s,
1638
                           GranuleDef *g0, GranuleDef *g1)
1639
{
1640
    int i, j, k, l;
1641
    int32_t v1, v2;
1642
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1643
    int32_t (*is_tab)[16];
1644
    int32_t *tab0, *tab1;
1645
    int non_zero_found_short[3];
1646

    
1647
    /* intensity stereo */
1648
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1649
        if (!s->lsf) {
1650
            is_tab = is_table;
1651
            sf_max = 7;
1652
        } else {
1653
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1654
            sf_max = 16;
1655
        }
1656

    
1657
        tab0 = g0->sb_hybrid + 576;
1658
        tab1 = g1->sb_hybrid + 576;
1659

    
1660
        non_zero_found_short[0] = 0;
1661
        non_zero_found_short[1] = 0;
1662
        non_zero_found_short[2] = 0;
1663
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1664
        for(i = 12;i >= g1->short_start;i--) {
1665
            /* for last band, use previous scale factor */
1666
            if (i != 11)
1667
                k -= 3;
1668
            len = band_size_short[s->sample_rate_index][i];
1669
            for(l=2;l>=0;l--) {
1670
                tab0 -= len;
1671
                tab1 -= len;
1672
                if (!non_zero_found_short[l]) {
1673
                    /* test if non zero band. if so, stop doing i-stereo */
1674
                    for(j=0;j<len;j++) {
1675
                        if (tab1[j] != 0) {
1676
                            non_zero_found_short[l] = 1;
1677
                            goto found1;
1678
                        }
1679
                    }
1680
                    sf = g1->scale_factors[k + l];
1681
                    if (sf >= sf_max)
1682
                        goto found1;
1683

    
1684
                    v1 = is_tab[0][sf];
1685
                    v2 = is_tab[1][sf];
1686
                    for(j=0;j<len;j++) {
1687
                        tmp0 = tab0[j];
1688
                        tab0[j] = MULL(tmp0, v1, FRAC_BITS);
1689
                        tab1[j] = MULL(tmp0, v2, FRAC_BITS);
1690
                    }
1691
                } else {
1692
                found1:
1693
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1694
                        /* lower part of the spectrum : do ms stereo
1695
                           if enabled */
1696
                        for(j=0;j<len;j++) {
1697
                            tmp0 = tab0[j];
1698
                            tmp1 = tab1[j];
1699
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1700
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1701
                        }
1702
                    }
1703
                }
1704
            }
1705
        }
1706

    
1707
        non_zero_found = non_zero_found_short[0] |
1708
            non_zero_found_short[1] |
1709
            non_zero_found_short[2];
1710

    
1711
        for(i = g1->long_end - 1;i >= 0;i--) {
1712
            len = band_size_long[s->sample_rate_index][i];
1713
            tab0 -= len;
1714
            tab1 -= len;
1715
            /* test if non zero band. if so, stop doing i-stereo */
1716
            if (!non_zero_found) {
1717
                for(j=0;j<len;j++) {
1718
                    if (tab1[j] != 0) {
1719
                        non_zero_found = 1;
1720
                        goto found2;
1721
                    }
1722
                }
1723
                /* for last band, use previous scale factor */
1724
                k = (i == 21) ? 20 : i;
1725
                sf = g1->scale_factors[k];
1726
                if (sf >= sf_max)
1727
                    goto found2;
1728
                v1 = is_tab[0][sf];
1729
                v2 = is_tab[1][sf];
1730
                for(j=0;j<len;j++) {
1731
                    tmp0 = tab0[j];
1732
                    tab0[j] = MULL(tmp0, v1, FRAC_BITS);
1733
                    tab1[j] = MULL(tmp0, v2, FRAC_BITS);
1734
                }
1735
            } else {
1736
            found2:
1737
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1738
                    /* lower part of the spectrum : do ms stereo
1739
                       if enabled */
1740
                    for(j=0;j<len;j++) {
1741
                        tmp0 = tab0[j];
1742
                        tmp1 = tab1[j];
1743
                        tab0[j] = MULL(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1744
                        tab1[j] = MULL(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1745
                    }
1746
                }
1747
            }
1748
        }
1749
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1750
        /* ms stereo ONLY */
1751
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1752
           global gain */
1753
        tab0 = g0->sb_hybrid;
1754
        tab1 = g1->sb_hybrid;
1755
        for(i=0;i<576;i++) {
1756
            tmp0 = tab0[i];
1757
            tmp1 = tab1[i];
1758
            tab0[i] = tmp0 + tmp1;
1759
            tab1[i] = tmp0 - tmp1;
1760
        }
1761
    }
1762
}
1763

    
1764
static void compute_antialias_integer(MPADecodeContext *s,
1765
                              GranuleDef *g)
1766
{
1767
    int32_t *ptr, *csa;
1768
    int n, i;
1769

    
1770
    /* we antialias only "long" bands */
1771
    if (g->block_type == 2) {
1772
        if (!g->switch_point)
1773
            return;
1774
        /* XXX: check this for 8000Hz case */
1775
        n = 1;
1776
    } else {
1777
        n = SBLIMIT - 1;
1778
    }
1779

    
1780
    ptr = g->sb_hybrid + 18;
1781
    for(i = n;i > 0;i--) {
1782
        int tmp0, tmp1, tmp2;
1783
        csa = &csa_table[0][0];
1784
#define INT_AA(j) \
1785
            tmp0 = ptr[-1-j];\
1786
            tmp1 = ptr[   j];\
1787
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1788
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1789
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1790

    
1791
        INT_AA(0)
1792
        INT_AA(1)
1793
        INT_AA(2)
1794
        INT_AA(3)
1795
        INT_AA(4)
1796
        INT_AA(5)
1797
        INT_AA(6)
1798
        INT_AA(7)
1799

    
1800
        ptr += 18;
1801
    }
1802
}
1803

    
1804
static void compute_antialias_float(MPADecodeContext *s,
1805
                              GranuleDef *g)
1806
{
1807
    int32_t *ptr;
1808
    int n, i;
1809

    
1810
    /* we antialias only "long" bands */
1811
    if (g->block_type == 2) {
1812
        if (!g->switch_point)
1813
            return;
1814
        /* XXX: check this for 8000Hz case */
1815
        n = 1;
1816
    } else {
1817
        n = SBLIMIT - 1;
1818
    }
1819

    
1820
    ptr = g->sb_hybrid + 18;
1821
    for(i = n;i > 0;i--) {
1822
        float tmp0, tmp1;
1823
        float *csa = &csa_table_float[0][0];
1824
#define FLOAT_AA(j)\
1825
        tmp0= ptr[-1-j];\
1826
        tmp1= ptr[   j];\
1827
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1828
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1829

    
1830
        FLOAT_AA(0)
1831
        FLOAT_AA(1)
1832
        FLOAT_AA(2)
1833
        FLOAT_AA(3)
1834
        FLOAT_AA(4)
1835
        FLOAT_AA(5)
1836
        FLOAT_AA(6)
1837
        FLOAT_AA(7)
1838

    
1839
        ptr += 18;
1840
    }
1841
}
1842

    
1843
static void compute_imdct(MPADecodeContext *s,
1844
                          GranuleDef *g,
1845
                          int32_t *sb_samples,
1846
                          int32_t *mdct_buf)
1847
{
1848
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
1849
    int32_t out2[12];
1850
    int i, j, mdct_long_end, v, sblimit;
1851

    
1852
    /* find last non zero block */
1853
    ptr = g->sb_hybrid + 576;
1854
    ptr1 = g->sb_hybrid + 2 * 18;
1855
    while (ptr >= ptr1) {
1856
        ptr -= 6;
1857
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
1858
        if (v != 0)
1859
            break;
1860
    }
1861
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1862

    
1863
    if (g->block_type == 2) {
1864
        /* XXX: check for 8000 Hz */
1865
        if (g->switch_point)
1866
            mdct_long_end = 2;
1867
        else
1868
            mdct_long_end = 0;
1869
    } else {
1870
        mdct_long_end = sblimit;
1871
    }
1872

    
1873
    buf = mdct_buf;
1874
    ptr = g->sb_hybrid;
1875
    for(j=0;j<mdct_long_end;j++) {
1876
        /* apply window & overlap with previous buffer */
1877
        out_ptr = sb_samples + j;
1878
        /* select window */
1879
        if (g->switch_point && j < 2)
1880
            win1 = mdct_win[0];
1881
        else
1882
            win1 = mdct_win[g->block_type];
1883
        /* select frequency inversion */
1884
        win = win1 + ((4 * 36) & -(j & 1));
1885
        imdct36(out_ptr, buf, ptr, win);
1886
        out_ptr += 18*SBLIMIT;
1887
        ptr += 18;
1888
        buf += 18;
1889
    }
1890
    for(j=mdct_long_end;j<sblimit;j++) {
1891
        /* select frequency inversion */
1892
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
1893
        out_ptr = sb_samples + j;
1894

    
1895
        for(i=0; i<6; i++){
1896
            *out_ptr = buf[i];
1897
            out_ptr += SBLIMIT;
1898
        }
1899
        imdct12(out2, ptr + 0);
1900
        for(i=0;i<6;i++) {
1901
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
1902
            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
1903
            out_ptr += SBLIMIT;
1904
        }
1905
        imdct12(out2, ptr + 1);
1906
        for(i=0;i<6;i++) {
1907
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
1908
            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
1909
            out_ptr += SBLIMIT;
1910
        }
1911
        imdct12(out2, ptr + 2);
1912
        for(i=0;i<6;i++) {
1913
            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
1914
            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
1915
            buf[i + 6*2] = 0;
1916
        }
1917
        ptr += 18;
1918
        buf += 18;
1919
    }
1920
    /* zero bands */
1921
    for(j=sblimit;j<SBLIMIT;j++) {
1922
        /* overlap */
1923
        out_ptr = sb_samples + j;
1924
        for(i=0;i<18;i++) {
1925
            *out_ptr = buf[i];
1926
            buf[i] = 0;
1927
            out_ptr += SBLIMIT;
1928
        }
1929
        buf += 18;
1930
    }
1931
}
1932

    
1933
/* main layer3 decoding function */
1934
static int mp_decode_layer3(MPADecodeContext *s)
1935
{
1936
    int nb_granules, main_data_begin, private_bits;
1937
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1938
    GranuleDef granules[2][2], *g;
1939
    int16_t exponents[576];
1940

    
1941
    /* read side info */
1942
    if (s->lsf) {
1943
        main_data_begin = get_bits(&s->gb, 8);
1944
        private_bits = get_bits(&s->gb, s->nb_channels);
1945
        nb_granules = 1;
1946
    } else {
1947
        main_data_begin = get_bits(&s->gb, 9);
1948
        if (s->nb_channels == 2)
1949
            private_bits = get_bits(&s->gb, 3);
1950
        else
1951
            private_bits = get_bits(&s->gb, 5);
1952
        nb_granules = 2;
1953
        for(ch=0;ch<s->nb_channels;ch++) {
1954
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
1955
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
1956
        }
1957
    }
1958

    
1959
    for(gr=0;gr<nb_granules;gr++) {
1960
        for(ch=0;ch<s->nb_channels;ch++) {
1961
            dprintf(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1962
            g = &granules[ch][gr];
1963
            g->part2_3_length = get_bits(&s->gb, 12);
1964
            g->big_values = get_bits(&s->gb, 9);
1965
            if(g->big_values > 288){
1966
                av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1967
                return -1;
1968
            }
1969

    
1970
            g->global_gain = get_bits(&s->gb, 8);
1971
            /* if MS stereo only is selected, we precompute the
1972
               1/sqrt(2) renormalization factor */
1973
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1974
                MODE_EXT_MS_STEREO)
1975
                g->global_gain -= 2;
1976
            if (s->lsf)
1977
                g->scalefac_compress = get_bits(&s->gb, 9);
1978
            else
1979
                g->scalefac_compress = get_bits(&s->gb, 4);
1980
            blocksplit_flag = get_bits1(&s->gb);
1981
            if (blocksplit_flag) {
1982
                g->block_type = get_bits(&s->gb, 2);
1983
                if (g->block_type == 0){
1984
                    av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1985
                    return -1;
1986
                }
1987
                g->switch_point = get_bits1(&s->gb);
1988
                for(i=0;i<2;i++)
1989
                    g->table_select[i] = get_bits(&s->gb, 5);
1990
                for(i=0;i<3;i++)
1991
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
1992
                ff_init_short_region(s, g);
1993
            } else {
1994
                int region_address1, region_address2;
1995
                g->block_type = 0;
1996
                g->switch_point = 0;
1997
                for(i=0;i<3;i++)
1998
                    g->table_select[i] = get_bits(&s->gb, 5);
1999
                /* compute huffman coded region sizes */
2000
                region_address1 = get_bits(&s->gb, 4);
2001
                region_address2 = get_bits(&s->gb, 3);
2002
                dprintf(s->avctx, "region1=%d region2=%d\n",
2003
                        region_address1, region_address2);
2004
                ff_init_long_region(s, g, region_address1, region_address2);
2005
            }
2006
            ff_region_offset2size(g);
2007
            ff_compute_band_indexes(s, g);
2008

    
2009
            g->preflag = 0;
2010
            if (!s->lsf)
2011
                g->preflag = get_bits1(&s->gb);
2012
            g->scalefac_scale = get_bits1(&s->gb);
2013
            g->count1table_select = get_bits1(&s->gb);
2014
            dprintf(s->avctx, "block_type=%d switch_point=%d\n",
2015
                    g->block_type, g->switch_point);
2016
        }
2017
    }
2018

    
2019
  if (!s->adu_mode) {
2020
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2021
    assert((get_bits_count(&s->gb) & 7) == 0);
2022
    /* now we get bits from the main_data_begin offset */
2023
    dprintf(s->avctx, "seekback: %d\n", main_data_begin);
2024
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2025

    
2026
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2027
    s->in_gb= s->gb;
2028
        init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
2029
        skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
2030
  }
2031

    
2032
    for(gr=0;gr<nb_granules;gr++) {
2033
        for(ch=0;ch<s->nb_channels;ch++) {
2034
            g = &granules[ch][gr];
2035
            if(get_bits_count(&s->gb)<0){
2036
                av_log(s->avctx, AV_LOG_DEBUG, "mdb:%d, lastbuf:%d skipping granule %d\n",
2037
                                            main_data_begin, s->last_buf_size, gr);
2038
                skip_bits_long(&s->gb, g->part2_3_length);
2039
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
2040
                if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer){
2041
                    skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
2042
                    s->gb= s->in_gb;
2043
                    s->in_gb.buffer=NULL;
2044
                }
2045
                continue;
2046
            }
2047

    
2048
            bits_pos = get_bits_count(&s->gb);
2049

    
2050
            if (!s->lsf) {
2051
                uint8_t *sc;
2052
                int slen, slen1, slen2;
2053

    
2054
                /* MPEG1 scale factors */
2055
                slen1 = slen_table[0][g->scalefac_compress];
2056
                slen2 = slen_table[1][g->scalefac_compress];
2057
                dprintf(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
2058
                if (g->block_type == 2) {
2059
                    n = g->switch_point ? 17 : 18;
2060
                    j = 0;
2061
                    if(slen1){
2062
                        for(i=0;i<n;i++)
2063
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
2064
                    }else{
2065
                        for(i=0;i<n;i++)
2066
                            g->scale_factors[j++] = 0;
2067
                    }
2068
                    if(slen2){
2069
                        for(i=0;i<18;i++)
2070
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
2071
                        for(i=0;i<3;i++)
2072
                            g->scale_factors[j++] = 0;
2073
                    }else{
2074
                        for(i=0;i<21;i++)
2075
                            g->scale_factors[j++] = 0;
2076
                    }
2077
                } else {
2078
                    sc = granules[ch][0].scale_factors;
2079
                    j = 0;
2080
                    for(k=0;k<4;k++) {
2081
                        n = (k == 0 ? 6 : 5);
2082
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2083
                            slen = (k < 2) ? slen1 : slen2;
2084
                            if(slen){
2085
                                for(i=0;i<n;i++)
2086
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
2087
                            }else{
2088
                                for(i=0;i<n;i++)
2089
                                    g->scale_factors[j++] = 0;
2090
                            }
2091
                        } else {
2092
                            /* simply copy from last granule */
2093
                            for(i=0;i<n;i++) {
2094
                                g->scale_factors[j] = sc[j];
2095
                                j++;
2096
                            }
2097
                        }
2098
                    }
2099
                    g->scale_factors[j++] = 0;
2100
                }
2101
            } else {
2102
                int tindex, tindex2, slen[4], sl, sf;
2103

    
2104
                /* LSF scale factors */
2105
                if (g->block_type == 2) {
2106
                    tindex = g->switch_point ? 2 : 1;
2107
                } else {
2108
                    tindex = 0;
2109
                }
2110
                sf = g->scalefac_compress;
2111
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2112
                    /* intensity stereo case */
2113
                    sf >>= 1;
2114
                    if (sf < 180) {
2115
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2116
                        tindex2 = 3;
2117
                    } else if (sf < 244) {
2118
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2119
                        tindex2 = 4;
2120
                    } else {
2121
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2122
                        tindex2 = 5;
2123
                    }
2124
                } else {
2125
                    /* normal case */
2126
                    if (sf < 400) {
2127
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2128
                        tindex2 = 0;
2129
                    } else if (sf < 500) {
2130
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2131
                        tindex2 = 1;
2132
                    } else {
2133
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2134
                        tindex2 = 2;
2135
                        g->preflag = 1;
2136
                    }
2137
                }
2138

    
2139
                j = 0;
2140
                for(k=0;k<4;k++) {
2141
                    n = lsf_nsf_table[tindex2][tindex][k];
2142
                    sl = slen[k];
2143
                    if(sl){
2144
                        for(i=0;i<n;i++)
2145
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
2146
                    }else{
2147
                        for(i=0;i<n;i++)
2148
                            g->scale_factors[j++] = 0;
2149
                    }
2150
                }
2151
                /* XXX: should compute exact size */
2152
                for(;j<40;j++)
2153
                    g->scale_factors[j] = 0;
2154
            }
2155

    
2156
            exponents_from_scale_factors(s, g, exponents);
2157

    
2158
            /* read Huffman coded residue */
2159
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
2160
        } /* ch */
2161

    
2162
        if (s->nb_channels == 2)
2163
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2164

    
2165
        for(ch=0;ch<s->nb_channels;ch++) {
2166
            g = &granules[ch][gr];
2167

    
2168
            reorder_block(s, g);
2169
            s->compute_antialias(s, g);
2170
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2171
        }
2172
    } /* gr */
2173
    if(get_bits_count(&s->gb)<0)
2174
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
2175
    return nb_granules * 18;
2176
}
2177

    
2178
static int mp_decode_frame(MPADecodeContext *s,
2179
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
2180
{
2181
    int i, nb_frames, ch;
2182
    OUT_INT *samples_ptr;
2183

    
2184
    init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE)*8);
2185

    
2186
    /* skip error protection field */
2187
    if (s->error_protection)
2188
        skip_bits(&s->gb, 16);
2189

    
2190
    dprintf(s->avctx, "frame %d:\n", s->frame_count);
2191
    switch(s->layer) {
2192
    case 1:
2193
        s->avctx->frame_size = 384;
2194
        nb_frames = mp_decode_layer1(s);
2195
        break;
2196
    case 2:
2197
        s->avctx->frame_size = 1152;
2198
        nb_frames = mp_decode_layer2(s);
2199
        break;
2200
    case 3:
2201
        s->avctx->frame_size = s->lsf ? 576 : 1152;
2202
    default:
2203
        nb_frames = mp_decode_layer3(s);
2204

    
2205
        s->last_buf_size=0;
2206
        if(s->in_gb.buffer){
2207
            align_get_bits(&s->gb);
2208
            i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2209
            if(i >= 0 && i <= BACKSTEP_SIZE){
2210
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
2211
                s->last_buf_size=i;
2212
            }else
2213
                av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
2214
            s->gb= s->in_gb;
2215
            s->in_gb.buffer= NULL;
2216
        }
2217

    
2218
        align_get_bits(&s->gb);
2219
        assert((get_bits_count(&s->gb) & 7) == 0);
2220
        i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2221

    
2222
        if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
2223
            if(i<0)
2224
                av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
2225
            i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
2226
        }
2227
        assert(i <= buf_size - HEADER_SIZE && i>= 0);
2228
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
2229
        s->last_buf_size += i;
2230

    
2231
        break;
2232
    }
2233

    
2234
    /* apply the synthesis filter */
2235
    for(ch=0;ch<s->nb_channels;ch++) {
2236
        samples_ptr = samples + ch;
2237
        for(i=0;i<nb_frames;i++) {
2238
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2239
                         window, &s->dither_state,
2240
                         samples_ptr, s->nb_channels,
2241
                         s->sb_samples[ch][i]);
2242
            samples_ptr += 32 * s->nb_channels;
2243
        }
2244
    }
2245

    
2246
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2247
}
2248

    
2249
static int decode_frame(AVCodecContext * avctx,
2250
                        void *data, int *data_size,
2251
                        AVPacket *avpkt)
2252
{
2253
    const uint8_t *buf = avpkt->data;
2254
    int buf_size = avpkt->size;
2255
    MPADecodeContext *s = avctx->priv_data;
2256
    uint32_t header;
2257
    int out_size;
2258
    OUT_INT *out_samples = data;
2259

    
2260
    if(buf_size < HEADER_SIZE)
2261
        return -1;
2262

    
2263
    header = AV_RB32(buf);
2264
    if(ff_mpa_check_header(header) < 0){
2265
        av_log(avctx, AV_LOG_ERROR, "Header missing\n");
2266
        return -1;
2267
    }
2268

    
2269
    if (ff_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
2270
        /* free format: prepare to compute frame size */
2271
        s->frame_size = -1;
2272
        return -1;
2273
    }
2274
    /* update codec info */
2275
    avctx->channels = s->nb_channels;
2276
    avctx->bit_rate = s->bit_rate;
2277
    avctx->sub_id = s->layer;
2278

    
2279
    if(s->frame_size<=0 || s->frame_size > buf_size){
2280
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2281
        return -1;
2282
    }else if(s->frame_size < buf_size){
2283
        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
2284
        buf_size= s->frame_size;
2285
    }
2286

    
2287
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2288
    if(out_size>=0){
2289
        *data_size = out_size;
2290
        avctx->sample_rate = s->sample_rate;
2291
        //FIXME maybe move the other codec info stuff from above here too
2292
    }else
2293
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed
2294
    s->frame_size = 0;
2295
    return buf_size;
2296
}
2297

    
2298
static void flush(AVCodecContext *avctx){
2299
    MPADecodeContext *s = avctx->priv_data;
2300
    memset(s->synth_buf, 0, sizeof(s->synth_buf));
2301
    s->last_buf_size= 0;
2302
}
2303

    
2304
#if CONFIG_MP3ADU_DECODER
2305
static int decode_frame_adu(AVCodecContext * avctx,
2306
                        void *data, int *data_size,
2307
                        AVPacket *avpkt)
2308
{
2309
    const uint8_t *buf = avpkt->data;
2310
    int buf_size = avpkt->size;
2311
    MPADecodeContext *s = avctx->priv_data;
2312
    uint32_t header;
2313
    int len, out_size;
2314
    OUT_INT *out_samples = data;
2315

    
2316
    len = buf_size;
2317

    
2318
    // Discard too short frames
2319
    if (buf_size < HEADER_SIZE) {
2320
        *data_size = 0;
2321
        return buf_size;
2322
    }
2323

    
2324

    
2325
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2326
        len = MPA_MAX_CODED_FRAME_SIZE;
2327

    
2328
    // Get header and restore sync word
2329
    header = AV_RB32(buf) | 0xffe00000;
2330

    
2331
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2332
        *data_size = 0;
2333
        return buf_size;
2334
    }
2335

    
2336
    ff_mpegaudio_decode_header((MPADecodeHeader *)s, header);
2337
    /* update codec info */
2338
    avctx->sample_rate = s->sample_rate;
2339
    avctx->channels = s->nb_channels;
2340
    avctx->bit_rate = s->bit_rate;
2341
    avctx->sub_id = s->layer;
2342

    
2343
    s->frame_size = len;
2344

    
2345
    if (avctx->parse_only) {
2346
        out_size = buf_size;
2347
    } else {
2348
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2349
    }
2350

    
2351
    *data_size = out_size;
2352
    return buf_size;
2353
}
2354
#endif /* CONFIG_MP3ADU_DECODER */
2355

    
2356
#if CONFIG_MP3ON4_DECODER
2357

    
2358
/**
2359
 * Context for MP3On4 decoder
2360
 */
2361
typedef struct MP3On4DecodeContext {
2362
    int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
2363
    int syncword; ///< syncword patch
2364
    const uint8_t *coff; ///< channels offsets in output buffer
2365
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
2366
} MP3On4DecodeContext;
2367

    
2368
#include "mpeg4audio.h"
2369

    
2370
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2371
static const uint8_t mp3Frames[8] = {0,1,1,2,3,3,4,5};   /* number of mp3 decoder instances */
2372
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2373
static const uint8_t chan_offset[8][5] = {
2374
    {0},
2375
    {0},            // C
2376
    {0},            // FLR
2377
    {2,0},          // C FLR
2378
    {2,0,3},        // C FLR BS
2379
    {4,0,2},        // C FLR BLRS
2380
    {4,0,2,5},      // C FLR BLRS LFE
2381
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2382
};
2383

    
2384

    
2385
static int decode_init_mp3on4(AVCodecContext * avctx)
2386
{
2387
    MP3On4DecodeContext *s = avctx->priv_data;
2388
    MPEG4AudioConfig cfg;
2389
    int i;
2390

    
2391
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2392
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2393
        return -1;
2394
    }
2395

    
2396
    ff_mpeg4audio_get_config(&cfg, avctx->extradata, avctx->extradata_size);
2397
    if (!cfg.chan_config || cfg.chan_config > 7) {
2398
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2399
        return -1;
2400
    }
2401
    s->frames = mp3Frames[cfg.chan_config];
2402
    s->coff = chan_offset[cfg.chan_config];
2403
    avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
2404

    
2405
    if (cfg.sample_rate < 16000)
2406
        s->syncword = 0xffe00000;
2407
    else
2408
        s->syncword = 0xfff00000;
2409

    
2410
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2411
     * We replace avctx->priv_data with the context of the first decoder so that
2412
     * decode_init() does not have to be changed.
2413
     * Other decoders will be initialized here copying data from the first context
2414
     */
2415
    // Allocate zeroed memory for the first decoder context
2416
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2417
    // Put decoder context in place to make init_decode() happy
2418
    avctx->priv_data = s->mp3decctx[0];
2419
    decode_init(avctx);
2420
    // Restore mp3on4 context pointer
2421
    avctx->priv_data = s;
2422
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2423

    
2424
    /* Create a separate codec/context for each frame (first is already ok).
2425
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2426
     */
2427
    for (i = 1; i < s->frames; i++) {
2428
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2429
        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2430
        s->mp3decctx[i]->adu_mode = 1;
2431
        s->mp3decctx[i]->avctx = avctx;
2432
    }
2433

    
2434
    return 0;
2435
}
2436

    
2437

    
2438
static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
2439
{
2440
    MP3On4DecodeContext *s = avctx->priv_data;
2441
    int i;
2442

    
2443
    for (i = 0; i < s->frames; i++)
2444
        if (s->mp3decctx[i])
2445
            av_free(s->mp3decctx[i]);
2446

    
2447
    return 0;
2448
}
2449

    
2450

    
2451
static int decode_frame_mp3on4(AVCodecContext * avctx,
2452
                        void *data, int *data_size,
2453
                        AVPacket *avpkt)
2454
{
2455
    const uint8_t *buf = avpkt->data;
2456
    int buf_size = avpkt->size;
2457
    MP3On4DecodeContext *s = avctx->priv_data;
2458
    MPADecodeContext *m;
2459
    int fsize, len = buf_size, out_size = 0;
2460
    uint32_t header;
2461
    OUT_INT *out_samples = data;
2462
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2463
    OUT_INT *outptr, *bp;
2464
    int fr, j, n;
2465

    
2466
    *data_size = 0;
2467
    // Discard too short frames
2468
    if (buf_size < HEADER_SIZE)
2469
        return -1;
2470

    
2471
    // If only one decoder interleave is not needed
2472
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2473

    
2474
    avctx->bit_rate = 0;
2475

    
2476
    for (fr = 0; fr < s->frames; fr++) {
2477
        fsize = AV_RB16(buf) >> 4;
2478
        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
2479
        m = s->mp3decctx[fr];
2480
        assert (m != NULL);
2481

    
2482
        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
2483

    
2484
        if (ff_mpa_check_header(header) < 0) // Bad header, discard block
2485
            break;
2486

    
2487
        ff_mpegaudio_decode_header((MPADecodeHeader *)m, header);
2488
        out_size += mp_decode_frame(m, outptr, buf, fsize);
2489
        buf += fsize;
2490
        len -= fsize;
2491

    
2492
        if(s->frames > 1) {
2493
            n = m->avctx->frame_size*m->nb_channels;
2494
            /* interleave output data */
2495
            bp = out_samples + s->coff[fr];
2496
            if(m->nb_channels == 1) {
2497
                for(j = 0; j < n; j++) {
2498
                    *bp = decoded_buf[j];
2499
                    bp += avctx->channels;
2500
                }
2501
            } else {
2502
                for(j = 0; j < n; j++) {
2503
                    bp[0] = decoded_buf[j++];
2504
                    bp[1] = decoded_buf[j];
2505
                    bp += avctx->channels;
2506
                }
2507
            }
2508
        }
2509
        avctx->bit_rate += m->bit_rate;
2510
    }
2511

    
2512
    /* update codec info */
2513
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2514

    
2515
    *data_size = out_size;
2516
    return buf_size;
2517
}
2518
#endif /* CONFIG_MP3ON4_DECODER */
2519

    
2520
#if CONFIG_MP1_DECODER
2521
AVCodec mp1_decoder =
2522
{
2523
    "mp1",
2524
    CODEC_TYPE_AUDIO,
2525
    CODEC_ID_MP1,
2526
    sizeof(MPADecodeContext),
2527
    decode_init,
2528
    NULL,
2529
    NULL,
2530
    decode_frame,
2531
    CODEC_CAP_PARSE_ONLY,
2532
    .flush= flush,
2533
    .long_name= NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
2534
};
2535
#endif
2536
#if CONFIG_MP2_DECODER
2537
AVCodec mp2_decoder =
2538
{
2539
    "mp2",
2540
    CODEC_TYPE_AUDIO,
2541
    CODEC_ID_MP2,
2542
    sizeof(MPADecodeContext),
2543
    decode_init,
2544
    NULL,
2545
    NULL,
2546
    decode_frame,
2547
    CODEC_CAP_PARSE_ONLY,
2548
    .flush= flush,
2549
    .long_name= NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2550
};
2551
#endif
2552
#if CONFIG_MP3_DECODER
2553
AVCodec mp3_decoder =
2554
{
2555
    "mp3",
2556
    CODEC_TYPE_AUDIO,
2557
    CODEC_ID_MP3,
2558
    sizeof(MPADecodeContext),
2559
    decode_init,
2560
    NULL,
2561
    NULL,
2562
    decode_frame,
2563
    CODEC_CAP_PARSE_ONLY,
2564
    .flush= flush,
2565
    .long_name= NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2566
};
2567
#endif
2568
#if CONFIG_MP3ADU_DECODER
2569
AVCodec mp3adu_decoder =
2570
{
2571
    "mp3adu",
2572
    CODEC_TYPE_AUDIO,
2573
    CODEC_ID_MP3ADU,
2574
    sizeof(MPADecodeContext),
2575
    decode_init,
2576
    NULL,
2577
    NULL,
2578
    decode_frame_adu,
2579
    CODEC_CAP_PARSE_ONLY,
2580
    .flush= flush,
2581
    .long_name= NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2582
};
2583
#endif
2584
#if CONFIG_MP3ON4_DECODER
2585
AVCodec mp3on4_decoder =
2586
{
2587
    "mp3on4",
2588
    CODEC_TYPE_AUDIO,
2589
    CODEC_ID_MP3ON4,
2590
    sizeof(MP3On4DecodeContext),
2591
    decode_init_mp3on4,
2592
    NULL,
2593
    decode_close_mp3on4,
2594
    decode_frame_mp3on4,
2595
    .flush= flush,
2596
    .long_name= NULL_IF_CONFIG_SMALL("MP3onMP4"),
2597
};
2598
#endif