Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 8e5606bf

History | View | Annotate | Download (85.4 KB)

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

    
22
/**
23
 * @file mpegaudiodec.c
24
 * MPEG Audio decoder.
25
 */
26

    
27
//#define DEBUG
28
#include "avcodec.h"
29
#include "bitstream.h"
30
#include "dsputil.h"
31

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

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

    
44
#include "mpegaudio.h"
45

    
46
#include "mathops.h"
47

    
48
#define FRAC_ONE    (1 << FRAC_BITS)
49

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

    
55
#define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
56

    
57
/****************/
58

    
59
#define HEADER_SIZE 4
60
#define BACKSTEP_SIZE 512
61
#define EXTRABYTES 24
62

    
63
struct GranuleDef;
64

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

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

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

    
124
#define MODE_EXT_MS_STEREO 2
125
#define MODE_EXT_I_STEREO  1
126

    
127
/* layer 3 huffman tables */
128
typedef struct HuffTable {
129
    int xsize;
130
    const uint8_t *bits;
131
    const uint16_t *codes;
132
} HuffTable;
133

    
134
#include "mpegaudiodectab.h"
135

    
136
static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
137
static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
138

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

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

    
163
#define SCALE_GEN(v) \
164
{ FIXR(1.0 * (v)), FIXR(0.7937005259 * (v)), FIXR(0.6299605249 * (v)) }
165

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

    
172
static MPA_INT window[512] __attribute__((aligned(16)));
173

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

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

    
190
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
191
{
192
    int shift, mod, val;
193

    
194
    shift = scale_factor_modshift[scale_factor];
195
    mod = shift & 3;
196
    shift >>= 2;
197

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

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

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

    
219
    return m;
220
}
221

    
222
/* all integer n^(4/3) computation code */
223
#define DEV_ORDER 13
224

    
225
#define POW_FRAC_BITS 24
226
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
227
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
228
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
229

    
230
static int dev_4_3_coefs[DEV_ORDER];
231

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

    
240
static void int_pow_init(void)
241
{
242
    int i, a;
243

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

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

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

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

    
304
#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
305
    avctx->sample_fmt= SAMPLE_FMT_S32;
306
#else
307
    avctx->sample_fmt= SAMPLE_FMT_S16;
308
#endif
309
    s->error_resilience= avctx->error_resilience;
310

    
311
    if(avctx->antialias_algo != FF_AA_FLOAT)
312
        s->compute_antialias= compute_antialias_integer;
313
    else
314
        s->compute_antialias= compute_antialias_float;
315

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

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

    
341
        ff_mpa_synth_init(window);
342

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

    
351
            memset(tmp_bits , 0, sizeof(tmp_bits ));
352
            memset(tmp_codes, 0, sizeof(tmp_codes));
353

    
354
            xsize = h->xsize;
355
            n = xsize * xsize;
356

    
357
            j = 0;
358
            for(x=0;x<xsize;x++) {
359
                for(y=0;y<xsize;y++){
360
                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
361
                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
362
                }
363
            }
364

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

    
374
        for(i=0;i<9;i++) {
375
            k = 0;
376
            for(j=0;j<22;j++) {
377
                band_index_long[i][j] = k;
378
                k += band_size_long[i][j];
379
            }
380
            band_index_long[i][22] = k;
381
        }
382

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

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

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

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

    
429
        for(i=0;i<16;i++) {
430
            double f;
431
            int e, k;
432

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

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

    
461
        /* compute mdct windows */
462
        for(i=0;i<36;i++) {
463
            for(j=0; j<4; j++){
464
                double d;
465

    
466
                if(j==2 && i%3 != 1)
467
                    continue;
468

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

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

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

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

    
510
#ifdef DEBUG
511
    s->frame_count = 0;
512
#endif
513
    if (avctx->codec_id == CODEC_ID_MP3ADU)
514
        s->adu_mode = 1;
515
    return 0;
516
}
517

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

    
520
/* cos(i*pi/64) */
521

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

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

    
548
#define COS2_0 FIXHR(0.50979557910415916894/2)
549
#define COS2_1 FIXHR(0.60134488693504528054/2)
550
#define COS2_2 FIXHR(0.89997622313641570463/2)
551
#define COS2_3 FIXHR(2.56291544774150617881/8)
552

    
553
#define COS3_0 FIXHR(0.54119610014619698439/2)
554
#define COS3_1 FIXHR(1.30656296487637652785/4)
555

    
556
#define COS4_0 FIXHR(0.70710678118654752439/2)
557

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

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

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

    
584
#define ADD(a, b) tab[a] += tab[b]
585

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

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

    
635

    
636

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

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

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

    
692
    /* pass 6 */
693

    
694
    ADD( 8, 12);
695
    ADD(12, 10);
696
    ADD(10, 14);
697
    ADD(14,  9);
698
    ADD( 9, 13);
699
    ADD(13, 11);
700
    ADD(11, 15);
701

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

    
719
    ADD(24, 28);
720
    ADD(28, 26);
721
    ADD(26, 30);
722
    ADD(30, 25);
723
    ADD(25, 29);
724
    ADD(29, 27);
725
    ADD(27, 31);
726

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

    
745
#if FRAC_BITS <= 15
746

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

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

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

    
765
#else
766

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

    
779
#   define MULS(ra, rb) MUL64(ra, rb)
780
#endif
781

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

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

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

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

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

    
861
    dct32(tmp, sb_samples);
862

    
863
    offset = *synth_buf_offset;
864
    synth_buf = synth_buf_ptr + offset;
865

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

    
881
    samples2 = samples + 31 * incr;
882
    w = window;
883
    w2 = window + 31;
884

    
885
    sum = *dither_state;
886
    p = synth_buf + 16;
887
    SUM8(sum, +=, w, p);
888
    p = synth_buf + 48;
889
    SUM8(sum, -=, w + 32, p);
890
    *samples = round_sample(&sum);
891
    samples += incr;
892
    w++;
893

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

    
903
        *samples = round_sample(&sum);
904
        samples += incr;
905
        sum += sum2;
906
        *samples2 = round_sample(&sum);
907
        samples2 -= incr;
908
        w++;
909
        w2--;
910
    }
911

    
912
    p = synth_buf + 32;
913
    SUM8(sum, -=, w + 32, p);
914
    *samples = round_sample(&sum);
915
    *dither_state= sum;
916

    
917
    offset = (offset - 32) & 511;
918
    *synth_buf_offset = offset;
919
}
920

    
921
#define C3 FIXHR(0.86602540378443864676/2)
922

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

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

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

    
955
    in0= in[0*3];
956
    in1= in[1*3] + in[0*3];
957
    in2= in[2*3] + in[1*3];
958
    in3= in[3*3] + in[2*3];
959
    in4= in[4*3] + in[3*3];
960
    in5= in[5*3] + in[4*3];
961
    in5 += in3;
962
    in3 += in1;
963

    
964
    in2= MULH(2*in2, C3);
965
    in3= MULH(4*in3, C3);
966

    
967
    t1 = in0 - in4;
968
    t2 = MULH(2*(in1 - in5), icos36h[4]);
969

    
970
    out[ 7]=
971
    out[10]= t1 + t2;
972
    out[ 1]=
973
    out[ 4]= t1 - t2;
974

    
975
    in0 += in4>>1;
976
    in4 = in0 + in2;
977
    in5 += 2*in1;
978
    in1 = MULH(in5 + in3, icos36h[1]);
979
    out[ 8]=
980
    out[ 9]= in4 + in1;
981
    out[ 2]=
982
    out[ 3]= in4 - in1;
983

    
984
    in0 -= in2;
985
    in5 = MULH(2*(in5 - in3), icos36h[7]);
986
    out[ 0]=
987
    out[ 5]= in0 - in5;
988
    out[ 6]=
989
    out[11]= in0 + in5;
990
}
991

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

    
1002

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

    
1009
    for(i=17;i>=1;i--)
1010
        in[i] += in[i-1];
1011
    for(i=17;i>=3;i-=2)
1012
        in[i] += in[i-2];
1013

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

1022
        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
1023
        t1 = in1[2*0] - in1[2*6];
1024
        tmp1[ 6] = t1 - (t2>>1);
1025
        tmp1[16] = t1 + t2;
1026

1027
        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
1028
        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
1029
        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
1030

1031
        tmp1[10] = (t3 - t0 - t2) >> 32;
1032
        tmp1[ 2] = (t3 + t0 + t1) >> 32;
1033
        tmp1[14] = (t3 + t2 - t1) >> 32;
1034

1035
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1036
        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
1037
        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
1038
        t0 = MUL64(2*in1[2*3], C3);
1039

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

1042
        tmp1[ 0] = (t2 + t3 + t0) >> 32;
1043
        tmp1[12] = (t2 + t1 - t0) >> 32;
1044
        tmp1[ 8] = (t3 - t1 - t0) >> 32;
1045
#else
1046
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1047

    
1048
        t3 = in1[2*0] + (in1[2*6]>>1);
1049
        t1 = in1[2*0] - in1[2*6];
1050
        tmp1[ 6] = t1 - (t2>>1);
1051
        tmp1[16] = t1 + t2;
1052

    
1053
        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1054
        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1055
        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1056

    
1057
        tmp1[10] = t3 - t0 - t2;
1058
        tmp1[ 2] = t3 + t0 + t1;
1059
        tmp1[14] = t3 + t2 - t1;
1060

    
1061
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1062
        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1063
        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1064
        t0 = MULH(2*in1[2*3], C3);
1065

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

    
1068
        tmp1[ 0] = t2 + t3 + t0;
1069
        tmp1[12] = t2 + t1 - t0;
1070
        tmp1[ 8] = t3 - t1 - t0;
1071
#endif
1072
    }
1073

    
1074
    i = 0;
1075
    for(j=0;j<4;j++) {
1076
        t0 = tmp[i];
1077
        t1 = tmp[i + 2];
1078
        s0 = t1 + t0;
1079
        s2 = t1 - t0;
1080

    
1081
        t2 = tmp[i + 1];
1082
        t3 = tmp[i + 3];
1083
        s1 = MULH(2*(t3 + t2), icos36h[j]);
1084
        s3 = MULL(t3 - t2, icos36[8 - j]);
1085

    
1086
        t0 = s0 + s1;
1087
        t1 = s0 - s1;
1088
        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1089
        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1090
        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1091
        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1092

    
1093
        t0 = s2 + s3;
1094
        t1 = s2 - s3;
1095
        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1096
        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1097
        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1098
        buf[      + j] = MULH(t0, win[18         + j]);
1099
        i += 4;
1100
    }
1101

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

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

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

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

    
1145
    if (s->mode == MPA_MONO)
1146
        s->nb_channels = 1;
1147
    else
1148
        s->nb_channels = 2;
1149

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

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

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

    
1199
    if (ff_mpa_check_header(head) != 0)
1200
        return -1;
1201

    
1202
    if (decode_header(s, head) != 0) {
1203
        return -1;
1204
    }
1205

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

    
1222
    *sample_rate = s->sample_rate;
1223
    avctx->channels = s->nb_channels;
1224
    avctx->bit_rate = s->bit_rate;
1225
    avctx->sub_id = s->layer;
1226
    return s->frame_size;
1227
}
1228

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

    
1236
    if (s->mode == MPA_JSTEREO)
1237
        bound = (s->mode_ext + 1) * 4;
1238
    else
1239
        bound = SBLIMIT;
1240

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

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

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

    
1296
/* bitrate is in kb/s */
1297
int l2_select_table(int bitrate, int nb_channels, int freq, int lsf)
1298
{
1299
    int ch_bitrate, table;
1300

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

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

    
1328
    /* select decoding table */
1329
    table = l2_select_table(s->bit_rate / 1000, s->nb_channels,
1330
                            s->sample_rate, s->lsf);
1331
    sblimit = sblimit_table[table];
1332
    alloc_table = alloc_tables[table];
1333

    
1334
    if (s->mode == MPA_JSTEREO)
1335
        bound = (s->mode_ext + 1) * 4;
1336
    else
1337
        bound = sblimit;
1338

    
1339
    dprintf("bound=%d sblimit=%d\n", bound, sblimit);
1340

    
1341
    /* sanity check */
1342
    if( bound > sblimit ) bound = sblimit;
1343

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

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

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

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

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

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

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

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

    
1556
    exp_ptr = exponents;
1557
    gain = g->global_gain - 210;
1558
    shift = g->scalefac_scale + 1;
1559

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

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

    
1586
/* handle n = 0 too */
1587
static inline int get_bitsz(GetBitContext *s, int n)
1588
{
1589
    if (n == 0)
1590
        return 0;
1591
    else
1592
        return get_bits(s, n);
1593
}
1594

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

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

    
1617
        if(!l){
1618
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1619
            s_index += 2*j;
1620
            continue;
1621
        }
1622

    
1623
        /* read huffcode and compute each couple */
1624
        for(;j>0;j--) {
1625
            int exponent, x, y, v;
1626
            int pos= get_bits_count(&s->gb);
1627

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

    
1645
            if(!y){
1646
                g->sb_hybrid[s_index  ] =
1647
                g->sb_hybrid[s_index+1] = 0;
1648
                s_index += 2;
1649
                continue;
1650
            }
1651

    
1652
            exponent= exponents[s_index];
1653

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

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

    
1730
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1731
        dprintf("t=%d code=%d\n", g->count1table_select, code);
1732
        g->sb_hybrid[s_index+0]=
1733
        g->sb_hybrid[s_index+1]=
1734
        g->sb_hybrid[s_index+2]=
1735
        g->sb_hybrid[s_index+3]= 0;
1736
        while(code){
1737
            const static int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1738
            int v;
1739
            int pos= s_index+idxtab[code];
1740
            code ^= 8>>idxtab[code];
1741
            v = exp_table[ exponents[pos] ];
1742
//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1743
            if(get_bits1(&s->gb))
1744
                v = -v;
1745
            g->sb_hybrid[pos] = v;
1746
        }
1747
        s_index+=4;
1748
    }
1749
    /* skip extension bits */
1750
    bits_left = end_pos - get_bits_count(&s->gb);
1751
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1752
    if (bits_left < 0 || bits_left > 16) {
1753
        av_log(NULL, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1754
        s_index=0;
1755
    }else if(bits_left > 0 && s->error_resilience >= FF_ER_AGGRESSIVE){
1756
        av_log(NULL, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1757
        s_index=0;
1758
    }
1759
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1760
    skip_bits_long(&s->gb, bits_left);
1761

    
1762
    return 0;
1763
}
1764

    
1765
/* Reorder short blocks from bitstream order to interleaved order. It
1766
   would be faster to do it in parsing, but the code would be far more
1767
   complicated */
1768
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1769
{
1770
    int i, j, len;
1771
    int32_t *ptr, *dst, *ptr1;
1772
    int32_t tmp[576];
1773

    
1774
    if (g->block_type != 2)
1775
        return;
1776

    
1777
    if (g->switch_point) {
1778
        if (s->sample_rate_index != 8) {
1779
            ptr = g->sb_hybrid + 36;
1780
        } else {
1781
            ptr = g->sb_hybrid + 48;
1782
        }
1783
    } else {
1784
        ptr = g->sb_hybrid;
1785
    }
1786

    
1787
    for(i=g->short_start;i<13;i++) {
1788
        len = band_size_short[s->sample_rate_index][i];
1789
        ptr1 = ptr;
1790
        dst = tmp;
1791
        for(j=len;j>0;j--) {
1792
            *dst++ = ptr[0*len];
1793
            *dst++ = ptr[1*len];
1794
            *dst++ = ptr[2*len];
1795
            ptr++;
1796
        }
1797
        ptr+=2*len;
1798
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1799
    }
1800
}
1801

    
1802
#define ISQRT2 FIXR(0.70710678118654752440)
1803

    
1804
static void compute_stereo(MPADecodeContext *s,
1805
                           GranuleDef *g0, GranuleDef *g1)
1806
{
1807
    int i, j, k, l;
1808
    int32_t v1, v2;
1809
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1810
    int32_t (*is_tab)[16];
1811
    int32_t *tab0, *tab1;
1812
    int non_zero_found_short[3];
1813

    
1814
    /* intensity stereo */
1815
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1816
        if (!s->lsf) {
1817
            is_tab = is_table;
1818
            sf_max = 7;
1819
        } else {
1820
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1821
            sf_max = 16;
1822
        }
1823

    
1824
        tab0 = g0->sb_hybrid + 576;
1825
        tab1 = g1->sb_hybrid + 576;
1826

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

    
1851
                    v1 = is_tab[0][sf];
1852
                    v2 = is_tab[1][sf];
1853
                    for(j=0;j<len;j++) {
1854
                        tmp0 = tab0[j];
1855
                        tab0[j] = MULL(tmp0, v1);
1856
                        tab1[j] = MULL(tmp0, v2);
1857
                    }
1858
                } else {
1859
                found1:
1860
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1861
                        /* lower part of the spectrum : do ms stereo
1862
                           if enabled */
1863
                        for(j=0;j<len;j++) {
1864
                            tmp0 = tab0[j];
1865
                            tmp1 = tab1[j];
1866
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1867
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1868
                        }
1869
                    }
1870
                }
1871
            }
1872
        }
1873

    
1874
        non_zero_found = non_zero_found_short[0] |
1875
            non_zero_found_short[1] |
1876
            non_zero_found_short[2];
1877

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

    
1931
static void compute_antialias_integer(MPADecodeContext *s,
1932
                              GranuleDef *g)
1933
{
1934
    int32_t *ptr, *csa;
1935
    int n, i;
1936

    
1937
    /* we antialias only "long" bands */
1938
    if (g->block_type == 2) {
1939
        if (!g->switch_point)
1940
            return;
1941
        /* XXX: check this for 8000Hz case */
1942
        n = 1;
1943
    } else {
1944
        n = SBLIMIT - 1;
1945
    }
1946

    
1947
    ptr = g->sb_hybrid + 18;
1948
    for(i = n;i > 0;i--) {
1949
        int tmp0, tmp1, tmp2;
1950
        csa = &csa_table[0][0];
1951
#define INT_AA(j) \
1952
            tmp0 = ptr[-1-j];\
1953
            tmp1 = ptr[   j];\
1954
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1955
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1956
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1957

    
1958
        INT_AA(0)
1959
        INT_AA(1)
1960
        INT_AA(2)
1961
        INT_AA(3)
1962
        INT_AA(4)
1963
        INT_AA(5)
1964
        INT_AA(6)
1965
        INT_AA(7)
1966

    
1967
        ptr += 18;
1968
    }
1969
}
1970

    
1971
static void compute_antialias_float(MPADecodeContext *s,
1972
                              GranuleDef *g)
1973
{
1974
    int32_t *ptr;
1975
    int n, i;
1976

    
1977
    /* we antialias only "long" bands */
1978
    if (g->block_type == 2) {
1979
        if (!g->switch_point)
1980
            return;
1981
        /* XXX: check this for 8000Hz case */
1982
        n = 1;
1983
    } else {
1984
        n = SBLIMIT - 1;
1985
    }
1986

    
1987
    ptr = g->sb_hybrid + 18;
1988
    for(i = n;i > 0;i--) {
1989
        float tmp0, tmp1;
1990
        float *csa = &csa_table_float[0][0];
1991
#define FLOAT_AA(j)\
1992
        tmp0= ptr[-1-j];\
1993
        tmp1= ptr[   j];\
1994
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1995
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1996

    
1997
        FLOAT_AA(0)
1998
        FLOAT_AA(1)
1999
        FLOAT_AA(2)
2000
        FLOAT_AA(3)
2001
        FLOAT_AA(4)
2002
        FLOAT_AA(5)
2003
        FLOAT_AA(6)
2004
        FLOAT_AA(7)
2005

    
2006
        ptr += 18;
2007
    }
2008
}
2009

    
2010
static void compute_imdct(MPADecodeContext *s,
2011
                          GranuleDef *g,
2012
                          int32_t *sb_samples,
2013
                          int32_t *mdct_buf)
2014
{
2015
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
2016
    int32_t out2[12];
2017
    int i, j, mdct_long_end, v, sblimit;
2018

    
2019
    /* find last non zero block */
2020
    ptr = g->sb_hybrid + 576;
2021
    ptr1 = g->sb_hybrid + 2 * 18;
2022
    while (ptr >= ptr1) {
2023
        ptr -= 6;
2024
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
2025
        if (v != 0)
2026
            break;
2027
    }
2028
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
2029

    
2030
    if (g->block_type == 2) {
2031
        /* XXX: check for 8000 Hz */
2032
        if (g->switch_point)
2033
            mdct_long_end = 2;
2034
        else
2035
            mdct_long_end = 0;
2036
    } else {
2037
        mdct_long_end = sblimit;
2038
    }
2039

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

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

    
2100
#if defined(DEBUG)
2101
void sample_dump(int fnum, int32_t *tab, int n)
2102
{
2103
    static FILE *files[16], *f;
2104
    char buf[512];
2105
    int i;
2106
    int32_t v;
2107

    
2108
    f = files[fnum];
2109
    if (!f) {
2110
        snprintf(buf, sizeof(buf), "/tmp/out%d.%s.pcm",
2111
                fnum,
2112
#ifdef USE_HIGHPRECISION
2113
                "hp"
2114
#else
2115
                "lp"
2116
#endif
2117
                );
2118
        f = fopen(buf, "w");
2119
        if (!f)
2120
            return;
2121
        files[fnum] = f;
2122
    }
2123

    
2124
    if (fnum == 0) {
2125
        static int pos = 0;
2126
        av_log(NULL, AV_LOG_DEBUG, "pos=%d\n", pos);
2127
        for(i=0;i<n;i++) {
2128
            av_log(NULL, AV_LOG_DEBUG, " %0.4f", (double)tab[i] / FRAC_ONE);
2129
            if ((i % 18) == 17)
2130
                av_log(NULL, AV_LOG_DEBUG, "\n");
2131
        }
2132
        pos += n;
2133
    }
2134
    for(i=0;i<n;i++) {
2135
        /* normalize to 23 frac bits */
2136
        v = tab[i] << (23 - FRAC_BITS);
2137
        fwrite(&v, 1, sizeof(int32_t), f);
2138
    }
2139
}
2140
#endif
2141

    
2142

    
2143
/* main layer3 decoding function */
2144
static int mp_decode_layer3(MPADecodeContext *s)
2145
{
2146
    int nb_granules, main_data_begin, private_bits;
2147
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
2148
    GranuleDef granules[2][2], *g;
2149
    int16_t exponents[576];
2150

    
2151
    /* read side info */
2152
    if (s->lsf) {
2153
        main_data_begin = get_bits(&s->gb, 8);
2154
        private_bits = get_bits(&s->gb, s->nb_channels);
2155
        nb_granules = 1;
2156
    } else {
2157
        main_data_begin = get_bits(&s->gb, 9);
2158
        if (s->nb_channels == 2)
2159
            private_bits = get_bits(&s->gb, 3);
2160
        else
2161
            private_bits = get_bits(&s->gb, 5);
2162
        nb_granules = 2;
2163
        for(ch=0;ch<s->nb_channels;ch++) {
2164
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
2165
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
2166
        }
2167
    }
2168

    
2169
    for(gr=0;gr<nb_granules;gr++) {
2170
        for(ch=0;ch<s->nb_channels;ch++) {
2171
            dprintf("gr=%d ch=%d: side_info\n", gr, ch);
2172
            g = &granules[ch][gr];
2173
            g->part2_3_length = get_bits(&s->gb, 12);
2174
            g->big_values = get_bits(&s->gb, 9);
2175
            if(g->big_values > 288){
2176
                av_log(NULL, AV_LOG_ERROR, "big_values too big\n");
2177
                return -1;
2178
            }
2179

    
2180
            g->global_gain = get_bits(&s->gb, 8);
2181
            /* if MS stereo only is selected, we precompute the
2182
               1/sqrt(2) renormalization factor */
2183
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
2184
                MODE_EXT_MS_STEREO)
2185
                g->global_gain -= 2;
2186
            if (s->lsf)
2187
                g->scalefac_compress = get_bits(&s->gb, 9);
2188
            else
2189
                g->scalefac_compress = get_bits(&s->gb, 4);
2190
            blocksplit_flag = get_bits(&s->gb, 1);
2191
            if (blocksplit_flag) {
2192
                g->block_type = get_bits(&s->gb, 2);
2193
                if (g->block_type == 0){
2194
                    av_log(NULL, AV_LOG_ERROR, "invalid block type\n");
2195
                    return -1;
2196
                }
2197
                g->switch_point = get_bits(&s->gb, 1);
2198
                for(i=0;i<2;i++)
2199
                    g->table_select[i] = get_bits(&s->gb, 5);
2200
                for(i=0;i<3;i++)
2201
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
2202
                /* compute huffman coded region sizes */
2203
                if (g->block_type == 2)
2204
                    g->region_size[0] = (36 / 2);
2205
                else {
2206
                    if (s->sample_rate_index <= 2)
2207
                        g->region_size[0] = (36 / 2);
2208
                    else if (s->sample_rate_index != 8)
2209
                        g->region_size[0] = (54 / 2);
2210
                    else
2211
                        g->region_size[0] = (108 / 2);
2212
                }
2213
                g->region_size[1] = (576 / 2);
2214
            } else {
2215
                int region_address1, region_address2, l;
2216
                g->block_type = 0;
2217
                g->switch_point = 0;
2218
                for(i=0;i<3;i++)
2219
                    g->table_select[i] = get_bits(&s->gb, 5);
2220
                /* compute huffman coded region sizes */
2221
                region_address1 = get_bits(&s->gb, 4);
2222
                region_address2 = get_bits(&s->gb, 3);
2223
                dprintf("region1=%d region2=%d\n",
2224
                        region_address1, region_address2);
2225
                g->region_size[0] =
2226
                    band_index_long[s->sample_rate_index][region_address1 + 1] >> 1;
2227
                l = region_address1 + region_address2 + 2;
2228
                /* should not overflow */
2229
                if (l > 22)
2230
                    l = 22;
2231
                g->region_size[1] =
2232
                    band_index_long[s->sample_rate_index][l] >> 1;
2233
            }
2234
            /* convert region offsets to region sizes and truncate
2235
               size to big_values */
2236
            g->region_size[2] = (576 / 2);
2237
            j = 0;
2238
            for(i=0;i<3;i++) {
2239
                k = FFMIN(g->region_size[i], g->big_values);
2240
                g->region_size[i] = k - j;
2241
                j = k;
2242
            }
2243

    
2244
            /* compute band indexes */
2245
            if (g->block_type == 2) {
2246
                if (g->switch_point) {
2247
                    /* if switched mode, we handle the 36 first samples as
2248
                       long blocks.  For 8000Hz, we handle the 48 first
2249
                       exponents as long blocks (XXX: check this!) */
2250
                    if (s->sample_rate_index <= 2)
2251
                        g->long_end = 8;
2252
                    else if (s->sample_rate_index != 8)
2253
                        g->long_end = 6;
2254
                    else
2255
                        g->long_end = 4; /* 8000 Hz */
2256

    
2257
                    g->short_start = 2 + (s->sample_rate_index != 8);
2258
                } else {
2259
                    g->long_end = 0;
2260
                    g->short_start = 0;
2261
                }
2262
            } else {
2263
                g->short_start = 13;
2264
                g->long_end = 22;
2265
            }
2266

    
2267
            g->preflag = 0;
2268
            if (!s->lsf)
2269
                g->preflag = get_bits(&s->gb, 1);
2270
            g->scalefac_scale = get_bits(&s->gb, 1);
2271
            g->count1table_select = get_bits(&s->gb, 1);
2272
            dprintf("block_type=%d switch_point=%d\n",
2273
                    g->block_type, g->switch_point);
2274
        }
2275
    }
2276

    
2277
  if (!s->adu_mode) {
2278
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2279
    assert((get_bits_count(&s->gb) & 7) == 0);
2280
    /* now we get bits from the main_data_begin offset */
2281
    dprintf("seekback: %d\n", main_data_begin);
2282
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2283

    
2284
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2285
    s->in_gb= s->gb;
2286
        init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
2287
        skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
2288
  }
2289

    
2290
    for(gr=0;gr<nb_granules;gr++) {
2291
        for(ch=0;ch<s->nb_channels;ch++) {
2292
            g = &granules[ch][gr];
2293
            if(get_bits_count(&s->gb)<0){
2294
                av_log(NULL, AV_LOG_ERROR, "mdb:%d, lastbuf:%d skiping granule %d\n",
2295
                                            main_data_begin, s->last_buf_size, gr);
2296
                skip_bits_long(&s->gb, g->part2_3_length);
2297
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
2298
                if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer){
2299
                    skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
2300
                    s->gb= s->in_gb;
2301
                    s->in_gb.buffer=NULL;
2302
                }
2303
                continue;
2304
            }
2305

    
2306
            bits_pos = get_bits_count(&s->gb);
2307

    
2308
            if (!s->lsf) {
2309
                uint8_t *sc;
2310
                int slen, slen1, slen2;
2311

    
2312
                /* MPEG1 scale factors */
2313
                slen1 = slen_table[0][g->scalefac_compress];
2314
                slen2 = slen_table[1][g->scalefac_compress];
2315
                dprintf("slen1=%d slen2=%d\n", slen1, slen2);
2316
                if (g->block_type == 2) {
2317
                    n = g->switch_point ? 17 : 18;
2318
                    j = 0;
2319
                    if(slen1){
2320
                        for(i=0;i<n;i++)
2321
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
2322
                    }else{
2323
                        for(i=0;i<n;i++)
2324
                            g->scale_factors[j++] = 0;
2325
                    }
2326
                    if(slen2){
2327
                        for(i=0;i<18;i++)
2328
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
2329
                        for(i=0;i<3;i++)
2330
                            g->scale_factors[j++] = 0;
2331
                    }else{
2332
                        for(i=0;i<21;i++)
2333
                            g->scale_factors[j++] = 0;
2334
                    }
2335
                } else {
2336
                    sc = granules[ch][0].scale_factors;
2337
                    j = 0;
2338
                    for(k=0;k<4;k++) {
2339
                        n = (k == 0 ? 6 : 5);
2340
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2341
                            slen = (k < 2) ? slen1 : slen2;
2342
                            if(slen){
2343
                                for(i=0;i<n;i++)
2344
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
2345
                            }else{
2346
                                for(i=0;i<n;i++)
2347
                                    g->scale_factors[j++] = 0;
2348
                            }
2349
                        } else {
2350
                            /* simply copy from last granule */
2351
                            for(i=0;i<n;i++) {
2352
                                g->scale_factors[j] = sc[j];
2353
                                j++;
2354
                            }
2355
                        }
2356
                    }
2357
                    g->scale_factors[j++] = 0;
2358
                }
2359
#if defined(DEBUG)
2360
                {
2361
                    dprintf("scfsi=%x gr=%d ch=%d scale_factors:\n",
2362
                           g->scfsi, gr, ch);
2363
                    for(i=0;i<j;i++)
2364
                        dprintf(" %d", g->scale_factors[i]);
2365
                    dprintf("\n");
2366
                }
2367
#endif
2368
            } else {
2369
                int tindex, tindex2, slen[4], sl, sf;
2370

    
2371
                /* LSF scale factors */
2372
                if (g->block_type == 2) {
2373
                    tindex = g->switch_point ? 2 : 1;
2374
                } else {
2375
                    tindex = 0;
2376
                }
2377
                sf = g->scalefac_compress;
2378
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2379
                    /* intensity stereo case */
2380
                    sf >>= 1;
2381
                    if (sf < 180) {
2382
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2383
                        tindex2 = 3;
2384
                    } else if (sf < 244) {
2385
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2386
                        tindex2 = 4;
2387
                    } else {
2388
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2389
                        tindex2 = 5;
2390
                    }
2391
                } else {
2392
                    /* normal case */
2393
                    if (sf < 400) {
2394
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2395
                        tindex2 = 0;
2396
                    } else if (sf < 500) {
2397
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2398
                        tindex2 = 1;
2399
                    } else {
2400
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2401
                        tindex2 = 2;
2402
                        g->preflag = 1;
2403
                    }
2404
                }
2405

    
2406
                j = 0;
2407
                for(k=0;k<4;k++) {
2408
                    n = lsf_nsf_table[tindex2][tindex][k];
2409
                    sl = slen[k];
2410
                    if(sl){
2411
                        for(i=0;i<n;i++)
2412
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
2413
                    }else{
2414
                        for(i=0;i<n;i++)
2415
                            g->scale_factors[j++] = 0;
2416
                    }
2417
                }
2418
                /* XXX: should compute exact size */
2419
                for(;j<40;j++)
2420
                    g->scale_factors[j] = 0;
2421
#if defined(DEBUG)
2422
                {
2423
                    dprintf("gr=%d ch=%d scale_factors:\n",
2424
                           gr, ch);
2425
                    for(i=0;i<40;i++)
2426
                        dprintf(" %d", g->scale_factors[i]);
2427
                    dprintf("\n");
2428
                }
2429
#endif
2430
            }
2431

    
2432
            exponents_from_scale_factors(s, g, exponents);
2433

    
2434
            /* read Huffman coded residue */
2435
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
2436
#if defined(DEBUG)
2437
            sample_dump(0, g->sb_hybrid, 576);
2438
#endif
2439
        } /* ch */
2440

    
2441
        if (s->nb_channels == 2)
2442
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2443

    
2444
        for(ch=0;ch<s->nb_channels;ch++) {
2445
            g = &granules[ch][gr];
2446

    
2447
            reorder_block(s, g);
2448
#if defined(DEBUG)
2449
            sample_dump(0, g->sb_hybrid, 576);
2450
#endif
2451
            s->compute_antialias(s, g);
2452
#if defined(DEBUG)
2453
            sample_dump(1, g->sb_hybrid, 576);
2454
#endif
2455
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2456
#if defined(DEBUG)
2457
            sample_dump(2, &s->sb_samples[ch][18 * gr][0], 576);
2458
#endif
2459
        }
2460
    } /* gr */
2461
    if(get_bits_count(&s->gb)<0)
2462
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
2463
    return nb_granules * 18;
2464
}
2465

    
2466
static int mp_decode_frame(MPADecodeContext *s,
2467
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
2468
{
2469
    int i, nb_frames, ch;
2470
    OUT_INT *samples_ptr;
2471

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

    
2474
    /* skip error protection field */
2475
    if (s->error_protection)
2476
        get_bits(&s->gb, 16);
2477

    
2478
    dprintf("frame %d:\n", s->frame_count);
2479
    switch(s->layer) {
2480
    case 1:
2481
        nb_frames = mp_decode_layer1(s);
2482
        break;
2483
    case 2:
2484
        nb_frames = mp_decode_layer2(s);
2485
        break;
2486
    case 3:
2487
    default:
2488
        nb_frames = mp_decode_layer3(s);
2489

    
2490
        s->last_buf_size=0;
2491
        if(s->in_gb.buffer){
2492
            align_get_bits(&s->gb);
2493
            i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2494
            if(i >= 0 && i <= BACKSTEP_SIZE){
2495
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
2496
                s->last_buf_size=i;
2497
            }else
2498
                av_log(NULL, AV_LOG_ERROR, "invalid old backstep %d\n", i);
2499
            s->gb= s->in_gb;
2500
            s->in_gb.buffer= NULL;
2501
        }
2502

    
2503
        align_get_bits(&s->gb);
2504
        assert((get_bits_count(&s->gb) & 7) == 0);
2505
        i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2506

    
2507
        if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
2508
            av_log(NULL, AV_LOG_ERROR, "invalid new backstep %d\n", i);
2509
            i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
2510
        }
2511
        assert(i <= buf_size - HEADER_SIZE && i>= 0);
2512
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
2513
        s->last_buf_size += i;
2514

    
2515
        break;
2516
    }
2517
#if defined(DEBUG)
2518
    for(i=0;i<nb_frames;i++) {
2519
        for(ch=0;ch<s->nb_channels;ch++) {
2520
            int j;
2521
            dprintf("%d-%d:", i, ch);
2522
            for(j=0;j<SBLIMIT;j++)
2523
                dprintf(" %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);
2524
            dprintf("\n");
2525
        }
2526
    }
2527
#endif
2528
    /* apply the synthesis filter */
2529
    for(ch=0;ch<s->nb_channels;ch++) {
2530
        samples_ptr = samples + ch;
2531
        for(i=0;i<nb_frames;i++) {
2532
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2533
                         window, &s->dither_state,
2534
                         samples_ptr, s->nb_channels,
2535
                         s->sb_samples[ch][i]);
2536
            samples_ptr += 32 * s->nb_channels;
2537
        }
2538
    }
2539
#ifdef DEBUG
2540
    s->frame_count++;
2541
#endif
2542
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2543
}
2544

    
2545
static int decode_frame(AVCodecContext * avctx,
2546
                        void *data, int *data_size,
2547
                        uint8_t * buf, int buf_size)
2548
{
2549
    MPADecodeContext *s = avctx->priv_data;
2550
    uint32_t header;
2551
    int out_size;
2552
    OUT_INT *out_samples = data;
2553

    
2554
retry:
2555
    if(buf_size < HEADER_SIZE)
2556
        return -1;
2557

    
2558
    header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
2559
    if(ff_mpa_check_header(header) < 0){
2560
        buf++;
2561
//        buf_size--;
2562
        av_log(avctx, AV_LOG_ERROR, "Header missing skipping one byte.\n");
2563
        goto retry;
2564
    }
2565

    
2566
    if (decode_header(s, header) == 1) {
2567
        /* free format: prepare to compute frame size */
2568
        s->frame_size = -1;
2569
        return -1;
2570
    }
2571
    /* update codec info */
2572
    avctx->channels = s->nb_channels;
2573
    avctx->bit_rate = s->bit_rate;
2574
    avctx->sub_id = s->layer;
2575
    switch(s->layer) {
2576
    case 1:
2577
        avctx->frame_size = 384;
2578
        break;
2579
    case 2:
2580
        avctx->frame_size = 1152;
2581
        break;
2582
    case 3:
2583
        if (s->lsf)
2584
            avctx->frame_size = 576;
2585
        else
2586
            avctx->frame_size = 1152;
2587
        break;
2588
    }
2589

    
2590
    if(s->frame_size<=0 || s->frame_size > buf_size){
2591
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2592
        return -1;
2593
    }else if(s->frame_size < buf_size){
2594
        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
2595
    }
2596

    
2597
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2598
    if(out_size>=0){
2599
        *data_size = out_size;
2600
        avctx->sample_rate = s->sample_rate;
2601
        //FIXME maybe move the other codec info stuff from above here too
2602
    }else
2603
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed
2604
    s->frame_size = 0;
2605
    return buf_size;
2606
}
2607

    
2608
static void flush(AVCodecContext *avctx){
2609
    MPADecodeContext *s = avctx->priv_data;
2610
    s->last_buf_size= 0;
2611
}
2612

    
2613
#ifdef CONFIG_MP3ADU_DECODER
2614
static int decode_frame_adu(AVCodecContext * avctx,
2615
                        void *data, int *data_size,
2616
                        uint8_t * buf, int buf_size)
2617
{
2618
    MPADecodeContext *s = avctx->priv_data;
2619
    uint32_t header;
2620
    int len, out_size;
2621
    OUT_INT *out_samples = data;
2622

    
2623
    len = buf_size;
2624

    
2625
    // Discard too short frames
2626
    if (buf_size < HEADER_SIZE) {
2627
        *data_size = 0;
2628
        return buf_size;
2629
    }
2630

    
2631

    
2632
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2633
        len = MPA_MAX_CODED_FRAME_SIZE;
2634

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

    
2638
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2639
        *data_size = 0;
2640
        return buf_size;
2641
    }
2642

    
2643
    decode_header(s, header);
2644
    /* update codec info */
2645
    avctx->sample_rate = s->sample_rate;
2646
    avctx->channels = s->nb_channels;
2647
    avctx->bit_rate = s->bit_rate;
2648
    avctx->sub_id = s->layer;
2649

    
2650
    avctx->frame_size=s->frame_size = len;
2651

    
2652
    if (avctx->parse_only) {
2653
        out_size = buf_size;
2654
    } else {
2655
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2656
    }
2657

    
2658
    *data_size = out_size;
2659
    return buf_size;
2660
}
2661
#endif /* CONFIG_MP3ADU_DECODER */
2662

    
2663
#ifdef CONFIG_MP3ON4_DECODER
2664
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2665
static int mp3Frames[16] = {0,1,1,2,3,3,4,5,2};   /* number of mp3 decoder instances */
2666
static int mp3Channels[16] = {0,1,2,3,4,5,6,8,4}; /* total output channels */
2667
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2668
static int chan_offset[9][5] = {
2669
    {0},
2670
    {0},            // C
2671
    {0},            // FLR
2672
    {2,0},          // C FLR
2673
    {2,0,3},        // C FLR BS
2674
    {4,0,2},        // C FLR BLRS
2675
    {4,0,2,5},      // C FLR BLRS LFE
2676
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2677
    {0,2}           // FLR BLRS
2678
};
2679

    
2680

    
2681
static int decode_init_mp3on4(AVCodecContext * avctx)
2682
{
2683
    MP3On4DecodeContext *s = avctx->priv_data;
2684
    int i;
2685

    
2686
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2687
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2688
        return -1;
2689
    }
2690

    
2691
    s->chan_cfg = (((unsigned char *)avctx->extradata)[1] >> 3) & 0x0f;
2692
    s->frames = mp3Frames[s->chan_cfg];
2693
    if(!s->frames) {
2694
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2695
        return -1;
2696
    }
2697
    avctx->channels = mp3Channels[s->chan_cfg];
2698

    
2699
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2700
     * We replace avctx->priv_data with the context of the first decoder so that
2701
     * decode_init() does not have to be changed.
2702
     * Other decoders will be inited here copying data from the first context
2703
     */
2704
    // Allocate zeroed memory for the first decoder context
2705
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2706
    // Put decoder context in place to make init_decode() happy
2707
    avctx->priv_data = s->mp3decctx[0];
2708
    decode_init(avctx);
2709
    // Restore mp3on4 context pointer
2710
    avctx->priv_data = s;
2711
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2712

    
2713
    /* Create a separate codec/context for each frame (first is already ok).
2714
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2715
     */
2716
    for (i = 1; i < s->frames; i++) {
2717
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2718
        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2719
        s->mp3decctx[i]->adu_mode = 1;
2720
    }
2721

    
2722
    return 0;
2723
}
2724

    
2725

    
2726
static int decode_close_mp3on4(AVCodecContext * avctx)
2727
{
2728
    MP3On4DecodeContext *s = avctx->priv_data;
2729
    int i;
2730

    
2731
    for (i = 0; i < s->frames; i++)
2732
        if (s->mp3decctx[i])
2733
            av_free(s->mp3decctx[i]);
2734

    
2735
    return 0;
2736
}
2737

    
2738

    
2739
static int decode_frame_mp3on4(AVCodecContext * avctx,
2740
                        void *data, int *data_size,
2741
                        uint8_t * buf, int buf_size)
2742
{
2743
    MP3On4DecodeContext *s = avctx->priv_data;
2744
    MPADecodeContext *m;
2745
    int len, out_size = 0;
2746
    uint32_t header;
2747
    OUT_INT *out_samples = data;
2748
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2749
    OUT_INT *outptr, *bp;
2750
    int fsize;
2751
    unsigned char *start2 = buf, *start;
2752
    int fr, i, j, n;
2753
    int off = avctx->channels;
2754
    int *coff = chan_offset[s->chan_cfg];
2755

    
2756
    len = buf_size;
2757

    
2758
    // Discard too short frames
2759
    if (buf_size < HEADER_SIZE) {
2760
        *data_size = 0;
2761
        return buf_size;
2762
    }
2763

    
2764
    // If only one decoder interleave is not needed
2765
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2766

    
2767
    for (fr = 0; fr < s->frames; fr++) {
2768
        start = start2;
2769
        fsize = (start[0] << 4) | (start[1] >> 4);
2770
        start2 += fsize;
2771
        if (fsize > len)
2772
            fsize = len;
2773
        len -= fsize;
2774
        if (fsize > MPA_MAX_CODED_FRAME_SIZE)
2775
            fsize = MPA_MAX_CODED_FRAME_SIZE;
2776
        m = s->mp3decctx[fr];
2777
        assert (m != NULL);
2778

    
2779
        // Get header
2780
        header = (start[0] << 24) | (start[1] << 16) | (start[2] << 8) | start[3] | 0xfff00000;
2781

    
2782
        if (ff_mpa_check_header(header) < 0) { // Bad header, discard block
2783
            *data_size = 0;
2784
            return buf_size;
2785
        }
2786

    
2787
        decode_header(m, header);
2788
        mp_decode_frame(m, decoded_buf, start, fsize);
2789

    
2790
        n = MPA_FRAME_SIZE * m->nb_channels;
2791
        out_size += n * sizeof(OUT_INT);
2792
        if(s->frames > 1) {
2793
            /* interleave output data */
2794
            bp = out_samples + coff[fr];
2795
            if(m->nb_channels == 1) {
2796
                for(j = 0; j < n; j++) {
2797
                    *bp = decoded_buf[j];
2798
                    bp += off;
2799
                }
2800
            } else {
2801
                for(j = 0; j < n; j++) {
2802
                    bp[0] = decoded_buf[j++];
2803
                    bp[1] = decoded_buf[j];
2804
                    bp += off;
2805
                }
2806
            }
2807
        }
2808
    }
2809

    
2810
    /* update codec info */
2811
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2812
    avctx->frame_size= buf_size;
2813
    avctx->bit_rate = 0;
2814
    for (i = 0; i < s->frames; i++)
2815
        avctx->bit_rate += s->mp3decctx[i]->bit_rate;
2816

    
2817
    *data_size = out_size;
2818
    return buf_size;
2819
}
2820
#endif /* CONFIG_MP3ON4_DECODER */
2821

    
2822
#ifdef CONFIG_MP2_DECODER
2823
AVCodec mp2_decoder =
2824
{
2825
    "mp2",
2826
    CODEC_TYPE_AUDIO,
2827
    CODEC_ID_MP2,
2828
    sizeof(MPADecodeContext),
2829
    decode_init,
2830
    NULL,
2831
    NULL,
2832
    decode_frame,
2833
    CODEC_CAP_PARSE_ONLY,
2834
};
2835
#endif
2836
#ifdef CONFIG_MP3_DECODER
2837
AVCodec mp3_decoder =
2838
{
2839
    "mp3",
2840
    CODEC_TYPE_AUDIO,
2841
    CODEC_ID_MP3,
2842
    sizeof(MPADecodeContext),
2843
    decode_init,
2844
    NULL,
2845
    NULL,
2846
    decode_frame,
2847
    CODEC_CAP_PARSE_ONLY,
2848
    .flush= flush,
2849
};
2850
#endif
2851
#ifdef CONFIG_MP3ADU_DECODER
2852
AVCodec mp3adu_decoder =
2853
{
2854
    "mp3adu",
2855
    CODEC_TYPE_AUDIO,
2856
    CODEC_ID_MP3ADU,
2857
    sizeof(MPADecodeContext),
2858
    decode_init,
2859
    NULL,
2860
    NULL,
2861
    decode_frame_adu,
2862
    CODEC_CAP_PARSE_ONLY,
2863
    .flush= flush,
2864
};
2865
#endif
2866
#ifdef CONFIG_MP3ON4_DECODER
2867
AVCodec mp3on4_decoder =
2868
{
2869
    "mp3on4",
2870
    CODEC_TYPE_AUDIO,
2871
    CODEC_ID_MP3ON4,
2872
    sizeof(MP3On4DecodeContext),
2873
    decode_init_mp3on4,
2874
    NULL,
2875
    decode_close_mp3on4,
2876
    decode_frame_mp3on4,
2877
    .flush= flush,
2878
};
2879
#endif