Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 0bd2483a

History | View | Annotate | Download (86.6 KB)

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

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

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

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

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

    
42
#include "mpegaudio.h"
43

    
44
#define FRAC_ONE    (1 << FRAC_BITS)
45

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

    
53
#define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
54
//#define MULH(a,b) (((int64_t)(a) * (int64_t)(b))>>32) //gcc 3.4 creates an incredibly bloated mess out of this
55
static always_inline int MULH(int a, int b){
56
    return ((int64_t)(a) * (int64_t)(b))>>32;
57
}
58

    
59
/****************/
60

    
61
#define HEADER_SIZE 4
62
#define BACKSTEP_SIZE 512
63

    
64
struct GranuleDef;
65

    
66
typedef struct MPADecodeContext {
67
    uint8_t inbuf1[2][MPA_MAX_CODED_FRAME_SIZE + BACKSTEP_SIZE];        /* input buffer */
68
    int inbuf_index;
69
    uint8_t *inbuf_ptr, *inbuf;
70
    int frame_size;
71
    int free_format_frame_size; /* frame size in case of free format
72
                                   (zero if currently unknown) */
73
    /* next header (used in free format parsing) */
74
    uint32_t free_format_next_header;
75
    int error_protection;
76
    int layer;
77
    int sample_rate;
78
    int sample_rate_index; /* between 0 and 8 */
79
    int bit_rate;
80
    int old_frame_size;
81
    GetBitContext gb;
82
    int nb_channels;
83
    int mode;
84
    int mode_ext;
85
    int lsf;
86
    MPA_INT synth_buf[MPA_MAX_CHANNELS][512 * 2] __attribute__((aligned(16)));
87
    int synth_buf_offset[MPA_MAX_CHANNELS];
88
    int32_t sb_samples[MPA_MAX_CHANNELS][36][SBLIMIT] __attribute__((aligned(16)));
89
    int32_t mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
90
#ifdef DEBUG
91
    int frame_count;
92
#endif
93
    void (*compute_antialias)(struct MPADecodeContext *s, struct GranuleDef *g);
94
    int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
95
    unsigned int dither_state;
96
} MPADecodeContext;
97

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

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

    
127
#define MODE_EXT_MS_STEREO 2
128
#define MODE_EXT_I_STEREO  1
129

    
130
/* layer 3 huffman tables */
131
typedef struct HuffTable {
132
    int xsize;
133
    const uint8_t *bits;
134
    const uint16_t *codes;
135
} HuffTable;
136

    
137
#include "mpegaudiodectab.h"
138

    
139
static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
140
static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
141

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

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

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

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

    
174
void ff_mpa_synth_init(MPA_INT *window);
175
static MPA_INT window[512] __attribute__((aligned(16)));
176

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

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

    
193
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
194
{
195
    int shift, mod, val;
196

    
197
    shift = scale_factor_modshift[scale_factor];
198
    mod = shift & 3;
199
    shift >>= 2;
200

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

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

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

    
222
    return m;
223
}
224

    
225
/* all integer n^(4/3) computation code */
226
#define DEV_ORDER 13
227

    
228
#define POW_FRAC_BITS 24
229
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
230
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
231
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
232

    
233
static int dev_4_3_coefs[DEV_ORDER];
234

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

    
243
static void int_pow_init(void)
244
{
245
    int i, a;
246

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

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

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

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

    
307
#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
308
    avctx->sample_fmt= SAMPLE_FMT_S32;
309
#else
310
    avctx->sample_fmt= SAMPLE_FMT_S16;
311
#endif
312

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

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

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

    
343
        ff_mpa_synth_init(window);
344

    
345
        /* huffman decode tables */
346
        huff_code_table[0] = NULL;
347
        for(i=1;i<16;i++) {
348
            const HuffTable *h = &mpa_huff_tables[i];
349
            int xsize, x, y;
350
            unsigned int n;
351
            uint8_t *code_table;
352

    
353
            xsize = h->xsize;
354
            n = xsize * xsize;
355
            /* XXX: fail test */
356
            init_vlc(&huff_vlc[i], 8, n,
357
                     h->bits, 1, 1, h->codes, 2, 2, 1);
358

    
359
            code_table = av_mallocz(n);
360
            j = 0;
361
            for(x=0;x<xsize;x++) {
362
                for(y=0;y<xsize;y++)
363
                    code_table[j++] = (x << 4) | y;
364
            }
365
            huff_code_table[i] = code_table;
366
        }
367
        for(i=0;i<2;i++) {
368
            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
369
                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);
370
        }
371

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

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

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

    
398
            /* normalized to FRAC_BITS */
399
            table_4_3_value[i] = m;
400
//            av_log(NULL, AV_LOG_DEBUG, "%d %d %f\n", i, m, pow((double)i, 4.0 / 3.0));
401
            table_4_3_exp[i] = -e;
402
        }
403

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

    
420
        for(i=0;i<16;i++) {
421
            double f;
422
            int e, k;
423

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

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

    
452
        /* compute mdct windows */
453
        for(i=0;i<36;i++) {
454
            for(j=0; j<4; j++){
455
                double d;
456

    
457
                if(j==2 && i%3 != 1)
458
                    continue;
459

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

    
473
                if(j==2)
474
                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));
475
                else
476
                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));
477
//                av_log(NULL, AV_LOG_DEBUG, "%2d %d %f\n", i,j,d / (1<<5));
478
            }
479
        }
480

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

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

    
501
    s->inbuf_index = 0;
502
    s->inbuf = &s->inbuf1[s->inbuf_index][BACKSTEP_SIZE];
503
    s->inbuf_ptr = s->inbuf;
504
#ifdef DEBUG
505
    s->frame_count = 0;
506
#endif
507
    if (avctx->codec_id == CODEC_ID_MP3ADU)
508
        s->adu_mode = 1;
509
    return 0;
510
}
511

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

    
514
/* cos(i*pi/64) */
515

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

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

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

    
547
#define COS3_0 FIXHR(0.54119610014619698439/2)
548
#define COS3_1 FIXHR(1.30656296487637652785/4)
549

    
550
#define COS4_0 FIXHR(0.70710678118654752439/2)
551

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

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

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

    
578
#define ADD(a, b) tab[a] += tab[b]
579

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

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

    
629

    
630

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

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

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

    
686
    /* pass 6 */
687

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

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

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

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

    
739
#if FRAC_BITS <= 15
740

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

    
753
#if defined(ARCH_POWERPC_405)
754

    
755
/* signed 16x16 -> 32 multiply add accumulate */
756
#define MACS(rt, ra, rb) \
757
    asm ("maclhw %0, %2, %3" : "=r" (rt) : "0" (rt), "r" (ra), "r" (rb));
758

    
759
/* signed 16x16 -> 32 multiply */
760
#define MULS(ra, rb) \
761
    ({ int __rt; asm ("mullhw %0, %1, %2" : "=r" (__rt) : "r" (ra), "r" (rb)); __rt; })
762

    
763
#else
764

    
765
/* signed 16x16 -> 32 multiply add accumulate */
766
#define MACS(rt, ra, rb) rt += (ra) * (rb)
767

    
768
/* signed 16x16 -> 32 multiply */
769
#define MULS(ra, rb) ((ra) * (rb))
770

    
771
#endif
772

    
773
#else
774

    
775
static inline int round_sample(int64_t *sum)
776
{
777
    int sum1;
778
    sum1 = (int)((*sum) >> OUT_SHIFT);
779
    *sum &= (1<<OUT_SHIFT)-1;
780
    if (sum1 < OUT_MIN)
781
        sum1 = OUT_MIN;
782
    else if (sum1 > OUT_MAX)
783
        sum1 = OUT_MAX;
784
    return sum1;
785
}
786

    
787
#define MULS(ra, rb) MUL64(ra, rb)
788

    
789
#endif
790

    
791
#define SUM8(sum, op, w, p) \
792
{                                               \
793
    sum op MULS((w)[0 * 64], p[0 * 64]);\
794
    sum op MULS((w)[1 * 64], p[1 * 64]);\
795
    sum op MULS((w)[2 * 64], p[2 * 64]);\
796
    sum op MULS((w)[3 * 64], p[3 * 64]);\
797
    sum op MULS((w)[4 * 64], p[4 * 64]);\
798
    sum op MULS((w)[5 * 64], p[5 * 64]);\
799
    sum op MULS((w)[6 * 64], p[6 * 64]);\
800
    sum op MULS((w)[7 * 64], p[7 * 64]);\
801
}
802

    
803
#define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
804
{                                               \
805
    int tmp;\
806
    tmp = p[0 * 64];\
807
    sum1 op1 MULS((w1)[0 * 64], tmp);\
808
    sum2 op2 MULS((w2)[0 * 64], tmp);\
809
    tmp = p[1 * 64];\
810
    sum1 op1 MULS((w1)[1 * 64], tmp);\
811
    sum2 op2 MULS((w2)[1 * 64], tmp);\
812
    tmp = p[2 * 64];\
813
    sum1 op1 MULS((w1)[2 * 64], tmp);\
814
    sum2 op2 MULS((w2)[2 * 64], tmp);\
815
    tmp = p[3 * 64];\
816
    sum1 op1 MULS((w1)[3 * 64], tmp);\
817
    sum2 op2 MULS((w2)[3 * 64], tmp);\
818
    tmp = p[4 * 64];\
819
    sum1 op1 MULS((w1)[4 * 64], tmp);\
820
    sum2 op2 MULS((w2)[4 * 64], tmp);\
821
    tmp = p[5 * 64];\
822
    sum1 op1 MULS((w1)[5 * 64], tmp);\
823
    sum2 op2 MULS((w2)[5 * 64], tmp);\
824
    tmp = p[6 * 64];\
825
    sum1 op1 MULS((w1)[6 * 64], tmp);\
826
    sum2 op2 MULS((w2)[6 * 64], tmp);\
827
    tmp = p[7 * 64];\
828
    sum1 op1 MULS((w1)[7 * 64], tmp);\
829
    sum2 op2 MULS((w2)[7 * 64], tmp);\
830
}
831

    
832
void ff_mpa_synth_init(MPA_INT *window)
833
{
834
    int i;
835

    
836
    /* max = 18760, max sum over all 16 coefs : 44736 */
837
    for(i=0;i<257;i++) {
838
        int v;
839
        v = mpa_enwindow[i];
840
#if WFRAC_BITS < 16
841
        v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
842
#endif
843
        window[i] = v;
844
        if ((i & 63) != 0)
845
            v = -v;
846
        if (i != 0)
847
            window[512 - i] = v;
848
    }
849
}
850

    
851
/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
852
   32 samples. */
853
/* XXX: optimize by avoiding ring buffer usage */
854
void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
855
                         MPA_INT *window, int *dither_state,
856
                         OUT_INT *samples, int incr,
857
                         int32_t sb_samples[SBLIMIT])
858
{
859
    int32_t tmp[32];
860
    register MPA_INT *synth_buf;
861
    register const MPA_INT *w, *w2, *p;
862
    int j, offset, v;
863
    OUT_INT *samples2;
864
#if FRAC_BITS <= 15
865
    int sum, sum2;
866
#else
867
    int64_t sum, sum2;
868
#endif
869

    
870
    dct32(tmp, sb_samples);
871

    
872
    offset = *synth_buf_offset;
873
    synth_buf = synth_buf_ptr + offset;
874

    
875
    for(j=0;j<32;j++) {
876
        v = tmp[j];
877
#if FRAC_BITS <= 15
878
        /* NOTE: can cause a loss in precision if very high amplitude
879
           sound */
880
        if (v > 32767)
881
            v = 32767;
882
        else if (v < -32768)
883
            v = -32768;
884
#endif
885
        synth_buf[j] = v;
886
    }
887
    /* copy to avoid wrap */
888
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
889

    
890
    samples2 = samples + 31 * incr;
891
    w = window;
892
    w2 = window + 31;
893

    
894
    sum = *dither_state;
895
    p = synth_buf + 16;
896
    SUM8(sum, +=, w, p);
897
    p = synth_buf + 48;
898
    SUM8(sum, -=, w + 32, p);
899
    *samples = round_sample(&sum);
900
    samples += incr;
901
    w++;
902

    
903
    /* we calculate two samples at the same time to avoid one memory
904
       access per two sample */
905
    for(j=1;j<16;j++) {
906
        sum2 = 0;
907
        p = synth_buf + 16 + j;
908
        SUM8P2(sum, +=, sum2, -=, w, w2, p);
909
        p = synth_buf + 48 - j;
910
        SUM8P2(sum, -=, sum2, -=, w + 32, w2 + 32, p);
911

    
912
        *samples = round_sample(&sum);
913
        samples += incr;
914
        sum += sum2;
915
        *samples2 = round_sample(&sum);
916
        samples2 -= incr;
917
        w++;
918
        w2--;
919
    }
920

    
921
    p = synth_buf + 32;
922
    SUM8(sum, -=, w + 32, p);
923
    *samples = round_sample(&sum);
924
    *dither_state= sum;
925

    
926
    offset = (offset - 32) & 511;
927
    *synth_buf_offset = offset;
928
}
929

    
930
#define C3 FIXHR(0.86602540378443864676/2)
931

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

    
945
/* 0.5 / cos(pi*(2*i+1)/36) */
946
static const int icos36h[9] = {
947
    FIXHR(0.50190991877167369479/2),
948
    FIXHR(0.51763809020504152469/2), //0
949
    FIXHR(0.55168895948124587824/2),
950
    FIXHR(0.61038729438072803416/2),
951
    FIXHR(0.70710678118654752439/2), //1
952
    FIXHR(0.87172339781054900991/2),
953
    FIXHR(1.18310079157624925896/4),
954
    FIXHR(1.93185165257813657349/4), //2
955
//    FIXHR(5.73685662283492756461),
956
};
957

    
958
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
959
   cases. */
960
static void imdct12(int *out, int *in)
961
{
962
    int in0, in1, in2, in3, in4, in5, t1, t2;
963

    
964
    in0= in[0*3];
965
    in1= in[1*3] + in[0*3];
966
    in2= in[2*3] + in[1*3];
967
    in3= in[3*3] + in[2*3];
968
    in4= in[4*3] + in[3*3];
969
    in5= in[5*3] + in[4*3];
970
    in5 += in3;
971
    in3 += in1;
972

    
973
    in2= MULH(2*in2, C3);
974
    in3= MULH(4*in3, C3);
975

    
976
    t1 = in0 - in4;
977
    t2 = MULH(2*(in1 - in5), icos36h[4]);
978

    
979
    out[ 7]=
980
    out[10]= t1 + t2;
981
    out[ 1]=
982
    out[ 4]= t1 - t2;
983

    
984
    in0 += in4>>1;
985
    in4 = in0 + in2;
986
    in5 += 2*in1;
987
    in1 = MULH(in5 + in3, icos36h[1]);
988
    out[ 8]=
989
    out[ 9]= in4 + in1;
990
    out[ 2]=
991
    out[ 3]= in4 - in1;
992

    
993
    in0 -= in2;
994
    in5 = MULH(2*(in5 - in3), icos36h[7]);
995
    out[ 0]=
996
    out[ 5]= in0 - in5;
997
    out[ 6]=
998
    out[11]= in0 + in5;
999
}
1000

    
1001
/* cos(pi*i/18) */
1002
#define C1 FIXHR(0.98480775301220805936/2)
1003
#define C2 FIXHR(0.93969262078590838405/2)
1004
#define C3 FIXHR(0.86602540378443864676/2)
1005
#define C4 FIXHR(0.76604444311897803520/2)
1006
#define C5 FIXHR(0.64278760968653932632/2)
1007
#define C6 FIXHR(0.5/2)
1008
#define C7 FIXHR(0.34202014332566873304/2)
1009
#define C8 FIXHR(0.17364817766693034885/2)
1010

    
1011

    
1012
/* using Lee like decomposition followed by hand coded 9 points DCT */
1013
static void imdct36(int *out, int *buf, int *in, int *win)
1014
{
1015
    int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
1016
    int tmp[18], *tmp1, *in1;
1017

    
1018
    for(i=17;i>=1;i--)
1019
        in[i] += in[i-1];
1020
    for(i=17;i>=3;i-=2)
1021
        in[i] += in[i-2];
1022

    
1023
    for(j=0;j<2;j++) {
1024
        tmp1 = tmp + j;
1025
        in1 = in + j;
1026
#if 0
1027
//more accurate but slower
1028
        int64_t t0, t1, t2, t3;
1029
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1030

1031
        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
1032
        t1 = in1[2*0] - in1[2*6];
1033
        tmp1[ 6] = t1 - (t2>>1);
1034
        tmp1[16] = t1 + t2;
1035

1036
        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
1037
        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
1038
        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
1039

1040
        tmp1[10] = (t3 - t0 - t2) >> 32;
1041
        tmp1[ 2] = (t3 + t0 + t1) >> 32;
1042
        tmp1[14] = (t3 + t2 - t1) >> 32;
1043

1044
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1045
        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
1046
        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
1047
        t0 = MUL64(2*in1[2*3], C3);
1048

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

1051
        tmp1[ 0] = (t2 + t3 + t0) >> 32;
1052
        tmp1[12] = (t2 + t1 - t0) >> 32;
1053
        tmp1[ 8] = (t3 - t1 - t0) >> 32;
1054
#else
1055
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1056

    
1057
        t3 = in1[2*0] + (in1[2*6]>>1);
1058
        t1 = in1[2*0] - in1[2*6];
1059
        tmp1[ 6] = t1 - (t2>>1);
1060
        tmp1[16] = t1 + t2;
1061

    
1062
        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1063
        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1064
        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1065

    
1066
        tmp1[10] = t3 - t0 - t2;
1067
        tmp1[ 2] = t3 + t0 + t1;
1068
        tmp1[14] = t3 + t2 - t1;
1069

    
1070
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1071
        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1072
        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1073
        t0 = MULH(2*in1[2*3], C3);
1074

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

    
1077
        tmp1[ 0] = t2 + t3 + t0;
1078
        tmp1[12] = t2 + t1 - t0;
1079
        tmp1[ 8] = t3 - t1 - t0;
1080
#endif
1081
    }
1082

    
1083
    i = 0;
1084
    for(j=0;j<4;j++) {
1085
        t0 = tmp[i];
1086
        t1 = tmp[i + 2];
1087
        s0 = t1 + t0;
1088
        s2 = t1 - t0;
1089

    
1090
        t2 = tmp[i + 1];
1091
        t3 = tmp[i + 3];
1092
        s1 = MULH(2*(t3 + t2), icos36h[j]);
1093
        s3 = MULL(t3 - t2, icos36[8 - j]);
1094

    
1095
        t0 = s0 + s1;
1096
        t1 = s0 - s1;
1097
        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1098
        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1099
        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1100
        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1101

    
1102
        t0 = s2 + s3;
1103
        t1 = s2 - s3;
1104
        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1105
        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1106
        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1107
        buf[      + j] = MULH(t0, win[18         + j]);
1108
        i += 4;
1109
    }
1110

    
1111
    s0 = tmp[16];
1112
    s1 = MULH(2*tmp[17], icos36h[4]);
1113
    t0 = s0 + s1;
1114
    t1 = s0 - s1;
1115
    out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
1116
    out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
1117
    buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
1118
    buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
1119
}
1120

    
1121
/* header decoding. MUST check the header before because no
1122
   consistency check is done there. Return 1 if free format found and
1123
   that the frame size must be computed externally */
1124
static int decode_header(MPADecodeContext *s, uint32_t header)
1125
{
1126
    int sample_rate, frame_size, mpeg25, padding;
1127
    int sample_rate_index, bitrate_index;
1128
    if (header & (1<<20)) {
1129
        s->lsf = (header & (1<<19)) ? 0 : 1;
1130
        mpeg25 = 0;
1131
    } else {
1132
        s->lsf = 1;
1133
        mpeg25 = 1;
1134
    }
1135

    
1136
    s->layer = 4 - ((header >> 17) & 3);
1137
    /* extract frequency */
1138
    sample_rate_index = (header >> 10) & 3;
1139
    sample_rate = mpa_freq_tab[sample_rate_index] >> (s->lsf + mpeg25);
1140
    sample_rate_index += 3 * (s->lsf + mpeg25);
1141
    s->sample_rate_index = sample_rate_index;
1142
    s->error_protection = ((header >> 16) & 1) ^ 1;
1143
    s->sample_rate = sample_rate;
1144

    
1145
    bitrate_index = (header >> 12) & 0xf;
1146
    padding = (header >> 9) & 1;
1147
    //extension = (header >> 8) & 1;
1148
    s->mode = (header >> 6) & 3;
1149
    s->mode_ext = (header >> 4) & 3;
1150
    //copyright = (header >> 3) & 1;
1151
    //original = (header >> 2) & 1;
1152
    //emphasis = header & 3;
1153

    
1154
    if (s->mode == MPA_MONO)
1155
        s->nb_channels = 1;
1156
    else
1157
        s->nb_channels = 2;
1158

    
1159
    if (bitrate_index != 0) {
1160
        frame_size = mpa_bitrate_tab[s->lsf][s->layer - 1][bitrate_index];
1161
        s->bit_rate = frame_size * 1000;
1162
        switch(s->layer) {
1163
        case 1:
1164
            frame_size = (frame_size * 12000) / sample_rate;
1165
            frame_size = (frame_size + padding) * 4;
1166
            break;
1167
        case 2:
1168
            frame_size = (frame_size * 144000) / sample_rate;
1169
            frame_size += padding;
1170
            break;
1171
        default:
1172
        case 3:
1173
            frame_size = (frame_size * 144000) / (sample_rate << s->lsf);
1174
            frame_size += padding;
1175
            break;
1176
        }
1177
        s->frame_size = frame_size;
1178
    } else {
1179
        /* if no frame size computed, signal it */
1180
        if (!s->free_format_frame_size)
1181
            return 1;
1182
        /* free format: compute bitrate and real frame size from the
1183
           frame size we extracted by reading the bitstream */
1184
        s->frame_size = s->free_format_frame_size;
1185
        switch(s->layer) {
1186
        case 1:
1187
            s->frame_size += padding  * 4;
1188
            s->bit_rate = (s->frame_size * sample_rate) / 48000;
1189
            break;
1190
        case 2:
1191
            s->frame_size += padding;
1192
            s->bit_rate = (s->frame_size * sample_rate) / 144000;
1193
            break;
1194
        default:
1195
        case 3:
1196
            s->frame_size += padding;
1197
            s->bit_rate = (s->frame_size * (sample_rate << s->lsf)) / 144000;
1198
            break;
1199
        }
1200
    }
1201

    
1202
#if defined(DEBUG)
1203
    dprintf("layer%d, %d Hz, %d kbits/s, ",
1204
           s->layer, s->sample_rate, s->bit_rate);
1205
    if (s->nb_channels == 2) {
1206
        if (s->layer == 3) {
1207
            if (s->mode_ext & MODE_EXT_MS_STEREO)
1208
                dprintf("ms-");
1209
            if (s->mode_ext & MODE_EXT_I_STEREO)
1210
                dprintf("i-");
1211
        }
1212
        dprintf("stereo");
1213
    } else {
1214
        dprintf("mono");
1215
    }
1216
    dprintf("\n");
1217
#endif
1218
    return 0;
1219
}
1220

    
1221
/* useful helper to get mpeg audio stream infos. Return -1 if error in
1222
   header, otherwise the coded frame size in bytes */
1223
int mpa_decode_header(AVCodecContext *avctx, uint32_t head)
1224
{
1225
    MPADecodeContext s1, *s = &s1;
1226
    memset( s, 0, sizeof(MPADecodeContext) );
1227

    
1228
    if (ff_mpa_check_header(head) != 0)
1229
        return -1;
1230

    
1231
    if (decode_header(s, head) != 0) {
1232
        return -1;
1233
    }
1234

    
1235
    switch(s->layer) {
1236
    case 1:
1237
        avctx->frame_size = 384;
1238
        break;
1239
    case 2:
1240
        avctx->frame_size = 1152;
1241
        break;
1242
    default:
1243
    case 3:
1244
        if (s->lsf)
1245
            avctx->frame_size = 576;
1246
        else
1247
            avctx->frame_size = 1152;
1248
        break;
1249
    }
1250

    
1251
    avctx->sample_rate = s->sample_rate;
1252
    avctx->channels = s->nb_channels;
1253
    avctx->bit_rate = s->bit_rate;
1254
    avctx->sub_id = s->layer;
1255
    return s->frame_size;
1256
}
1257

    
1258
/* return the number of decoded frames */
1259
static int mp_decode_layer1(MPADecodeContext *s)
1260
{
1261
    int bound, i, v, n, ch, j, mant;
1262
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1263
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1264

    
1265
    if (s->mode == MPA_JSTEREO)
1266
        bound = (s->mode_ext + 1) * 4;
1267
    else
1268
        bound = SBLIMIT;
1269

    
1270
    /* allocation bits */
1271
    for(i=0;i<bound;i++) {
1272
        for(ch=0;ch<s->nb_channels;ch++) {
1273
            allocation[ch][i] = get_bits(&s->gb, 4);
1274
        }
1275
    }
1276
    for(i=bound;i<SBLIMIT;i++) {
1277
        allocation[0][i] = get_bits(&s->gb, 4);
1278
    }
1279

    
1280
    /* scale factors */
1281
    for(i=0;i<bound;i++) {
1282
        for(ch=0;ch<s->nb_channels;ch++) {
1283
            if (allocation[ch][i])
1284
                scale_factors[ch][i] = get_bits(&s->gb, 6);
1285
        }
1286
    }
1287
    for(i=bound;i<SBLIMIT;i++) {
1288
        if (allocation[0][i]) {
1289
            scale_factors[0][i] = get_bits(&s->gb, 6);
1290
            scale_factors[1][i] = get_bits(&s->gb, 6);
1291
        }
1292
    }
1293

    
1294
    /* compute samples */
1295
    for(j=0;j<12;j++) {
1296
        for(i=0;i<bound;i++) {
1297
            for(ch=0;ch<s->nb_channels;ch++) {
1298
                n = allocation[ch][i];
1299
                if (n) {
1300
                    mant = get_bits(&s->gb, n + 1);
1301
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
1302
                } else {
1303
                    v = 0;
1304
                }
1305
                s->sb_samples[ch][j][i] = v;
1306
            }
1307
        }
1308
        for(i=bound;i<SBLIMIT;i++) {
1309
            n = allocation[0][i];
1310
            if (n) {
1311
                mant = get_bits(&s->gb, n + 1);
1312
                v = l1_unscale(n, mant, scale_factors[0][i]);
1313
                s->sb_samples[0][j][i] = v;
1314
                v = l1_unscale(n, mant, scale_factors[1][i]);
1315
                s->sb_samples[1][j][i] = v;
1316
            } else {
1317
                s->sb_samples[0][j][i] = 0;
1318
                s->sb_samples[1][j][i] = 0;
1319
            }
1320
        }
1321
    }
1322
    return 12;
1323
}
1324

    
1325
/* bitrate is in kb/s */
1326
int l2_select_table(int bitrate, int nb_channels, int freq, int lsf)
1327
{
1328
    int ch_bitrate, table;
1329

    
1330
    ch_bitrate = bitrate / nb_channels;
1331
    if (!lsf) {
1332
        if ((freq == 48000 && ch_bitrate >= 56) ||
1333
            (ch_bitrate >= 56 && ch_bitrate <= 80))
1334
            table = 0;
1335
        else if (freq != 48000 && ch_bitrate >= 96)
1336
            table = 1;
1337
        else if (freq != 32000 && ch_bitrate <= 48)
1338
            table = 2;
1339
        else
1340
            table = 3;
1341
    } else {
1342
        table = 4;
1343
    }
1344
    return table;
1345
}
1346

    
1347
static int mp_decode_layer2(MPADecodeContext *s)
1348
{
1349
    int sblimit; /* number of used subbands */
1350
    const unsigned char *alloc_table;
1351
    int table, bit_alloc_bits, i, j, ch, bound, v;
1352
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1353
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1354
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1355
    int scale, qindex, bits, steps, k, l, m, b;
1356

    
1357
    /* select decoding table */
1358
    table = l2_select_table(s->bit_rate / 1000, s->nb_channels,
1359
                            s->sample_rate, s->lsf);
1360
    sblimit = sblimit_table[table];
1361
    alloc_table = alloc_tables[table];
1362

    
1363
    if (s->mode == MPA_JSTEREO)
1364
        bound = (s->mode_ext + 1) * 4;
1365
    else
1366
        bound = sblimit;
1367

    
1368
    dprintf("bound=%d sblimit=%d\n", bound, sblimit);
1369

    
1370
    /* sanity check */
1371
    if( bound > sblimit ) bound = sblimit;
1372

    
1373
    /* parse bit allocation */
1374
    j = 0;
1375
    for(i=0;i<bound;i++) {
1376
        bit_alloc_bits = alloc_table[j];
1377
        for(ch=0;ch<s->nb_channels;ch++) {
1378
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1379
        }
1380
        j += 1 << bit_alloc_bits;
1381
    }
1382
    for(i=bound;i<sblimit;i++) {
1383
        bit_alloc_bits = alloc_table[j];
1384
        v = get_bits(&s->gb, bit_alloc_bits);
1385
        bit_alloc[0][i] = v;
1386
        bit_alloc[1][i] = v;
1387
        j += 1 << bit_alloc_bits;
1388
    }
1389

    
1390
#ifdef DEBUG
1391
    {
1392
        for(ch=0;ch<s->nb_channels;ch++) {
1393
            for(i=0;i<sblimit;i++)
1394
                dprintf(" %d", bit_alloc[ch][i]);
1395
            dprintf("\n");
1396
        }
1397
    }
1398
#endif
1399

    
1400
    /* scale codes */
1401
    for(i=0;i<sblimit;i++) {
1402
        for(ch=0;ch<s->nb_channels;ch++) {
1403
            if (bit_alloc[ch][i])
1404
                scale_code[ch][i] = get_bits(&s->gb, 2);
1405
        }
1406
    }
1407

    
1408
    /* scale factors */
1409
    for(i=0;i<sblimit;i++) {
1410
        for(ch=0;ch<s->nb_channels;ch++) {
1411
            if (bit_alloc[ch][i]) {
1412
                sf = scale_factors[ch][i];
1413
                switch(scale_code[ch][i]) {
1414
                default:
1415
                case 0:
1416
                    sf[0] = get_bits(&s->gb, 6);
1417
                    sf[1] = get_bits(&s->gb, 6);
1418
                    sf[2] = get_bits(&s->gb, 6);
1419
                    break;
1420
                case 2:
1421
                    sf[0] = get_bits(&s->gb, 6);
1422
                    sf[1] = sf[0];
1423
                    sf[2] = sf[0];
1424
                    break;
1425
                case 1:
1426
                    sf[0] = get_bits(&s->gb, 6);
1427
                    sf[2] = get_bits(&s->gb, 6);
1428
                    sf[1] = sf[0];
1429
                    break;
1430
                case 3:
1431
                    sf[0] = get_bits(&s->gb, 6);
1432
                    sf[2] = get_bits(&s->gb, 6);
1433
                    sf[1] = sf[2];
1434
                    break;
1435
                }
1436
            }
1437
        }
1438
    }
1439

    
1440
#ifdef DEBUG
1441
    for(ch=0;ch<s->nb_channels;ch++) {
1442
        for(i=0;i<sblimit;i++) {
1443
            if (bit_alloc[ch][i]) {
1444
                sf = scale_factors[ch][i];
1445
                dprintf(" %d %d %d", sf[0], sf[1], sf[2]);
1446
            } else {
1447
                dprintf(" -");
1448
            }
1449
        }
1450
        dprintf("\n");
1451
    }
1452
#endif
1453

    
1454
    /* samples */
1455
    for(k=0;k<3;k++) {
1456
        for(l=0;l<12;l+=3) {
1457
            j = 0;
1458
            for(i=0;i<bound;i++) {
1459
                bit_alloc_bits = alloc_table[j];
1460
                for(ch=0;ch<s->nb_channels;ch++) {
1461
                    b = bit_alloc[ch][i];
1462
                    if (b) {
1463
                        scale = scale_factors[ch][i][k];
1464
                        qindex = alloc_table[j+b];
1465
                        bits = quant_bits[qindex];
1466
                        if (bits < 0) {
1467
                            /* 3 values at the same time */
1468
                            v = get_bits(&s->gb, -bits);
1469
                            steps = quant_steps[qindex];
1470
                            s->sb_samples[ch][k * 12 + l + 0][i] =
1471
                                l2_unscale_group(steps, v % steps, scale);
1472
                            v = v / steps;
1473
                            s->sb_samples[ch][k * 12 + l + 1][i] =
1474
                                l2_unscale_group(steps, v % steps, scale);
1475
                            v = v / steps;
1476
                            s->sb_samples[ch][k * 12 + l + 2][i] =
1477
                                l2_unscale_group(steps, v, scale);
1478
                        } else {
1479
                            for(m=0;m<3;m++) {
1480
                                v = get_bits(&s->gb, bits);
1481
                                v = l1_unscale(bits - 1, v, scale);
1482
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
1483
                            }
1484
                        }
1485
                    } else {
1486
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1487
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1488
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1489
                    }
1490
                }
1491
                /* next subband in alloc table */
1492
                j += 1 << bit_alloc_bits;
1493
            }
1494
            /* XXX: find a way to avoid this duplication of code */
1495
            for(i=bound;i<sblimit;i++) {
1496
                bit_alloc_bits = alloc_table[j];
1497
                b = bit_alloc[0][i];
1498
                if (b) {
1499
                    int mant, scale0, scale1;
1500
                    scale0 = scale_factors[0][i][k];
1501
                    scale1 = scale_factors[1][i][k];
1502
                    qindex = alloc_table[j+b];
1503
                    bits = quant_bits[qindex];
1504
                    if (bits < 0) {
1505
                        /* 3 values at the same time */
1506
                        v = get_bits(&s->gb, -bits);
1507
                        steps = quant_steps[qindex];
1508
                        mant = v % steps;
1509
                        v = v / steps;
1510
                        s->sb_samples[0][k * 12 + l + 0][i] =
1511
                            l2_unscale_group(steps, mant, scale0);
1512
                        s->sb_samples[1][k * 12 + l + 0][i] =
1513
                            l2_unscale_group(steps, mant, scale1);
1514
                        mant = v % steps;
1515
                        v = v / steps;
1516
                        s->sb_samples[0][k * 12 + l + 1][i] =
1517
                            l2_unscale_group(steps, mant, scale0);
1518
                        s->sb_samples[1][k * 12 + l + 1][i] =
1519
                            l2_unscale_group(steps, mant, scale1);
1520
                        s->sb_samples[0][k * 12 + l + 2][i] =
1521
                            l2_unscale_group(steps, v, scale0);
1522
                        s->sb_samples[1][k * 12 + l + 2][i] =
1523
                            l2_unscale_group(steps, v, scale1);
1524
                    } else {
1525
                        for(m=0;m<3;m++) {
1526
                            mant = get_bits(&s->gb, bits);
1527
                            s->sb_samples[0][k * 12 + l + m][i] =
1528
                                l1_unscale(bits - 1, mant, scale0);
1529
                            s->sb_samples[1][k * 12 + l + m][i] =
1530
                                l1_unscale(bits - 1, mant, scale1);
1531
                        }
1532
                    }
1533
                } else {
1534
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
1535
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
1536
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
1537
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
1538
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
1539
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
1540
                }
1541
                /* next subband in alloc table */
1542
                j += 1 << bit_alloc_bits;
1543
            }
1544
            /* fill remaining samples to zero */
1545
            for(i=sblimit;i<SBLIMIT;i++) {
1546
                for(ch=0;ch<s->nb_channels;ch++) {
1547
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1548
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1549
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1550
                }
1551
            }
1552
        }
1553
    }
1554
    return 3 * 12;
1555
}
1556

    
1557
/*
1558
 * Seek back in the stream for backstep bytes (at most 511 bytes)
1559
 */
1560
static void seek_to_maindata(MPADecodeContext *s, unsigned int backstep)
1561
{
1562
    uint8_t *ptr;
1563

    
1564
    /* compute current position in stream */
1565
    ptr = (uint8_t *)(s->gb.buffer + (get_bits_count(&s->gb)>>3));
1566

    
1567
    /* copy old data before current one */
1568
    ptr -= backstep;
1569
    memcpy(ptr, s->inbuf1[s->inbuf_index ^ 1] +
1570
           BACKSTEP_SIZE + s->old_frame_size - backstep, backstep);
1571
    /* init get bits again */
1572
    init_get_bits(&s->gb, ptr, (s->frame_size + backstep)*8);
1573

    
1574
    /* prepare next buffer */
1575
    s->inbuf_index ^= 1;
1576
    s->inbuf = &s->inbuf1[s->inbuf_index][BACKSTEP_SIZE];
1577
    s->old_frame_size = s->frame_size;
1578
}
1579

    
1580
static inline void lsf_sf_expand(int *slen,
1581
                                 int sf, int n1, int n2, int n3)
1582
{
1583
    if (n3) {
1584
        slen[3] = sf % n3;
1585
        sf /= n3;
1586
    } else {
1587
        slen[3] = 0;
1588
    }
1589
    if (n2) {
1590
        slen[2] = sf % n2;
1591
        sf /= n2;
1592
    } else {
1593
        slen[2] = 0;
1594
    }
1595
    slen[1] = sf % n1;
1596
    sf /= n1;
1597
    slen[0] = sf;
1598
}
1599

    
1600
static void exponents_from_scale_factors(MPADecodeContext *s,
1601
                                         GranuleDef *g,
1602
                                         int16_t *exponents)
1603
{
1604
    const uint8_t *bstab, *pretab;
1605
    int len, i, j, k, l, v0, shift, gain, gains[3];
1606
    int16_t *exp_ptr;
1607

    
1608
    exp_ptr = exponents;
1609
    gain = g->global_gain - 210;
1610
    shift = g->scalefac_scale + 1;
1611

    
1612
    bstab = band_size_long[s->sample_rate_index];
1613
    pretab = mpa_pretab[g->preflag];
1614
    for(i=0;i<g->long_end;i++) {
1615
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift);
1616
        len = bstab[i];
1617
        for(j=len;j>0;j--)
1618
            *exp_ptr++ = v0;
1619
    }
1620

    
1621
    if (g->short_start < 13) {
1622
        bstab = band_size_short[s->sample_rate_index];
1623
        gains[0] = gain - (g->subblock_gain[0] << 3);
1624
        gains[1] = gain - (g->subblock_gain[1] << 3);
1625
        gains[2] = gain - (g->subblock_gain[2] << 3);
1626
        k = g->long_end;
1627
        for(i=g->short_start;i<13;i++) {
1628
            len = bstab[i];
1629
            for(l=0;l<3;l++) {
1630
                v0 = gains[l] - (g->scale_factors[k++] << shift);
1631
                for(j=len;j>0;j--)
1632
                *exp_ptr++ = v0;
1633
            }
1634
        }
1635
    }
1636
}
1637

    
1638
/* handle n = 0 too */
1639
static inline int get_bitsz(GetBitContext *s, int n)
1640
{
1641
    if (n == 0)
1642
        return 0;
1643
    else
1644
        return get_bits(s, n);
1645
}
1646

    
1647
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1648
                          int16_t *exponents, int end_pos)
1649
{
1650
    int s_index;
1651
    int linbits, code, x, y, l, v, i, j, k, pos;
1652
    GetBitContext last_gb;
1653
    VLC *vlc;
1654
    uint8_t *code_table;
1655

    
1656
    /* low frequencies (called big values) */
1657
    s_index = 0;
1658
    for(i=0;i<3;i++) {
1659
        j = g->region_size[i];
1660
        if (j == 0)
1661
            continue;
1662
        /* select vlc table */
1663
        k = g->table_select[i];
1664
        l = mpa_huff_data[k][0];
1665
        linbits = mpa_huff_data[k][1];
1666
        vlc = &huff_vlc[l];
1667
        code_table = huff_code_table[l];
1668

    
1669
        /* read huffcode and compute each couple */
1670
        for(;j>0;j--) {
1671
            if (get_bits_count(&s->gb) >= end_pos)
1672
                break;
1673
            if (code_table) {
1674
                code = get_vlc2(&s->gb, vlc->table, 8, 3);
1675
                if (code < 0)
1676
                    return -1;
1677
                y = code_table[code];
1678
                x = y >> 4;
1679
                y = y & 0x0f;
1680
            } else {
1681
                x = 0;
1682
                y = 0;
1683
            }
1684
            dprintf("region=%d n=%d x=%d y=%d exp=%d\n",
1685
                    i, g->region_size[i] - j, x, y, exponents[s_index]);
1686
            if (x) {
1687
                if (x == 15)
1688
                    x += get_bitsz(&s->gb, linbits);
1689
                v = l3_unscale(x, exponents[s_index]);
1690
                if (get_bits1(&s->gb))
1691
                    v = -v;
1692
            } else {
1693
                v = 0;
1694
            }
1695
            g->sb_hybrid[s_index++] = v;
1696
            if (y) {
1697
                if (y == 15)
1698
                    y += get_bitsz(&s->gb, linbits);
1699
                v = l3_unscale(y, exponents[s_index]);
1700
                if (get_bits1(&s->gb))
1701
                    v = -v;
1702
            } else {
1703
                v = 0;
1704
            }
1705
            g->sb_hybrid[s_index++] = v;
1706
        }
1707
    }
1708

    
1709
    /* high frequencies */
1710
    vlc = &huff_quad_vlc[g->count1table_select];
1711
    last_gb.buffer = NULL;
1712
    while (s_index <= 572) {
1713
        pos = get_bits_count(&s->gb);
1714
        if (pos >= end_pos) {
1715
            if (pos > end_pos && last_gb.buffer != NULL) {
1716
                /* some encoders generate an incorrect size for this
1717
                   part. We must go back into the data */
1718
                s_index -= 4;
1719
                s->gb = last_gb;
1720
            }
1721
            break;
1722
        }
1723
        last_gb= s->gb;
1724

    
1725
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 2);
1726
        dprintf("t=%d code=%d\n", g->count1table_select, code);
1727
        if (code < 0)
1728
            return -1;
1729
        for(i=0;i<4;i++) {
1730
            if (code & (8 >> i)) {
1731
                /* non zero value. Could use a hand coded function for
1732
                   'one' value */
1733
                v = l3_unscale(1, exponents[s_index]);
1734
                if(get_bits1(&s->gb))
1735
                    v = -v;
1736
            } else {
1737
                v = 0;
1738
            }
1739
            g->sb_hybrid[s_index++] = v;
1740
        }
1741
    }
1742
    while (s_index < 576)
1743
        g->sb_hybrid[s_index++] = 0;
1744
    return 0;
1745
}
1746

    
1747
/* Reorder short blocks from bitstream order to interleaved order. It
1748
   would be faster to do it in parsing, but the code would be far more
1749
   complicated */
1750
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1751
{
1752
    int i, j, k, len;
1753
    int32_t *ptr, *dst, *ptr1;
1754
    int32_t tmp[576];
1755

    
1756
    if (g->block_type != 2)
1757
        return;
1758

    
1759
    if (g->switch_point) {
1760
        if (s->sample_rate_index != 8) {
1761
            ptr = g->sb_hybrid + 36;
1762
        } else {
1763
            ptr = g->sb_hybrid + 48;
1764
        }
1765
    } else {
1766
        ptr = g->sb_hybrid;
1767
    }
1768

    
1769
    for(i=g->short_start;i<13;i++) {
1770
        len = band_size_short[s->sample_rate_index][i];
1771
        ptr1 = ptr;
1772
        for(k=0;k<3;k++) {
1773
            dst = tmp + k;
1774
            for(j=len;j>0;j--) {
1775
                *dst = *ptr++;
1776
                dst += 3;
1777
            }
1778
        }
1779
        memcpy(ptr1, tmp, len * 3 * sizeof(int32_t));
1780
    }
1781
}
1782

    
1783
#define ISQRT2 FIXR(0.70710678118654752440)
1784

    
1785
static void compute_stereo(MPADecodeContext *s,
1786
                           GranuleDef *g0, GranuleDef *g1)
1787
{
1788
    int i, j, k, l;
1789
    int32_t v1, v2;
1790
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1791
    int32_t (*is_tab)[16];
1792
    int32_t *tab0, *tab1;
1793
    int non_zero_found_short[3];
1794

    
1795
    /* intensity stereo */
1796
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1797
        if (!s->lsf) {
1798
            is_tab = is_table;
1799
            sf_max = 7;
1800
        } else {
1801
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1802
            sf_max = 16;
1803
        }
1804

    
1805
        tab0 = g0->sb_hybrid + 576;
1806
        tab1 = g1->sb_hybrid + 576;
1807

    
1808
        non_zero_found_short[0] = 0;
1809
        non_zero_found_short[1] = 0;
1810
        non_zero_found_short[2] = 0;
1811
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1812
        for(i = 12;i >= g1->short_start;i--) {
1813
            /* for last band, use previous scale factor */
1814
            if (i != 11)
1815
                k -= 3;
1816
            len = band_size_short[s->sample_rate_index][i];
1817
            for(l=2;l>=0;l--) {
1818
                tab0 -= len;
1819
                tab1 -= len;
1820
                if (!non_zero_found_short[l]) {
1821
                    /* test if non zero band. if so, stop doing i-stereo */
1822
                    for(j=0;j<len;j++) {
1823
                        if (tab1[j] != 0) {
1824
                            non_zero_found_short[l] = 1;
1825
                            goto found1;
1826
                        }
1827
                    }
1828
                    sf = g1->scale_factors[k + l];
1829
                    if (sf >= sf_max)
1830
                        goto found1;
1831

    
1832
                    v1 = is_tab[0][sf];
1833
                    v2 = is_tab[1][sf];
1834
                    for(j=0;j<len;j++) {
1835
                        tmp0 = tab0[j];
1836
                        tab0[j] = MULL(tmp0, v1);
1837
                        tab1[j] = MULL(tmp0, v2);
1838
                    }
1839
                } else {
1840
                found1:
1841
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1842
                        /* lower part of the spectrum : do ms stereo
1843
                           if enabled */
1844
                        for(j=0;j<len;j++) {
1845
                            tmp0 = tab0[j];
1846
                            tmp1 = tab1[j];
1847
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1848
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1849
                        }
1850
                    }
1851
                }
1852
            }
1853
        }
1854

    
1855
        non_zero_found = non_zero_found_short[0] |
1856
            non_zero_found_short[1] |
1857
            non_zero_found_short[2];
1858

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

    
1912
static void compute_antialias_integer(MPADecodeContext *s,
1913
                              GranuleDef *g)
1914
{
1915
    int32_t *ptr, *csa;
1916
    int n, i;
1917

    
1918
    /* we antialias only "long" bands */
1919
    if (g->block_type == 2) {
1920
        if (!g->switch_point)
1921
            return;
1922
        /* XXX: check this for 8000Hz case */
1923
        n = 1;
1924
    } else {
1925
        n = SBLIMIT - 1;
1926
    }
1927

    
1928
    ptr = g->sb_hybrid + 18;
1929
    for(i = n;i > 0;i--) {
1930
        int tmp0, tmp1, tmp2;
1931
        csa = &csa_table[0][0];
1932
#define INT_AA(j) \
1933
            tmp0 = ptr[-1-j];\
1934
            tmp1 = ptr[   j];\
1935
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1936
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1937
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1938

    
1939
        INT_AA(0)
1940
        INT_AA(1)
1941
        INT_AA(2)
1942
        INT_AA(3)
1943
        INT_AA(4)
1944
        INT_AA(5)
1945
        INT_AA(6)
1946
        INT_AA(7)
1947

    
1948
        ptr += 18;
1949
    }
1950
}
1951

    
1952
static void compute_antialias_float(MPADecodeContext *s,
1953
                              GranuleDef *g)
1954
{
1955
    int32_t *ptr;
1956
    int n, i;
1957

    
1958
    /* we antialias only "long" bands */
1959
    if (g->block_type == 2) {
1960
        if (!g->switch_point)
1961
            return;
1962
        /* XXX: check this for 8000Hz case */
1963
        n = 1;
1964
    } else {
1965
        n = SBLIMIT - 1;
1966
    }
1967

    
1968
    ptr = g->sb_hybrid + 18;
1969
    for(i = n;i > 0;i--) {
1970
        float tmp0, tmp1;
1971
        float *csa = &csa_table_float[0][0];
1972
#define FLOAT_AA(j)\
1973
        tmp0= ptr[-1-j];\
1974
        tmp1= ptr[   j];\
1975
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1976
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1977

    
1978
        FLOAT_AA(0)
1979
        FLOAT_AA(1)
1980
        FLOAT_AA(2)
1981
        FLOAT_AA(3)
1982
        FLOAT_AA(4)
1983
        FLOAT_AA(5)
1984
        FLOAT_AA(6)
1985
        FLOAT_AA(7)
1986

    
1987
        ptr += 18;
1988
    }
1989
}
1990

    
1991
static void compute_imdct(MPADecodeContext *s,
1992
                          GranuleDef *g,
1993
                          int32_t *sb_samples,
1994
                          int32_t *mdct_buf)
1995
{
1996
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
1997
    int32_t out2[12];
1998
    int i, j, mdct_long_end, v, sblimit;
1999

    
2000
    /* find last non zero block */
2001
    ptr = g->sb_hybrid + 576;
2002
    ptr1 = g->sb_hybrid + 2 * 18;
2003
    while (ptr >= ptr1) {
2004
        ptr -= 6;
2005
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
2006
        if (v != 0)
2007
            break;
2008
    }
2009
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
2010

    
2011
    if (g->block_type == 2) {
2012
        /* XXX: check for 8000 Hz */
2013
        if (g->switch_point)
2014
            mdct_long_end = 2;
2015
        else
2016
            mdct_long_end = 0;
2017
    } else {
2018
        mdct_long_end = sblimit;
2019
    }
2020

    
2021
    buf = mdct_buf;
2022
    ptr = g->sb_hybrid;
2023
    for(j=0;j<mdct_long_end;j++) {
2024
        /* apply window & overlap with previous buffer */
2025
        out_ptr = sb_samples + j;
2026
        /* select window */
2027
        if (g->switch_point && j < 2)
2028
            win1 = mdct_win[0];
2029
        else
2030
            win1 = mdct_win[g->block_type];
2031
        /* select frequency inversion */
2032
        win = win1 + ((4 * 36) & -(j & 1));
2033
        imdct36(out_ptr, buf, ptr, win);
2034
        out_ptr += 18*SBLIMIT;
2035
        ptr += 18;
2036
        buf += 18;
2037
    }
2038
    for(j=mdct_long_end;j<sblimit;j++) {
2039
        /* select frequency inversion */
2040
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
2041
        out_ptr = sb_samples + j;
2042

    
2043
        for(i=0; i<6; i++){
2044
            *out_ptr = buf[i];
2045
            out_ptr += SBLIMIT;
2046
        }
2047
        imdct12(out2, ptr + 0);
2048
        for(i=0;i<6;i++) {
2049
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
2050
            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
2051
            out_ptr += SBLIMIT;
2052
        }
2053
        imdct12(out2, ptr + 1);
2054
        for(i=0;i<6;i++) {
2055
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
2056
            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
2057
            out_ptr += SBLIMIT;
2058
        }
2059
        imdct12(out2, ptr + 2);
2060
        for(i=0;i<6;i++) {
2061
            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
2062
            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
2063
            buf[i + 6*2] = 0;
2064
        }
2065
        ptr += 18;
2066
        buf += 18;
2067
    }
2068
    /* zero bands */
2069
    for(j=sblimit;j<SBLIMIT;j++) {
2070
        /* overlap */
2071
        out_ptr = sb_samples + j;
2072
        for(i=0;i<18;i++) {
2073
            *out_ptr = buf[i];
2074
            buf[i] = 0;
2075
            out_ptr += SBLIMIT;
2076
        }
2077
        buf += 18;
2078
    }
2079
}
2080

    
2081
#if defined(DEBUG)
2082
void sample_dump(int fnum, int32_t *tab, int n)
2083
{
2084
    static FILE *files[16], *f;
2085
    char buf[512];
2086
    int i;
2087
    int32_t v;
2088

    
2089
    f = files[fnum];
2090
    if (!f) {
2091
        snprintf(buf, sizeof(buf), "/tmp/out%d.%s.pcm",
2092
                fnum,
2093
#ifdef USE_HIGHPRECISION
2094
                "hp"
2095
#else
2096
                "lp"
2097
#endif
2098
                );
2099
        f = fopen(buf, "w");
2100
        if (!f)
2101
            return;
2102
        files[fnum] = f;
2103
    }
2104

    
2105
    if (fnum == 0) {
2106
        static int pos = 0;
2107
        av_log(NULL, AV_LOG_DEBUG, "pos=%d\n", pos);
2108
        for(i=0;i<n;i++) {
2109
            av_log(NULL, AV_LOG_DEBUG, " %0.4f", (double)tab[i] / FRAC_ONE);
2110
            if ((i % 18) == 17)
2111
                av_log(NULL, AV_LOG_DEBUG, "\n");
2112
        }
2113
        pos += n;
2114
    }
2115
    for(i=0;i<n;i++) {
2116
        /* normalize to 23 frac bits */
2117
        v = tab[i] << (23 - FRAC_BITS);
2118
        fwrite(&v, 1, sizeof(int32_t), f);
2119
    }
2120
}
2121
#endif
2122

    
2123

    
2124
/* main layer3 decoding function */
2125
static int mp_decode_layer3(MPADecodeContext *s)
2126
{
2127
    int nb_granules, main_data_begin, private_bits;
2128
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos, bits_left;
2129
    GranuleDef granules[2][2], *g;
2130
    int16_t exponents[576];
2131

    
2132
    /* read side info */
2133
    if (s->lsf) {
2134
        main_data_begin = get_bits(&s->gb, 8);
2135
        if (s->nb_channels == 2)
2136
            private_bits = get_bits(&s->gb, 2);
2137
        else
2138
            private_bits = get_bits(&s->gb, 1);
2139
        nb_granules = 1;
2140
    } else {
2141
        main_data_begin = get_bits(&s->gb, 9);
2142
        if (s->nb_channels == 2)
2143
            private_bits = get_bits(&s->gb, 3);
2144
        else
2145
            private_bits = get_bits(&s->gb, 5);
2146
        nb_granules = 2;
2147
        for(ch=0;ch<s->nb_channels;ch++) {
2148
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
2149
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
2150
        }
2151
    }
2152

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

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

    
2236
                    if (s->sample_rate_index != 8)
2237
                        g->short_start = 3;
2238
                    else
2239
                        g->short_start = 2;
2240
                } else {
2241
                    g->long_end = 0;
2242
                    g->short_start = 0;
2243
                }
2244
            } else {
2245
                g->short_start = 13;
2246
                g->long_end = 22;
2247
            }
2248

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

    
2259
  if (!s->adu_mode) {
2260
    /* now we get bits from the main_data_begin offset */
2261
    dprintf("seekback: %d\n", main_data_begin);
2262
    seek_to_maindata(s, main_data_begin);
2263
  }
2264

    
2265
    for(gr=0;gr<nb_granules;gr++) {
2266
        for(ch=0;ch<s->nb_channels;ch++) {
2267
            g = &granules[ch][gr];
2268

    
2269
            bits_pos = get_bits_count(&s->gb);
2270

    
2271
            if (!s->lsf) {
2272
                uint8_t *sc;
2273
                int slen, slen1, slen2;
2274

    
2275
                /* MPEG1 scale factors */
2276
                slen1 = slen_table[0][g->scalefac_compress];
2277
                slen2 = slen_table[1][g->scalefac_compress];
2278
                dprintf("slen1=%d slen2=%d\n", slen1, slen2);
2279
                if (g->block_type == 2) {
2280
                    n = g->switch_point ? 17 : 18;
2281
                    j = 0;
2282
                    for(i=0;i<n;i++)
2283
                        g->scale_factors[j++] = get_bitsz(&s->gb, slen1);
2284
                    for(i=0;i<18;i++)
2285
                        g->scale_factors[j++] = get_bitsz(&s->gb, slen2);
2286
                    for(i=0;i<3;i++)
2287
                        g->scale_factors[j++] = 0;
2288
                } else {
2289
                    sc = granules[ch][0].scale_factors;
2290
                    j = 0;
2291
                    for(k=0;k<4;k++) {
2292
                        n = (k == 0 ? 6 : 5);
2293
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2294
                            slen = (k < 2) ? slen1 : slen2;
2295
                            for(i=0;i<n;i++)
2296
                                g->scale_factors[j++] = get_bitsz(&s->gb, slen);
2297
                        } else {
2298
                            /* simply copy from last granule */
2299
                            for(i=0;i<n;i++) {
2300
                                g->scale_factors[j] = sc[j];
2301
                                j++;
2302
                            }
2303
                        }
2304
                    }
2305
                    g->scale_factors[j++] = 0;
2306
                }
2307
#if defined(DEBUG)
2308
                {
2309
                    dprintf("scfsi=%x gr=%d ch=%d scale_factors:\n",
2310
                           g->scfsi, gr, ch);
2311
                    for(i=0;i<j;i++)
2312
                        dprintf(" %d", g->scale_factors[i]);
2313
                    dprintf("\n");
2314
                }
2315
#endif
2316
            } else {
2317
                int tindex, tindex2, slen[4], sl, sf;
2318

    
2319
                /* LSF scale factors */
2320
                if (g->block_type == 2) {
2321
                    tindex = g->switch_point ? 2 : 1;
2322
                } else {
2323
                    tindex = 0;
2324
                }
2325
                sf = g->scalefac_compress;
2326
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2327
                    /* intensity stereo case */
2328
                    sf >>= 1;
2329
                    if (sf < 180) {
2330
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2331
                        tindex2 = 3;
2332
                    } else if (sf < 244) {
2333
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2334
                        tindex2 = 4;
2335
                    } else {
2336
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2337
                        tindex2 = 5;
2338
                    }
2339
                } else {
2340
                    /* normal case */
2341
                    if (sf < 400) {
2342
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2343
                        tindex2 = 0;
2344
                    } else if (sf < 500) {
2345
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2346
                        tindex2 = 1;
2347
                    } else {
2348
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2349
                        tindex2 = 2;
2350
                        g->preflag = 1;
2351
                    }
2352
                }
2353

    
2354
                j = 0;
2355
                for(k=0;k<4;k++) {
2356
                    n = lsf_nsf_table[tindex2][tindex][k];
2357
                    sl = slen[k];
2358
                    for(i=0;i<n;i++)
2359
                        g->scale_factors[j++] = get_bitsz(&s->gb, sl);
2360
                }
2361
                /* XXX: should compute exact size */
2362
                for(;j<40;j++)
2363
                    g->scale_factors[j] = 0;
2364
#if defined(DEBUG)
2365
                {
2366
                    dprintf("gr=%d ch=%d scale_factors:\n",
2367
                           gr, ch);
2368
                    for(i=0;i<40;i++)
2369
                        dprintf(" %d", g->scale_factors[i]);
2370
                    dprintf("\n");
2371
                }
2372
#endif
2373
            }
2374

    
2375
            exponents_from_scale_factors(s, g, exponents);
2376

    
2377
            /* read Huffman coded residue */
2378
            if (huffman_decode(s, g, exponents,
2379
                               bits_pos + g->part2_3_length) < 0)
2380
                return -1;
2381
#if defined(DEBUG)
2382
            sample_dump(0, g->sb_hybrid, 576);
2383
#endif
2384

    
2385
            /* skip extension bits */
2386
            bits_left = g->part2_3_length - (get_bits_count(&s->gb) - bits_pos);
2387
            if (bits_left < 0) {
2388
                dprintf("bits_left=%d\n", bits_left);
2389
                return -1;
2390
            }
2391
            while (bits_left >= 16) {
2392
                skip_bits(&s->gb, 16);
2393
                bits_left -= 16;
2394
            }
2395
            if (bits_left > 0)
2396
                skip_bits(&s->gb, bits_left);
2397
        } /* ch */
2398

    
2399
        if (s->nb_channels == 2)
2400
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2401

    
2402
        for(ch=0;ch<s->nb_channels;ch++) {
2403
            g = &granules[ch][gr];
2404

    
2405
            reorder_block(s, g);
2406
#if defined(DEBUG)
2407
            sample_dump(0, g->sb_hybrid, 576);
2408
#endif
2409
            s->compute_antialias(s, g);
2410
#if defined(DEBUG)
2411
            sample_dump(1, g->sb_hybrid, 576);
2412
#endif
2413
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2414
#if defined(DEBUG)
2415
            sample_dump(2, &s->sb_samples[ch][18 * gr][0], 576);
2416
#endif
2417
        }
2418
    } /* gr */
2419
    return nb_granules * 18;
2420
}
2421

    
2422
static int mp_decode_frame(MPADecodeContext *s,
2423
                           OUT_INT *samples)
2424
{
2425
    int i, nb_frames, ch;
2426
    OUT_INT *samples_ptr;
2427

    
2428
    init_get_bits(&s->gb, s->inbuf + HEADER_SIZE,
2429
                  (s->inbuf_ptr - s->inbuf - HEADER_SIZE)*8);
2430

    
2431
    /* skip error protection field */
2432
    if (s->error_protection)
2433
        get_bits(&s->gb, 16);
2434

    
2435
    dprintf("frame %d:\n", s->frame_count);
2436
    switch(s->layer) {
2437
    case 1:
2438
        nb_frames = mp_decode_layer1(s);
2439
        break;
2440
    case 2:
2441
        nb_frames = mp_decode_layer2(s);
2442
        break;
2443
    case 3:
2444
    default:
2445
        nb_frames = mp_decode_layer3(s);
2446
        break;
2447
    }
2448
#if defined(DEBUG)
2449
    for(i=0;i<nb_frames;i++) {
2450
        for(ch=0;ch<s->nb_channels;ch++) {
2451
            int j;
2452
            dprintf("%d-%d:", i, ch);
2453
            for(j=0;j<SBLIMIT;j++)
2454
                dprintf(" %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);
2455
            dprintf("\n");
2456
        }
2457
    }
2458
#endif
2459
    /* apply the synthesis filter */
2460
    for(ch=0;ch<s->nb_channels;ch++) {
2461
        samples_ptr = samples + ch;
2462
        for(i=0;i<nb_frames;i++) {
2463
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2464
                         window, &s->dither_state,
2465
                         samples_ptr, s->nb_channels,
2466
                         s->sb_samples[ch][i]);
2467
            samples_ptr += 32 * s->nb_channels;
2468
        }
2469
    }
2470
#ifdef DEBUG
2471
    s->frame_count++;
2472
#endif
2473
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2474
}
2475

    
2476
static int decode_frame(AVCodecContext * avctx,
2477
                        void *data, int *data_size,
2478
                        uint8_t * buf, int buf_size)
2479
{
2480
    MPADecodeContext *s = avctx->priv_data;
2481
    uint32_t header;
2482
    uint8_t *buf_ptr;
2483
    int len, out_size;
2484
    OUT_INT *out_samples = data;
2485

    
2486
    buf_ptr = buf;
2487
    while (buf_size > 0) {
2488
        len = s->inbuf_ptr - s->inbuf;
2489
        if (s->frame_size == 0) {
2490
            /* special case for next header for first frame in free
2491
               format case (XXX: find a simpler method) */
2492
            if (s->free_format_next_header != 0) {
2493
                s->inbuf[0] = s->free_format_next_header >> 24;
2494
                s->inbuf[1] = s->free_format_next_header >> 16;
2495
                s->inbuf[2] = s->free_format_next_header >> 8;
2496
                s->inbuf[3] = s->free_format_next_header;
2497
                s->inbuf_ptr = s->inbuf + 4;
2498
                s->free_format_next_header = 0;
2499
                goto got_header;
2500
            }
2501
            /* no header seen : find one. We need at least HEADER_SIZE
2502
               bytes to parse it */
2503
            len = HEADER_SIZE - len;
2504
            if (len > buf_size)
2505
                len = buf_size;
2506
            if (len > 0) {
2507
                memcpy(s->inbuf_ptr, buf_ptr, len);
2508
                buf_ptr += len;
2509
                buf_size -= len;
2510
                s->inbuf_ptr += len;
2511
            }
2512
            if ((s->inbuf_ptr - s->inbuf) >= HEADER_SIZE) {
2513
            got_header:
2514
                header = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |
2515
                    (s->inbuf[2] << 8) | s->inbuf[3];
2516

    
2517
                if (ff_mpa_check_header(header) < 0) {
2518
                    /* no sync found : move by one byte (inefficient, but simple!) */
2519
                    memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);
2520
                    s->inbuf_ptr--;
2521
                    dprintf("skip %x\n", header);
2522
                    /* reset free format frame size to give a chance
2523
                       to get a new bitrate */
2524
                    s->free_format_frame_size = 0;
2525
                } else {
2526
                    if (decode_header(s, header) == 1) {
2527
                        /* free format: prepare to compute frame size */
2528
                        s->frame_size = -1;
2529
                    }
2530
                    /* update codec info */
2531
                    avctx->sample_rate = s->sample_rate;
2532
                    avctx->channels = s->nb_channels;
2533
                    avctx->bit_rate = s->bit_rate;
2534
                    avctx->sub_id = s->layer;
2535
                    switch(s->layer) {
2536
                    case 1:
2537
                        avctx->frame_size = 384;
2538
                        break;
2539
                    case 2:
2540
                        avctx->frame_size = 1152;
2541
                        break;
2542
                    case 3:
2543
                        if (s->lsf)
2544
                            avctx->frame_size = 576;
2545
                        else
2546
                            avctx->frame_size = 1152;
2547
                        break;
2548
                    }
2549
                }
2550
            }
2551
        } else if (s->frame_size == -1) {
2552
            /* free format : find next sync to compute frame size */
2553
            len = MPA_MAX_CODED_FRAME_SIZE - len;
2554
            if (len > buf_size)
2555
                len = buf_size;
2556
            if (len == 0) {
2557
                /* frame too long: resync */
2558
                s->frame_size = 0;
2559
                memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);
2560
                s->inbuf_ptr--;
2561
            } else {
2562
                uint8_t *p, *pend;
2563
                uint32_t header1;
2564
                int padding;
2565

    
2566
                memcpy(s->inbuf_ptr, buf_ptr, len);
2567
                /* check for header */
2568
                p = s->inbuf_ptr - 3;
2569
                pend = s->inbuf_ptr + len - 4;
2570
                while (p <= pend) {
2571
                    header = (p[0] << 24) | (p[1] << 16) |
2572
                        (p[2] << 8) | p[3];
2573
                    header1 = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |
2574
                        (s->inbuf[2] << 8) | s->inbuf[3];
2575
                    /* check with high probability that we have a
2576
                       valid header */
2577
                    if ((header & SAME_HEADER_MASK) ==
2578
                        (header1 & SAME_HEADER_MASK)) {
2579
                        /* header found: update pointers */
2580
                        len = (p + 4) - s->inbuf_ptr;
2581
                        buf_ptr += len;
2582
                        buf_size -= len;
2583
                        s->inbuf_ptr = p;
2584
                        /* compute frame size */
2585
                        s->free_format_next_header = header;
2586
                        s->free_format_frame_size = s->inbuf_ptr - s->inbuf;
2587
                        padding = (header1 >> 9) & 1;
2588
                        if (s->layer == 1)
2589
                            s->free_format_frame_size -= padding * 4;
2590
                        else
2591
                            s->free_format_frame_size -= padding;
2592
                        dprintf("free frame size=%d padding=%d\n",
2593
                                s->free_format_frame_size, padding);
2594
                        decode_header(s, header1);
2595
                        goto next_data;
2596
                    }
2597
                    p++;
2598
                }
2599
                /* not found: simply increase pointers */
2600
                buf_ptr += len;
2601
                s->inbuf_ptr += len;
2602
                buf_size -= len;
2603
            }
2604
        } else if (len < s->frame_size) {
2605
            if (s->frame_size > MPA_MAX_CODED_FRAME_SIZE)
2606
                s->frame_size = MPA_MAX_CODED_FRAME_SIZE;
2607
            len = s->frame_size - len;
2608
            if (len > buf_size)
2609
                len = buf_size;
2610
            memcpy(s->inbuf_ptr, buf_ptr, len);
2611
            buf_ptr += len;
2612
            s->inbuf_ptr += len;
2613
            buf_size -= len;
2614
        }
2615
    next_data:
2616
        if (s->frame_size > 0 &&
2617
            (s->inbuf_ptr - s->inbuf) >= s->frame_size) {
2618
            if (avctx->parse_only) {
2619
                /* simply return the frame data */
2620
                *(uint8_t **)data = s->inbuf;
2621
                out_size = s->inbuf_ptr - s->inbuf;
2622
            } else {
2623
                out_size = mp_decode_frame(s, out_samples);
2624
            }
2625
            s->inbuf_ptr = s->inbuf;
2626
            s->frame_size = 0;
2627
            if(out_size>=0)
2628
                *data_size = out_size;
2629
            else
2630
                av_log(avctx, AV_LOG_DEBUG, "Error while decoding mpeg audio frame\n"); //FIXME return -1 / but also return the number of bytes consumed
2631
            break;
2632
        }
2633
    }
2634
    return buf_ptr - buf;
2635
}
2636

    
2637

    
2638
static int decode_frame_adu(AVCodecContext * avctx,
2639
                        void *data, int *data_size,
2640
                        uint8_t * buf, int buf_size)
2641
{
2642
    MPADecodeContext *s = avctx->priv_data;
2643
    uint32_t header;
2644
    int len, out_size;
2645
    OUT_INT *out_samples = data;
2646

    
2647
    len = buf_size;
2648

    
2649
    // Discard too short frames
2650
    if (buf_size < HEADER_SIZE) {
2651
        *data_size = 0;
2652
        return buf_size;
2653
    }
2654

    
2655

    
2656
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2657
        len = MPA_MAX_CODED_FRAME_SIZE;
2658

    
2659
    memcpy(s->inbuf, buf, len);
2660
    s->inbuf_ptr = s->inbuf + len;
2661

    
2662
    // Get header and restore sync word
2663
    header = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |
2664
              (s->inbuf[2] << 8) | s->inbuf[3] | 0xffe00000;
2665

    
2666
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2667
        *data_size = 0;
2668
        return buf_size;
2669
    }
2670

    
2671
    decode_header(s, header);
2672
    /* update codec info */
2673
    avctx->sample_rate = s->sample_rate;
2674
    avctx->channels = s->nb_channels;
2675
    avctx->bit_rate = s->bit_rate;
2676
    avctx->sub_id = s->layer;
2677

    
2678
    avctx->frame_size=s->frame_size = len;
2679

    
2680
    if (avctx->parse_only) {
2681
        /* simply return the frame data */
2682
        *(uint8_t **)data = s->inbuf;
2683
        out_size = s->inbuf_ptr - s->inbuf;
2684
    } else {
2685
        out_size = mp_decode_frame(s, out_samples);
2686
    }
2687

    
2688
    *data_size = out_size;
2689
    return buf_size;
2690
}
2691

    
2692

    
2693
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2694
static int mp3Frames[16] = {0,1,1,2,3,3,4,5,2};   /* number of mp3 decoder instances */
2695
static int mp3Channels[16] = {0,1,2,3,4,5,6,8,4}; /* total output channels */
2696
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2697
static int chan_offset[9][5] = {
2698
    {0},
2699
    {0},            // C
2700
    {0},            // FLR
2701
    {2,0},          // C FLR
2702
    {2,0,3},        // C FLR BS
2703
    {4,0,2},        // C FLR BLRS
2704
    {4,0,2,5},      // C FLR BLRS LFE
2705
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2706
    {0,2}           // FLR BLRS
2707
};
2708

    
2709

    
2710
static int decode_init_mp3on4(AVCodecContext * avctx)
2711
{
2712
    MP3On4DecodeContext *s = avctx->priv_data;
2713
    int i;
2714

    
2715
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2716
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2717
        return -1;
2718
    }
2719

    
2720
    s->chan_cfg = (((unsigned char *)avctx->extradata)[1] >> 3) & 0x0f;
2721
    s->frames = mp3Frames[s->chan_cfg];
2722
    if(!s->frames) {
2723
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2724
        return -1;
2725
    }
2726
    avctx->channels = mp3Channels[s->chan_cfg];
2727

    
2728
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2729
     * We replace avctx->priv_data with the context of the first decoder so that
2730
     * decode_init() does not have to be changed.
2731
     * Other decoders will be inited here copying data from the first context
2732
     */
2733
    // Allocate zeroed memory for the first decoder context
2734
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2735
    // Put decoder context in place to make init_decode() happy
2736
    avctx->priv_data = s->mp3decctx[0];
2737
    decode_init(avctx);
2738
    // Restore mp3on4 context pointer
2739
    avctx->priv_data = s;
2740
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2741

    
2742
    /* Create a separate codec/context for each frame (first is already ok).
2743
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2744
     */
2745
    for (i = 1; i < s->frames; i++) {
2746
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2747
        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2748
        s->mp3decctx[i]->inbuf = &s->mp3decctx[i]->inbuf1[0][BACKSTEP_SIZE];
2749
        s->mp3decctx[i]->inbuf_ptr = s->mp3decctx[i]->inbuf;
2750
        s->mp3decctx[i]->adu_mode = 1;
2751
    }
2752

    
2753
    return 0;
2754
}
2755

    
2756

    
2757
static int decode_close_mp3on4(AVCodecContext * avctx)
2758
{
2759
    MP3On4DecodeContext *s = avctx->priv_data;
2760
    int i;
2761

    
2762
    for (i = 0; i < s->frames; i++)
2763
        if (s->mp3decctx[i])
2764
            av_free(s->mp3decctx[i]);
2765

    
2766
    return 0;
2767
}
2768

    
2769

    
2770
static int decode_frame_mp3on4(AVCodecContext * avctx,
2771
                        void *data, int *data_size,
2772
                        uint8_t * buf, int buf_size)
2773
{
2774
    MP3On4DecodeContext *s = avctx->priv_data;
2775
    MPADecodeContext *m;
2776
    int len, out_size = 0;
2777
    uint32_t header;
2778
    OUT_INT *out_samples = data;
2779
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2780
    OUT_INT *outptr, *bp;
2781
    int fsize;
2782
    unsigned char *start2 = buf, *start;
2783
    int fr, i, j, n;
2784
    int off = avctx->channels;
2785
    int *coff = chan_offset[s->chan_cfg];
2786

    
2787
    len = buf_size;
2788

    
2789
    // Discard too short frames
2790
    if (buf_size < HEADER_SIZE) {
2791
        *data_size = 0;
2792
        return buf_size;
2793
    }
2794

    
2795
    // If only one decoder interleave is not needed
2796
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2797

    
2798
    for (fr = 0; fr < s->frames; fr++) {
2799
        start = start2;
2800
        fsize = (start[0] << 4) | (start[1] >> 4);
2801
        start2 += fsize;
2802
        if (fsize > len)
2803
            fsize = len;
2804
        len -= fsize;
2805
        if (fsize > MPA_MAX_CODED_FRAME_SIZE)
2806
            fsize = MPA_MAX_CODED_FRAME_SIZE;
2807
        m = s->mp3decctx[fr];
2808
        assert (m != NULL);
2809
        /* copy original to new */
2810
        m->inbuf_ptr = m->inbuf + fsize;
2811
        memcpy(m->inbuf, start, fsize);
2812

    
2813
        // Get header
2814
        header = (m->inbuf[0] << 24) | (m->inbuf[1] << 16) |
2815
                  (m->inbuf[2] << 8) | m->inbuf[3] | 0xfff00000;
2816

    
2817
        if (ff_mpa_check_header(header) < 0) { // Bad header, discard block
2818
            *data_size = 0;
2819
            return buf_size;
2820
        }
2821

    
2822
        decode_header(m, header);
2823
        mp_decode_frame(m, decoded_buf);
2824

    
2825
        n = MPA_FRAME_SIZE * m->nb_channels;
2826
        out_size += n * sizeof(OUT_INT);
2827
        if(s->frames > 1) {
2828
            /* interleave output data */
2829
            bp = out_samples + coff[fr];
2830
            if(m->nb_channels == 1) {
2831
                for(j = 0; j < n; j++) {
2832
                    *bp = decoded_buf[j];
2833
                    bp += off;
2834
                }
2835
            } else {
2836
                for(j = 0; j < n; j++) {
2837
                    bp[0] = decoded_buf[j++];
2838
                    bp[1] = decoded_buf[j];
2839
                    bp += off;
2840
                }
2841
            }
2842
        }
2843
    }
2844

    
2845
    /* update codec info */
2846
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2847
    avctx->frame_size= buf_size;
2848
    avctx->bit_rate = 0;
2849
    for (i = 0; i < s->frames; i++)
2850
        avctx->bit_rate += s->mp3decctx[i]->bit_rate;
2851

    
2852
    *data_size = out_size;
2853
    return buf_size;
2854
}
2855

    
2856

    
2857
AVCodec mp2_decoder =
2858
{
2859
    "mp2",
2860
    CODEC_TYPE_AUDIO,
2861
    CODEC_ID_MP2,
2862
    sizeof(MPADecodeContext),
2863
    decode_init,
2864
    NULL,
2865
    NULL,
2866
    decode_frame,
2867
    CODEC_CAP_PARSE_ONLY,
2868
};
2869

    
2870
AVCodec mp3_decoder =
2871
{
2872
    "mp3",
2873
    CODEC_TYPE_AUDIO,
2874
    CODEC_ID_MP3,
2875
    sizeof(MPADecodeContext),
2876
    decode_init,
2877
    NULL,
2878
    NULL,
2879
    decode_frame,
2880
    CODEC_CAP_PARSE_ONLY,
2881
};
2882

    
2883
AVCodec mp3adu_decoder =
2884
{
2885
    "mp3adu",
2886
    CODEC_TYPE_AUDIO,
2887
    CODEC_ID_MP3ADU,
2888
    sizeof(MPADecodeContext),
2889
    decode_init,
2890
    NULL,
2891
    NULL,
2892
    decode_frame_adu,
2893
    CODEC_CAP_PARSE_ONLY,
2894
};
2895

    
2896
AVCodec mp3on4_decoder =
2897
{
2898
    "mp3on4",
2899
    CODEC_TYPE_AUDIO,
2900
    CODEC_ID_MP3ON4,
2901
    sizeof(MP3On4DecodeContext),
2902
    decode_init_mp3on4,
2903
    NULL,
2904
    decode_close_mp3on4,
2905
    decode_frame_mp3on4,
2906
    0
2907
};