Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 11c23b64

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

    
27
#include "avcodec.h"
28
#include "bitstream.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
/* define USE_HIGHPRECISION to have a bit exact (but slower) mpeg
38
   audio decoder */
39
#ifdef CONFIG_MPEGAUDIO_HP
40
#   define USE_HIGHPRECISION
41
#endif
42

    
43
#include "mpegaudio.h"
44
#include "mpegaudiodecheader.h"
45

    
46
#include "mathops.h"
47

    
48
/* WARNING: only correct for posititive numbers */
49
#define FIXR(a)   ((int)((a) * FRAC_ONE + 0.5))
50
#define FRAC_RND(a) (((a) + (FRAC_ONE/2)) >> FRAC_BITS)
51

    
52
#define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
53

    
54
/****************/
55

    
56
#define HEADER_SIZE 4
57

    
58
/* layer 3 "granule" */
59
typedef struct GranuleDef {
60
    uint8_t scfsi;
61
    int part2_3_length;
62
    int big_values;
63
    int global_gain;
64
    int scalefac_compress;
65
    uint8_t block_type;
66
    uint8_t switch_point;
67
    int table_select[3];
68
    int subblock_gain[3];
69
    uint8_t scalefac_scale;
70
    uint8_t count1table_select;
71
    int region_size[3]; /* number of huffman codes in each region */
72
    int preflag;
73
    int short_start, long_end; /* long/short band indexes */
74
    uint8_t scale_factors[40];
75
    int32_t sb_hybrid[SBLIMIT * 18]; /* 576 samples */
76
} GranuleDef;
77

    
78
#include "mpegaudiodata.h"
79
#include "mpegaudiodectab.h"
80

    
81
static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
82
static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
83

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

    
114
/* lower 2 bits: modulo 3, higher bits: shift */
115
static uint16_t scale_factor_modshift[64];
116
/* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
117
static int32_t scale_factor_mult[15][3];
118
/* mult table for layer 2 group quantization */
119

    
120
#define SCALE_GEN(v) \
121
{ FIXR(1.0 * (v)), FIXR(0.7937005259 * (v)), FIXR(0.6299605249 * (v)) }
122

    
123
static const int32_t scale_factor_mult2[3][3] = {
124
    SCALE_GEN(4.0 / 3.0), /* 3 steps */
125
    SCALE_GEN(4.0 / 5.0), /* 5 steps */
126
    SCALE_GEN(4.0 / 9.0), /* 9 steps */
127
};
128

    
129
static DECLARE_ALIGNED_16(MPA_INT, window[512]);
130

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

    
145
void ff_init_short_region(MPADecodeContext *s, GranuleDef *g){
146
    if (g->block_type == 2)
147
        g->region_size[0] = (36 / 2);
148
    else {
149
        if (s->sample_rate_index <= 2)
150
            g->region_size[0] = (36 / 2);
151
        else if (s->sample_rate_index != 8)
152
            g->region_size[0] = (54 / 2);
153
        else
154
            g->region_size[0] = (108 / 2);
155
    }
156
    g->region_size[1] = (576 / 2);
157
}
158

    
159
void ff_init_long_region(MPADecodeContext *s, GranuleDef *g, int ra1, int ra2){
160
    int l;
161
    g->region_size[0] =
162
        band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
163
    /* should not overflow */
164
    l = FFMIN(ra1 + ra2 + 2, 22);
165
    g->region_size[1] =
166
        band_index_long[s->sample_rate_index][l] >> 1;
167
}
168

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

    
182
            g->short_start = 2 + (s->sample_rate_index != 8);
183
        } else {
184
            g->long_end = 0;
185
            g->short_start = 0;
186
        }
187
    } else {
188
        g->short_start = 13;
189
        g->long_end = 22;
190
    }
191
}
192

    
193
/* layer 1 unscaling */
194
/* n = number of bits of the mantissa minus 1 */
195
static inline int l1_unscale(int n, int mant, int scale_factor)
196
{
197
    int shift, mod;
198
    int64_t val;
199

    
200
    shift = scale_factor_modshift[scale_factor];
201
    mod = shift & 3;
202
    shift >>= 2;
203
    val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
204
    shift += n;
205
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
206
    return (int)((val + (1LL << (shift - 1))) >> shift);
207
}
208

    
209
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
210
{
211
    int shift, mod, val;
212

    
213
    shift = scale_factor_modshift[scale_factor];
214
    mod = shift & 3;
215
    shift >>= 2;
216

    
217
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
218
    /* NOTE: at this point, 0 <= shift <= 21 */
219
    if (shift > 0)
220
        val = (val + (1 << (shift - 1))) >> shift;
221
    return val;
222
}
223

    
224
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
225
static inline int l3_unscale(int value, int exponent)
226
{
227
    unsigned int m;
228
    int e;
229

    
230
    e = table_4_3_exp  [4*value + (exponent&3)];
231
    m = table_4_3_value[4*value + (exponent&3)];
232
    e -= (exponent >> 2);
233
    assert(e>=1);
234
    if (e > 31)
235
        return 0;
236
    m = (m + (1 << (e-1))) >> e;
237

    
238
    return m;
239
}
240

    
241
/* all integer n^(4/3) computation code */
242
#define DEV_ORDER 13
243

    
244
#define POW_FRAC_BITS 24
245
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
246
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
247
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
248

    
249
static int dev_4_3_coefs[DEV_ORDER];
250

    
251
#if 0 /* unused */
252
static int pow_mult3[3] = {
253
    POW_FIX(1.0),
254
    POW_FIX(1.25992104989487316476),
255
    POW_FIX(1.58740105196819947474),
256
};
257
#endif
258

    
259
static void int_pow_init(void)
260
{
261
    int i, a;
262

    
263
    a = POW_FIX(1.0);
264
    for(i=0;i<DEV_ORDER;i++) {
265
        a = POW_MULL(a, POW_FIX(4.0 / 3.0) - i * POW_FIX(1.0)) / (i + 1);
266
        dev_4_3_coefs[i] = a;
267
    }
268
}
269

    
270
#if 0 /* unused, remove? */
271
/* return the mantissa and the binary exponent */
272
static int int_pow(int i, int *exp_ptr)
273
{
274
    int e, er, eq, j;
275
    int a, a1;
276

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

    
317
static int decode_init(AVCodecContext * avctx)
318
{
319
    MPADecodeContext *s = avctx->priv_data;
320
    static int init=0;
321
    int i, j, k;
322

    
323
    s->avctx = avctx;
324

    
325
#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
326
    avctx->sample_fmt= SAMPLE_FMT_S32;
327
#else
328
    avctx->sample_fmt= SAMPLE_FMT_S16;
329
#endif
330
    s->error_recognition= avctx->error_recognition;
331

    
332
    if(avctx->antialias_algo != FF_AA_FLOAT)
333
        s->compute_antialias= compute_antialias_integer;
334
    else
335
        s->compute_antialias= compute_antialias_float;
336

    
337
    if (!init && !avctx->parse_only) {
338
        int offset;
339

    
340
        /* scale factors table for layer 1/2 */
341
        for(i=0;i<64;i++) {
342
            int shift, mod;
343
            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
344
            shift = (i / 3);
345
            mod = i % 3;
346
            scale_factor_modshift[i] = mod | (shift << 2);
347
        }
348

    
349
        /* scale factor multiply for layer 1 */
350
        for(i=0;i<15;i++) {
351
            int n, norm;
352
            n = i + 2;
353
            norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
354
            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm, FRAC_BITS);
355
            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm, FRAC_BITS);
356
            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm, FRAC_BITS);
357
            dprintf(avctx, "%d: norm=%x s=%x %x %x\n",
358
                    i, norm,
359
                    scale_factor_mult[i][0],
360
                    scale_factor_mult[i][1],
361
                    scale_factor_mult[i][2]);
362
        }
363

    
364
        ff_mpa_synth_init(window);
365

    
366
        /* huffman decode tables */
367
        offset = 0;
368
        for(i=1;i<16;i++) {
369
            const HuffTable *h = &mpa_huff_tables[i];
370
            int xsize, x, y;
371
            unsigned int n;
372
            uint8_t  tmp_bits [512];
373
            uint16_t tmp_codes[512];
374

    
375
            memset(tmp_bits , 0, sizeof(tmp_bits ));
376
            memset(tmp_codes, 0, sizeof(tmp_codes));
377

    
378
            xsize = h->xsize;
379
            n = xsize * xsize;
380

    
381
            j = 0;
382
            for(x=0;x<xsize;x++) {
383
                for(y=0;y<xsize;y++){
384
                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
385
                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
386
                }
387
            }
388

    
389
            /* XXX: fail test */
390
            huff_vlc[i].table = huff_vlc_tables+offset;
391
            huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
392
            init_vlc(&huff_vlc[i], 7, 512,
393
                     tmp_bits, 1, 1, tmp_codes, 2, 2,
394
                     INIT_VLC_USE_NEW_STATIC);
395
            offset += huff_vlc_tables_sizes[i];
396
        }
397
        assert(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
398

    
399
        offset = 0;
400
        for(i=0;i<2;i++) {
401
            huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
402
            huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
403
            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
404
                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
405
                     INIT_VLC_USE_NEW_STATIC);
406
            offset += huff_quad_vlc_tables_sizes[i];
407
        }
408
        assert(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
409

    
410
        for(i=0;i<9;i++) {
411
            k = 0;
412
            for(j=0;j<22;j++) {
413
                band_index_long[i][j] = k;
414
                k += band_size_long[i][j];
415
            }
416
            band_index_long[i][22] = k;
417
        }
418

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

    
421
        int_pow_init();
422
        for(i=1;i<TABLE_4_3_SIZE;i++) {
423
            double f, fm;
424
            int e, m;
425
            f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);
426
            fm = frexp(f, &e);
427
            m = (uint32_t)(fm*(1LL<<31) + 0.5);
428
            e+= FRAC_BITS - 31 + 5 - 100;
429

    
430
            /* normalized to FRAC_BITS */
431
            table_4_3_value[i] = m;
432
            table_4_3_exp[i] = -e;
433
        }
434
        for(i=0; i<512*16; i++){
435
            int exponent= (i>>4);
436
            double f= pow(i&15, 4.0 / 3.0) * pow(2, (exponent-400)*0.25 + FRAC_BITS + 5);
437
            expval_table[exponent][i&15]= llrint(f);
438
            if((i&15)==1)
439
                exp_table[exponent]= llrint(f);
440
        }
441

    
442
        for(i=0;i<7;i++) {
443
            float f;
444
            int v;
445
            if (i != 6) {
446
                f = tan((double)i * M_PI / 12.0);
447
                v = FIXR(f / (1.0 + f));
448
            } else {
449
                v = FIXR(1.0);
450
            }
451
            is_table[0][i] = v;
452
            is_table[1][6 - i] = v;
453
        }
454
        /* invalid values */
455
        for(i=7;i<16;i++)
456
            is_table[0][i] = is_table[1][i] = 0.0;
457

    
458
        for(i=0;i<16;i++) {
459
            double f;
460
            int e, k;
461

    
462
            for(j=0;j<2;j++) {
463
                e = -(j + 1) * ((i + 1) >> 1);
464
                f = pow(2.0, e / 4.0);
465
                k = i & 1;
466
                is_table_lsf[j][k ^ 1][i] = FIXR(f);
467
                is_table_lsf[j][k][i] = FIXR(1.0);
468
                dprintf(avctx, "is_table_lsf %d %d: %x %x\n",
469
                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
470
            }
471
        }
472

    
473
        for(i=0;i<8;i++) {
474
            float ci, cs, ca;
475
            ci = ci_table[i];
476
            cs = 1.0 / sqrt(1.0 + ci * ci);
477
            ca = cs * ci;
478
            csa_table[i][0] = FIXHR(cs/4);
479
            csa_table[i][1] = FIXHR(ca/4);
480
            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
481
            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
482
            csa_table_float[i][0] = cs;
483
            csa_table_float[i][1] = ca;
484
            csa_table_float[i][2] = ca + cs;
485
            csa_table_float[i][3] = ca - cs;
486
        }
487

    
488
        /* compute mdct windows */
489
        for(i=0;i<36;i++) {
490
            for(j=0; j<4; j++){
491
                double d;
492

    
493
                if(j==2 && i%3 != 1)
494
                    continue;
495

    
496
                d= sin(M_PI * (i + 0.5) / 36.0);
497
                if(j==1){
498
                    if     (i>=30) d= 0;
499
                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);
500
                    else if(i>=18) d= 1;
501
                }else if(j==3){
502
                    if     (i<  6) d= 0;
503
                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);
504
                    else if(i< 18) d= 1;
505
                }
506
                //merge last stage of imdct into the window coefficients
507
                d*= 0.5 / cos(M_PI*(2*i + 19)/72);
508

    
509
                if(j==2)
510
                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));
511
                else
512
                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));
513
            }
514
        }
515

    
516
        /* NOTE: we do frequency inversion adter the MDCT by changing
517
           the sign of the right window coefs */
518
        for(j=0;j<4;j++) {
519
            for(i=0;i<36;i+=2) {
520
                mdct_win[j + 4][i] = mdct_win[j][i];
521
                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
522
            }
523
        }
524

    
525
        init = 1;
526
    }
527

    
528
    if (avctx->codec_id == CODEC_ID_MP3ADU)
529
        s->adu_mode = 1;
530
    return 0;
531
}
532

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

    
535
/* cos(i*pi/64) */
536

    
537
#define COS0_0  FIXHR(0.50060299823519630134/2)
538
#define COS0_1  FIXHR(0.50547095989754365998/2)
539
#define COS0_2  FIXHR(0.51544730992262454697/2)
540
#define COS0_3  FIXHR(0.53104259108978417447/2)
541
#define COS0_4  FIXHR(0.55310389603444452782/2)
542
#define COS0_5  FIXHR(0.58293496820613387367/2)
543
#define COS0_6  FIXHR(0.62250412303566481615/2)
544
#define COS0_7  FIXHR(0.67480834145500574602/2)
545
#define COS0_8  FIXHR(0.74453627100229844977/2)
546
#define COS0_9  FIXHR(0.83934964541552703873/2)
547
#define COS0_10 FIXHR(0.97256823786196069369/2)
548
#define COS0_11 FIXHR(1.16943993343288495515/4)
549
#define COS0_12 FIXHR(1.48416461631416627724/4)
550
#define COS0_13 FIXHR(2.05778100995341155085/8)
551
#define COS0_14 FIXHR(3.40760841846871878570/8)
552
#define COS0_15 FIXHR(10.19000812354805681150/32)
553

    
554
#define COS1_0 FIXHR(0.50241928618815570551/2)
555
#define COS1_1 FIXHR(0.52249861493968888062/2)
556
#define COS1_2 FIXHR(0.56694403481635770368/2)
557
#define COS1_3 FIXHR(0.64682178335999012954/2)
558
#define COS1_4 FIXHR(0.78815462345125022473/2)
559
#define COS1_5 FIXHR(1.06067768599034747134/4)
560
#define COS1_6 FIXHR(1.72244709823833392782/4)
561
#define COS1_7 FIXHR(5.10114861868916385802/16)
562

    
563
#define COS2_0 FIXHR(0.50979557910415916894/2)
564
#define COS2_1 FIXHR(0.60134488693504528054/2)
565
#define COS2_2 FIXHR(0.89997622313641570463/2)
566
#define COS2_3 FIXHR(2.56291544774150617881/8)
567

    
568
#define COS3_0 FIXHR(0.54119610014619698439/2)
569
#define COS3_1 FIXHR(1.30656296487637652785/4)
570

    
571
#define COS4_0 FIXHR(0.70710678118654752439/2)
572

    
573
/* butterfly operator */
574
#define BF(a, b, c, s)\
575
{\
576
    tmp0 = tab[a] + tab[b];\
577
    tmp1 = tab[a] - tab[b];\
578
    tab[a] = tmp0;\
579
    tab[b] = MULH(tmp1<<(s), c);\
580
}
581

    
582
#define BF1(a, b, c, d)\
583
{\
584
    BF(a, b, COS4_0, 1);\
585
    BF(c, d,-COS4_0, 1);\
586
    tab[c] += tab[d];\
587
}
588

    
589
#define BF2(a, b, c, d)\
590
{\
591
    BF(a, b, COS4_0, 1);\
592
    BF(c, d,-COS4_0, 1);\
593
    tab[c] += tab[d];\
594
    tab[a] += tab[c];\
595
    tab[c] += tab[b];\
596
    tab[b] += tab[d];\
597
}
598

    
599
#define ADD(a, b) tab[a] += tab[b]
600

    
601
/* DCT32 without 1/sqrt(2) coef zero scaling. */
602
static void dct32(int32_t *out, int32_t *tab)
603
{
604
    int tmp0, tmp1;
605

    
606
    /* pass 1 */
607
    BF( 0, 31, COS0_0 , 1);
608
    BF(15, 16, COS0_15, 5);
609
    /* pass 2 */
610
    BF( 0, 15, COS1_0 , 1);
611
    BF(16, 31,-COS1_0 , 1);
612
    /* pass 1 */
613
    BF( 7, 24, COS0_7 , 1);
614
    BF( 8, 23, COS0_8 , 1);
615
    /* pass 2 */
616
    BF( 7,  8, COS1_7 , 4);
617
    BF(23, 24,-COS1_7 , 4);
618
    /* pass 3 */
619
    BF( 0,  7, COS2_0 , 1);
620
    BF( 8, 15,-COS2_0 , 1);
621
    BF(16, 23, COS2_0 , 1);
622
    BF(24, 31,-COS2_0 , 1);
623
    /* pass 1 */
624
    BF( 3, 28, COS0_3 , 1);
625
    BF(12, 19, COS0_12, 2);
626
    /* pass 2 */
627
    BF( 3, 12, COS1_3 , 1);
628
    BF(19, 28,-COS1_3 , 1);
629
    /* pass 1 */
630
    BF( 4, 27, COS0_4 , 1);
631
    BF(11, 20, COS0_11, 2);
632
    /* pass 2 */
633
    BF( 4, 11, COS1_4 , 1);
634
    BF(20, 27,-COS1_4 , 1);
635
    /* pass 3 */
636
    BF( 3,  4, COS2_3 , 3);
637
    BF(11, 12,-COS2_3 , 3);
638
    BF(19, 20, COS2_3 , 3);
639
    BF(27, 28,-COS2_3 , 3);
640
    /* pass 4 */
641
    BF( 0,  3, COS3_0 , 1);
642
    BF( 4,  7,-COS3_0 , 1);
643
    BF( 8, 11, COS3_0 , 1);
644
    BF(12, 15,-COS3_0 , 1);
645
    BF(16, 19, COS3_0 , 1);
646
    BF(20, 23,-COS3_0 , 1);
647
    BF(24, 27, COS3_0 , 1);
648
    BF(28, 31,-COS3_0 , 1);
649

    
650

    
651

    
652
    /* pass 1 */
653
    BF( 1, 30, COS0_1 , 1);
654
    BF(14, 17, COS0_14, 3);
655
    /* pass 2 */
656
    BF( 1, 14, COS1_1 , 1);
657
    BF(17, 30,-COS1_1 , 1);
658
    /* pass 1 */
659
    BF( 6, 25, COS0_6 , 1);
660
    BF( 9, 22, COS0_9 , 1);
661
    /* pass 2 */
662
    BF( 6,  9, COS1_6 , 2);
663
    BF(22, 25,-COS1_6 , 2);
664
    /* pass 3 */
665
    BF( 1,  6, COS2_1 , 1);
666
    BF( 9, 14,-COS2_1 , 1);
667
    BF(17, 22, COS2_1 , 1);
668
    BF(25, 30,-COS2_1 , 1);
669

    
670
    /* pass 1 */
671
    BF( 2, 29, COS0_2 , 1);
672
    BF(13, 18, COS0_13, 3);
673
    /* pass 2 */
674
    BF( 2, 13, COS1_2 , 1);
675
    BF(18, 29,-COS1_2 , 1);
676
    /* pass 1 */
677
    BF( 5, 26, COS0_5 , 1);
678
    BF(10, 21, COS0_10, 1);
679
    /* pass 2 */
680
    BF( 5, 10, COS1_5 , 2);
681
    BF(21, 26,-COS1_5 , 2);
682
    /* pass 3 */
683
    BF( 2,  5, COS2_2 , 1);
684
    BF(10, 13,-COS2_2 , 1);
685
    BF(18, 21, COS2_2 , 1);
686
    BF(26, 29,-COS2_2 , 1);
687
    /* pass 4 */
688
    BF( 1,  2, COS3_1 , 2);
689
    BF( 5,  6,-COS3_1 , 2);
690
    BF( 9, 10, COS3_1 , 2);
691
    BF(13, 14,-COS3_1 , 2);
692
    BF(17, 18, COS3_1 , 2);
693
    BF(21, 22,-COS3_1 , 2);
694
    BF(25, 26, COS3_1 , 2);
695
    BF(29, 30,-COS3_1 , 2);
696

    
697
    /* pass 5 */
698
    BF1( 0,  1,  2,  3);
699
    BF2( 4,  5,  6,  7);
700
    BF1( 8,  9, 10, 11);
701
    BF2(12, 13, 14, 15);
702
    BF1(16, 17, 18, 19);
703
    BF2(20, 21, 22, 23);
704
    BF1(24, 25, 26, 27);
705
    BF2(28, 29, 30, 31);
706

    
707
    /* pass 6 */
708

    
709
    ADD( 8, 12);
710
    ADD(12, 10);
711
    ADD(10, 14);
712
    ADD(14,  9);
713
    ADD( 9, 13);
714
    ADD(13, 11);
715
    ADD(11, 15);
716

    
717
    out[ 0] = tab[0];
718
    out[16] = tab[1];
719
    out[ 8] = tab[2];
720
    out[24] = tab[3];
721
    out[ 4] = tab[4];
722
    out[20] = tab[5];
723
    out[12] = tab[6];
724
    out[28] = tab[7];
725
    out[ 2] = tab[8];
726
    out[18] = tab[9];
727
    out[10] = tab[10];
728
    out[26] = tab[11];
729
    out[ 6] = tab[12];
730
    out[22] = tab[13];
731
    out[14] = tab[14];
732
    out[30] = tab[15];
733

    
734
    ADD(24, 28);
735
    ADD(28, 26);
736
    ADD(26, 30);
737
    ADD(30, 25);
738
    ADD(25, 29);
739
    ADD(29, 27);
740
    ADD(27, 31);
741

    
742
    out[ 1] = tab[16] + tab[24];
743
    out[17] = tab[17] + tab[25];
744
    out[ 9] = tab[18] + tab[26];
745
    out[25] = tab[19] + tab[27];
746
    out[ 5] = tab[20] + tab[28];
747
    out[21] = tab[21] + tab[29];
748
    out[13] = tab[22] + tab[30];
749
    out[29] = tab[23] + tab[31];
750
    out[ 3] = tab[24] + tab[20];
751
    out[19] = tab[25] + tab[21];
752
    out[11] = tab[26] + tab[22];
753
    out[27] = tab[27] + tab[23];
754
    out[ 7] = tab[28] + tab[18];
755
    out[23] = tab[29] + tab[19];
756
    out[15] = tab[30] + tab[17];
757
    out[31] = tab[31];
758
}
759

    
760
#if FRAC_BITS <= 15
761

    
762
static inline int round_sample(int *sum)
763
{
764
    int sum1;
765
    sum1 = (*sum) >> OUT_SHIFT;
766
    *sum &= (1<<OUT_SHIFT)-1;
767
    if (sum1 < OUT_MIN)
768
        sum1 = OUT_MIN;
769
    else if (sum1 > OUT_MAX)
770
        sum1 = OUT_MAX;
771
    return sum1;
772
}
773

    
774
/* signed 16x16 -> 32 multiply add accumulate */
775
#define MACS(rt, ra, rb) MAC16(rt, ra, rb)
776

    
777
/* signed 16x16 -> 32 multiply */
778
#define MULS(ra, rb) MUL16(ra, rb)
779

    
780
#define MLSS(rt, ra, rb) MLS16(rt, ra, rb)
781

    
782
#else
783

    
784
static inline int round_sample(int64_t *sum)
785
{
786
    int sum1;
787
    sum1 = (int)((*sum) >> OUT_SHIFT);
788
    *sum &= (1<<OUT_SHIFT)-1;
789
    if (sum1 < OUT_MIN)
790
        sum1 = OUT_MIN;
791
    else if (sum1 > OUT_MAX)
792
        sum1 = OUT_MAX;
793
    return sum1;
794
}
795

    
796
#   define MULS(ra, rb) MUL64(ra, rb)
797
#   define MACS(rt, ra, rb) MAC64(rt, ra, rb)
798
#   define MLSS(rt, ra, rb) MLS64(rt, ra, rb)
799
#endif
800

    
801
#define SUM8(op, sum, w, p)               \
802
{                                         \
803
    op(sum, (w)[0 * 64], p[0 * 64]);      \
804
    op(sum, (w)[1 * 64], p[1 * 64]);      \
805
    op(sum, (w)[2 * 64], p[2 * 64]);      \
806
    op(sum, (w)[3 * 64], p[3 * 64]);      \
807
    op(sum, (w)[4 * 64], p[4 * 64]);      \
808
    op(sum, (w)[5 * 64], p[5 * 64]);      \
809
    op(sum, (w)[6 * 64], p[6 * 64]);      \
810
    op(sum, (w)[7 * 64], p[7 * 64]);      \
811
}
812

    
813
#define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
814
{                                               \
815
    int tmp;\
816
    tmp = p[0 * 64];\
817
    op1(sum1, (w1)[0 * 64], tmp);\
818
    op2(sum2, (w2)[0 * 64], tmp);\
819
    tmp = p[1 * 64];\
820
    op1(sum1, (w1)[1 * 64], tmp);\
821
    op2(sum2, (w2)[1 * 64], tmp);\
822
    tmp = p[2 * 64];\
823
    op1(sum1, (w1)[2 * 64], tmp);\
824
    op2(sum2, (w2)[2 * 64], tmp);\
825
    tmp = p[3 * 64];\
826
    op1(sum1, (w1)[3 * 64], tmp);\
827
    op2(sum2, (w2)[3 * 64], tmp);\
828
    tmp = p[4 * 64];\
829
    op1(sum1, (w1)[4 * 64], tmp);\
830
    op2(sum2, (w2)[4 * 64], tmp);\
831
    tmp = p[5 * 64];\
832
    op1(sum1, (w1)[5 * 64], tmp);\
833
    op2(sum2, (w2)[5 * 64], tmp);\
834
    tmp = p[6 * 64];\
835
    op1(sum1, (w1)[6 * 64], tmp);\
836
    op2(sum2, (w2)[6 * 64], tmp);\
837
    tmp = p[7 * 64];\
838
    op1(sum1, (w1)[7 * 64], tmp);\
839
    op2(sum2, (w2)[7 * 64], tmp);\
840
}
841

    
842
void ff_mpa_synth_init(MPA_INT *window)
843
{
844
    int i;
845

    
846
    /* max = 18760, max sum over all 16 coefs : 44736 */
847
    for(i=0;i<257;i++) {
848
        int v;
849
        v = ff_mpa_enwindow[i];
850
#if WFRAC_BITS < 16
851
        v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
852
#endif
853
        window[i] = v;
854
        if ((i & 63) != 0)
855
            v = -v;
856
        if (i != 0)
857
            window[512 - i] = v;
858
    }
859
}
860

    
861
/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
862
   32 samples. */
863
/* XXX: optimize by avoiding ring buffer usage */
864
void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
865
                         MPA_INT *window, int *dither_state,
866
                         OUT_INT *samples, int incr,
867
                         int32_t sb_samples[SBLIMIT])
868
{
869
    int32_t tmp[32];
870
    register MPA_INT *synth_buf;
871
    register const MPA_INT *w, *w2, *p;
872
    int j, offset, v;
873
    OUT_INT *samples2;
874
#if FRAC_BITS <= 15
875
    int sum, sum2;
876
#else
877
    int64_t sum, sum2;
878
#endif
879

    
880
    dct32(tmp, sb_samples);
881

    
882
    offset = *synth_buf_offset;
883
    synth_buf = synth_buf_ptr + offset;
884

    
885
    for(j=0;j<32;j++) {
886
        v = tmp[j];
887
#if FRAC_BITS <= 15
888
        /* NOTE: can cause a loss in precision if very high amplitude
889
           sound */
890
        v = av_clip_int16(v);
891
#endif
892
        synth_buf[j] = v;
893
    }
894
    /* copy to avoid wrap */
895
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
896

    
897
    samples2 = samples + 31 * incr;
898
    w = window;
899
    w2 = window + 31;
900

    
901
    sum = *dither_state;
902
    p = synth_buf + 16;
903
    SUM8(MACS, sum, w, p);
904
    p = synth_buf + 48;
905
    SUM8(MLSS, sum, w + 32, p);
906
    *samples = round_sample(&sum);
907
    samples += incr;
908
    w++;
909

    
910
    /* we calculate two samples at the same time to avoid one memory
911
       access per two sample */
912
    for(j=1;j<16;j++) {
913
        sum2 = 0;
914
        p = synth_buf + 16 + j;
915
        SUM8P2(sum, MACS, sum2, MLSS, w, w2, p);
916
        p = synth_buf + 48 - j;
917
        SUM8P2(sum, MLSS, sum2, MLSS, w + 32, w2 + 32, p);
918

    
919
        *samples = round_sample(&sum);
920
        samples += incr;
921
        sum += sum2;
922
        *samples2 = round_sample(&sum);
923
        samples2 -= incr;
924
        w++;
925
        w2--;
926
    }
927

    
928
    p = synth_buf + 32;
929
    SUM8(MLSS, sum, w + 32, p);
930
    *samples = round_sample(&sum);
931
    *dither_state= sum;
932

    
933
    offset = (offset - 32) & 511;
934
    *synth_buf_offset = offset;
935
}
936

    
937
#define C3 FIXHR(0.86602540378443864676/2)
938

    
939
/* 0.5 / cos(pi*(2*i+1)/36) */
940
static const int icos36[9] = {
941
    FIXR(0.50190991877167369479),
942
    FIXR(0.51763809020504152469), //0
943
    FIXR(0.55168895948124587824),
944
    FIXR(0.61038729438072803416),
945
    FIXR(0.70710678118654752439), //1
946
    FIXR(0.87172339781054900991),
947
    FIXR(1.18310079157624925896),
948
    FIXR(1.93185165257813657349), //2
949
    FIXR(5.73685662283492756461),
950
};
951

    
952
/* 0.5 / cos(pi*(2*i+1)/36) */
953
static const int icos36h[9] = {
954
    FIXHR(0.50190991877167369479/2),
955
    FIXHR(0.51763809020504152469/2), //0
956
    FIXHR(0.55168895948124587824/2),
957
    FIXHR(0.61038729438072803416/2),
958
    FIXHR(0.70710678118654752439/2), //1
959
    FIXHR(0.87172339781054900991/2),
960
    FIXHR(1.18310079157624925896/4),
961
    FIXHR(1.93185165257813657349/4), //2
962
//    FIXHR(5.73685662283492756461),
963
};
964

    
965
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
966
   cases. */
967
static void imdct12(int *out, int *in)
968
{
969
    int in0, in1, in2, in3, in4, in5, t1, t2;
970

    
971
    in0= in[0*3];
972
    in1= in[1*3] + in[0*3];
973
    in2= in[2*3] + in[1*3];
974
    in3= in[3*3] + in[2*3];
975
    in4= in[4*3] + in[3*3];
976
    in5= in[5*3] + in[4*3];
977
    in5 += in3;
978
    in3 += in1;
979

    
980
    in2= MULH(2*in2, C3);
981
    in3= MULH(4*in3, C3);
982

    
983
    t1 = in0 - in4;
984
    t2 = MULH(2*(in1 - in5), icos36h[4]);
985

    
986
    out[ 7]=
987
    out[10]= t1 + t2;
988
    out[ 1]=
989
    out[ 4]= t1 - t2;
990

    
991
    in0 += in4>>1;
992
    in4 = in0 + in2;
993
    in5 += 2*in1;
994
    in1 = MULH(in5 + in3, icos36h[1]);
995
    out[ 8]=
996
    out[ 9]= in4 + in1;
997
    out[ 2]=
998
    out[ 3]= in4 - in1;
999

    
1000
    in0 -= in2;
1001
    in5 = MULH(2*(in5 - in3), icos36h[7]);
1002
    out[ 0]=
1003
    out[ 5]= in0 - in5;
1004
    out[ 6]=
1005
    out[11]= in0 + in5;
1006
}
1007

    
1008
/* cos(pi*i/18) */
1009
#define C1 FIXHR(0.98480775301220805936/2)
1010
#define C2 FIXHR(0.93969262078590838405/2)
1011
#define C3 FIXHR(0.86602540378443864676/2)
1012
#define C4 FIXHR(0.76604444311897803520/2)
1013
#define C5 FIXHR(0.64278760968653932632/2)
1014
#define C6 FIXHR(0.5/2)
1015
#define C7 FIXHR(0.34202014332566873304/2)
1016
#define C8 FIXHR(0.17364817766693034885/2)
1017

    
1018

    
1019
/* using Lee like decomposition followed by hand coded 9 points DCT */
1020
static void imdct36(int *out, int *buf, int *in, int *win)
1021
{
1022
    int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
1023
    int tmp[18], *tmp1, *in1;
1024

    
1025
    for(i=17;i>=1;i--)
1026
        in[i] += in[i-1];
1027
    for(i=17;i>=3;i-=2)
1028
        in[i] += in[i-2];
1029

    
1030
    for(j=0;j<2;j++) {
1031
        tmp1 = tmp + j;
1032
        in1 = in + j;
1033
#if 0
1034
//more accurate but slower
1035
        int64_t t0, t1, t2, t3;
1036
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1037

1038
        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
1039
        t1 = in1[2*0] - in1[2*6];
1040
        tmp1[ 6] = t1 - (t2>>1);
1041
        tmp1[16] = t1 + t2;
1042

1043
        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
1044
        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
1045
        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
1046

1047
        tmp1[10] = (t3 - t0 - t2) >> 32;
1048
        tmp1[ 2] = (t3 + t0 + t1) >> 32;
1049
        tmp1[14] = (t3 + t2 - t1) >> 32;
1050

1051
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1052
        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
1053
        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
1054
        t0 = MUL64(2*in1[2*3], C3);
1055

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

1058
        tmp1[ 0] = (t2 + t3 + t0) >> 32;
1059
        tmp1[12] = (t2 + t1 - t0) >> 32;
1060
        tmp1[ 8] = (t3 - t1 - t0) >> 32;
1061
#else
1062
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1063

    
1064
        t3 = in1[2*0] + (in1[2*6]>>1);
1065
        t1 = in1[2*0] - in1[2*6];
1066
        tmp1[ 6] = t1 - (t2>>1);
1067
        tmp1[16] = t1 + t2;
1068

    
1069
        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1070
        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1071
        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1072

    
1073
        tmp1[10] = t3 - t0 - t2;
1074
        tmp1[ 2] = t3 + t0 + t1;
1075
        tmp1[14] = t3 + t2 - t1;
1076

    
1077
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1078
        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1079
        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1080
        t0 = MULH(2*in1[2*3], C3);
1081

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

    
1084
        tmp1[ 0] = t2 + t3 + t0;
1085
        tmp1[12] = t2 + t1 - t0;
1086
        tmp1[ 8] = t3 - t1 - t0;
1087
#endif
1088
    }
1089

    
1090
    i = 0;
1091
    for(j=0;j<4;j++) {
1092
        t0 = tmp[i];
1093
        t1 = tmp[i + 2];
1094
        s0 = t1 + t0;
1095
        s2 = t1 - t0;
1096

    
1097
        t2 = tmp[i + 1];
1098
        t3 = tmp[i + 3];
1099
        s1 = MULH(2*(t3 + t2), icos36h[j]);
1100
        s3 = MULL(t3 - t2, icos36[8 - j], FRAC_BITS);
1101

    
1102
        t0 = s0 + s1;
1103
        t1 = s0 - s1;
1104
        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1105
        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1106
        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1107
        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1108

    
1109
        t0 = s2 + s3;
1110
        t1 = s2 - s3;
1111
        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1112
        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1113
        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1114
        buf[      + j] = MULH(t0, win[18         + j]);
1115
        i += 4;
1116
    }
1117

    
1118
    s0 = tmp[16];
1119
    s1 = MULH(2*tmp[17], icos36h[4]);
1120
    t0 = s0 + s1;
1121
    t1 = s0 - s1;
1122
    out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
1123
    out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
1124
    buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
1125
    buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
1126
}
1127

    
1128
/* return the number of decoded frames */
1129
static int mp_decode_layer1(MPADecodeContext *s)
1130
{
1131
    int bound, i, v, n, ch, j, mant;
1132
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1133
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1134

    
1135
    if (s->mode == MPA_JSTEREO)
1136
        bound = (s->mode_ext + 1) * 4;
1137
    else
1138
        bound = SBLIMIT;
1139

    
1140
    /* allocation bits */
1141
    for(i=0;i<bound;i++) {
1142
        for(ch=0;ch<s->nb_channels;ch++) {
1143
            allocation[ch][i] = get_bits(&s->gb, 4);
1144
        }
1145
    }
1146
    for(i=bound;i<SBLIMIT;i++) {
1147
        allocation[0][i] = get_bits(&s->gb, 4);
1148
    }
1149

    
1150
    /* scale factors */
1151
    for(i=0;i<bound;i++) {
1152
        for(ch=0;ch<s->nb_channels;ch++) {
1153
            if (allocation[ch][i])
1154
                scale_factors[ch][i] = get_bits(&s->gb, 6);
1155
        }
1156
    }
1157
    for(i=bound;i<SBLIMIT;i++) {
1158
        if (allocation[0][i]) {
1159
            scale_factors[0][i] = get_bits(&s->gb, 6);
1160
            scale_factors[1][i] = get_bits(&s->gb, 6);
1161
        }
1162
    }
1163

    
1164
    /* compute samples */
1165
    for(j=0;j<12;j++) {
1166
        for(i=0;i<bound;i++) {
1167
            for(ch=0;ch<s->nb_channels;ch++) {
1168
                n = allocation[ch][i];
1169
                if (n) {
1170
                    mant = get_bits(&s->gb, n + 1);
1171
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
1172
                } else {
1173
                    v = 0;
1174
                }
1175
                s->sb_samples[ch][j][i] = v;
1176
            }
1177
        }
1178
        for(i=bound;i<SBLIMIT;i++) {
1179
            n = allocation[0][i];
1180
            if (n) {
1181
                mant = get_bits(&s->gb, n + 1);
1182
                v = l1_unscale(n, mant, scale_factors[0][i]);
1183
                s->sb_samples[0][j][i] = v;
1184
                v = l1_unscale(n, mant, scale_factors[1][i]);
1185
                s->sb_samples[1][j][i] = v;
1186
            } else {
1187
                s->sb_samples[0][j][i] = 0;
1188
                s->sb_samples[1][j][i] = 0;
1189
            }
1190
        }
1191
    }
1192
    return 12;
1193
}
1194

    
1195
static int mp_decode_layer2(MPADecodeContext *s)
1196
{
1197
    int sblimit; /* number of used subbands */
1198
    const unsigned char *alloc_table;
1199
    int table, bit_alloc_bits, i, j, ch, bound, v;
1200
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1201
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1202
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1203
    int scale, qindex, bits, steps, k, l, m, b;
1204

    
1205
    /* select decoding table */
1206
    table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
1207
                            s->sample_rate, s->lsf);
1208
    sblimit = ff_mpa_sblimit_table[table];
1209
    alloc_table = ff_mpa_alloc_tables[table];
1210

    
1211
    if (s->mode == MPA_JSTEREO)
1212
        bound = (s->mode_ext + 1) * 4;
1213
    else
1214
        bound = sblimit;
1215

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

    
1218
    /* sanity check */
1219
    if( bound > sblimit ) bound = sblimit;
1220

    
1221
    /* parse bit allocation */
1222
    j = 0;
1223
    for(i=0;i<bound;i++) {
1224
        bit_alloc_bits = alloc_table[j];
1225
        for(ch=0;ch<s->nb_channels;ch++) {
1226
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1227
        }
1228
        j += 1 << bit_alloc_bits;
1229
    }
1230
    for(i=bound;i<sblimit;i++) {
1231
        bit_alloc_bits = alloc_table[j];
1232
        v = get_bits(&s->gb, bit_alloc_bits);
1233
        bit_alloc[0][i] = v;
1234
        bit_alloc[1][i] = v;
1235
        j += 1 << bit_alloc_bits;
1236
    }
1237

    
1238
    /* scale codes */
1239
    for(i=0;i<sblimit;i++) {
1240
        for(ch=0;ch<s->nb_channels;ch++) {
1241
            if (bit_alloc[ch][i])
1242
                scale_code[ch][i] = get_bits(&s->gb, 2);
1243
        }
1244
    }
1245

    
1246
    /* scale factors */
1247
    for(i=0;i<sblimit;i++) {
1248
        for(ch=0;ch<s->nb_channels;ch++) {
1249
            if (bit_alloc[ch][i]) {
1250
                sf = scale_factors[ch][i];
1251
                switch(scale_code[ch][i]) {
1252
                default:
1253
                case 0:
1254
                    sf[0] = get_bits(&s->gb, 6);
1255
                    sf[1] = get_bits(&s->gb, 6);
1256
                    sf[2] = get_bits(&s->gb, 6);
1257
                    break;
1258
                case 2:
1259
                    sf[0] = get_bits(&s->gb, 6);
1260
                    sf[1] = sf[0];
1261
                    sf[2] = sf[0];
1262
                    break;
1263
                case 1:
1264
                    sf[0] = get_bits(&s->gb, 6);
1265
                    sf[2] = get_bits(&s->gb, 6);
1266
                    sf[1] = sf[0];
1267
                    break;
1268
                case 3:
1269
                    sf[0] = get_bits(&s->gb, 6);
1270
                    sf[2] = get_bits(&s->gb, 6);
1271
                    sf[1] = sf[2];
1272
                    break;
1273
                }
1274
            }
1275
        }
1276
    }
1277

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

    
1381
static inline void lsf_sf_expand(int *slen,
1382
                                 int sf, int n1, int n2, int n3)
1383
{
1384
    if (n3) {
1385
        slen[3] = sf % n3;
1386
        sf /= n3;
1387
    } else {
1388
        slen[3] = 0;
1389
    }
1390
    if (n2) {
1391
        slen[2] = sf % n2;
1392
        sf /= n2;
1393
    } else {
1394
        slen[2] = 0;
1395
    }
1396
    slen[1] = sf % n1;
1397
    sf /= n1;
1398
    slen[0] = sf;
1399
}
1400

    
1401
static void exponents_from_scale_factors(MPADecodeContext *s,
1402
                                         GranuleDef *g,
1403
                                         int16_t *exponents)
1404
{
1405
    const uint8_t *bstab, *pretab;
1406
    int len, i, j, k, l, v0, shift, gain, gains[3];
1407
    int16_t *exp_ptr;
1408

    
1409
    exp_ptr = exponents;
1410
    gain = g->global_gain - 210;
1411
    shift = g->scalefac_scale + 1;
1412

    
1413
    bstab = band_size_long[s->sample_rate_index];
1414
    pretab = mpa_pretab[g->preflag];
1415
    for(i=0;i<g->long_end;i++) {
1416
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1417
        len = bstab[i];
1418
        for(j=len;j>0;j--)
1419
            *exp_ptr++ = v0;
1420
    }
1421

    
1422
    if (g->short_start < 13) {
1423
        bstab = band_size_short[s->sample_rate_index];
1424
        gains[0] = gain - (g->subblock_gain[0] << 3);
1425
        gains[1] = gain - (g->subblock_gain[1] << 3);
1426
        gains[2] = gain - (g->subblock_gain[2] << 3);
1427
        k = g->long_end;
1428
        for(i=g->short_start;i<13;i++) {
1429
            len = bstab[i];
1430
            for(l=0;l<3;l++) {
1431
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1432
                for(j=len;j>0;j--)
1433
                *exp_ptr++ = v0;
1434
            }
1435
        }
1436
    }
1437
}
1438

    
1439
/* handle n = 0 too */
1440
static inline int get_bitsz(GetBitContext *s, int n)
1441
{
1442
    if (n == 0)
1443
        return 0;
1444
    else
1445
        return get_bits(s, n);
1446
}
1447

    
1448

    
1449
static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos, int *end_pos2){
1450
    if(s->in_gb.buffer && *pos >= s->gb.size_in_bits){
1451
        s->gb= s->in_gb;
1452
        s->in_gb.buffer=NULL;
1453
        assert((get_bits_count(&s->gb) & 7) == 0);
1454
        skip_bits_long(&s->gb, *pos - *end_pos);
1455
        *end_pos2=
1456
        *end_pos= *end_pos2 + get_bits_count(&s->gb) - *pos;
1457
        *pos= get_bits_count(&s->gb);
1458
    }
1459
}
1460

    
1461
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1462
                          int16_t *exponents, int end_pos2)
1463
{
1464
    int s_index;
1465
    int i;
1466
    int last_pos, bits_left;
1467
    VLC *vlc;
1468
    int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1469

    
1470
    /* low frequencies (called big values) */
1471
    s_index = 0;
1472
    for(i=0;i<3;i++) {
1473
        int j, k, l, linbits;
1474
        j = g->region_size[i];
1475
        if (j == 0)
1476
            continue;
1477
        /* select vlc table */
1478
        k = g->table_select[i];
1479
        l = mpa_huff_data[k][0];
1480
        linbits = mpa_huff_data[k][1];
1481
        vlc = &huff_vlc[l];
1482

    
1483
        if(!l){
1484
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1485
            s_index += 2*j;
1486
            continue;
1487
        }
1488

    
1489
        /* read huffcode and compute each couple */
1490
        for(;j>0;j--) {
1491
            int exponent, x, y, v;
1492
            int pos= get_bits_count(&s->gb);
1493

    
1494
            if (pos >= end_pos){
1495
//                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1496
                switch_buffer(s, &pos, &end_pos, &end_pos2);
1497
//                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1498
                if(pos >= end_pos)
1499
                    break;
1500
            }
1501
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
1502

    
1503
            if(!y){
1504
                g->sb_hybrid[s_index  ] =
1505
                g->sb_hybrid[s_index+1] = 0;
1506
                s_index += 2;
1507
                continue;
1508
            }
1509

    
1510
            exponent= exponents[s_index];
1511

    
1512
            dprintf(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
1513
                    i, g->region_size[i] - j, x, y, exponent);
1514
            if(y&16){
1515
                x = y >> 5;
1516
                y = y & 0x0f;
1517
                if (x < 15){
1518
                    v = expval_table[ exponent ][ x ];
1519
//                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
1520
                }else{
1521
                    x += get_bitsz(&s->gb, linbits);
1522
                    v = l3_unscale(x, exponent);
1523
                }
1524
                if (get_bits1(&s->gb))
1525
                    v = -v;
1526
                g->sb_hybrid[s_index] = v;
1527
                if (y < 15){
1528
                    v = expval_table[ exponent ][ y ];
1529
                }else{
1530
                    y += get_bitsz(&s->gb, linbits);
1531
                    v = l3_unscale(y, exponent);
1532
                }
1533
                if (get_bits1(&s->gb))
1534
                    v = -v;
1535
                g->sb_hybrid[s_index+1] = v;
1536
            }else{
1537
                x = y >> 5;
1538
                y = y & 0x0f;
1539
                x += y;
1540
                if (x < 15){
1541
                    v = expval_table[ exponent ][ x ];
1542
                }else{
1543
                    x += get_bitsz(&s->gb, linbits);
1544
                    v = l3_unscale(x, exponent);
1545
                }
1546
                if (get_bits1(&s->gb))
1547
                    v = -v;
1548
                g->sb_hybrid[s_index+!!y] = v;
1549
                g->sb_hybrid[s_index+ !y] = 0;
1550
            }
1551
            s_index+=2;
1552
        }
1553
    }
1554

    
1555
    /* high frequencies */
1556
    vlc = &huff_quad_vlc[g->count1table_select];
1557
    last_pos=0;
1558
    while (s_index <= 572) {
1559
        int pos, code;
1560
        pos = get_bits_count(&s->gb);
1561
        if (pos >= end_pos) {
1562
            if (pos > end_pos2 && last_pos){
1563
                /* some encoders generate an incorrect size for this
1564
                   part. We must go back into the data */
1565
                s_index -= 4;
1566
                skip_bits_long(&s->gb, last_pos - pos);
1567
                av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1568
                if(s->error_recognition >= FF_ER_COMPLIANT)
1569
                    s_index=0;
1570
                break;
1571
            }
1572
//                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1573
            switch_buffer(s, &pos, &end_pos, &end_pos2);
1574
//                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1575
            if(pos >= end_pos)
1576
                break;
1577
        }
1578
        last_pos= pos;
1579

    
1580
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1581
        dprintf(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1582
        g->sb_hybrid[s_index+0]=
1583
        g->sb_hybrid[s_index+1]=
1584
        g->sb_hybrid[s_index+2]=
1585
        g->sb_hybrid[s_index+3]= 0;
1586
        while(code){
1587
            static const int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1588
            int v;
1589
            int pos= s_index+idxtab[code];
1590
            code ^= 8>>idxtab[code];
1591
            v = exp_table[ exponents[pos] ];
1592
//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1593
            if(get_bits1(&s->gb))
1594
                v = -v;
1595
            g->sb_hybrid[pos] = v;
1596
        }
1597
        s_index+=4;
1598
    }
1599
    /* skip extension bits */
1600
    bits_left = end_pos2 - get_bits_count(&s->gb);
1601
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1602
    if (bits_left < 0 && s->error_recognition >= FF_ER_COMPLIANT) {
1603
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1604
        s_index=0;
1605
    }else if(bits_left > 0 && s->error_recognition >= FF_ER_AGGRESSIVE){
1606
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1607
        s_index=0;
1608
    }
1609
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1610
    skip_bits_long(&s->gb, bits_left);
1611

    
1612
    i= get_bits_count(&s->gb);
1613
    switch_buffer(s, &i, &end_pos, &end_pos2);
1614

    
1615
    return 0;
1616
}
1617

    
1618
/* Reorder short blocks from bitstream order to interleaved order. It
1619
   would be faster to do it in parsing, but the code would be far more
1620
   complicated */
1621
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1622
{
1623
    int i, j, len;
1624
    int32_t *ptr, *dst, *ptr1;
1625
    int32_t tmp[576];
1626

    
1627
    if (g->block_type != 2)
1628
        return;
1629

    
1630
    if (g->switch_point) {
1631
        if (s->sample_rate_index != 8) {
1632
            ptr = g->sb_hybrid + 36;
1633
        } else {
1634
            ptr = g->sb_hybrid + 48;
1635
        }
1636
    } else {
1637
        ptr = g->sb_hybrid;
1638
    }
1639

    
1640
    for(i=g->short_start;i<13;i++) {
1641
        len = band_size_short[s->sample_rate_index][i];
1642
        ptr1 = ptr;
1643
        dst = tmp;
1644
        for(j=len;j>0;j--) {
1645
            *dst++ = ptr[0*len];
1646
            *dst++ = ptr[1*len];
1647
            *dst++ = ptr[2*len];
1648
            ptr++;
1649
        }
1650
        ptr+=2*len;
1651
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1652
    }
1653
}
1654

    
1655
#define ISQRT2 FIXR(0.70710678118654752440)
1656

    
1657
static void compute_stereo(MPADecodeContext *s,
1658
                           GranuleDef *g0, GranuleDef *g1)
1659
{
1660
    int i, j, k, l;
1661
    int32_t v1, v2;
1662
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1663
    int32_t (*is_tab)[16];
1664
    int32_t *tab0, *tab1;
1665
    int non_zero_found_short[3];
1666

    
1667
    /* intensity stereo */
1668
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1669
        if (!s->lsf) {
1670
            is_tab = is_table;
1671
            sf_max = 7;
1672
        } else {
1673
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1674
            sf_max = 16;
1675
        }
1676

    
1677
        tab0 = g0->sb_hybrid + 576;
1678
        tab1 = g1->sb_hybrid + 576;
1679

    
1680
        non_zero_found_short[0] = 0;
1681
        non_zero_found_short[1] = 0;
1682
        non_zero_found_short[2] = 0;
1683
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1684
        for(i = 12;i >= g1->short_start;i--) {
1685
            /* for last band, use previous scale factor */
1686
            if (i != 11)
1687
                k -= 3;
1688
            len = band_size_short[s->sample_rate_index][i];
1689
            for(l=2;l>=0;l--) {
1690
                tab0 -= len;
1691
                tab1 -= len;
1692
                if (!non_zero_found_short[l]) {
1693
                    /* test if non zero band. if so, stop doing i-stereo */
1694
                    for(j=0;j<len;j++) {
1695
                        if (tab1[j] != 0) {
1696
                            non_zero_found_short[l] = 1;
1697
                            goto found1;
1698
                        }
1699
                    }
1700
                    sf = g1->scale_factors[k + l];
1701
                    if (sf >= sf_max)
1702
                        goto found1;
1703

    
1704
                    v1 = is_tab[0][sf];
1705
                    v2 = is_tab[1][sf];
1706
                    for(j=0;j<len;j++) {
1707
                        tmp0 = tab0[j];
1708
                        tab0[j] = MULL(tmp0, v1, FRAC_BITS);
1709
                        tab1[j] = MULL(tmp0, v2, FRAC_BITS);
1710
                    }
1711
                } else {
1712
                found1:
1713
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1714
                        /* lower part of the spectrum : do ms stereo
1715
                           if enabled */
1716
                        for(j=0;j<len;j++) {
1717
                            tmp0 = tab0[j];
1718
                            tmp1 = tab1[j];
1719
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1720
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1721
                        }
1722
                    }
1723
                }
1724
            }
1725
        }
1726

    
1727
        non_zero_found = non_zero_found_short[0] |
1728
            non_zero_found_short[1] |
1729
            non_zero_found_short[2];
1730

    
1731
        for(i = g1->long_end - 1;i >= 0;i--) {
1732
            len = band_size_long[s->sample_rate_index][i];
1733
            tab0 -= len;
1734
            tab1 -= len;
1735
            /* test if non zero band. if so, stop doing i-stereo */
1736
            if (!non_zero_found) {
1737
                for(j=0;j<len;j++) {
1738
                    if (tab1[j] != 0) {
1739
                        non_zero_found = 1;
1740
                        goto found2;
1741
                    }
1742
                }
1743
                /* for last band, use previous scale factor */
1744
                k = (i == 21) ? 20 : i;
1745
                sf = g1->scale_factors[k];
1746
                if (sf >= sf_max)
1747
                    goto found2;
1748
                v1 = is_tab[0][sf];
1749
                v2 = is_tab[1][sf];
1750
                for(j=0;j<len;j++) {
1751
                    tmp0 = tab0[j];
1752
                    tab0[j] = MULL(tmp0, v1, FRAC_BITS);
1753
                    tab1[j] = MULL(tmp0, v2, FRAC_BITS);
1754
                }
1755
            } else {
1756
            found2:
1757
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1758
                    /* lower part of the spectrum : do ms stereo
1759
                       if enabled */
1760
                    for(j=0;j<len;j++) {
1761
                        tmp0 = tab0[j];
1762
                        tmp1 = tab1[j];
1763
                        tab0[j] = MULL(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1764
                        tab1[j] = MULL(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1765
                    }
1766
                }
1767
            }
1768
        }
1769
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1770
        /* ms stereo ONLY */
1771
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1772
           global gain */
1773
        tab0 = g0->sb_hybrid;
1774
        tab1 = g1->sb_hybrid;
1775
        for(i=0;i<576;i++) {
1776
            tmp0 = tab0[i];
1777
            tmp1 = tab1[i];
1778
            tab0[i] = tmp0 + tmp1;
1779
            tab1[i] = tmp0 - tmp1;
1780
        }
1781
    }
1782
}
1783

    
1784
static void compute_antialias_integer(MPADecodeContext *s,
1785
                              GranuleDef *g)
1786
{
1787
    int32_t *ptr, *csa;
1788
    int n, i;
1789

    
1790
    /* we antialias only "long" bands */
1791
    if (g->block_type == 2) {
1792
        if (!g->switch_point)
1793
            return;
1794
        /* XXX: check this for 8000Hz case */
1795
        n = 1;
1796
    } else {
1797
        n = SBLIMIT - 1;
1798
    }
1799

    
1800
    ptr = g->sb_hybrid + 18;
1801
    for(i = n;i > 0;i--) {
1802
        int tmp0, tmp1, tmp2;
1803
        csa = &csa_table[0][0];
1804
#define INT_AA(j) \
1805
            tmp0 = ptr[-1-j];\
1806
            tmp1 = ptr[   j];\
1807
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1808
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1809
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1810

    
1811
        INT_AA(0)
1812
        INT_AA(1)
1813
        INT_AA(2)
1814
        INT_AA(3)
1815
        INT_AA(4)
1816
        INT_AA(5)
1817
        INT_AA(6)
1818
        INT_AA(7)
1819

    
1820
        ptr += 18;
1821
    }
1822
}
1823

    
1824
static void compute_antialias_float(MPADecodeContext *s,
1825
                              GranuleDef *g)
1826
{
1827
    int32_t *ptr;
1828
    int n, i;
1829

    
1830
    /* we antialias only "long" bands */
1831
    if (g->block_type == 2) {
1832
        if (!g->switch_point)
1833
            return;
1834
        /* XXX: check this for 8000Hz case */
1835
        n = 1;
1836
    } else {
1837
        n = SBLIMIT - 1;
1838
    }
1839

    
1840
    ptr = g->sb_hybrid + 18;
1841
    for(i = n;i > 0;i--) {
1842
        float tmp0, tmp1;
1843
        float *csa = &csa_table_float[0][0];
1844
#define FLOAT_AA(j)\
1845
        tmp0= ptr[-1-j];\
1846
        tmp1= ptr[   j];\
1847
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1848
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1849

    
1850
        FLOAT_AA(0)
1851
        FLOAT_AA(1)
1852
        FLOAT_AA(2)
1853
        FLOAT_AA(3)
1854
        FLOAT_AA(4)
1855
        FLOAT_AA(5)
1856
        FLOAT_AA(6)
1857
        FLOAT_AA(7)
1858

    
1859
        ptr += 18;
1860
    }
1861
}
1862

    
1863
static void compute_imdct(MPADecodeContext *s,
1864
                          GranuleDef *g,
1865
                          int32_t *sb_samples,
1866
                          int32_t *mdct_buf)
1867
{
1868
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
1869
    int32_t out2[12];
1870
    int i, j, mdct_long_end, v, sblimit;
1871

    
1872
    /* find last non zero block */
1873
    ptr = g->sb_hybrid + 576;
1874
    ptr1 = g->sb_hybrid + 2 * 18;
1875
    while (ptr >= ptr1) {
1876
        ptr -= 6;
1877
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
1878
        if (v != 0)
1879
            break;
1880
    }
1881
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1882

    
1883
    if (g->block_type == 2) {
1884
        /* XXX: check for 8000 Hz */
1885
        if (g->switch_point)
1886
            mdct_long_end = 2;
1887
        else
1888
            mdct_long_end = 0;
1889
    } else {
1890
        mdct_long_end = sblimit;
1891
    }
1892

    
1893
    buf = mdct_buf;
1894
    ptr = g->sb_hybrid;
1895
    for(j=0;j<mdct_long_end;j++) {
1896
        /* apply window & overlap with previous buffer */
1897
        out_ptr = sb_samples + j;
1898
        /* select window */
1899
        if (g->switch_point && j < 2)
1900
            win1 = mdct_win[0];
1901
        else
1902
            win1 = mdct_win[g->block_type];
1903
        /* select frequency inversion */
1904
        win = win1 + ((4 * 36) & -(j & 1));
1905
        imdct36(out_ptr, buf, ptr, win);
1906
        out_ptr += 18*SBLIMIT;
1907
        ptr += 18;
1908
        buf += 18;
1909
    }
1910
    for(j=mdct_long_end;j<sblimit;j++) {
1911
        /* select frequency inversion */
1912
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
1913
        out_ptr = sb_samples + j;
1914

    
1915
        for(i=0; i<6; i++){
1916
            *out_ptr = buf[i];
1917
            out_ptr += SBLIMIT;
1918
        }
1919
        imdct12(out2, ptr + 0);
1920
        for(i=0;i<6;i++) {
1921
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
1922
            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
1923
            out_ptr += SBLIMIT;
1924
        }
1925
        imdct12(out2, ptr + 1);
1926
        for(i=0;i<6;i++) {
1927
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
1928
            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
1929
            out_ptr += SBLIMIT;
1930
        }
1931
        imdct12(out2, ptr + 2);
1932
        for(i=0;i<6;i++) {
1933
            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
1934
            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
1935
            buf[i + 6*2] = 0;
1936
        }
1937
        ptr += 18;
1938
        buf += 18;
1939
    }
1940
    /* zero bands */
1941
    for(j=sblimit;j<SBLIMIT;j++) {
1942
        /* overlap */
1943
        out_ptr = sb_samples + j;
1944
        for(i=0;i<18;i++) {
1945
            *out_ptr = buf[i];
1946
            buf[i] = 0;
1947
            out_ptr += SBLIMIT;
1948
        }
1949
        buf += 18;
1950
    }
1951
}
1952

    
1953
/* main layer3 decoding function */
1954
static int mp_decode_layer3(MPADecodeContext *s)
1955
{
1956
    int nb_granules, main_data_begin, private_bits;
1957
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1958
    GranuleDef granules[2][2], *g;
1959
    int16_t exponents[576];
1960

    
1961
    /* read side info */
1962
    if (s->lsf) {
1963
        main_data_begin = get_bits(&s->gb, 8);
1964
        private_bits = get_bits(&s->gb, s->nb_channels);
1965
        nb_granules = 1;
1966
    } else {
1967
        main_data_begin = get_bits(&s->gb, 9);
1968
        if (s->nb_channels == 2)
1969
            private_bits = get_bits(&s->gb, 3);
1970
        else
1971
            private_bits = get_bits(&s->gb, 5);
1972
        nb_granules = 2;
1973
        for(ch=0;ch<s->nb_channels;ch++) {
1974
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
1975
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
1976
        }
1977
    }
1978

    
1979
    for(gr=0;gr<nb_granules;gr++) {
1980
        for(ch=0;ch<s->nb_channels;ch++) {
1981
            dprintf(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1982
            g = &granules[ch][gr];
1983
            g->part2_3_length = get_bits(&s->gb, 12);
1984
            g->big_values = get_bits(&s->gb, 9);
1985
            if(g->big_values > 288){
1986
                av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1987
                return -1;
1988
            }
1989

    
1990
            g->global_gain = get_bits(&s->gb, 8);
1991
            /* if MS stereo only is selected, we precompute the
1992
               1/sqrt(2) renormalization factor */
1993
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1994
                MODE_EXT_MS_STEREO)
1995
                g->global_gain -= 2;
1996
            if (s->lsf)
1997
                g->scalefac_compress = get_bits(&s->gb, 9);
1998
            else
1999
                g->scalefac_compress = get_bits(&s->gb, 4);
2000
            blocksplit_flag = get_bits1(&s->gb);
2001
            if (blocksplit_flag) {
2002
                g->block_type = get_bits(&s->gb, 2);
2003
                if (g->block_type == 0){
2004
                    av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
2005
                    return -1;
2006
                }
2007
                g->switch_point = get_bits1(&s->gb);
2008
                for(i=0;i<2;i++)
2009
                    g->table_select[i] = get_bits(&s->gb, 5);
2010
                for(i=0;i<3;i++)
2011
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
2012
                ff_init_short_region(s, g);
2013
            } else {
2014
                int region_address1, region_address2;
2015
                g->block_type = 0;
2016
                g->switch_point = 0;
2017
                for(i=0;i<3;i++)
2018
                    g->table_select[i] = get_bits(&s->gb, 5);
2019
                /* compute huffman coded region sizes */
2020
                region_address1 = get_bits(&s->gb, 4);
2021
                region_address2 = get_bits(&s->gb, 3);
2022
                dprintf(s->avctx, "region1=%d region2=%d\n",
2023
                        region_address1, region_address2);
2024
                ff_init_long_region(s, g, region_address1, region_address2);
2025
            }
2026
            ff_region_offset2size(g);
2027
            ff_compute_band_indexes(s, g);
2028

    
2029
            g->preflag = 0;
2030
            if (!s->lsf)
2031
                g->preflag = get_bits1(&s->gb);
2032
            g->scalefac_scale = get_bits1(&s->gb);
2033
            g->count1table_select = get_bits1(&s->gb);
2034
            dprintf(s->avctx, "block_type=%d switch_point=%d\n",
2035
                    g->block_type, g->switch_point);
2036
        }
2037
    }
2038

    
2039
  if (!s->adu_mode) {
2040
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2041
    assert((get_bits_count(&s->gb) & 7) == 0);
2042
    /* now we get bits from the main_data_begin offset */
2043
    dprintf(s->avctx, "seekback: %d\n", main_data_begin);
2044
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2045

    
2046
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2047
    s->in_gb= s->gb;
2048
        init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
2049
        skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
2050
  }
2051

    
2052
    for(gr=0;gr<nb_granules;gr++) {
2053
        for(ch=0;ch<s->nb_channels;ch++) {
2054
            g = &granules[ch][gr];
2055
            if(get_bits_count(&s->gb)<0){
2056
                av_log(s->avctx, AV_LOG_ERROR, "mdb:%d, lastbuf:%d skipping granule %d\n",
2057
                                            main_data_begin, s->last_buf_size, gr);
2058
                skip_bits_long(&s->gb, g->part2_3_length);
2059
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
2060
                if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer){
2061
                    skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
2062
                    s->gb= s->in_gb;
2063
                    s->in_gb.buffer=NULL;
2064
                }
2065
                continue;
2066
            }
2067

    
2068
            bits_pos = get_bits_count(&s->gb);
2069

    
2070
            if (!s->lsf) {
2071
                uint8_t *sc;
2072
                int slen, slen1, slen2;
2073

    
2074
                /* MPEG1 scale factors */
2075
                slen1 = slen_table[0][g->scalefac_compress];
2076
                slen2 = slen_table[1][g->scalefac_compress];
2077
                dprintf(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
2078
                if (g->block_type == 2) {
2079
                    n = g->switch_point ? 17 : 18;
2080
                    j = 0;
2081
                    if(slen1){
2082
                        for(i=0;i<n;i++)
2083
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
2084
                    }else{
2085
                        for(i=0;i<n;i++)
2086
                            g->scale_factors[j++] = 0;
2087
                    }
2088
                    if(slen2){
2089
                        for(i=0;i<18;i++)
2090
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
2091
                        for(i=0;i<3;i++)
2092
                            g->scale_factors[j++] = 0;
2093
                    }else{
2094
                        for(i=0;i<21;i++)
2095
                            g->scale_factors[j++] = 0;
2096
                    }
2097
                } else {
2098
                    sc = granules[ch][0].scale_factors;
2099
                    j = 0;
2100
                    for(k=0;k<4;k++) {
2101
                        n = (k == 0 ? 6 : 5);
2102
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2103
                            slen = (k < 2) ? slen1 : slen2;
2104
                            if(slen){
2105
                                for(i=0;i<n;i++)
2106
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
2107
                            }else{
2108
                                for(i=0;i<n;i++)
2109
                                    g->scale_factors[j++] = 0;
2110
                            }
2111
                        } else {
2112
                            /* simply copy from last granule */
2113
                            for(i=0;i<n;i++) {
2114
                                g->scale_factors[j] = sc[j];
2115
                                j++;
2116
                            }
2117
                        }
2118
                    }
2119
                    g->scale_factors[j++] = 0;
2120
                }
2121
            } else {
2122
                int tindex, tindex2, slen[4], sl, sf;
2123

    
2124
                /* LSF scale factors */
2125
                if (g->block_type == 2) {
2126
                    tindex = g->switch_point ? 2 : 1;
2127
                } else {
2128
                    tindex = 0;
2129
                }
2130
                sf = g->scalefac_compress;
2131
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2132
                    /* intensity stereo case */
2133
                    sf >>= 1;
2134
                    if (sf < 180) {
2135
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2136
                        tindex2 = 3;
2137
                    } else if (sf < 244) {
2138
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2139
                        tindex2 = 4;
2140
                    } else {
2141
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2142
                        tindex2 = 5;
2143
                    }
2144
                } else {
2145
                    /* normal case */
2146
                    if (sf < 400) {
2147
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2148
                        tindex2 = 0;
2149
                    } else if (sf < 500) {
2150
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2151
                        tindex2 = 1;
2152
                    } else {
2153
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2154
                        tindex2 = 2;
2155
                        g->preflag = 1;
2156
                    }
2157
                }
2158

    
2159
                j = 0;
2160
                for(k=0;k<4;k++) {
2161
                    n = lsf_nsf_table[tindex2][tindex][k];
2162
                    sl = slen[k];
2163
                    if(sl){
2164
                        for(i=0;i<n;i++)
2165
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
2166
                    }else{
2167
                        for(i=0;i<n;i++)
2168
                            g->scale_factors[j++] = 0;
2169
                    }
2170
                }
2171
                /* XXX: should compute exact size */
2172
                for(;j<40;j++)
2173
                    g->scale_factors[j] = 0;
2174
            }
2175

    
2176
            exponents_from_scale_factors(s, g, exponents);
2177

    
2178
            /* read Huffman coded residue */
2179
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
2180
        } /* ch */
2181

    
2182
        if (s->nb_channels == 2)
2183
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2184

    
2185
        for(ch=0;ch<s->nb_channels;ch++) {
2186
            g = &granules[ch][gr];
2187

    
2188
            reorder_block(s, g);
2189
            s->compute_antialias(s, g);
2190
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2191
        }
2192
    } /* gr */
2193
    if(get_bits_count(&s->gb)<0)
2194
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
2195
    return nb_granules * 18;
2196
}
2197

    
2198
static int mp_decode_frame(MPADecodeContext *s,
2199
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
2200
{
2201
    int i, nb_frames, ch;
2202
    OUT_INT *samples_ptr;
2203

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

    
2206
    /* skip error protection field */
2207
    if (s->error_protection)
2208
        skip_bits(&s->gb, 16);
2209

    
2210
    dprintf(s->avctx, "frame %d:\n", s->frame_count);
2211
    switch(s->layer) {
2212
    case 1:
2213
        s->avctx->frame_size = 384;
2214
        nb_frames = mp_decode_layer1(s);
2215
        break;
2216
    case 2:
2217
        s->avctx->frame_size = 1152;
2218
        nb_frames = mp_decode_layer2(s);
2219
        break;
2220
    case 3:
2221
        s->avctx->frame_size = s->lsf ? 576 : 1152;
2222
    default:
2223
        nb_frames = mp_decode_layer3(s);
2224

    
2225
        s->last_buf_size=0;
2226
        if(s->in_gb.buffer){
2227
            align_get_bits(&s->gb);
2228
            i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2229
            if(i >= 0 && i <= BACKSTEP_SIZE){
2230
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
2231
                s->last_buf_size=i;
2232
            }else
2233
                av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
2234
            s->gb= s->in_gb;
2235
            s->in_gb.buffer= NULL;
2236
        }
2237

    
2238
        align_get_bits(&s->gb);
2239
        assert((get_bits_count(&s->gb) & 7) == 0);
2240
        i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2241

    
2242
        if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
2243
            if(i<0)
2244
                av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
2245
            i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
2246
        }
2247
        assert(i <= buf_size - HEADER_SIZE && i>= 0);
2248
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
2249
        s->last_buf_size += i;
2250

    
2251
        break;
2252
    }
2253

    
2254
    /* apply the synthesis filter */
2255
    for(ch=0;ch<s->nb_channels;ch++) {
2256
        samples_ptr = samples + ch;
2257
        for(i=0;i<nb_frames;i++) {
2258
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2259
                         window, &s->dither_state,
2260
                         samples_ptr, s->nb_channels,
2261
                         s->sb_samples[ch][i]);
2262
            samples_ptr += 32 * s->nb_channels;
2263
        }
2264
    }
2265

    
2266
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2267
}
2268

    
2269
static int decode_frame(AVCodecContext * avctx,
2270
                        void *data, int *data_size,
2271
                        const uint8_t * buf, int buf_size)
2272
{
2273
    MPADecodeContext *s = avctx->priv_data;
2274
    uint32_t header;
2275
    int out_size;
2276
    OUT_INT *out_samples = data;
2277

    
2278
retry:
2279
    if(buf_size < HEADER_SIZE)
2280
        return -1;
2281

    
2282
    header = AV_RB32(buf);
2283
    if(ff_mpa_check_header(header) < 0){
2284
        buf++;
2285
//        buf_size--;
2286
        av_log(avctx, AV_LOG_ERROR, "Header missing skipping one byte.\n");
2287
        goto retry;
2288
    }
2289

    
2290
    if (ff_mpegaudio_decode_header(s, header) == 1) {
2291
        /* free format: prepare to compute frame size */
2292
        s->frame_size = -1;
2293
        return -1;
2294
    }
2295
    /* update codec info */
2296
    avctx->channels = s->nb_channels;
2297
    avctx->bit_rate = s->bit_rate;
2298
    avctx->sub_id = s->layer;
2299

    
2300
    if(s->frame_size<=0 || s->frame_size > buf_size){
2301
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2302
        return -1;
2303
    }else if(s->frame_size < buf_size){
2304
        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
2305
        buf_size= s->frame_size;
2306
    }
2307

    
2308
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2309
    if(out_size>=0){
2310
        *data_size = out_size;
2311
        avctx->sample_rate = s->sample_rate;
2312
        //FIXME maybe move the other codec info stuff from above here too
2313
    }else
2314
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed
2315
    s->frame_size = 0;
2316
    return buf_size;
2317
}
2318

    
2319
static void flush(AVCodecContext *avctx){
2320
    MPADecodeContext *s = avctx->priv_data;
2321
    memset(s->synth_buf, 0, sizeof(s->synth_buf));
2322
    s->last_buf_size= 0;
2323
}
2324

    
2325
#ifdef CONFIG_MP3ADU_DECODER
2326
static int decode_frame_adu(AVCodecContext * avctx,
2327
                        void *data, int *data_size,
2328
                        const uint8_t * buf, int buf_size)
2329
{
2330
    MPADecodeContext *s = avctx->priv_data;
2331
    uint32_t header;
2332
    int len, out_size;
2333
    OUT_INT *out_samples = data;
2334

    
2335
    len = buf_size;
2336

    
2337
    // Discard too short frames
2338
    if (buf_size < HEADER_SIZE) {
2339
        *data_size = 0;
2340
        return buf_size;
2341
    }
2342

    
2343

    
2344
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2345
        len = MPA_MAX_CODED_FRAME_SIZE;
2346

    
2347
    // Get header and restore sync word
2348
    header = AV_RB32(buf) | 0xffe00000;
2349

    
2350
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2351
        *data_size = 0;
2352
        return buf_size;
2353
    }
2354

    
2355
    ff_mpegaudio_decode_header(s, header);
2356
    /* update codec info */
2357
    avctx->sample_rate = s->sample_rate;
2358
    avctx->channels = s->nb_channels;
2359
    avctx->bit_rate = s->bit_rate;
2360
    avctx->sub_id = s->layer;
2361

    
2362
    s->frame_size = len;
2363

    
2364
    if (avctx->parse_only) {
2365
        out_size = buf_size;
2366
    } else {
2367
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2368
    }
2369

    
2370
    *data_size = out_size;
2371
    return buf_size;
2372
}
2373
#endif /* CONFIG_MP3ADU_DECODER */
2374

    
2375
#ifdef CONFIG_MP3ON4_DECODER
2376

    
2377
/**
2378
 * Context for MP3On4 decoder
2379
 */
2380
typedef struct MP3On4DecodeContext {
2381
    int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
2382
    int syncword; ///< syncword patch
2383
    const uint8_t *coff; ///< channels offsets in output buffer
2384
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
2385
} MP3On4DecodeContext;
2386

    
2387
#include "mpeg4audio.h"
2388

    
2389
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2390
static const uint8_t mp3Frames[8] = {0,1,1,2,3,3,4,5};   /* number of mp3 decoder instances */
2391
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2392
static const uint8_t chan_offset[8][5] = {
2393
    {0},
2394
    {0},            // C
2395
    {0},            // FLR
2396
    {2,0},          // C FLR
2397
    {2,0,3},        // C FLR BS
2398
    {4,0,2},        // C FLR BLRS
2399
    {4,0,2,5},      // C FLR BLRS LFE
2400
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2401
};
2402

    
2403

    
2404
static int decode_init_mp3on4(AVCodecContext * avctx)
2405
{
2406
    MP3On4DecodeContext *s = avctx->priv_data;
2407
    MPEG4AudioConfig cfg;
2408
    int i;
2409

    
2410
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2411
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2412
        return -1;
2413
    }
2414

    
2415
    ff_mpeg4audio_get_config(&cfg, avctx->extradata, avctx->extradata_size);
2416
    if (!cfg.chan_config || cfg.chan_config > 7) {
2417
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2418
        return -1;
2419
    }
2420
    s->frames = mp3Frames[cfg.chan_config];
2421
    s->coff = chan_offset[cfg.chan_config];
2422
    avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
2423

    
2424
    if (cfg.sample_rate < 16000)
2425
        s->syncword = 0xffe00000;
2426
    else
2427
        s->syncword = 0xfff00000;
2428

    
2429
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2430
     * We replace avctx->priv_data with the context of the first decoder so that
2431
     * decode_init() does not have to be changed.
2432
     * Other decoders will be initialized here copying data from the first context
2433
     */
2434
    // Allocate zeroed memory for the first decoder context
2435
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2436
    // Put decoder context in place to make init_decode() happy
2437
    avctx->priv_data = s->mp3decctx[0];
2438
    decode_init(avctx);
2439
    // Restore mp3on4 context pointer
2440
    avctx->priv_data = s;
2441
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2442

    
2443
    /* Create a separate codec/context for each frame (first is already ok).
2444
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2445
     */
2446
    for (i = 1; i < s->frames; i++) {
2447
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2448
        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2449
        s->mp3decctx[i]->adu_mode = 1;
2450
        s->mp3decctx[i]->avctx = avctx;
2451
    }
2452

    
2453
    return 0;
2454
}
2455

    
2456

    
2457
static int decode_close_mp3on4(AVCodecContext * avctx)
2458
{
2459
    MP3On4DecodeContext *s = avctx->priv_data;
2460
    int i;
2461

    
2462
    for (i = 0; i < s->frames; i++)
2463
        if (s->mp3decctx[i])
2464
            av_free(s->mp3decctx[i]);
2465

    
2466
    return 0;
2467
}
2468

    
2469

    
2470
static int decode_frame_mp3on4(AVCodecContext * avctx,
2471
                        void *data, int *data_size,
2472
                        const uint8_t * buf, int buf_size)
2473
{
2474
    MP3On4DecodeContext *s = avctx->priv_data;
2475
    MPADecodeContext *m;
2476
    int fsize, len = buf_size, out_size = 0;
2477
    uint32_t header;
2478
    OUT_INT *out_samples = data;
2479
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2480
    OUT_INT *outptr, *bp;
2481
    int fr, j, n;
2482

    
2483
    *data_size = 0;
2484
    // Discard too short frames
2485
    if (buf_size < HEADER_SIZE)
2486
        return -1;
2487

    
2488
    // If only one decoder interleave is not needed
2489
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2490

    
2491
    avctx->bit_rate = 0;
2492

    
2493
    for (fr = 0; fr < s->frames; fr++) {
2494
        fsize = AV_RB16(buf) >> 4;
2495
        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
2496
        m = s->mp3decctx[fr];
2497
        assert (m != NULL);
2498

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

    
2501
        if (ff_mpa_check_header(header) < 0) // Bad header, discard block
2502
            break;
2503

    
2504
        ff_mpegaudio_decode_header(m, header);
2505
        out_size += mp_decode_frame(m, outptr, buf, fsize);
2506
        buf += fsize;
2507
        len -= fsize;
2508

    
2509
        if(s->frames > 1) {
2510
            n = m->avctx->frame_size*m->nb_channels;
2511
            /* interleave output data */
2512
            bp = out_samples + s->coff[fr];
2513
            if(m->nb_channels == 1) {
2514
                for(j = 0; j < n; j++) {
2515
                    *bp = decoded_buf[j];
2516
                    bp += avctx->channels;
2517
                }
2518
            } else {
2519
                for(j = 0; j < n; j++) {
2520
                    bp[0] = decoded_buf[j++];
2521
                    bp[1] = decoded_buf[j];
2522
                    bp += avctx->channels;
2523
                }
2524
            }
2525
        }
2526
        avctx->bit_rate += m->bit_rate;
2527
    }
2528

    
2529
    /* update codec info */
2530
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2531

    
2532
    *data_size = out_size;
2533
    return buf_size;
2534
}
2535
#endif /* CONFIG_MP3ON4_DECODER */
2536

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