Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 191e8ca7

History | View | Annotate | Download (83.8 KB)

1
/*
2
 * MPEG Audio decoder
3
 * Copyright (c) 2001, 2002 Fabrice Bellard.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
 */
19

    
20
/**
21
 * @file mpegaudiodec.c
22
 * MPEG Audio decoder.
23
 */
24

    
25
//#define DEBUG
26
#include "avcodec.h"
27
#include "bitstream.h"
28
#include "dsputil.h"
29

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

    
36
/* define USE_HIGHPRECISION to have a bit exact (but slower) mpeg
37
   audio decoder */
38
#ifdef CONFIG_MPEGAUDIO_HP
39
#   define USE_HIGHPRECISION
40
#endif
41

    
42
#include "mpegaudio.h"
43

    
44
#include "mathops.h"
45

    
46
#define FRAC_ONE    (1 << FRAC_BITS)
47

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

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

    
55
/****************/
56

    
57
#define HEADER_SIZE 4
58
#define BACKSTEP_SIZE 512
59
#define EXTRABYTES 24
60

    
61
struct GranuleDef;
62

    
63
typedef struct MPADecodeContext {
64
    DECLARE_ALIGNED_8(uint8_t, last_buf[2*BACKSTEP_SIZE + EXTRABYTES]);
65
    int last_buf_size;
66
    int frame_size;
67
    /* next header (used in free format parsing) */
68
    uint32_t free_format_next_header;
69
    int error_protection;
70
    int layer;
71
    int sample_rate;
72
    int sample_rate_index; /* between 0 and 8 */
73
    int bit_rate;
74
    GetBitContext gb;
75
    GetBitContext in_gb;
76
    int nb_channels;
77
    int mode;
78
    int mode_ext;
79
    int lsf;
80
    MPA_INT synth_buf[MPA_MAX_CHANNELS][512 * 2] __attribute__((aligned(16)));
81
    int synth_buf_offset[MPA_MAX_CHANNELS];
82
    int32_t sb_samples[MPA_MAX_CHANNELS][36][SBLIMIT] __attribute__((aligned(16)));
83
    int32_t mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
84
#ifdef DEBUG
85
    int frame_count;
86
#endif
87
    void (*compute_antialias)(struct MPADecodeContext *s, struct GranuleDef *g);
88
    int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
89
    int dither_state;
90
} MPADecodeContext;
91

    
92
/**
93
 * Context for MP3On4 decoder
94
 */
95
typedef struct MP3On4DecodeContext {
96
    int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
97
    int chan_cfg; ///< channel config number
98
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
99
} MP3On4DecodeContext;
100

    
101
/* layer 3 "granule" */
102
typedef struct GranuleDef {
103
    uint8_t scfsi;
104
    int part2_3_length;
105
    int big_values;
106
    int global_gain;
107
    int scalefac_compress;
108
    uint8_t block_type;
109
    uint8_t switch_point;
110
    int table_select[3];
111
    int subblock_gain[3];
112
    uint8_t scalefac_scale;
113
    uint8_t count1table_select;
114
    int region_size[3]; /* number of huffman codes in each region */
115
    int preflag;
116
    int short_start, long_end; /* long/short band indexes */
117
    uint8_t scale_factors[40];
118
    int32_t sb_hybrid[SBLIMIT * 18]; /* 576 samples */
119
} GranuleDef;
120

    
121
#define MODE_EXT_MS_STEREO 2
122
#define MODE_EXT_I_STEREO  1
123

    
124
/* layer 3 huffman tables */
125
typedef struct HuffTable {
126
    int xsize;
127
    const uint8_t *bits;
128
    const uint16_t *codes;
129
} HuffTable;
130

    
131
#include "mpegaudiodectab.h"
132

    
133
static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
134
static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
135

    
136
/* vlc structure for decoding layer 3 huffman tables */
137
static VLC huff_vlc[16];
138
static VLC huff_quad_vlc[2];
139
/* computed from band_size_long */
140
static uint16_t band_index_long[9][23];
141
/* XXX: free when all decoders are closed */
142
#define TABLE_4_3_SIZE (8191 + 16)*4
143
static int8_t  *table_4_3_exp;
144
static uint32_t *table_4_3_value;
145
static uint32_t exp_table[512];
146
static uint32_t expval_table[512][16];
147
/* intensity stereo coef table */
148
static int32_t is_table[2][16];
149
static int32_t is_table_lsf[2][2][16];
150
static int32_t csa_table[8][4];
151
static float csa_table_float[8][4];
152
static int32_t mdct_win[8][36];
153

    
154
/* lower 2 bits: modulo 3, higher bits: shift */
155
static uint16_t scale_factor_modshift[64];
156
/* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
157
static int32_t scale_factor_mult[15][3];
158
/* mult table for layer 2 group quantization */
159

    
160
#define SCALE_GEN(v) \
161
{ FIXR(1.0 * (v)), FIXR(0.7937005259 * (v)), FIXR(0.6299605249 * (v)) }
162

    
163
static const int32_t scale_factor_mult2[3][3] = {
164
    SCALE_GEN(4.0 / 3.0), /* 3 steps */
165
    SCALE_GEN(4.0 / 5.0), /* 5 steps */
166
    SCALE_GEN(4.0 / 9.0), /* 9 steps */
167
};
168

    
169
static MPA_INT window[512] __attribute__((aligned(16)));
170

    
171
/* layer 1 unscaling */
172
/* n = number of bits of the mantissa minus 1 */
173
static inline int l1_unscale(int n, int mant, int scale_factor)
174
{
175
    int shift, mod;
176
    int64_t val;
177

    
178
    shift = scale_factor_modshift[scale_factor];
179
    mod = shift & 3;
180
    shift >>= 2;
181
    val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
182
    shift += n;
183
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
184
    return (int)((val + (1LL << (shift - 1))) >> shift);
185
}
186

    
187
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
188
{
189
    int shift, mod, val;
190

    
191
    shift = scale_factor_modshift[scale_factor];
192
    mod = shift & 3;
193
    shift >>= 2;
194

    
195
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
196
    /* NOTE: at this point, 0 <= shift <= 21 */
197
    if (shift > 0)
198
        val = (val + (1 << (shift - 1))) >> shift;
199
    return val;
200
}
201

    
202
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
203
static inline int l3_unscale(int value, int exponent)
204
{
205
    unsigned int m;
206
    int e;
207

    
208
    e = table_4_3_exp  [4*value + (exponent&3)];
209
    m = table_4_3_value[4*value + (exponent&3)];
210
    e -= (exponent >> 2);
211
    assert(e>=1);
212
    if (e > 31)
213
        return 0;
214
    m = (m + (1 << (e-1))) >> e;
215

    
216
    return m;
217
}
218

    
219
/* all integer n^(4/3) computation code */
220
#define DEV_ORDER 13
221

    
222
#define POW_FRAC_BITS 24
223
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
224
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
225
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
226

    
227
static int dev_4_3_coefs[DEV_ORDER];
228

    
229
#if 0 /* unused */
230
static int pow_mult3[3] = {
231
    POW_FIX(1.0),
232
    POW_FIX(1.25992104989487316476),
233
    POW_FIX(1.58740105196819947474),
234
};
235
#endif
236

    
237
static void int_pow_init(void)
238
{
239
    int i, a;
240

    
241
    a = POW_FIX(1.0);
242
    for(i=0;i<DEV_ORDER;i++) {
243
        a = POW_MULL(a, POW_FIX(4.0 / 3.0) - i * POW_FIX(1.0)) / (i + 1);
244
        dev_4_3_coefs[i] = a;
245
    }
246
}
247

    
248
#if 0 /* unused, remove? */
249
/* return the mantissa and the binary exponent */
250
static int int_pow(int i, int *exp_ptr)
251
{
252
    int e, er, eq, j;
253
    int a, a1;
254

255
    /* renormalize */
256
    a = i;
257
    e = POW_FRAC_BITS;
258
    while (a < (1 << (POW_FRAC_BITS - 1))) {
259
        a = a << 1;
260
        e--;
261
    }
262
    a -= (1 << POW_FRAC_BITS);
263
    a1 = 0;
264
    for(j = DEV_ORDER - 1; j >= 0; j--)
265
        a1 = POW_MULL(a, dev_4_3_coefs[j] + a1);
266
    a = (1 << POW_FRAC_BITS) + a1;
267
    /* exponent compute (exact) */
268
    e = e * 4;
269
    er = e % 3;
270
    eq = e / 3;
271
    a = POW_MULL(a, pow_mult3[er]);
272
    while (a >= 2 * POW_FRAC_ONE) {
273
        a = a >> 1;
274
        eq++;
275
    }
276
    /* convert to float */
277
    while (a < POW_FRAC_ONE) {
278
        a = a << 1;
279
        eq--;
280
    }
281
    /* now POW_FRAC_ONE <= a < 2 * POW_FRAC_ONE */
282
#if POW_FRAC_BITS > FRAC_BITS
283
    a = (a + (1 << (POW_FRAC_BITS - FRAC_BITS - 1))) >> (POW_FRAC_BITS - FRAC_BITS);
284
    /* correct overflow */
285
    if (a >= 2 * (1 << FRAC_BITS)) {
286
        a = a >> 1;
287
        eq++;
288
    }
289
#endif
290
    *exp_ptr = eq;
291
    return a;
292
}
293
#endif
294

    
295
static int decode_init(AVCodecContext * avctx)
296
{
297
    MPADecodeContext *s = avctx->priv_data;
298
    static int init=0;
299
    int i, j, k;
300

    
301
#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
302
    avctx->sample_fmt= SAMPLE_FMT_S32;
303
#else
304
    avctx->sample_fmt= SAMPLE_FMT_S16;
305
#endif
306

    
307
    if(avctx->antialias_algo != FF_AA_FLOAT)
308
        s->compute_antialias= compute_antialias_integer;
309
    else
310
        s->compute_antialias= compute_antialias_float;
311

    
312
    if (!init && !avctx->parse_only) {
313
        /* scale factors table for layer 1/2 */
314
        for(i=0;i<64;i++) {
315
            int shift, mod;
316
            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
317
            shift = (i / 3);
318
            mod = i % 3;
319
            scale_factor_modshift[i] = mod | (shift << 2);
320
        }
321

    
322
        /* scale factor multiply for layer 1 */
323
        for(i=0;i<15;i++) {
324
            int n, norm;
325
            n = i + 2;
326
            norm = ((int64_t_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
327
            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm);
328
            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm);
329
            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm);
330
            dprintf("%d: norm=%x s=%x %x %x\n",
331
                    i, norm,
332
                    scale_factor_mult[i][0],
333
                    scale_factor_mult[i][1],
334
                    scale_factor_mult[i][2]);
335
        }
336

    
337
        ff_mpa_synth_init(window);
338

    
339
        /* huffman decode tables */
340
        for(i=1;i<16;i++) {
341
            const HuffTable *h = &mpa_huff_tables[i];
342
            int xsize, x, y;
343
            unsigned int n;
344
            uint8_t  tmp_bits [512];
345
            uint16_t tmp_codes[512];
346

    
347
            memset(tmp_bits , 0, sizeof(tmp_bits ));
348
            memset(tmp_codes, 0, sizeof(tmp_codes));
349

    
350
            xsize = h->xsize;
351
            n = xsize * xsize;
352

    
353
            j = 0;
354
            for(x=0;x<xsize;x++) {
355
                for(y=0;y<xsize;y++){
356
                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
357
                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
358
                }
359
            }
360

    
361
            /* XXX: fail test */
362
            init_vlc(&huff_vlc[i], 7, 512,
363
                     tmp_bits, 1, 1, tmp_codes, 2, 2, 1);
364
        }
365
        for(i=0;i<2;i++) {
366
            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
367
                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);
368
        }
369

    
370
        for(i=0;i<9;i++) {
371
            k = 0;
372
            for(j=0;j<22;j++) {
373
                band_index_long[i][j] = k;
374
                k += band_size_long[i][j];
375
            }
376
            band_index_long[i][22] = k;
377
        }
378

    
379
        /* compute n ^ (4/3) and store it in mantissa/exp format */
380
        table_4_3_exp= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_exp[0]));
381
        if(!table_4_3_exp)
382
            return -1;
383
        table_4_3_value= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_value[0]));
384
        if(!table_4_3_value)
385
            return -1;
386

    
387
        int_pow_init();
388
        for(i=1;i<TABLE_4_3_SIZE;i++) {
389
            double f, fm;
390
            int e, m;
391
            f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);
392
            fm = frexp(f, &e);
393
            m = (uint32_t)(fm*(1LL<<31) + 0.5);
394
            e+= FRAC_BITS - 31 + 5 - 100;
395

    
396
            /* normalized to FRAC_BITS */
397
            table_4_3_value[i] = m;
398
//            av_log(NULL, AV_LOG_DEBUG, "%d %d %f\n", i, m, pow((double)i, 4.0 / 3.0));
399
            table_4_3_exp[i] = -e;
400
        }
401
        for(i=0; i<512*16; i++){
402
            int exponent= (i>>4);
403
            double f= pow(i&15, 4.0 / 3.0) * pow(2, (exponent-400)*0.25 + FRAC_BITS + 5);
404
            expval_table[exponent][i&15]= llrint(f);
405
            if((i&15)==1)
406
                exp_table[exponent]= llrint(f);
407
        }
408

    
409
        for(i=0;i<7;i++) {
410
            float f;
411
            int v;
412
            if (i != 6) {
413
                f = tan((double)i * M_PI / 12.0);
414
                v = FIXR(f / (1.0 + f));
415
            } else {
416
                v = FIXR(1.0);
417
            }
418
            is_table[0][i] = v;
419
            is_table[1][6 - i] = v;
420
        }
421
        /* invalid values */
422
        for(i=7;i<16;i++)
423
            is_table[0][i] = is_table[1][i] = 0.0;
424

    
425
        for(i=0;i<16;i++) {
426
            double f;
427
            int e, k;
428

    
429
            for(j=0;j<2;j++) {
430
                e = -(j + 1) * ((i + 1) >> 1);
431
                f = pow(2.0, e / 4.0);
432
                k = i & 1;
433
                is_table_lsf[j][k ^ 1][i] = FIXR(f);
434
                is_table_lsf[j][k][i] = FIXR(1.0);
435
                dprintf("is_table_lsf %d %d: %x %x\n",
436
                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
437
            }
438
        }
439

    
440
        for(i=0;i<8;i++) {
441
            float ci, cs, ca;
442
            ci = ci_table[i];
443
            cs = 1.0 / sqrt(1.0 + ci * ci);
444
            ca = cs * ci;
445
            csa_table[i][0] = FIXHR(cs/4);
446
            csa_table[i][1] = FIXHR(ca/4);
447
            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
448
            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
449
            csa_table_float[i][0] = cs;
450
            csa_table_float[i][1] = ca;
451
            csa_table_float[i][2] = ca + cs;
452
            csa_table_float[i][3] = ca - cs;
453
//            printf("%d %d %d %d\n", FIX(cs), FIX(cs-1), FIX(ca), FIX(cs)-FIX(ca));
454
//            av_log(NULL, AV_LOG_DEBUG,"%f %f %f %f\n", cs, ca, ca+cs, ca-cs);
455
        }
456

    
457
        /* compute mdct windows */
458
        for(i=0;i<36;i++) {
459
            for(j=0; j<4; j++){
460
                double d;
461

    
462
                if(j==2 && i%3 != 1)
463
                    continue;
464

    
465
                d= sin(M_PI * (i + 0.5) / 36.0);
466
                if(j==1){
467
                    if     (i>=30) d= 0;
468
                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);
469
                    else if(i>=18) d= 1;
470
                }else if(j==3){
471
                    if     (i<  6) d= 0;
472
                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);
473
                    else if(i< 18) d= 1;
474
                }
475
                //merge last stage of imdct into the window coefficients
476
                d*= 0.5 / cos(M_PI*(2*i + 19)/72);
477

    
478
                if(j==2)
479
                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));
480
                else
481
                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));
482
//                av_log(NULL, AV_LOG_DEBUG, "%2d %d %f\n", i,j,d / (1<<5));
483
            }
484
        }
485

    
486
        /* NOTE: we do frequency inversion adter the MDCT by changing
487
           the sign of the right window coefs */
488
        for(j=0;j<4;j++) {
489
            for(i=0;i<36;i+=2) {
490
                mdct_win[j + 4][i] = mdct_win[j][i];
491
                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
492
            }
493
        }
494

    
495
#if defined(DEBUG)
496
        for(j=0;j<8;j++) {
497
            av_log(avctx, AV_LOG_DEBUG, "win%d=\n", j);
498
            for(i=0;i<36;i++)
499
                av_log(avctx, AV_LOG_DEBUG, "%f, ", (double)mdct_win[j][i] / FRAC_ONE);
500
            av_log(avctx, AV_LOG_DEBUG, "\n");
501
        }
502
#endif
503
        init = 1;
504
    }
505

    
506
#ifdef DEBUG
507
    s->frame_count = 0;
508
#endif
509
    if (avctx->codec_id == CODEC_ID_MP3ADU)
510
        s->adu_mode = 1;
511
    return 0;
512
}
513

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

    
516
/* cos(i*pi/64) */
517

    
518
#define COS0_0  FIXHR(0.50060299823519630134/2)
519
#define COS0_1  FIXHR(0.50547095989754365998/2)
520
#define COS0_2  FIXHR(0.51544730992262454697/2)
521
#define COS0_3  FIXHR(0.53104259108978417447/2)
522
#define COS0_4  FIXHR(0.55310389603444452782/2)
523
#define COS0_5  FIXHR(0.58293496820613387367/2)
524
#define COS0_6  FIXHR(0.62250412303566481615/2)
525
#define COS0_7  FIXHR(0.67480834145500574602/2)
526
#define COS0_8  FIXHR(0.74453627100229844977/2)
527
#define COS0_9  FIXHR(0.83934964541552703873/2)
528
#define COS0_10 FIXHR(0.97256823786196069369/2)
529
#define COS0_11 FIXHR(1.16943993343288495515/4)
530
#define COS0_12 FIXHR(1.48416461631416627724/4)
531
#define COS0_13 FIXHR(2.05778100995341155085/8)
532
#define COS0_14 FIXHR(3.40760841846871878570/8)
533
#define COS0_15 FIXHR(10.19000812354805681150/32)
534

    
535
#define COS1_0 FIXHR(0.50241928618815570551/2)
536
#define COS1_1 FIXHR(0.52249861493968888062/2)
537
#define COS1_2 FIXHR(0.56694403481635770368/2)
538
#define COS1_3 FIXHR(0.64682178335999012954/2)
539
#define COS1_4 FIXHR(0.78815462345125022473/2)
540
#define COS1_5 FIXHR(1.06067768599034747134/4)
541
#define COS1_6 FIXHR(1.72244709823833392782/4)
542
#define COS1_7 FIXHR(5.10114861868916385802/16)
543

    
544
#define COS2_0 FIXHR(0.50979557910415916894/2)
545
#define COS2_1 FIXHR(0.60134488693504528054/2)
546
#define COS2_2 FIXHR(0.89997622313641570463/2)
547
#define COS2_3 FIXHR(2.56291544774150617881/8)
548

    
549
#define COS3_0 FIXHR(0.54119610014619698439/2)
550
#define COS3_1 FIXHR(1.30656296487637652785/4)
551

    
552
#define COS4_0 FIXHR(0.70710678118654752439/2)
553

    
554
/* butterfly operator */
555
#define BF(a, b, c, s)\
556
{\
557
    tmp0 = tab[a] + tab[b];\
558
    tmp1 = tab[a] - tab[b];\
559
    tab[a] = tmp0;\
560
    tab[b] = MULH(tmp1<<(s), c);\
561
}
562

    
563
#define BF1(a, b, c, d)\
564
{\
565
    BF(a, b, COS4_0, 1);\
566
    BF(c, d,-COS4_0, 1);\
567
    tab[c] += tab[d];\
568
}
569

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

    
580
#define ADD(a, b) tab[a] += tab[b]
581

    
582
/* DCT32 without 1/sqrt(2) coef zero scaling. */
583
static void dct32(int32_t *out, int32_t *tab)
584
{
585
    int tmp0, tmp1;
586

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

    
631

    
632

    
633
    /* pass 1 */
634
    BF( 1, 30, COS0_1 , 1);
635
    BF(14, 17, COS0_14, 3);
636
    /* pass 2 */
637
    BF( 1, 14, COS1_1 , 1);
638
    BF(17, 30,-COS1_1 , 1);
639
    /* pass 1 */
640
    BF( 6, 25, COS0_6 , 1);
641
    BF( 9, 22, COS0_9 , 1);
642
    /* pass 2 */
643
    BF( 6,  9, COS1_6 , 2);
644
    BF(22, 25,-COS1_6 , 2);
645
    /* pass 3 */
646
    BF( 1,  6, COS2_1 , 1);
647
    BF( 9, 14,-COS2_1 , 1);
648
    BF(17, 22, COS2_1 , 1);
649
    BF(25, 30,-COS2_1 , 1);
650

    
651
    /* pass 1 */
652
    BF( 2, 29, COS0_2 , 1);
653
    BF(13, 18, COS0_13, 3);
654
    /* pass 2 */
655
    BF( 2, 13, COS1_2 , 1);
656
    BF(18, 29,-COS1_2 , 1);
657
    /* pass 1 */
658
    BF( 5, 26, COS0_5 , 1);
659
    BF(10, 21, COS0_10, 1);
660
    /* pass 2 */
661
    BF( 5, 10, COS1_5 , 2);
662
    BF(21, 26,-COS1_5 , 2);
663
    /* pass 3 */
664
    BF( 2,  5, COS2_2 , 1);
665
    BF(10, 13,-COS2_2 , 1);
666
    BF(18, 21, COS2_2 , 1);
667
    BF(26, 29,-COS2_2 , 1);
668
    /* pass 4 */
669
    BF( 1,  2, COS3_1 , 2);
670
    BF( 5,  6,-COS3_1 , 2);
671
    BF( 9, 10, COS3_1 , 2);
672
    BF(13, 14,-COS3_1 , 2);
673
    BF(17, 18, COS3_1 , 2);
674
    BF(21, 22,-COS3_1 , 2);
675
    BF(25, 26, COS3_1 , 2);
676
    BF(29, 30,-COS3_1 , 2);
677

    
678
    /* pass 5 */
679
    BF1( 0,  1,  2,  3);
680
    BF2( 4,  5,  6,  7);
681
    BF1( 8,  9, 10, 11);
682
    BF2(12, 13, 14, 15);
683
    BF1(16, 17, 18, 19);
684
    BF2(20, 21, 22, 23);
685
    BF1(24, 25, 26, 27);
686
    BF2(28, 29, 30, 31);
687

    
688
    /* pass 6 */
689

    
690
    ADD( 8, 12);
691
    ADD(12, 10);
692
    ADD(10, 14);
693
    ADD(14,  9);
694
    ADD( 9, 13);
695
    ADD(13, 11);
696
    ADD(11, 15);
697

    
698
    out[ 0] = tab[0];
699
    out[16] = tab[1];
700
    out[ 8] = tab[2];
701
    out[24] = tab[3];
702
    out[ 4] = tab[4];
703
    out[20] = tab[5];
704
    out[12] = tab[6];
705
    out[28] = tab[7];
706
    out[ 2] = tab[8];
707
    out[18] = tab[9];
708
    out[10] = tab[10];
709
    out[26] = tab[11];
710
    out[ 6] = tab[12];
711
    out[22] = tab[13];
712
    out[14] = tab[14];
713
    out[30] = tab[15];
714

    
715
    ADD(24, 28);
716
    ADD(28, 26);
717
    ADD(26, 30);
718
    ADD(30, 25);
719
    ADD(25, 29);
720
    ADD(29, 27);
721
    ADD(27, 31);
722

    
723
    out[ 1] = tab[16] + tab[24];
724
    out[17] = tab[17] + tab[25];
725
    out[ 9] = tab[18] + tab[26];
726
    out[25] = tab[19] + tab[27];
727
    out[ 5] = tab[20] + tab[28];
728
    out[21] = tab[21] + tab[29];
729
    out[13] = tab[22] + tab[30];
730
    out[29] = tab[23] + tab[31];
731
    out[ 3] = tab[24] + tab[20];
732
    out[19] = tab[25] + tab[21];
733
    out[11] = tab[26] + tab[22];
734
    out[27] = tab[27] + tab[23];
735
    out[ 7] = tab[28] + tab[18];
736
    out[23] = tab[29] + tab[19];
737
    out[15] = tab[30] + tab[17];
738
    out[31] = tab[31];
739
}
740

    
741
#if FRAC_BITS <= 15
742

    
743
static inline int round_sample(int *sum)
744
{
745
    int sum1;
746
    sum1 = (*sum) >> OUT_SHIFT;
747
    *sum &= (1<<OUT_SHIFT)-1;
748
    if (sum1 < OUT_MIN)
749
        sum1 = OUT_MIN;
750
    else if (sum1 > OUT_MAX)
751
        sum1 = OUT_MAX;
752
    return sum1;
753
}
754

    
755
/* signed 16x16 -> 32 multiply add accumulate */
756
#define MACS(rt, ra, rb) MAC16(rt, ra, rb)
757

    
758
/* signed 16x16 -> 32 multiply */
759
#define MULS(ra, rb) MUL16(ra, rb)
760

    
761
#else
762

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

    
775
#   define MULS(ra, rb) MUL64(ra, rb)
776
#endif
777

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

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

    
819
void ff_mpa_synth_init(MPA_INT *window)
820
{
821
    int i;
822

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

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

    
857
    dct32(tmp, sb_samples);
858

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

    
862
    for(j=0;j<32;j++) {
863
        v = tmp[j];
864
#if FRAC_BITS <= 15
865
        /* NOTE: can cause a loss in precision if very high amplitude
866
           sound */
867
        if (v > 32767)
868
            v = 32767;
869
        else if (v < -32768)
870
            v = -32768;
871
#endif
872
        synth_buf[j] = v;
873
    }
874
    /* copy to avoid wrap */
875
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
876

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

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

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

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

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

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

    
917
#define C3 FIXHR(0.86602540378443864676/2)
918

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

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

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

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

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

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

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

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

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

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

    
998

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1108
/* header decoding. MUST check the header before because no
1109
   consistency check is done there. Return 1 if free format found and
1110
   that the frame size must be computed externally */
1111
static int decode_header(MPADecodeContext *s, uint32_t header)
1112
{
1113
    int sample_rate, frame_size, mpeg25, padding;
1114
    int sample_rate_index, bitrate_index;
1115
    if (header & (1<<20)) {
1116
        s->lsf = (header & (1<<19)) ? 0 : 1;
1117
        mpeg25 = 0;
1118
    } else {
1119
        s->lsf = 1;
1120
        mpeg25 = 1;
1121
    }
1122

    
1123
    s->layer = 4 - ((header >> 17) & 3);
1124
    /* extract frequency */
1125
    sample_rate_index = (header >> 10) & 3;
1126
    sample_rate = mpa_freq_tab[sample_rate_index] >> (s->lsf + mpeg25);
1127
    sample_rate_index += 3 * (s->lsf + mpeg25);
1128
    s->sample_rate_index = sample_rate_index;
1129
    s->error_protection = ((header >> 16) & 1) ^ 1;
1130
    s->sample_rate = sample_rate;
1131

    
1132
    bitrate_index = (header >> 12) & 0xf;
1133
    padding = (header >> 9) & 1;
1134
    //extension = (header >> 8) & 1;
1135
    s->mode = (header >> 6) & 3;
1136
    s->mode_ext = (header >> 4) & 3;
1137
    //copyright = (header >> 3) & 1;
1138
    //original = (header >> 2) & 1;
1139
    //emphasis = header & 3;
1140

    
1141
    if (s->mode == MPA_MONO)
1142
        s->nb_channels = 1;
1143
    else
1144
        s->nb_channels = 2;
1145

    
1146
    if (bitrate_index != 0) {
1147
        frame_size = mpa_bitrate_tab[s->lsf][s->layer - 1][bitrate_index];
1148
        s->bit_rate = frame_size * 1000;
1149
        switch(s->layer) {
1150
        case 1:
1151
            frame_size = (frame_size * 12000) / sample_rate;
1152
            frame_size = (frame_size + padding) * 4;
1153
            break;
1154
        case 2:
1155
            frame_size = (frame_size * 144000) / sample_rate;
1156
            frame_size += padding;
1157
            break;
1158
        default:
1159
        case 3:
1160
            frame_size = (frame_size * 144000) / (sample_rate << s->lsf);
1161
            frame_size += padding;
1162
            break;
1163
        }
1164
        s->frame_size = frame_size;
1165
    } else {
1166
        /* if no frame size computed, signal it */
1167
        return 1;
1168
    }
1169

    
1170
#if defined(DEBUG)
1171
    dprintf("layer%d, %d Hz, %d kbits/s, ",
1172
           s->layer, s->sample_rate, s->bit_rate);
1173
    if (s->nb_channels == 2) {
1174
        if (s->layer == 3) {
1175
            if (s->mode_ext & MODE_EXT_MS_STEREO)
1176
                dprintf("ms-");
1177
            if (s->mode_ext & MODE_EXT_I_STEREO)
1178
                dprintf("i-");
1179
        }
1180
        dprintf("stereo");
1181
    } else {
1182
        dprintf("mono");
1183
    }
1184
    dprintf("\n");
1185
#endif
1186
    return 0;
1187
}
1188

    
1189
/* useful helper to get mpeg audio stream infos. Return -1 if error in
1190
   header, otherwise the coded frame size in bytes */
1191
int mpa_decode_header(AVCodecContext *avctx, uint32_t head)
1192
{
1193
    MPADecodeContext s1, *s = &s1;
1194

    
1195
    if (ff_mpa_check_header(head) != 0)
1196
        return -1;
1197

    
1198
    if (decode_header(s, head) != 0) {
1199
        return -1;
1200
    }
1201

    
1202
    switch(s->layer) {
1203
    case 1:
1204
        avctx->frame_size = 384;
1205
        break;
1206
    case 2:
1207
        avctx->frame_size = 1152;
1208
        break;
1209
    default:
1210
    case 3:
1211
        if (s->lsf)
1212
            avctx->frame_size = 576;
1213
        else
1214
            avctx->frame_size = 1152;
1215
        break;
1216
    }
1217

    
1218
    avctx->sample_rate = s->sample_rate;
1219
    avctx->channels = s->nb_channels;
1220
    avctx->bit_rate = s->bit_rate;
1221
    avctx->sub_id = s->layer;
1222
    return s->frame_size;
1223
}
1224

    
1225
/* return the number of decoded frames */
1226
static int mp_decode_layer1(MPADecodeContext *s)
1227
{
1228
    int bound, i, v, n, ch, j, mant;
1229
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1230
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1231

    
1232
    if (s->mode == MPA_JSTEREO)
1233
        bound = (s->mode_ext + 1) * 4;
1234
    else
1235
        bound = SBLIMIT;
1236

    
1237
    /* allocation bits */
1238
    for(i=0;i<bound;i++) {
1239
        for(ch=0;ch<s->nb_channels;ch++) {
1240
            allocation[ch][i] = get_bits(&s->gb, 4);
1241
        }
1242
    }
1243
    for(i=bound;i<SBLIMIT;i++) {
1244
        allocation[0][i] = get_bits(&s->gb, 4);
1245
    }
1246

    
1247
    /* scale factors */
1248
    for(i=0;i<bound;i++) {
1249
        for(ch=0;ch<s->nb_channels;ch++) {
1250
            if (allocation[ch][i])
1251
                scale_factors[ch][i] = get_bits(&s->gb, 6);
1252
        }
1253
    }
1254
    for(i=bound;i<SBLIMIT;i++) {
1255
        if (allocation[0][i]) {
1256
            scale_factors[0][i] = get_bits(&s->gb, 6);
1257
            scale_factors[1][i] = get_bits(&s->gb, 6);
1258
        }
1259
    }
1260

    
1261
    /* compute samples */
1262
    for(j=0;j<12;j++) {
1263
        for(i=0;i<bound;i++) {
1264
            for(ch=0;ch<s->nb_channels;ch++) {
1265
                n = allocation[ch][i];
1266
                if (n) {
1267
                    mant = get_bits(&s->gb, n + 1);
1268
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
1269
                } else {
1270
                    v = 0;
1271
                }
1272
                s->sb_samples[ch][j][i] = v;
1273
            }
1274
        }
1275
        for(i=bound;i<SBLIMIT;i++) {
1276
            n = allocation[0][i];
1277
            if (n) {
1278
                mant = get_bits(&s->gb, n + 1);
1279
                v = l1_unscale(n, mant, scale_factors[0][i]);
1280
                s->sb_samples[0][j][i] = v;
1281
                v = l1_unscale(n, mant, scale_factors[1][i]);
1282
                s->sb_samples[1][j][i] = v;
1283
            } else {
1284
                s->sb_samples[0][j][i] = 0;
1285
                s->sb_samples[1][j][i] = 0;
1286
            }
1287
        }
1288
    }
1289
    return 12;
1290
}
1291

    
1292
/* bitrate is in kb/s */
1293
int l2_select_table(int bitrate, int nb_channels, int freq, int lsf)
1294
{
1295
    int ch_bitrate, table;
1296

    
1297
    ch_bitrate = bitrate / nb_channels;
1298
    if (!lsf) {
1299
        if ((freq == 48000 && ch_bitrate >= 56) ||
1300
            (ch_bitrate >= 56 && ch_bitrate <= 80))
1301
            table = 0;
1302
        else if (freq != 48000 && ch_bitrate >= 96)
1303
            table = 1;
1304
        else if (freq != 32000 && ch_bitrate <= 48)
1305
            table = 2;
1306
        else
1307
            table = 3;
1308
    } else {
1309
        table = 4;
1310
    }
1311
    return table;
1312
}
1313

    
1314
static int mp_decode_layer2(MPADecodeContext *s)
1315
{
1316
    int sblimit; /* number of used subbands */
1317
    const unsigned char *alloc_table;
1318
    int table, bit_alloc_bits, i, j, ch, bound, v;
1319
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1320
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1321
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1322
    int scale, qindex, bits, steps, k, l, m, b;
1323

    
1324
    /* select decoding table */
1325
    table = l2_select_table(s->bit_rate / 1000, s->nb_channels,
1326
                            s->sample_rate, s->lsf);
1327
    sblimit = sblimit_table[table];
1328
    alloc_table = alloc_tables[table];
1329

    
1330
    if (s->mode == MPA_JSTEREO)
1331
        bound = (s->mode_ext + 1) * 4;
1332
    else
1333
        bound = sblimit;
1334

    
1335
    dprintf("bound=%d sblimit=%d\n", bound, sblimit);
1336

    
1337
    /* sanity check */
1338
    if( bound > sblimit ) bound = sblimit;
1339

    
1340
    /* parse bit allocation */
1341
    j = 0;
1342
    for(i=0;i<bound;i++) {
1343
        bit_alloc_bits = alloc_table[j];
1344
        for(ch=0;ch<s->nb_channels;ch++) {
1345
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1346
        }
1347
        j += 1 << bit_alloc_bits;
1348
    }
1349
    for(i=bound;i<sblimit;i++) {
1350
        bit_alloc_bits = alloc_table[j];
1351
        v = get_bits(&s->gb, bit_alloc_bits);
1352
        bit_alloc[0][i] = v;
1353
        bit_alloc[1][i] = v;
1354
        j += 1 << bit_alloc_bits;
1355
    }
1356

    
1357
#ifdef DEBUG
1358
    {
1359
        for(ch=0;ch<s->nb_channels;ch++) {
1360
            for(i=0;i<sblimit;i++)
1361
                dprintf(" %d", bit_alloc[ch][i]);
1362
            dprintf("\n");
1363
        }
1364
    }
1365
#endif
1366

    
1367
    /* scale codes */
1368
    for(i=0;i<sblimit;i++) {
1369
        for(ch=0;ch<s->nb_channels;ch++) {
1370
            if (bit_alloc[ch][i])
1371
                scale_code[ch][i] = get_bits(&s->gb, 2);
1372
        }
1373
    }
1374

    
1375
    /* scale factors */
1376
    for(i=0;i<sblimit;i++) {
1377
        for(ch=0;ch<s->nb_channels;ch++) {
1378
            if (bit_alloc[ch][i]) {
1379
                sf = scale_factors[ch][i];
1380
                switch(scale_code[ch][i]) {
1381
                default:
1382
                case 0:
1383
                    sf[0] = get_bits(&s->gb, 6);
1384
                    sf[1] = get_bits(&s->gb, 6);
1385
                    sf[2] = get_bits(&s->gb, 6);
1386
                    break;
1387
                case 2:
1388
                    sf[0] = get_bits(&s->gb, 6);
1389
                    sf[1] = sf[0];
1390
                    sf[2] = sf[0];
1391
                    break;
1392
                case 1:
1393
                    sf[0] = get_bits(&s->gb, 6);
1394
                    sf[2] = get_bits(&s->gb, 6);
1395
                    sf[1] = sf[0];
1396
                    break;
1397
                case 3:
1398
                    sf[0] = get_bits(&s->gb, 6);
1399
                    sf[2] = get_bits(&s->gb, 6);
1400
                    sf[1] = sf[2];
1401
                    break;
1402
                }
1403
            }
1404
        }
1405
    }
1406

    
1407
#ifdef DEBUG
1408
    for(ch=0;ch<s->nb_channels;ch++) {
1409
        for(i=0;i<sblimit;i++) {
1410
            if (bit_alloc[ch][i]) {
1411
                sf = scale_factors[ch][i];
1412
                dprintf(" %d %d %d", sf[0], sf[1], sf[2]);
1413
            } else {
1414
                dprintf(" -");
1415
            }
1416
        }
1417
        dprintf("\n");
1418
    }
1419
#endif
1420

    
1421
    /* samples */
1422
    for(k=0;k<3;k++) {
1423
        for(l=0;l<12;l+=3) {
1424
            j = 0;
1425
            for(i=0;i<bound;i++) {
1426
                bit_alloc_bits = alloc_table[j];
1427
                for(ch=0;ch<s->nb_channels;ch++) {
1428
                    b = bit_alloc[ch][i];
1429
                    if (b) {
1430
                        scale = scale_factors[ch][i][k];
1431
                        qindex = alloc_table[j+b];
1432
                        bits = quant_bits[qindex];
1433
                        if (bits < 0) {
1434
                            /* 3 values at the same time */
1435
                            v = get_bits(&s->gb, -bits);
1436
                            steps = quant_steps[qindex];
1437
                            s->sb_samples[ch][k * 12 + l + 0][i] =
1438
                                l2_unscale_group(steps, v % steps, scale);
1439
                            v = v / steps;
1440
                            s->sb_samples[ch][k * 12 + l + 1][i] =
1441
                                l2_unscale_group(steps, v % steps, scale);
1442
                            v = v / steps;
1443
                            s->sb_samples[ch][k * 12 + l + 2][i] =
1444
                                l2_unscale_group(steps, v, scale);
1445
                        } else {
1446
                            for(m=0;m<3;m++) {
1447
                                v = get_bits(&s->gb, bits);
1448
                                v = l1_unscale(bits - 1, v, scale);
1449
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
1450
                            }
1451
                        }
1452
                    } else {
1453
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1454
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1455
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1456
                    }
1457
                }
1458
                /* next subband in alloc table */
1459
                j += 1 << bit_alloc_bits;
1460
            }
1461
            /* XXX: find a way to avoid this duplication of code */
1462
            for(i=bound;i<sblimit;i++) {
1463
                bit_alloc_bits = alloc_table[j];
1464
                b = bit_alloc[0][i];
1465
                if (b) {
1466
                    int mant, scale0, scale1;
1467
                    scale0 = scale_factors[0][i][k];
1468
                    scale1 = scale_factors[1][i][k];
1469
                    qindex = alloc_table[j+b];
1470
                    bits = quant_bits[qindex];
1471
                    if (bits < 0) {
1472
                        /* 3 values at the same time */
1473
                        v = get_bits(&s->gb, -bits);
1474
                        steps = quant_steps[qindex];
1475
                        mant = v % steps;
1476
                        v = v / steps;
1477
                        s->sb_samples[0][k * 12 + l + 0][i] =
1478
                            l2_unscale_group(steps, mant, scale0);
1479
                        s->sb_samples[1][k * 12 + l + 0][i] =
1480
                            l2_unscale_group(steps, mant, scale1);
1481
                        mant = v % steps;
1482
                        v = v / steps;
1483
                        s->sb_samples[0][k * 12 + l + 1][i] =
1484
                            l2_unscale_group(steps, mant, scale0);
1485
                        s->sb_samples[1][k * 12 + l + 1][i] =
1486
                            l2_unscale_group(steps, mant, scale1);
1487
                        s->sb_samples[0][k * 12 + l + 2][i] =
1488
                            l2_unscale_group(steps, v, scale0);
1489
                        s->sb_samples[1][k * 12 + l + 2][i] =
1490
                            l2_unscale_group(steps, v, scale1);
1491
                    } else {
1492
                        for(m=0;m<3;m++) {
1493
                            mant = get_bits(&s->gb, bits);
1494
                            s->sb_samples[0][k * 12 + l + m][i] =
1495
                                l1_unscale(bits - 1, mant, scale0);
1496
                            s->sb_samples[1][k * 12 + l + m][i] =
1497
                                l1_unscale(bits - 1, mant, scale1);
1498
                        }
1499
                    }
1500
                } else {
1501
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
1502
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
1503
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
1504
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
1505
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
1506
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
1507
                }
1508
                /* next subband in alloc table */
1509
                j += 1 << bit_alloc_bits;
1510
            }
1511
            /* fill remaining samples to zero */
1512
            for(i=sblimit;i<SBLIMIT;i++) {
1513
                for(ch=0;ch<s->nb_channels;ch++) {
1514
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1515
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1516
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1517
                }
1518
            }
1519
        }
1520
    }
1521
    return 3 * 12;
1522
}
1523

    
1524
static inline void lsf_sf_expand(int *slen,
1525
                                 int sf, int n1, int n2, int n3)
1526
{
1527
    if (n3) {
1528
        slen[3] = sf % n3;
1529
        sf /= n3;
1530
    } else {
1531
        slen[3] = 0;
1532
    }
1533
    if (n2) {
1534
        slen[2] = sf % n2;
1535
        sf /= n2;
1536
    } else {
1537
        slen[2] = 0;
1538
    }
1539
    slen[1] = sf % n1;
1540
    sf /= n1;
1541
    slen[0] = sf;
1542
}
1543

    
1544
static void exponents_from_scale_factors(MPADecodeContext *s,
1545
                                         GranuleDef *g,
1546
                                         int16_t *exponents)
1547
{
1548
    const uint8_t *bstab, *pretab;
1549
    int len, i, j, k, l, v0, shift, gain, gains[3];
1550
    int16_t *exp_ptr;
1551

    
1552
    exp_ptr = exponents;
1553
    gain = g->global_gain - 210;
1554
    shift = g->scalefac_scale + 1;
1555

    
1556
    bstab = band_size_long[s->sample_rate_index];
1557
    pretab = mpa_pretab[g->preflag];
1558
    for(i=0;i<g->long_end;i++) {
1559
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1560
        len = bstab[i];
1561
        for(j=len;j>0;j--)
1562
            *exp_ptr++ = v0;
1563
    }
1564

    
1565
    if (g->short_start < 13) {
1566
        bstab = band_size_short[s->sample_rate_index];
1567
        gains[0] = gain - (g->subblock_gain[0] << 3);
1568
        gains[1] = gain - (g->subblock_gain[1] << 3);
1569
        gains[2] = gain - (g->subblock_gain[2] << 3);
1570
        k = g->long_end;
1571
        for(i=g->short_start;i<13;i++) {
1572
            len = bstab[i];
1573
            for(l=0;l<3;l++) {
1574
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1575
                for(j=len;j>0;j--)
1576
                *exp_ptr++ = v0;
1577
            }
1578
        }
1579
    }
1580
}
1581

    
1582
/* handle n = 0 too */
1583
static inline int get_bitsz(GetBitContext *s, int n)
1584
{
1585
    if (n == 0)
1586
        return 0;
1587
    else
1588
        return get_bits(s, n);
1589
}
1590

    
1591
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1592
                          int16_t *exponents, int end_pos2)
1593
{
1594
    int s_index;
1595
    int i;
1596
    int last_pos, bits_left;
1597
    VLC *vlc;
1598
    int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1599

    
1600
    /* low frequencies (called big values) */
1601
    s_index = 0;
1602
    for(i=0;i<3;i++) {
1603
        int j, k, l, linbits;
1604
        j = g->region_size[i];
1605
        if (j == 0)
1606
            continue;
1607
        /* select vlc table */
1608
        k = g->table_select[i];
1609
        l = mpa_huff_data[k][0];
1610
        linbits = mpa_huff_data[k][1];
1611
        vlc = &huff_vlc[l];
1612

    
1613
        if(!l){
1614
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1615
            s_index += 2*j;
1616
            continue;
1617
        }
1618

    
1619
        /* read huffcode and compute each couple */
1620
        for(;j>0;j--) {
1621
            int exponent, x, y, v;
1622
            int pos= get_bits_count(&s->gb);
1623

    
1624
            if (pos >= end_pos){
1625
//                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1626
                if(s->in_gb.buffer && pos >= s->gb.size_in_bits){
1627
                    s->gb= s->in_gb;
1628
                    s->in_gb.buffer=NULL;
1629
                    assert((get_bits_count(&s->gb) & 7) == 0);
1630
                    skip_bits_long(&s->gb, pos - end_pos);
1631
                    end_pos2=
1632
                    end_pos= end_pos2 + get_bits_count(&s->gb) - pos;
1633
                    pos= get_bits_count(&s->gb);
1634
                }
1635
//                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1636
                if(pos >= end_pos)
1637
                    break;
1638
            }
1639
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
1640

    
1641
            if(!y){
1642
                g->sb_hybrid[s_index  ] =
1643
                g->sb_hybrid[s_index+1] = 0;
1644
                s_index += 2;
1645
                continue;
1646
            }
1647

    
1648
            exponent= exponents[s_index];
1649

    
1650
            dprintf("region=%d n=%d x=%d y=%d exp=%d\n",
1651
                    i, g->region_size[i] - j, x, y, exponent);
1652
            if(y&16){
1653
                x = y >> 5;
1654
                y = y & 0x0f;
1655
                if (x < 15){
1656
                    v = expval_table[ exponent ][ x ];
1657
//                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
1658
                }else{
1659
                    x += get_bitsz(&s->gb, linbits);
1660
                    v = l3_unscale(x, exponent);
1661
                }
1662
                if (get_bits1(&s->gb))
1663
                    v = -v;
1664
                g->sb_hybrid[s_index] = v;
1665
                if (y < 15){
1666
                    v = expval_table[ exponent ][ y ];
1667
                }else{
1668
                    y += get_bitsz(&s->gb, linbits);
1669
                    v = l3_unscale(y, exponent);
1670
                }
1671
                if (get_bits1(&s->gb))
1672
                    v = -v;
1673
                g->sb_hybrid[s_index+1] = v;
1674
            }else{
1675
                x = y >> 5;
1676
                y = y & 0x0f;
1677
                x += y;
1678
                if (x < 15){
1679
                    v = expval_table[ exponent ][ x ];
1680
                }else{
1681
                    x += get_bitsz(&s->gb, linbits);
1682
                    v = l3_unscale(x, exponent);
1683
                }
1684
                if (get_bits1(&s->gb))
1685
                    v = -v;
1686
                g->sb_hybrid[s_index+!!y] = v;
1687
                g->sb_hybrid[s_index+ !y] = 0;
1688
            }
1689
            s_index+=2;
1690
        }
1691
    }
1692

    
1693
    /* high frequencies */
1694
    vlc = &huff_quad_vlc[g->count1table_select];
1695
    last_pos=0;
1696
    while (s_index <= 572) {
1697
        int pos, code;
1698
        pos = get_bits_count(&s->gb);
1699
        if (pos >= end_pos) {
1700
            if (pos > end_pos2 && last_pos){
1701
                /* some encoders generate an incorrect size for this
1702
                   part. We must go back into the data */
1703
                s_index -= 4;
1704
                skip_bits_long(&s->gb, last_pos - pos);
1705
                av_log(NULL, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1706
                break;
1707
            }
1708
//                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1709
            if(s->in_gb.buffer && pos >= s->gb.size_in_bits){
1710
                s->gb= s->in_gb;
1711
                s->in_gb.buffer=NULL;
1712
                assert((get_bits_count(&s->gb) & 7) == 0);
1713
                skip_bits_long(&s->gb, pos - end_pos);
1714
                end_pos2=
1715
                end_pos= end_pos2 + get_bits_count(&s->gb) - pos;
1716
                pos= get_bits_count(&s->gb);
1717
            }
1718
//                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1719
            if(pos >= end_pos)
1720
                break;
1721
        }
1722
        last_pos= pos;
1723

    
1724
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1725
        dprintf("t=%d code=%d\n", g->count1table_select, code);
1726
        g->sb_hybrid[s_index+0]=
1727
        g->sb_hybrid[s_index+1]=
1728
        g->sb_hybrid[s_index+2]=
1729
        g->sb_hybrid[s_index+3]= 0;
1730
        while(code){
1731
            const static int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1732
            int v;
1733
            int pos= s_index+idxtab[code];
1734
            code ^= 8>>idxtab[code];
1735
            v = exp_table[ exponents[pos] ];
1736
//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1737
            if(get_bits1(&s->gb))
1738
                v = -v;
1739
            g->sb_hybrid[pos] = v;
1740
        }
1741
        s_index+=4;
1742
    }
1743
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1744

    
1745
    /* skip extension bits */
1746
    bits_left = end_pos - get_bits_count(&s->gb);
1747
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1748
    if (bits_left < 0) {
1749
        dprintf("bits_left=%d\n", bits_left);
1750
        return -1;
1751
    }
1752
    skip_bits_long(&s->gb, bits_left);
1753

    
1754
    return 0;
1755
}
1756

    
1757
/* Reorder short blocks from bitstream order to interleaved order. It
1758
   would be faster to do it in parsing, but the code would be far more
1759
   complicated */
1760
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1761
{
1762
    int i, j, len;
1763
    int32_t *ptr, *dst, *ptr1;
1764
    int32_t tmp[576];
1765

    
1766
    if (g->block_type != 2)
1767
        return;
1768

    
1769
    if (g->switch_point) {
1770
        if (s->sample_rate_index != 8) {
1771
            ptr = g->sb_hybrid + 36;
1772
        } else {
1773
            ptr = g->sb_hybrid + 48;
1774
        }
1775
    } else {
1776
        ptr = g->sb_hybrid;
1777
    }
1778

    
1779
    for(i=g->short_start;i<13;i++) {
1780
        len = band_size_short[s->sample_rate_index][i];
1781
        ptr1 = ptr;
1782
        dst = tmp;
1783
        for(j=len;j>0;j--) {
1784
            *dst++ = ptr[0*len];
1785
            *dst++ = ptr[1*len];
1786
            *dst++ = ptr[2*len];
1787
            ptr++;
1788
        }
1789
        ptr+=2*len;
1790
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1791
    }
1792
}
1793

    
1794
#define ISQRT2 FIXR(0.70710678118654752440)
1795

    
1796
static void compute_stereo(MPADecodeContext *s,
1797
                           GranuleDef *g0, GranuleDef *g1)
1798
{
1799
    int i, j, k, l;
1800
    int32_t v1, v2;
1801
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1802
    int32_t (*is_tab)[16];
1803
    int32_t *tab0, *tab1;
1804
    int non_zero_found_short[3];
1805

    
1806
    /* intensity stereo */
1807
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1808
        if (!s->lsf) {
1809
            is_tab = is_table;
1810
            sf_max = 7;
1811
        } else {
1812
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1813
            sf_max = 16;
1814
        }
1815

    
1816
        tab0 = g0->sb_hybrid + 576;
1817
        tab1 = g1->sb_hybrid + 576;
1818

    
1819
        non_zero_found_short[0] = 0;
1820
        non_zero_found_short[1] = 0;
1821
        non_zero_found_short[2] = 0;
1822
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1823
        for(i = 12;i >= g1->short_start;i--) {
1824
            /* for last band, use previous scale factor */
1825
            if (i != 11)
1826
                k -= 3;
1827
            len = band_size_short[s->sample_rate_index][i];
1828
            for(l=2;l>=0;l--) {
1829
                tab0 -= len;
1830
                tab1 -= len;
1831
                if (!non_zero_found_short[l]) {
1832
                    /* test if non zero band. if so, stop doing i-stereo */
1833
                    for(j=0;j<len;j++) {
1834
                        if (tab1[j] != 0) {
1835
                            non_zero_found_short[l] = 1;
1836
                            goto found1;
1837
                        }
1838
                    }
1839
                    sf = g1->scale_factors[k + l];
1840
                    if (sf >= sf_max)
1841
                        goto found1;
1842

    
1843
                    v1 = is_tab[0][sf];
1844
                    v2 = is_tab[1][sf];
1845
                    for(j=0;j<len;j++) {
1846
                        tmp0 = tab0[j];
1847
                        tab0[j] = MULL(tmp0, v1);
1848
                        tab1[j] = MULL(tmp0, v2);
1849
                    }
1850
                } else {
1851
                found1:
1852
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1853
                        /* lower part of the spectrum : do ms stereo
1854
                           if enabled */
1855
                        for(j=0;j<len;j++) {
1856
                            tmp0 = tab0[j];
1857
                            tmp1 = tab1[j];
1858
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1859
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1860
                        }
1861
                    }
1862
                }
1863
            }
1864
        }
1865

    
1866
        non_zero_found = non_zero_found_short[0] |
1867
            non_zero_found_short[1] |
1868
            non_zero_found_short[2];
1869

    
1870
        for(i = g1->long_end - 1;i >= 0;i--) {
1871
            len = band_size_long[s->sample_rate_index][i];
1872
            tab0 -= len;
1873
            tab1 -= len;
1874
            /* test if non zero band. if so, stop doing i-stereo */
1875
            if (!non_zero_found) {
1876
                for(j=0;j<len;j++) {
1877
                    if (tab1[j] != 0) {
1878
                        non_zero_found = 1;
1879
                        goto found2;
1880
                    }
1881
                }
1882
                /* for last band, use previous scale factor */
1883
                k = (i == 21) ? 20 : i;
1884
                sf = g1->scale_factors[k];
1885
                if (sf >= sf_max)
1886
                    goto found2;
1887
                v1 = is_tab[0][sf];
1888
                v2 = is_tab[1][sf];
1889
                for(j=0;j<len;j++) {
1890
                    tmp0 = tab0[j];
1891
                    tab0[j] = MULL(tmp0, v1);
1892
                    tab1[j] = MULL(tmp0, v2);
1893
                }
1894
            } else {
1895
            found2:
1896
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1897
                    /* lower part of the spectrum : do ms stereo
1898
                       if enabled */
1899
                    for(j=0;j<len;j++) {
1900
                        tmp0 = tab0[j];
1901
                        tmp1 = tab1[j];
1902
                        tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1903
                        tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1904
                    }
1905
                }
1906
            }
1907
        }
1908
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1909
        /* ms stereo ONLY */
1910
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1911
           global gain */
1912
        tab0 = g0->sb_hybrid;
1913
        tab1 = g1->sb_hybrid;
1914
        for(i=0;i<576;i++) {
1915
            tmp0 = tab0[i];
1916
            tmp1 = tab1[i];
1917
            tab0[i] = tmp0 + tmp1;
1918
            tab1[i] = tmp0 - tmp1;
1919
        }
1920
    }
1921
}
1922

    
1923
static void compute_antialias_integer(MPADecodeContext *s,
1924
                              GranuleDef *g)
1925
{
1926
    int32_t *ptr, *csa;
1927
    int n, i;
1928

    
1929
    /* we antialias only "long" bands */
1930
    if (g->block_type == 2) {
1931
        if (!g->switch_point)
1932
            return;
1933
        /* XXX: check this for 8000Hz case */
1934
        n = 1;
1935
    } else {
1936
        n = SBLIMIT - 1;
1937
    }
1938

    
1939
    ptr = g->sb_hybrid + 18;
1940
    for(i = n;i > 0;i--) {
1941
        int tmp0, tmp1, tmp2;
1942
        csa = &csa_table[0][0];
1943
#define INT_AA(j) \
1944
            tmp0 = ptr[-1-j];\
1945
            tmp1 = ptr[   j];\
1946
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1947
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1948
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1949

    
1950
        INT_AA(0)
1951
        INT_AA(1)
1952
        INT_AA(2)
1953
        INT_AA(3)
1954
        INT_AA(4)
1955
        INT_AA(5)
1956
        INT_AA(6)
1957
        INT_AA(7)
1958

    
1959
        ptr += 18;
1960
    }
1961
}
1962

    
1963
static void compute_antialias_float(MPADecodeContext *s,
1964
                              GranuleDef *g)
1965
{
1966
    int32_t *ptr;
1967
    int n, i;
1968

    
1969
    /* we antialias only "long" bands */
1970
    if (g->block_type == 2) {
1971
        if (!g->switch_point)
1972
            return;
1973
        /* XXX: check this for 8000Hz case */
1974
        n = 1;
1975
    } else {
1976
        n = SBLIMIT - 1;
1977
    }
1978

    
1979
    ptr = g->sb_hybrid + 18;
1980
    for(i = n;i > 0;i--) {
1981
        float tmp0, tmp1;
1982
        float *csa = &csa_table_float[0][0];
1983
#define FLOAT_AA(j)\
1984
        tmp0= ptr[-1-j];\
1985
        tmp1= ptr[   j];\
1986
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1987
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1988

    
1989
        FLOAT_AA(0)
1990
        FLOAT_AA(1)
1991
        FLOAT_AA(2)
1992
        FLOAT_AA(3)
1993
        FLOAT_AA(4)
1994
        FLOAT_AA(5)
1995
        FLOAT_AA(6)
1996
        FLOAT_AA(7)
1997

    
1998
        ptr += 18;
1999
    }
2000
}
2001

    
2002
static void compute_imdct(MPADecodeContext *s,
2003
                          GranuleDef *g,
2004
                          int32_t *sb_samples,
2005
                          int32_t *mdct_buf)
2006
{
2007
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
2008
    int32_t out2[12];
2009
    int i, j, mdct_long_end, v, sblimit;
2010

    
2011
    /* find last non zero block */
2012
    ptr = g->sb_hybrid + 576;
2013
    ptr1 = g->sb_hybrid + 2 * 18;
2014
    while (ptr >= ptr1) {
2015
        ptr -= 6;
2016
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
2017
        if (v != 0)
2018
            break;
2019
    }
2020
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
2021

    
2022
    if (g->block_type == 2) {
2023
        /* XXX: check for 8000 Hz */
2024
        if (g->switch_point)
2025
            mdct_long_end = 2;
2026
        else
2027
            mdct_long_end = 0;
2028
    } else {
2029
        mdct_long_end = sblimit;
2030
    }
2031

    
2032
    buf = mdct_buf;
2033
    ptr = g->sb_hybrid;
2034
    for(j=0;j<mdct_long_end;j++) {
2035
        /* apply window & overlap with previous buffer */
2036
        out_ptr = sb_samples + j;
2037
        /* select window */
2038
        if (g->switch_point && j < 2)
2039
            win1 = mdct_win[0];
2040
        else
2041
            win1 = mdct_win[g->block_type];
2042
        /* select frequency inversion */
2043
        win = win1 + ((4 * 36) & -(j & 1));
2044
        imdct36(out_ptr, buf, ptr, win);
2045
        out_ptr += 18*SBLIMIT;
2046
        ptr += 18;
2047
        buf += 18;
2048
    }
2049
    for(j=mdct_long_end;j<sblimit;j++) {
2050
        /* select frequency inversion */
2051
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
2052
        out_ptr = sb_samples + j;
2053

    
2054
        for(i=0; i<6; i++){
2055
            *out_ptr = buf[i];
2056
            out_ptr += SBLIMIT;
2057
        }
2058
        imdct12(out2, ptr + 0);
2059
        for(i=0;i<6;i++) {
2060
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
2061
            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
2062
            out_ptr += SBLIMIT;
2063
        }
2064
        imdct12(out2, ptr + 1);
2065
        for(i=0;i<6;i++) {
2066
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
2067
            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
2068
            out_ptr += SBLIMIT;
2069
        }
2070
        imdct12(out2, ptr + 2);
2071
        for(i=0;i<6;i++) {
2072
            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
2073
            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
2074
            buf[i + 6*2] = 0;
2075
        }
2076
        ptr += 18;
2077
        buf += 18;
2078
    }
2079
    /* zero bands */
2080
    for(j=sblimit;j<SBLIMIT;j++) {
2081
        /* overlap */
2082
        out_ptr = sb_samples + j;
2083
        for(i=0;i<18;i++) {
2084
            *out_ptr = buf[i];
2085
            buf[i] = 0;
2086
            out_ptr += SBLIMIT;
2087
        }
2088
        buf += 18;
2089
    }
2090
}
2091

    
2092
#if defined(DEBUG)
2093
void sample_dump(int fnum, int32_t *tab, int n)
2094
{
2095
    static FILE *files[16], *f;
2096
    char buf[512];
2097
    int i;
2098
    int32_t v;
2099

    
2100
    f = files[fnum];
2101
    if (!f) {
2102
        snprintf(buf, sizeof(buf), "/tmp/out%d.%s.pcm",
2103
                fnum,
2104
#ifdef USE_HIGHPRECISION
2105
                "hp"
2106
#else
2107
                "lp"
2108
#endif
2109
                );
2110
        f = fopen(buf, "w");
2111
        if (!f)
2112
            return;
2113
        files[fnum] = f;
2114
    }
2115

    
2116
    if (fnum == 0) {
2117
        static int pos = 0;
2118
        av_log(NULL, AV_LOG_DEBUG, "pos=%d\n", pos);
2119
        for(i=0;i<n;i++) {
2120
            av_log(NULL, AV_LOG_DEBUG, " %0.4f", (double)tab[i] / FRAC_ONE);
2121
            if ((i % 18) == 17)
2122
                av_log(NULL, AV_LOG_DEBUG, "\n");
2123
        }
2124
        pos += n;
2125
    }
2126
    for(i=0;i<n;i++) {
2127
        /* normalize to 23 frac bits */
2128
        v = tab[i] << (23 - FRAC_BITS);
2129
        fwrite(&v, 1, sizeof(int32_t), f);
2130
    }
2131
}
2132
#endif
2133

    
2134

    
2135
/* main layer3 decoding function */
2136
static int mp_decode_layer3(MPADecodeContext *s)
2137
{
2138
    int nb_granules, main_data_begin, private_bits;
2139
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
2140
    GranuleDef granules[2][2], *g;
2141
    int16_t exponents[576];
2142

    
2143
    /* read side info */
2144
    if (s->lsf) {
2145
        main_data_begin = get_bits(&s->gb, 8);
2146
        private_bits = get_bits(&s->gb, s->nb_channels);
2147
        nb_granules = 1;
2148
    } else {
2149
        main_data_begin = get_bits(&s->gb, 9);
2150
        if (s->nb_channels == 2)
2151
            private_bits = get_bits(&s->gb, 3);
2152
        else
2153
            private_bits = get_bits(&s->gb, 5);
2154
        nb_granules = 2;
2155
        for(ch=0;ch<s->nb_channels;ch++) {
2156
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
2157
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
2158
        }
2159
    }
2160

    
2161
    for(gr=0;gr<nb_granules;gr++) {
2162
        for(ch=0;ch<s->nb_channels;ch++) {
2163
            dprintf("gr=%d ch=%d: side_info\n", gr, ch);
2164
            g = &granules[ch][gr];
2165
            g->part2_3_length = get_bits(&s->gb, 12);
2166
            g->big_values = get_bits(&s->gb, 9);
2167
            g->global_gain = get_bits(&s->gb, 8);
2168
            /* if MS stereo only is selected, we precompute the
2169
               1/sqrt(2) renormalization factor */
2170
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
2171
                MODE_EXT_MS_STEREO)
2172
                g->global_gain -= 2;
2173
            if (s->lsf)
2174
                g->scalefac_compress = get_bits(&s->gb, 9);
2175
            else
2176
                g->scalefac_compress = get_bits(&s->gb, 4);
2177
            blocksplit_flag = get_bits(&s->gb, 1);
2178
            if (blocksplit_flag) {
2179
                g->block_type = get_bits(&s->gb, 2);
2180
                if (g->block_type == 0)
2181
                    return -1;
2182
                g->switch_point = get_bits(&s->gb, 1);
2183
                for(i=0;i<2;i++)
2184
                    g->table_select[i] = get_bits(&s->gb, 5);
2185
                for(i=0;i<3;i++)
2186
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
2187
                /* compute huffman coded region sizes */
2188
                if (g->block_type == 2)
2189
                    g->region_size[0] = (36 / 2);
2190
                else {
2191
                    if (s->sample_rate_index <= 2)
2192
                        g->region_size[0] = (36 / 2);
2193
                    else if (s->sample_rate_index != 8)
2194
                        g->region_size[0] = (54 / 2);
2195
                    else
2196
                        g->region_size[0] = (108 / 2);
2197
                }
2198
                g->region_size[1] = (576 / 2);
2199
            } else {
2200
                int region_address1, region_address2, l;
2201
                g->block_type = 0;
2202
                g->switch_point = 0;
2203
                for(i=0;i<3;i++)
2204
                    g->table_select[i] = get_bits(&s->gb, 5);
2205
                /* compute huffman coded region sizes */
2206
                region_address1 = get_bits(&s->gb, 4);
2207
                region_address2 = get_bits(&s->gb, 3);
2208
                dprintf("region1=%d region2=%d\n",
2209
                        region_address1, region_address2);
2210
                g->region_size[0] =
2211
                    band_index_long[s->sample_rate_index][region_address1 + 1] >> 1;
2212
                l = region_address1 + region_address2 + 2;
2213
                /* should not overflow */
2214
                if (l > 22)
2215
                    l = 22;
2216
                g->region_size[1] =
2217
                    band_index_long[s->sample_rate_index][l] >> 1;
2218
            }
2219
            /* convert region offsets to region sizes and truncate
2220
               size to big_values */
2221
            g->region_size[2] = (576 / 2);
2222
            j = 0;
2223
            for(i=0;i<3;i++) {
2224
                k = FFMIN(g->region_size[i], g->big_values);
2225
                g->region_size[i] = k - j;
2226
                j = k;
2227
            }
2228

    
2229
            /* compute band indexes */
2230
            if (g->block_type == 2) {
2231
                if (g->switch_point) {
2232
                    /* if switched mode, we handle the 36 first samples as
2233
                       long blocks.  For 8000Hz, we handle the 48 first
2234
                       exponents as long blocks (XXX: check this!) */
2235
                    if (s->sample_rate_index <= 2)
2236
                        g->long_end = 8;
2237
                    else if (s->sample_rate_index != 8)
2238
                        g->long_end = 6;
2239
                    else
2240
                        g->long_end = 4; /* 8000 Hz */
2241

    
2242
                    g->short_start = 2 + (s->sample_rate_index != 8);
2243
                } else {
2244
                    g->long_end = 0;
2245
                    g->short_start = 0;
2246
                }
2247
            } else {
2248
                g->short_start = 13;
2249
                g->long_end = 22;
2250
            }
2251

    
2252
            g->preflag = 0;
2253
            if (!s->lsf)
2254
                g->preflag = get_bits(&s->gb, 1);
2255
            g->scalefac_scale = get_bits(&s->gb, 1);
2256
            g->count1table_select = get_bits(&s->gb, 1);
2257
            dprintf("block_type=%d switch_point=%d\n",
2258
                    g->block_type, g->switch_point);
2259
        }
2260
    }
2261

    
2262
  if (!s->adu_mode) {
2263
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2264
    assert((get_bits_count(&s->gb) & 7) == 0);
2265
    /* now we get bits from the main_data_begin offset */
2266
    dprintf("seekback: %d\n", main_data_begin);
2267
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2268
    if(main_data_begin > s->last_buf_size){
2269
        av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2270
        s->last_buf_size= main_data_begin;
2271
      }
2272

    
2273
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2274
    s->in_gb= s->gb;
2275
    init_get_bits(&s->gb, s->last_buf + s->last_buf_size - main_data_begin, main_data_begin*8);
2276
  }
2277

    
2278
    for(gr=0;gr<nb_granules;gr++) {
2279
        for(ch=0;ch<s->nb_channels;ch++) {
2280
            g = &granules[ch][gr];
2281

    
2282
            bits_pos = get_bits_count(&s->gb);
2283

    
2284
            if (!s->lsf) {
2285
                uint8_t *sc;
2286
                int slen, slen1, slen2;
2287

    
2288
                /* MPEG1 scale factors */
2289
                slen1 = slen_table[0][g->scalefac_compress];
2290
                slen2 = slen_table[1][g->scalefac_compress];
2291
                dprintf("slen1=%d slen2=%d\n", slen1, slen2);
2292
                if (g->block_type == 2) {
2293
                    n = g->switch_point ? 17 : 18;
2294
                    j = 0;
2295
                    if(slen1){
2296
                        for(i=0;i<n;i++)
2297
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
2298
                    }else{
2299
                        for(i=0;i<n;i++)
2300
                            g->scale_factors[j++] = 0;
2301
                    }
2302
                    if(slen2){
2303
                        for(i=0;i<18;i++)
2304
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
2305
                        for(i=0;i<3;i++)
2306
                            g->scale_factors[j++] = 0;
2307
                    }else{
2308
                        for(i=0;i<21;i++)
2309
                            g->scale_factors[j++] = 0;
2310
                    }
2311
                } else {
2312
                    sc = granules[ch][0].scale_factors;
2313
                    j = 0;
2314
                    for(k=0;k<4;k++) {
2315
                        n = (k == 0 ? 6 : 5);
2316
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2317
                            slen = (k < 2) ? slen1 : slen2;
2318
                            if(slen){
2319
                                for(i=0;i<n;i++)
2320
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
2321
                            }else{
2322
                                for(i=0;i<n;i++)
2323
                                    g->scale_factors[j++] = 0;
2324
                            }
2325
                        } else {
2326
                            /* simply copy from last granule */
2327
                            for(i=0;i<n;i++) {
2328
                                g->scale_factors[j] = sc[j];
2329
                                j++;
2330
                            }
2331
                        }
2332
                    }
2333
                    g->scale_factors[j++] = 0;
2334
                }
2335
#if defined(DEBUG)
2336
                {
2337
                    dprintf("scfsi=%x gr=%d ch=%d scale_factors:\n",
2338
                           g->scfsi, gr, ch);
2339
                    for(i=0;i<j;i++)
2340
                        dprintf(" %d", g->scale_factors[i]);
2341
                    dprintf("\n");
2342
                }
2343
#endif
2344
            } else {
2345
                int tindex, tindex2, slen[4], sl, sf;
2346

    
2347
                /* LSF scale factors */
2348
                if (g->block_type == 2) {
2349
                    tindex = g->switch_point ? 2 : 1;
2350
                } else {
2351
                    tindex = 0;
2352
                }
2353
                sf = g->scalefac_compress;
2354
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2355
                    /* intensity stereo case */
2356
                    sf >>= 1;
2357
                    if (sf < 180) {
2358
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2359
                        tindex2 = 3;
2360
                    } else if (sf < 244) {
2361
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2362
                        tindex2 = 4;
2363
                    } else {
2364
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2365
                        tindex2 = 5;
2366
                    }
2367
                } else {
2368
                    /* normal case */
2369
                    if (sf < 400) {
2370
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2371
                        tindex2 = 0;
2372
                    } else if (sf < 500) {
2373
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2374
                        tindex2 = 1;
2375
                    } else {
2376
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2377
                        tindex2 = 2;
2378
                        g->preflag = 1;
2379
                    }
2380
                }
2381

    
2382
                j = 0;
2383
                for(k=0;k<4;k++) {
2384
                    n = lsf_nsf_table[tindex2][tindex][k];
2385
                    sl = slen[k];
2386
                    if(sl){
2387
                        for(i=0;i<n;i++)
2388
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
2389
                    }else{
2390
                        for(i=0;i<n;i++)
2391
                            g->scale_factors[j++] = 0;
2392
                    }
2393
                }
2394
                /* XXX: should compute exact size */
2395
                for(;j<40;j++)
2396
                    g->scale_factors[j] = 0;
2397
#if defined(DEBUG)
2398
                {
2399
                    dprintf("gr=%d ch=%d scale_factors:\n",
2400
                           gr, ch);
2401
                    for(i=0;i<40;i++)
2402
                        dprintf(" %d", g->scale_factors[i]);
2403
                    dprintf("\n");
2404
                }
2405
#endif
2406
            }
2407

    
2408
            exponents_from_scale_factors(s, g, exponents);
2409

    
2410
            /* read Huffman coded residue */
2411
            if (huffman_decode(s, g, exponents,
2412
                               bits_pos + g->part2_3_length) < 0)
2413
                return -1;
2414
#if defined(DEBUG)
2415
            sample_dump(0, g->sb_hybrid, 576);
2416
#endif
2417
        } /* ch */
2418

    
2419
        if (s->nb_channels == 2)
2420
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2421

    
2422
        for(ch=0;ch<s->nb_channels;ch++) {
2423
            g = &granules[ch][gr];
2424

    
2425
            reorder_block(s, g);
2426
#if defined(DEBUG)
2427
            sample_dump(0, g->sb_hybrid, 576);
2428
#endif
2429
            s->compute_antialias(s, g);
2430
#if defined(DEBUG)
2431
            sample_dump(1, g->sb_hybrid, 576);
2432
#endif
2433
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2434
#if defined(DEBUG)
2435
            sample_dump(2, &s->sb_samples[ch][18 * gr][0], 576);
2436
#endif
2437
        }
2438
    } /* gr */
2439
    return nb_granules * 18;
2440
}
2441

    
2442
static int mp_decode_frame(MPADecodeContext *s,
2443
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
2444
{
2445
    int i, nb_frames, ch;
2446
    OUT_INT *samples_ptr;
2447

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

    
2450
    /* skip error protection field */
2451
    if (s->error_protection)
2452
        get_bits(&s->gb, 16);
2453

    
2454
    dprintf("frame %d:\n", s->frame_count);
2455
    switch(s->layer) {
2456
    case 1:
2457
        nb_frames = mp_decode_layer1(s);
2458
        break;
2459
    case 2:
2460
        nb_frames = mp_decode_layer2(s);
2461
        break;
2462
    case 3:
2463
    default:
2464
        nb_frames = mp_decode_layer3(s);
2465

    
2466
        s->last_buf_size=0;
2467
        if(s->in_gb.buffer){
2468
            align_get_bits(&s->gb);
2469
            i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2470
            if(i >= 0 && i <= BACKSTEP_SIZE){
2471
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
2472
                s->last_buf_size=i;
2473
            }else
2474
                av_log(NULL, AV_LOG_ERROR, "invalid old backstep %d\n", i);
2475
            s->gb= s->in_gb;
2476
        }
2477

    
2478
        align_get_bits(&s->gb);
2479
        assert((get_bits_count(&s->gb) & 7) == 0);
2480
        i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2481

    
2482
        if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
2483
            av_log(NULL, AV_LOG_ERROR, "invalid new backstep %d\n", i);
2484
            i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
2485
        }
2486
        assert(i <= buf_size - HEADER_SIZE && i>= 0);
2487
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
2488
        s->last_buf_size += i;
2489

    
2490
        break;
2491
    }
2492
#if defined(DEBUG)
2493
    for(i=0;i<nb_frames;i++) {
2494
        for(ch=0;ch<s->nb_channels;ch++) {
2495
            int j;
2496
            dprintf("%d-%d:", i, ch);
2497
            for(j=0;j<SBLIMIT;j++)
2498
                dprintf(" %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);
2499
            dprintf("\n");
2500
        }
2501
    }
2502
#endif
2503
    /* apply the synthesis filter */
2504
    for(ch=0;ch<s->nb_channels;ch++) {
2505
        samples_ptr = samples + ch;
2506
        for(i=0;i<nb_frames;i++) {
2507
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2508
                         window, &s->dither_state,
2509
                         samples_ptr, s->nb_channels,
2510
                         s->sb_samples[ch][i]);
2511
            samples_ptr += 32 * s->nb_channels;
2512
        }
2513
    }
2514
#ifdef DEBUG
2515
    s->frame_count++;
2516
#endif
2517
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2518
}
2519

    
2520
static int decode_frame(AVCodecContext * avctx,
2521
                        void *data, int *data_size,
2522
                        uint8_t * buf, int buf_size)
2523
{
2524
    MPADecodeContext *s = avctx->priv_data;
2525
    uint32_t header;
2526
    int out_size;
2527
    OUT_INT *out_samples = data;
2528

    
2529
retry:
2530
    if(buf_size < HEADER_SIZE)
2531
        return -1;
2532

    
2533
    header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
2534
    if(ff_mpa_check_header(header) < 0){
2535
        buf++;
2536
//        buf_size--;
2537
        av_log(avctx, AV_LOG_ERROR, "header missing skiping one byte\n");
2538
        goto retry;
2539
    }
2540

    
2541
    if (decode_header(s, header) == 1) {
2542
        /* free format: prepare to compute frame size */
2543
        s->frame_size = -1;
2544
        return -1;
2545
    }
2546
    /* update codec info */
2547
    avctx->sample_rate = s->sample_rate;
2548
    avctx->channels = s->nb_channels;
2549
    avctx->bit_rate = s->bit_rate;
2550
    avctx->sub_id = s->layer;
2551
    switch(s->layer) {
2552
    case 1:
2553
        avctx->frame_size = 384;
2554
        break;
2555
    case 2:
2556
        avctx->frame_size = 1152;
2557
        break;
2558
    case 3:
2559
        if (s->lsf)
2560
            avctx->frame_size = 576;
2561
        else
2562
            avctx->frame_size = 1152;
2563
        break;
2564
    }
2565

    
2566
    if(s->frame_size<=0 || s->frame_size > buf_size){
2567
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2568
        return -1;
2569
    }else if(s->frame_size < buf_size){
2570
        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
2571
    }
2572

    
2573
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2574
    if(out_size>=0)
2575
        *data_size = out_size;
2576
    else
2577
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding mpeg audio frame\n"); //FIXME return -1 / but also return the number of bytes consumed
2578
    s->frame_size = 0;
2579
    return buf_size;
2580
}
2581

    
2582

    
2583
static int decode_frame_adu(AVCodecContext * avctx,
2584
                        void *data, int *data_size,
2585
                        uint8_t * buf, int buf_size)
2586
{
2587
    MPADecodeContext *s = avctx->priv_data;
2588
    uint32_t header;
2589
    int len, out_size;
2590
    OUT_INT *out_samples = data;
2591

    
2592
    len = buf_size;
2593

    
2594
    // Discard too short frames
2595
    if (buf_size < HEADER_SIZE) {
2596
        *data_size = 0;
2597
        return buf_size;
2598
    }
2599

    
2600

    
2601
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2602
        len = MPA_MAX_CODED_FRAME_SIZE;
2603

    
2604
    // Get header and restore sync word
2605
    header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3] | 0xffe00000;
2606

    
2607
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2608
        *data_size = 0;
2609
        return buf_size;
2610
    }
2611

    
2612
    decode_header(s, header);
2613
    /* update codec info */
2614
    avctx->sample_rate = s->sample_rate;
2615
    avctx->channels = s->nb_channels;
2616
    avctx->bit_rate = s->bit_rate;
2617
    avctx->sub_id = s->layer;
2618

    
2619
    avctx->frame_size=s->frame_size = len;
2620

    
2621
    if (avctx->parse_only) {
2622
        out_size = buf_size;
2623
    } else {
2624
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2625
    }
2626

    
2627
    *data_size = out_size;
2628
    return buf_size;
2629
}
2630

    
2631

    
2632
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2633
static int mp3Frames[16] = {0,1,1,2,3,3,4,5,2};   /* number of mp3 decoder instances */
2634
static int mp3Channels[16] = {0,1,2,3,4,5,6,8,4}; /* total output channels */
2635
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2636
static int chan_offset[9][5] = {
2637
    {0},
2638
    {0},            // C
2639
    {0},            // FLR
2640
    {2,0},          // C FLR
2641
    {2,0,3},        // C FLR BS
2642
    {4,0,2},        // C FLR BLRS
2643
    {4,0,2,5},      // C FLR BLRS LFE
2644
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2645
    {0,2}           // FLR BLRS
2646
};
2647

    
2648

    
2649
static int decode_init_mp3on4(AVCodecContext * avctx)
2650
{
2651
    MP3On4DecodeContext *s = avctx->priv_data;
2652
    int i;
2653

    
2654
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2655
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2656
        return -1;
2657
    }
2658

    
2659
    s->chan_cfg = (((unsigned char *)avctx->extradata)[1] >> 3) & 0x0f;
2660
    s->frames = mp3Frames[s->chan_cfg];
2661
    if(!s->frames) {
2662
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2663
        return -1;
2664
    }
2665
    avctx->channels = mp3Channels[s->chan_cfg];
2666

    
2667
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2668
     * We replace avctx->priv_data with the context of the first decoder so that
2669
     * decode_init() does not have to be changed.
2670
     * Other decoders will be inited here copying data from the first context
2671
     */
2672
    // Allocate zeroed memory for the first decoder context
2673
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2674
    // Put decoder context in place to make init_decode() happy
2675
    avctx->priv_data = s->mp3decctx[0];
2676
    decode_init(avctx);
2677
    // Restore mp3on4 context pointer
2678
    avctx->priv_data = s;
2679
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2680

    
2681
    /* Create a separate codec/context for each frame (first is already ok).
2682
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2683
     */
2684
    for (i = 1; i < s->frames; i++) {
2685
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2686
        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2687
        s->mp3decctx[i]->adu_mode = 1;
2688
    }
2689

    
2690
    return 0;
2691
}
2692

    
2693

    
2694
static int decode_close_mp3on4(AVCodecContext * avctx)
2695
{
2696
    MP3On4DecodeContext *s = avctx->priv_data;
2697
    int i;
2698

    
2699
    for (i = 0; i < s->frames; i++)
2700
        if (s->mp3decctx[i])
2701
            av_free(s->mp3decctx[i]);
2702

    
2703
    return 0;
2704
}
2705

    
2706

    
2707
static int decode_frame_mp3on4(AVCodecContext * avctx,
2708
                        void *data, int *data_size,
2709
                        uint8_t * buf, int buf_size)
2710
{
2711
    MP3On4DecodeContext *s = avctx->priv_data;
2712
    MPADecodeContext *m;
2713
    int len, out_size = 0;
2714
    uint32_t header;
2715
    OUT_INT *out_samples = data;
2716
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2717
    OUT_INT *outptr, *bp;
2718
    int fsize;
2719
    unsigned char *start2 = buf, *start;
2720
    int fr, i, j, n;
2721
    int off = avctx->channels;
2722
    int *coff = chan_offset[s->chan_cfg];
2723

    
2724
    len = buf_size;
2725

    
2726
    // Discard too short frames
2727
    if (buf_size < HEADER_SIZE) {
2728
        *data_size = 0;
2729
        return buf_size;
2730
    }
2731

    
2732
    // If only one decoder interleave is not needed
2733
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2734

    
2735
    for (fr = 0; fr < s->frames; fr++) {
2736
        start = start2;
2737
        fsize = (start[0] << 4) | (start[1] >> 4);
2738
        start2 += fsize;
2739
        if (fsize > len)
2740
            fsize = len;
2741
        len -= fsize;
2742
        if (fsize > MPA_MAX_CODED_FRAME_SIZE)
2743
            fsize = MPA_MAX_CODED_FRAME_SIZE;
2744
        m = s->mp3decctx[fr];
2745
        assert (m != NULL);
2746

    
2747
        // Get header
2748
        header = (start[0] << 24) | (start[1] << 16) | (start[2] << 8) | start[3] | 0xfff00000;
2749

    
2750
        if (ff_mpa_check_header(header) < 0) { // Bad header, discard block
2751
            *data_size = 0;
2752
            return buf_size;
2753
        }
2754

    
2755
        decode_header(m, header);
2756
        mp_decode_frame(m, decoded_buf, start, fsize);
2757

    
2758
        n = MPA_FRAME_SIZE * m->nb_channels;
2759
        out_size += n * sizeof(OUT_INT);
2760
        if(s->frames > 1) {
2761
            /* interleave output data */
2762
            bp = out_samples + coff[fr];
2763
            if(m->nb_channels == 1) {
2764
                for(j = 0; j < n; j++) {
2765
                    *bp = decoded_buf[j];
2766
                    bp += off;
2767
                }
2768
            } else {
2769
                for(j = 0; j < n; j++) {
2770
                    bp[0] = decoded_buf[j++];
2771
                    bp[1] = decoded_buf[j];
2772
                    bp += off;
2773
                }
2774
            }
2775
        }
2776
    }
2777

    
2778
    /* update codec info */
2779
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2780
    avctx->frame_size= buf_size;
2781
    avctx->bit_rate = 0;
2782
    for (i = 0; i < s->frames; i++)
2783
        avctx->bit_rate += s->mp3decctx[i]->bit_rate;
2784

    
2785
    *data_size = out_size;
2786
    return buf_size;
2787
}
2788

    
2789

    
2790
AVCodec mp2_decoder =
2791
{
2792
    "mp2",
2793
    CODEC_TYPE_AUDIO,
2794
    CODEC_ID_MP2,
2795
    sizeof(MPADecodeContext),
2796
    decode_init,
2797
    NULL,
2798
    NULL,
2799
    decode_frame,
2800
    CODEC_CAP_PARSE_ONLY,
2801
};
2802

    
2803
AVCodec mp3_decoder =
2804
{
2805
    "mp3",
2806
    CODEC_TYPE_AUDIO,
2807
    CODEC_ID_MP3,
2808
    sizeof(MPADecodeContext),
2809
    decode_init,
2810
    NULL,
2811
    NULL,
2812
    decode_frame,
2813
    CODEC_CAP_PARSE_ONLY,
2814
};
2815

    
2816
AVCodec mp3adu_decoder =
2817
{
2818
    "mp3adu",
2819
    CODEC_TYPE_AUDIO,
2820
    CODEC_ID_MP3ADU,
2821
    sizeof(MPADecodeContext),
2822
    decode_init,
2823
    NULL,
2824
    NULL,
2825
    decode_frame_adu,
2826
    CODEC_CAP_PARSE_ONLY,
2827
};
2828

    
2829
AVCodec mp3on4_decoder =
2830
{
2831
    "mp3on4",
2832
    CODEC_TYPE_AUDIO,
2833
    CODEC_ID_MP3ON4,
2834
    sizeof(MP3On4DecodeContext),
2835
    decode_init_mp3on4,
2836
    NULL,
2837
    decode_close_mp3on4,
2838
    decode_frame_mp3on4,
2839
    0
2840
};