Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 06e7fb82

History | View | Annotate | Download (85.5 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
#ifdef ARCH_X86
47
#   define MULL(ra, rb) \
48
        ({ int rt, dummy; asm (\
49
            "imull %3               \n\t"\
50
            "shrdl %4, %%edx, %%eax \n\t"\
51
            : "=a"(rt), "=d"(dummy)\
52
            : "a" (ra), "rm" (rb), "i"(FRAC_BITS));\
53
         rt; })
54
#   define MUL64(ra, rb) \
55
        ({ int64_t rt; asm ("imull %2\n\t" : "=A"(rt) : "a" (ra), "g" (rb)); rt; })
56
#   define MULH(ra, rb) \
57
        ({ int rt, dummy; asm ("imull %3\n\t" : "=d"(rt), "=a"(dummy): "a" (ra), "rm" (rb)); rt; })
58
#elif defined(ARCH_ARMV4L)
59
#   define MULL(a, b) \
60
        ({  int lo, hi;\
61
            asm("smull %0, %1, %2, %3     \n\t"\
62
                "mov   %0, %0,     lsr %4\n\t"\
63
                "add   %1, %0, %1, lsl %5\n\t"\
64
            : "=&r"(lo), "=&r"(hi)\
65
            : "r"(b), "r"(a), "i"(FRAC_BITS), "i"(32-FRAC_BITS));\
66
         hi; })
67
#   define MUL64(a,b) ((int64_t)(a) * (int64_t)(b))
68
#   define MULH(a, b) ({ int lo, hi; asm ("smull %0, %1, %2, %3" : "=&r"(lo), "=&r"(hi) : "r"(b), "r"(a)); hi; })
69
#else
70
#   define MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> FRAC_BITS)
71
#   define MUL64(a,b) ((int64_t)(a) * (int64_t)(b))
72
//#define MULH(a,b) (((int64_t)(a) * (int64_t)(b))>>32) //gcc 3.4 creates an incredibly bloated mess out of this
73
static always_inline int MULH(int a, int b){
74
    return ((int64_t)(a) * (int64_t)(b))>>32;
75
}
76
#endif
77
#define FIX(a)   ((int)((a) * FRAC_ONE))
78
/* WARNING: only correct for posititive numbers */
79
#define FIXR(a)   ((int)((a) * FRAC_ONE + 0.5))
80
#define FRAC_RND(a) (((a) + (FRAC_ONE/2)) >> FRAC_BITS)
81

    
82
#define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
83

    
84
/****************/
85

    
86
#define HEADER_SIZE 4
87
#define BACKSTEP_SIZE 512
88
#define EXTRABYTES 24
89

    
90
struct GranuleDef;
91

    
92
typedef struct MPADecodeContext {
93
    DECLARE_ALIGNED_8(uint8_t, last_buf[BACKSTEP_SIZE + EXTRABYTES + MPA_MAX_CODED_FRAME_SIZE]); //FIXME we dont need that much
94
    int last_buf_size;
95
    int frame_size;
96
    int free_format_frame_size; /* frame size in case of free format
97
                                   (zero if currently unknown) */
98
    /* next header (used in free format parsing) */
99
    uint32_t free_format_next_header;
100
    int error_protection;
101
    int layer;
102
    int sample_rate;
103
    int sample_rate_index; /* between 0 and 8 */
104
    int bit_rate;
105
    int old_frame_size;
106
    GetBitContext gb;
107
    GetBitContext in_gb;
108
    int nb_channels;
109
    int mode;
110
    int mode_ext;
111
    int lsf;
112
    MPA_INT synth_buf[MPA_MAX_CHANNELS][512 * 2] __attribute__((aligned(16)));
113
    int synth_buf_offset[MPA_MAX_CHANNELS];
114
    int32_t sb_samples[MPA_MAX_CHANNELS][36][SBLIMIT] __attribute__((aligned(16)));
115
    int32_t mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
116
#ifdef DEBUG
117
    int frame_count;
118
#endif
119
    void (*compute_antialias)(struct MPADecodeContext *s, struct GranuleDef *g);
120
    int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
121
    unsigned int dither_state;
122
} MPADecodeContext;
123

    
124
/**
125
 * Context for MP3On4 decoder
126
 */
127
typedef struct MP3On4DecodeContext {
128
    int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
129
    int chan_cfg; ///< channel config number
130
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
131
} MP3On4DecodeContext;
132

    
133
/* layer 3 "granule" */
134
typedef struct GranuleDef {
135
    uint8_t scfsi;
136
    int part2_3_length;
137
    int big_values;
138
    int global_gain;
139
    int scalefac_compress;
140
    uint8_t block_type;
141
    uint8_t switch_point;
142
    int table_select[3];
143
    int subblock_gain[3];
144
    uint8_t scalefac_scale;
145
    uint8_t count1table_select;
146
    int region_size[3]; /* number of huffman codes in each region */
147
    int preflag;
148
    int short_start, long_end; /* long/short band indexes */
149
    uint8_t scale_factors[40];
150
    int32_t sb_hybrid[SBLIMIT * 18]; /* 576 samples */
151
} GranuleDef;
152

    
153
#define MODE_EXT_MS_STEREO 2
154
#define MODE_EXT_I_STEREO  1
155

    
156
/* layer 3 huffman tables */
157
typedef struct HuffTable {
158
    int xsize;
159
    const uint8_t *bits;
160
    const uint16_t *codes;
161
} HuffTable;
162

    
163
#include "mpegaudiodectab.h"
164

    
165
static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
166
static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
167

    
168
/* vlc structure for decoding layer 3 huffman tables */
169
static VLC huff_vlc[16];
170
static VLC huff_quad_vlc[2];
171
/* computed from band_size_long */
172
static uint16_t band_index_long[9][23];
173
/* XXX: free when all decoders are closed */
174
#define TABLE_4_3_SIZE (8191 + 16)*4
175
static int8_t  *table_4_3_exp;
176
static uint32_t *table_4_3_value;
177
static uint32_t exp_table[512];
178
static uint32_t expval_table[512][16];
179
/* intensity stereo coef table */
180
static int32_t is_table[2][16];
181
static int32_t is_table_lsf[2][2][16];
182
static int32_t csa_table[8][4];
183
static float csa_table_float[8][4];
184
static int32_t mdct_win[8][36];
185

    
186
/* lower 2 bits: modulo 3, higher bits: shift */
187
static uint16_t scale_factor_modshift[64];
188
/* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
189
static int32_t scale_factor_mult[15][3];
190
/* mult table for layer 2 group quantization */
191

    
192
#define SCALE_GEN(v) \
193
{ FIXR(1.0 * (v)), FIXR(0.7937005259 * (v)), FIXR(0.6299605249 * (v)) }
194

    
195
static const int32_t scale_factor_mult2[3][3] = {
196
    SCALE_GEN(4.0 / 3.0), /* 3 steps */
197
    SCALE_GEN(4.0 / 5.0), /* 5 steps */
198
    SCALE_GEN(4.0 / 9.0), /* 9 steps */
199
};
200

    
201
void ff_mpa_synth_init(MPA_INT *window);
202
static MPA_INT window[512] __attribute__((aligned(16)));
203

    
204
/* layer 1 unscaling */
205
/* n = number of bits of the mantissa minus 1 */
206
static inline int l1_unscale(int n, int mant, int scale_factor)
207
{
208
    int shift, mod;
209
    int64_t val;
210

    
211
    shift = scale_factor_modshift[scale_factor];
212
    mod = shift & 3;
213
    shift >>= 2;
214
    val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
215
    shift += n;
216
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
217
    return (int)((val + (1LL << (shift - 1))) >> shift);
218
}
219

    
220
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
221
{
222
    int shift, mod, val;
223

    
224
    shift = scale_factor_modshift[scale_factor];
225
    mod = shift & 3;
226
    shift >>= 2;
227

    
228
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
229
    /* NOTE: at this point, 0 <= shift <= 21 */
230
    if (shift > 0)
231
        val = (val + (1 << (shift - 1))) >> shift;
232
    return val;
233
}
234

    
235
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
236
static inline int l3_unscale(int value, int exponent)
237
{
238
    unsigned int m;
239
    int e;
240

    
241
    e = table_4_3_exp  [4*value + (exponent&3)];
242
    m = table_4_3_value[4*value + (exponent&3)];
243
    e -= (exponent >> 2);
244
    assert(e>=1);
245
    if (e > 31)
246
        return 0;
247
    m = (m + (1 << (e-1))) >> e;
248

    
249
    return m;
250
}
251

    
252
/* all integer n^(4/3) computation code */
253
#define DEV_ORDER 13
254

    
255
#define POW_FRAC_BITS 24
256
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
257
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
258
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
259

    
260
static int dev_4_3_coefs[DEV_ORDER];
261

    
262
#if 0 /* unused */
263
static int pow_mult3[3] = {
264
    POW_FIX(1.0),
265
    POW_FIX(1.25992104989487316476),
266
    POW_FIX(1.58740105196819947474),
267
};
268
#endif
269

    
270
static void int_pow_init(void)
271
{
272
    int i, a;
273

    
274
    a = POW_FIX(1.0);
275
    for(i=0;i<DEV_ORDER;i++) {
276
        a = POW_MULL(a, POW_FIX(4.0 / 3.0) - i * POW_FIX(1.0)) / (i + 1);
277
        dev_4_3_coefs[i] = a;
278
    }
279
}
280

    
281
#if 0 /* unused, remove? */
282
/* return the mantissa and the binary exponent */
283
static int int_pow(int i, int *exp_ptr)
284
{
285
    int e, er, eq, j;
286
    int a, a1;
287

288
    /* renormalize */
289
    a = i;
290
    e = POW_FRAC_BITS;
291
    while (a < (1 << (POW_FRAC_BITS - 1))) {
292
        a = a << 1;
293
        e--;
294
    }
295
    a -= (1 << POW_FRAC_BITS);
296
    a1 = 0;
297
    for(j = DEV_ORDER - 1; j >= 0; j--)
298
        a1 = POW_MULL(a, dev_4_3_coefs[j] + a1);
299
    a = (1 << POW_FRAC_BITS) + a1;
300
    /* exponent compute (exact) */
301
    e = e * 4;
302
    er = e % 3;
303
    eq = e / 3;
304
    a = POW_MULL(a, pow_mult3[er]);
305
    while (a >= 2 * POW_FRAC_ONE) {
306
        a = a >> 1;
307
        eq++;
308
    }
309
    /* convert to float */
310
    while (a < POW_FRAC_ONE) {
311
        a = a << 1;
312
        eq--;
313
    }
314
    /* now POW_FRAC_ONE <= a < 2 * POW_FRAC_ONE */
315
#if POW_FRAC_BITS > FRAC_BITS
316
    a = (a + (1 << (POW_FRAC_BITS - FRAC_BITS - 1))) >> (POW_FRAC_BITS - FRAC_BITS);
317
    /* correct overflow */
318
    if (a >= 2 * (1 << FRAC_BITS)) {
319
        a = a >> 1;
320
        eq++;
321
    }
322
#endif
323
    *exp_ptr = eq;
324
    return a;
325
}
326
#endif
327

    
328
static int decode_init(AVCodecContext * avctx)
329
{
330
    MPADecodeContext *s = avctx->priv_data;
331
    static int init=0;
332
    int i, j, k;
333

    
334
#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
335
    avctx->sample_fmt= SAMPLE_FMT_S32;
336
#else
337
    avctx->sample_fmt= SAMPLE_FMT_S16;
338
#endif
339

    
340
    if(avctx->antialias_algo != FF_AA_FLOAT)
341
        s->compute_antialias= compute_antialias_integer;
342
    else
343
        s->compute_antialias= compute_antialias_float;
344

    
345
    if (!init && !avctx->parse_only) {
346
        /* scale factors table for layer 1/2 */
347
        for(i=0;i<64;i++) {
348
            int shift, mod;
349
            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
350
            shift = (i / 3);
351
            mod = i % 3;
352
            scale_factor_modshift[i] = mod | (shift << 2);
353
        }
354

    
355
        /* scale factor multiply for layer 1 */
356
        for(i=0;i<15;i++) {
357
            int n, norm;
358
            n = i + 2;
359
            norm = ((int64_t_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
360
            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm);
361
            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm);
362
            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm);
363
            dprintf("%d: norm=%x s=%x %x %x\n",
364
                    i, norm,
365
                    scale_factor_mult[i][0],
366
                    scale_factor_mult[i][1],
367
                    scale_factor_mult[i][2]);
368
        }
369

    
370
        ff_mpa_synth_init(window);
371

    
372
        /* huffman decode tables */
373
        for(i=1;i<16;i++) {
374
            const HuffTable *h = &mpa_huff_tables[i];
375
            int xsize, x, y;
376
            unsigned int n;
377
            uint8_t  tmp_bits [512];
378
            uint16_t tmp_codes[512];
379

    
380
            memset(tmp_bits , 0, sizeof(tmp_bits ));
381
            memset(tmp_codes, 0, sizeof(tmp_codes));
382

    
383
            xsize = h->xsize;
384
            n = xsize * xsize;
385

    
386
            j = 0;
387
            for(x=0;x<xsize;x++) {
388
                for(y=0;y<xsize;y++){
389
                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
390
                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
391
                }
392
            }
393

    
394
            /* XXX: fail test */
395
            init_vlc(&huff_vlc[i], 7, 512,
396
                     tmp_bits, 1, 1, tmp_codes, 2, 2, 1);
397
        }
398
        for(i=0;i<2;i++) {
399
            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
400
                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);
401
        }
402

    
403
        for(i=0;i<9;i++) {
404
            k = 0;
405
            for(j=0;j<22;j++) {
406
                band_index_long[i][j] = k;
407
                k += band_size_long[i][j];
408
            }
409
            band_index_long[i][22] = k;
410
        }
411

    
412
        /* compute n ^ (4/3) and store it in mantissa/exp format */
413
        table_4_3_exp= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_exp[0]));
414
        if(!table_4_3_exp)
415
            return -1;
416
        table_4_3_value= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_value[0]));
417
        if(!table_4_3_value)
418
            return -1;
419

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

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

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

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

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

    
473
        for(i=0;i<8;i++) {
474
            float ci, cs, ca;
475
            ci = ci_table[i];
476
            cs = 1.0 / sqrt(1.0 + ci * ci);
477
            ca = cs * ci;
478
            csa_table[i][0] = FIXHR(cs/4);
479
            csa_table[i][1] = FIXHR(ca/4);
480
            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
481
            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
482
            csa_table_float[i][0] = cs;
483
            csa_table_float[i][1] = ca;
484
            csa_table_float[i][2] = ca + cs;
485
            csa_table_float[i][3] = ca - cs;
486
//            printf("%d %d %d %d\n", FIX(cs), FIX(cs-1), FIX(ca), FIX(cs)-FIX(ca));
487
//            av_log(NULL, AV_LOG_DEBUG,"%f %f %f %f\n", cs, ca, ca+cs, ca-cs);
488
        }
489

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

    
495
                if(j==2 && i%3 != 1)
496
                    continue;
497

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

    
511
                if(j==2)
512
                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));
513
                else
514
                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));
515
//                av_log(NULL, AV_LOG_DEBUG, "%2d %d %f\n", i,j,d / (1<<5));
516
            }
517
        }
518

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

    
528
#if defined(DEBUG)
529
        for(j=0;j<8;j++) {
530
            av_log(avctx, AV_LOG_DEBUG, "win%d=\n", j);
531
            for(i=0;i<36;i++)
532
                av_log(avctx, AV_LOG_DEBUG, "%f, ", (double)mdct_win[j][i] / FRAC_ONE);
533
            av_log(avctx, AV_LOG_DEBUG, "\n");
534
        }
535
#endif
536
        init = 1;
537
    }
538

    
539
#ifdef DEBUG
540
    s->frame_count = 0;
541
#endif
542
    if (avctx->codec_id == CODEC_ID_MP3ADU)
543
        s->adu_mode = 1;
544
    return 0;
545
}
546

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

    
549
/* cos(i*pi/64) */
550

    
551
#define COS0_0  FIXHR(0.50060299823519630134/2)
552
#define COS0_1  FIXHR(0.50547095989754365998/2)
553
#define COS0_2  FIXHR(0.51544730992262454697/2)
554
#define COS0_3  FIXHR(0.53104259108978417447/2)
555
#define COS0_4  FIXHR(0.55310389603444452782/2)
556
#define COS0_5  FIXHR(0.58293496820613387367/2)
557
#define COS0_6  FIXHR(0.62250412303566481615/2)
558
#define COS0_7  FIXHR(0.67480834145500574602/2)
559
#define COS0_8  FIXHR(0.74453627100229844977/2)
560
#define COS0_9  FIXHR(0.83934964541552703873/2)
561
#define COS0_10 FIXHR(0.97256823786196069369/2)
562
#define COS0_11 FIXHR(1.16943993343288495515/4)
563
#define COS0_12 FIXHR(1.48416461631416627724/4)
564
#define COS0_13 FIXHR(2.05778100995341155085/8)
565
#define COS0_14 FIXHR(3.40760841846871878570/8)
566
#define COS0_15 FIXHR(10.19000812354805681150/32)
567

    
568
#define COS1_0 FIXHR(0.50241928618815570551/2)
569
#define COS1_1 FIXHR(0.52249861493968888062/2)
570
#define COS1_2 FIXHR(0.56694403481635770368/2)
571
#define COS1_3 FIXHR(0.64682178335999012954/2)
572
#define COS1_4 FIXHR(0.78815462345125022473/2)
573
#define COS1_5 FIXHR(1.06067768599034747134/4)
574
#define COS1_6 FIXHR(1.72244709823833392782/4)
575
#define COS1_7 FIXHR(5.10114861868916385802/16)
576

    
577
#define COS2_0 FIXHR(0.50979557910415916894/2)
578
#define COS2_1 FIXHR(0.60134488693504528054/2)
579
#define COS2_2 FIXHR(0.89997622313641570463/2)
580
#define COS2_3 FIXHR(2.56291544774150617881/8)
581

    
582
#define COS3_0 FIXHR(0.54119610014619698439/2)
583
#define COS3_1 FIXHR(1.30656296487637652785/4)
584

    
585
#define COS4_0 FIXHR(0.70710678118654752439/2)
586

    
587
/* butterfly operator */
588
#define BF(a, b, c, s)\
589
{\
590
    tmp0 = tab[a] + tab[b];\
591
    tmp1 = tab[a] - tab[b];\
592
    tab[a] = tmp0;\
593
    tab[b] = MULH(tmp1<<(s), c);\
594
}
595

    
596
#define BF1(a, b, c, d)\
597
{\
598
    BF(a, b, COS4_0, 1);\
599
    BF(c, d,-COS4_0, 1);\
600
    tab[c] += tab[d];\
601
}
602

    
603
#define BF2(a, b, c, d)\
604
{\
605
    BF(a, b, COS4_0, 1);\
606
    BF(c, d,-COS4_0, 1);\
607
    tab[c] += tab[d];\
608
    tab[a] += tab[c];\
609
    tab[c] += tab[b];\
610
    tab[b] += tab[d];\
611
}
612

    
613
#define ADD(a, b) tab[a] += tab[b]
614

    
615
/* DCT32 without 1/sqrt(2) coef zero scaling. */
616
static void dct32(int32_t *out, int32_t *tab)
617
{
618
    int tmp0, tmp1;
619

    
620
    /* pass 1 */
621
    BF( 0, 31, COS0_0 , 1);
622
    BF(15, 16, COS0_15, 5);
623
    /* pass 2 */
624
    BF( 0, 15, COS1_0 , 1);
625
    BF(16, 31,-COS1_0 , 1);
626
    /* pass 1 */
627
    BF( 7, 24, COS0_7 , 1);
628
    BF( 8, 23, COS0_8 , 1);
629
    /* pass 2 */
630
    BF( 7,  8, COS1_7 , 4);
631
    BF(23, 24,-COS1_7 , 4);
632
    /* pass 3 */
633
    BF( 0,  7, COS2_0 , 1);
634
    BF( 8, 15,-COS2_0 , 1);
635
    BF(16, 23, COS2_0 , 1);
636
    BF(24, 31,-COS2_0 , 1);
637
    /* pass 1 */
638
    BF( 3, 28, COS0_3 , 1);
639
    BF(12, 19, COS0_12, 2);
640
    /* pass 2 */
641
    BF( 3, 12, COS1_3 , 1);
642
    BF(19, 28,-COS1_3 , 1);
643
    /* pass 1 */
644
    BF( 4, 27, COS0_4 , 1);
645
    BF(11, 20, COS0_11, 2);
646
    /* pass 2 */
647
    BF( 4, 11, COS1_4 , 1);
648
    BF(20, 27,-COS1_4 , 1);
649
    /* pass 3 */
650
    BF( 3,  4, COS2_3 , 3);
651
    BF(11, 12,-COS2_3 , 3);
652
    BF(19, 20, COS2_3 , 3);
653
    BF(27, 28,-COS2_3 , 3);
654
    /* pass 4 */
655
    BF( 0,  3, COS3_0 , 1);
656
    BF( 4,  7,-COS3_0 , 1);
657
    BF( 8, 11, COS3_0 , 1);
658
    BF(12, 15,-COS3_0 , 1);
659
    BF(16, 19, COS3_0 , 1);
660
    BF(20, 23,-COS3_0 , 1);
661
    BF(24, 27, COS3_0 , 1);
662
    BF(28, 31,-COS3_0 , 1);
663

    
664

    
665

    
666
    /* pass 1 */
667
    BF( 1, 30, COS0_1 , 1);
668
    BF(14, 17, COS0_14, 3);
669
    /* pass 2 */
670
    BF( 1, 14, COS1_1 , 1);
671
    BF(17, 30,-COS1_1 , 1);
672
    /* pass 1 */
673
    BF( 6, 25, COS0_6 , 1);
674
    BF( 9, 22, COS0_9 , 1);
675
    /* pass 2 */
676
    BF( 6,  9, COS1_6 , 2);
677
    BF(22, 25,-COS1_6 , 2);
678
    /* pass 3 */
679
    BF( 1,  6, COS2_1 , 1);
680
    BF( 9, 14,-COS2_1 , 1);
681
    BF(17, 22, COS2_1 , 1);
682
    BF(25, 30,-COS2_1 , 1);
683

    
684
    /* pass 1 */
685
    BF( 2, 29, COS0_2 , 1);
686
    BF(13, 18, COS0_13, 3);
687
    /* pass 2 */
688
    BF( 2, 13, COS1_2 , 1);
689
    BF(18, 29,-COS1_2 , 1);
690
    /* pass 1 */
691
    BF( 5, 26, COS0_5 , 1);
692
    BF(10, 21, COS0_10, 1);
693
    /* pass 2 */
694
    BF( 5, 10, COS1_5 , 2);
695
    BF(21, 26,-COS1_5 , 2);
696
    /* pass 3 */
697
    BF( 2,  5, COS2_2 , 1);
698
    BF(10, 13,-COS2_2 , 1);
699
    BF(18, 21, COS2_2 , 1);
700
    BF(26, 29,-COS2_2 , 1);
701
    /* pass 4 */
702
    BF( 1,  2, COS3_1 , 2);
703
    BF( 5,  6,-COS3_1 , 2);
704
    BF( 9, 10, COS3_1 , 2);
705
    BF(13, 14,-COS3_1 , 2);
706
    BF(17, 18, COS3_1 , 2);
707
    BF(21, 22,-COS3_1 , 2);
708
    BF(25, 26, COS3_1 , 2);
709
    BF(29, 30,-COS3_1 , 2);
710

    
711
    /* pass 5 */
712
    BF1( 0,  1,  2,  3);
713
    BF2( 4,  5,  6,  7);
714
    BF1( 8,  9, 10, 11);
715
    BF2(12, 13, 14, 15);
716
    BF1(16, 17, 18, 19);
717
    BF2(20, 21, 22, 23);
718
    BF1(24, 25, 26, 27);
719
    BF2(28, 29, 30, 31);
720

    
721
    /* pass 6 */
722

    
723
    ADD( 8, 12);
724
    ADD(12, 10);
725
    ADD(10, 14);
726
    ADD(14,  9);
727
    ADD( 9, 13);
728
    ADD(13, 11);
729
    ADD(11, 15);
730

    
731
    out[ 0] = tab[0];
732
    out[16] = tab[1];
733
    out[ 8] = tab[2];
734
    out[24] = tab[3];
735
    out[ 4] = tab[4];
736
    out[20] = tab[5];
737
    out[12] = tab[6];
738
    out[28] = tab[7];
739
    out[ 2] = tab[8];
740
    out[18] = tab[9];
741
    out[10] = tab[10];
742
    out[26] = tab[11];
743
    out[ 6] = tab[12];
744
    out[22] = tab[13];
745
    out[14] = tab[14];
746
    out[30] = tab[15];
747

    
748
    ADD(24, 28);
749
    ADD(28, 26);
750
    ADD(26, 30);
751
    ADD(30, 25);
752
    ADD(25, 29);
753
    ADD(29, 27);
754
    ADD(27, 31);
755

    
756
    out[ 1] = tab[16] + tab[24];
757
    out[17] = tab[17] + tab[25];
758
    out[ 9] = tab[18] + tab[26];
759
    out[25] = tab[19] + tab[27];
760
    out[ 5] = tab[20] + tab[28];
761
    out[21] = tab[21] + tab[29];
762
    out[13] = tab[22] + tab[30];
763
    out[29] = tab[23] + tab[31];
764
    out[ 3] = tab[24] + tab[20];
765
    out[19] = tab[25] + tab[21];
766
    out[11] = tab[26] + tab[22];
767
    out[27] = tab[27] + tab[23];
768
    out[ 7] = tab[28] + tab[18];
769
    out[23] = tab[29] + tab[19];
770
    out[15] = tab[30] + tab[17];
771
    out[31] = tab[31];
772
}
773

    
774
#if FRAC_BITS <= 15
775

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

    
788
#   if defined(ARCH_POWERPC_405)
789
        /* signed 16x16 -> 32 multiply add accumulate */
790
#       define MACS(rt, ra, rb) \
791
            asm ("maclhw %0, %2, %3" : "=r" (rt) : "0" (rt), "r" (ra), "r" (rb));
792

    
793
        /* signed 16x16 -> 32 multiply */
794
#       define MULS(ra, rb) \
795
            ({ int __rt; asm ("mullhw %0, %1, %2" : "=r" (__rt) : "r" (ra), "r" (rb)); __rt; })
796
#   else
797
        /* signed 16x16 -> 32 multiply add accumulate */
798
#       define MACS(rt, ra, rb) rt += (ra) * (rb)
799

    
800
        /* signed 16x16 -> 32 multiply */
801
#       define MULS(ra, rb) ((ra) * (rb))
802
#   endif
803
#else
804

    
805
static inline int round_sample(int64_t *sum)
806
{
807
    int sum1;
808
    sum1 = (int)((*sum) >> OUT_SHIFT);
809
    *sum &= (1<<OUT_SHIFT)-1;
810
    if (sum1 < OUT_MIN)
811
        sum1 = OUT_MIN;
812
    else if (sum1 > OUT_MAX)
813
        sum1 = OUT_MAX;
814
    return sum1;
815
}
816

    
817
#   define MULS(ra, rb) MUL64(ra, rb)
818
#endif
819

    
820
#define SUM8(sum, op, w, p) \
821
{                                               \
822
    sum op MULS((w)[0 * 64], p[0 * 64]);\
823
    sum op MULS((w)[1 * 64], p[1 * 64]);\
824
    sum op MULS((w)[2 * 64], p[2 * 64]);\
825
    sum op MULS((w)[3 * 64], p[3 * 64]);\
826
    sum op MULS((w)[4 * 64], p[4 * 64]);\
827
    sum op MULS((w)[5 * 64], p[5 * 64]);\
828
    sum op MULS((w)[6 * 64], p[6 * 64]);\
829
    sum op MULS((w)[7 * 64], p[7 * 64]);\
830
}
831

    
832
#define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
833
{                                               \
834
    int tmp;\
835
    tmp = p[0 * 64];\
836
    sum1 op1 MULS((w1)[0 * 64], tmp);\
837
    sum2 op2 MULS((w2)[0 * 64], tmp);\
838
    tmp = p[1 * 64];\
839
    sum1 op1 MULS((w1)[1 * 64], tmp);\
840
    sum2 op2 MULS((w2)[1 * 64], tmp);\
841
    tmp = p[2 * 64];\
842
    sum1 op1 MULS((w1)[2 * 64], tmp);\
843
    sum2 op2 MULS((w2)[2 * 64], tmp);\
844
    tmp = p[3 * 64];\
845
    sum1 op1 MULS((w1)[3 * 64], tmp);\
846
    sum2 op2 MULS((w2)[3 * 64], tmp);\
847
    tmp = p[4 * 64];\
848
    sum1 op1 MULS((w1)[4 * 64], tmp);\
849
    sum2 op2 MULS((w2)[4 * 64], tmp);\
850
    tmp = p[5 * 64];\
851
    sum1 op1 MULS((w1)[5 * 64], tmp);\
852
    sum2 op2 MULS((w2)[5 * 64], tmp);\
853
    tmp = p[6 * 64];\
854
    sum1 op1 MULS((w1)[6 * 64], tmp);\
855
    sum2 op2 MULS((w2)[6 * 64], tmp);\
856
    tmp = p[7 * 64];\
857
    sum1 op1 MULS((w1)[7 * 64], tmp);\
858
    sum2 op2 MULS((w2)[7 * 64], tmp);\
859
}
860

    
861
void ff_mpa_synth_init(MPA_INT *window)
862
{
863
    int i;
864

    
865
    /* max = 18760, max sum over all 16 coefs : 44736 */
866
    for(i=0;i<257;i++) {
867
        int v;
868
        v = mpa_enwindow[i];
869
#if WFRAC_BITS < 16
870
        v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
871
#endif
872
        window[i] = v;
873
        if ((i & 63) != 0)
874
            v = -v;
875
        if (i != 0)
876
            window[512 - i] = v;
877
    }
878
}
879

    
880
/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
881
   32 samples. */
882
/* XXX: optimize by avoiding ring buffer usage */
883
void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
884
                         MPA_INT *window, int *dither_state,
885
                         OUT_INT *samples, int incr,
886
                         int32_t sb_samples[SBLIMIT])
887
{
888
    int32_t tmp[32];
889
    register MPA_INT *synth_buf;
890
    register const MPA_INT *w, *w2, *p;
891
    int j, offset, v;
892
    OUT_INT *samples2;
893
#if FRAC_BITS <= 15
894
    int sum, sum2;
895
#else
896
    int64_t sum, sum2;
897
#endif
898

    
899
    dct32(tmp, sb_samples);
900

    
901
    offset = *synth_buf_offset;
902
    synth_buf = synth_buf_ptr + offset;
903

    
904
    for(j=0;j<32;j++) {
905
        v = tmp[j];
906
#if FRAC_BITS <= 15
907
        /* NOTE: can cause a loss in precision if very high amplitude
908
           sound */
909
        if (v > 32767)
910
            v = 32767;
911
        else if (v < -32768)
912
            v = -32768;
913
#endif
914
        synth_buf[j] = v;
915
    }
916
    /* copy to avoid wrap */
917
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
918

    
919
    samples2 = samples + 31 * incr;
920
    w = window;
921
    w2 = window + 31;
922

    
923
    sum = *dither_state;
924
    p = synth_buf + 16;
925
    SUM8(sum, +=, w, p);
926
    p = synth_buf + 48;
927
    SUM8(sum, -=, w + 32, p);
928
    *samples = round_sample(&sum);
929
    samples += incr;
930
    w++;
931

    
932
    /* we calculate two samples at the same time to avoid one memory
933
       access per two sample */
934
    for(j=1;j<16;j++) {
935
        sum2 = 0;
936
        p = synth_buf + 16 + j;
937
        SUM8P2(sum, +=, sum2, -=, w, w2, p);
938
        p = synth_buf + 48 - j;
939
        SUM8P2(sum, -=, sum2, -=, w + 32, w2 + 32, p);
940

    
941
        *samples = round_sample(&sum);
942
        samples += incr;
943
        sum += sum2;
944
        *samples2 = round_sample(&sum);
945
        samples2 -= incr;
946
        w++;
947
        w2--;
948
    }
949

    
950
    p = synth_buf + 32;
951
    SUM8(sum, -=, w + 32, p);
952
    *samples = round_sample(&sum);
953
    *dither_state= sum;
954

    
955
    offset = (offset - 32) & 511;
956
    *synth_buf_offset = offset;
957
}
958

    
959
#define C3 FIXHR(0.86602540378443864676/2)
960

    
961
/* 0.5 / cos(pi*(2*i+1)/36) */
962
static const int icos36[9] = {
963
    FIXR(0.50190991877167369479),
964
    FIXR(0.51763809020504152469), //0
965
    FIXR(0.55168895948124587824),
966
    FIXR(0.61038729438072803416),
967
    FIXR(0.70710678118654752439), //1
968
    FIXR(0.87172339781054900991),
969
    FIXR(1.18310079157624925896),
970
    FIXR(1.93185165257813657349), //2
971
    FIXR(5.73685662283492756461),
972
};
973

    
974
/* 0.5 / cos(pi*(2*i+1)/36) */
975
static const int icos36h[9] = {
976
    FIXHR(0.50190991877167369479/2),
977
    FIXHR(0.51763809020504152469/2), //0
978
    FIXHR(0.55168895948124587824/2),
979
    FIXHR(0.61038729438072803416/2),
980
    FIXHR(0.70710678118654752439/2), //1
981
    FIXHR(0.87172339781054900991/2),
982
    FIXHR(1.18310079157624925896/4),
983
    FIXHR(1.93185165257813657349/4), //2
984
//    FIXHR(5.73685662283492756461),
985
};
986

    
987
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
988
   cases. */
989
static void imdct12(int *out, int *in)
990
{
991
    int in0, in1, in2, in3, in4, in5, t1, t2;
992

    
993
    in0= in[0*3];
994
    in1= in[1*3] + in[0*3];
995
    in2= in[2*3] + in[1*3];
996
    in3= in[3*3] + in[2*3];
997
    in4= in[4*3] + in[3*3];
998
    in5= in[5*3] + in[4*3];
999
    in5 += in3;
1000
    in3 += in1;
1001

    
1002
    in2= MULH(2*in2, C3);
1003
    in3= MULH(4*in3, C3);
1004

    
1005
    t1 = in0 - in4;
1006
    t2 = MULH(2*(in1 - in5), icos36h[4]);
1007

    
1008
    out[ 7]=
1009
    out[10]= t1 + t2;
1010
    out[ 1]=
1011
    out[ 4]= t1 - t2;
1012

    
1013
    in0 += in4>>1;
1014
    in4 = in0 + in2;
1015
    in5 += 2*in1;
1016
    in1 = MULH(in5 + in3, icos36h[1]);
1017
    out[ 8]=
1018
    out[ 9]= in4 + in1;
1019
    out[ 2]=
1020
    out[ 3]= in4 - in1;
1021

    
1022
    in0 -= in2;
1023
    in5 = MULH(2*(in5 - in3), icos36h[7]);
1024
    out[ 0]=
1025
    out[ 5]= in0 - in5;
1026
    out[ 6]=
1027
    out[11]= in0 + in5;
1028
}
1029

    
1030
/* cos(pi*i/18) */
1031
#define C1 FIXHR(0.98480775301220805936/2)
1032
#define C2 FIXHR(0.93969262078590838405/2)
1033
#define C3 FIXHR(0.86602540378443864676/2)
1034
#define C4 FIXHR(0.76604444311897803520/2)
1035
#define C5 FIXHR(0.64278760968653932632/2)
1036
#define C6 FIXHR(0.5/2)
1037
#define C7 FIXHR(0.34202014332566873304/2)
1038
#define C8 FIXHR(0.17364817766693034885/2)
1039

    
1040

    
1041
/* using Lee like decomposition followed by hand coded 9 points DCT */
1042
static void imdct36(int *out, int *buf, int *in, int *win)
1043
{
1044
    int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
1045
    int tmp[18], *tmp1, *in1;
1046

    
1047
    for(i=17;i>=1;i--)
1048
        in[i] += in[i-1];
1049
    for(i=17;i>=3;i-=2)
1050
        in[i] += in[i-2];
1051

    
1052
    for(j=0;j<2;j++) {
1053
        tmp1 = tmp + j;
1054
        in1 = in + j;
1055
#if 0
1056
//more accurate but slower
1057
        int64_t t0, t1, t2, t3;
1058
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1059

1060
        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
1061
        t1 = in1[2*0] - in1[2*6];
1062
        tmp1[ 6] = t1 - (t2>>1);
1063
        tmp1[16] = t1 + t2;
1064

1065
        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
1066
        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
1067
        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
1068

1069
        tmp1[10] = (t3 - t0 - t2) >> 32;
1070
        tmp1[ 2] = (t3 + t0 + t1) >> 32;
1071
        tmp1[14] = (t3 + t2 - t1) >> 32;
1072

1073
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1074
        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
1075
        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
1076
        t0 = MUL64(2*in1[2*3], C3);
1077

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

1080
        tmp1[ 0] = (t2 + t3 + t0) >> 32;
1081
        tmp1[12] = (t2 + t1 - t0) >> 32;
1082
        tmp1[ 8] = (t3 - t1 - t0) >> 32;
1083
#else
1084
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1085

    
1086
        t3 = in1[2*0] + (in1[2*6]>>1);
1087
        t1 = in1[2*0] - in1[2*6];
1088
        tmp1[ 6] = t1 - (t2>>1);
1089
        tmp1[16] = t1 + t2;
1090

    
1091
        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1092
        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1093
        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1094

    
1095
        tmp1[10] = t3 - t0 - t2;
1096
        tmp1[ 2] = t3 + t0 + t1;
1097
        tmp1[14] = t3 + t2 - t1;
1098

    
1099
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1100
        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1101
        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1102
        t0 = MULH(2*in1[2*3], C3);
1103

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

    
1106
        tmp1[ 0] = t2 + t3 + t0;
1107
        tmp1[12] = t2 + t1 - t0;
1108
        tmp1[ 8] = t3 - t1 - t0;
1109
#endif
1110
    }
1111

    
1112
    i = 0;
1113
    for(j=0;j<4;j++) {
1114
        t0 = tmp[i];
1115
        t1 = tmp[i + 2];
1116
        s0 = t1 + t0;
1117
        s2 = t1 - t0;
1118

    
1119
        t2 = tmp[i + 1];
1120
        t3 = tmp[i + 3];
1121
        s1 = MULH(2*(t3 + t2), icos36h[j]);
1122
        s3 = MULL(t3 - t2, icos36[8 - j]);
1123

    
1124
        t0 = s0 + s1;
1125
        t1 = s0 - s1;
1126
        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1127
        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1128
        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1129
        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1130

    
1131
        t0 = s2 + s3;
1132
        t1 = s2 - s3;
1133
        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1134
        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1135
        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1136
        buf[      + j] = MULH(t0, win[18         + j]);
1137
        i += 4;
1138
    }
1139

    
1140
    s0 = tmp[16];
1141
    s1 = MULH(2*tmp[17], icos36h[4]);
1142
    t0 = s0 + s1;
1143
    t1 = s0 - s1;
1144
    out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
1145
    out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
1146
    buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
1147
    buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
1148
}
1149

    
1150
/* header decoding. MUST check the header before because no
1151
   consistency check is done there. Return 1 if free format found and
1152
   that the frame size must be computed externally */
1153
static int decode_header(MPADecodeContext *s, uint32_t header)
1154
{
1155
    int sample_rate, frame_size, mpeg25, padding;
1156
    int sample_rate_index, bitrate_index;
1157
    if (header & (1<<20)) {
1158
        s->lsf = (header & (1<<19)) ? 0 : 1;
1159
        mpeg25 = 0;
1160
    } else {
1161
        s->lsf = 1;
1162
        mpeg25 = 1;
1163
    }
1164

    
1165
    s->layer = 4 - ((header >> 17) & 3);
1166
    /* extract frequency */
1167
    sample_rate_index = (header >> 10) & 3;
1168
    sample_rate = mpa_freq_tab[sample_rate_index] >> (s->lsf + mpeg25);
1169
    sample_rate_index += 3 * (s->lsf + mpeg25);
1170
    s->sample_rate_index = sample_rate_index;
1171
    s->error_protection = ((header >> 16) & 1) ^ 1;
1172
    s->sample_rate = sample_rate;
1173

    
1174
    bitrate_index = (header >> 12) & 0xf;
1175
    padding = (header >> 9) & 1;
1176
    //extension = (header >> 8) & 1;
1177
    s->mode = (header >> 6) & 3;
1178
    s->mode_ext = (header >> 4) & 3;
1179
    //copyright = (header >> 3) & 1;
1180
    //original = (header >> 2) & 1;
1181
    //emphasis = header & 3;
1182

    
1183
    if (s->mode == MPA_MONO)
1184
        s->nb_channels = 1;
1185
    else
1186
        s->nb_channels = 2;
1187

    
1188
    if (bitrate_index != 0) {
1189
        frame_size = mpa_bitrate_tab[s->lsf][s->layer - 1][bitrate_index];
1190
        s->bit_rate = frame_size * 1000;
1191
        switch(s->layer) {
1192
        case 1:
1193
            frame_size = (frame_size * 12000) / sample_rate;
1194
            frame_size = (frame_size + padding) * 4;
1195
            break;
1196
        case 2:
1197
            frame_size = (frame_size * 144000) / sample_rate;
1198
            frame_size += padding;
1199
            break;
1200
        default:
1201
        case 3:
1202
            frame_size = (frame_size * 144000) / (sample_rate << s->lsf);
1203
            frame_size += padding;
1204
            break;
1205
        }
1206
        s->frame_size = frame_size;
1207
    } else {
1208
        /* if no frame size computed, signal it */
1209
        if (!s->free_format_frame_size)
1210
            return 1;
1211
        /* free format: compute bitrate and real frame size from the
1212
           frame size we extracted by reading the bitstream */
1213
        s->frame_size = s->free_format_frame_size;
1214
        switch(s->layer) {
1215
        case 1:
1216
            s->frame_size += padding  * 4;
1217
            s->bit_rate = (s->frame_size * sample_rate) / 48000;
1218
            break;
1219
        case 2:
1220
            s->frame_size += padding;
1221
            s->bit_rate = (s->frame_size * sample_rate) / 144000;
1222
            break;
1223
        default:
1224
        case 3:
1225
            s->frame_size += padding;
1226
            s->bit_rate = (s->frame_size * (sample_rate << s->lsf)) / 144000;
1227
            break;
1228
        }
1229
    }
1230

    
1231
#if defined(DEBUG)
1232
    dprintf("layer%d, %d Hz, %d kbits/s, ",
1233
           s->layer, s->sample_rate, s->bit_rate);
1234
    if (s->nb_channels == 2) {
1235
        if (s->layer == 3) {
1236
            if (s->mode_ext & MODE_EXT_MS_STEREO)
1237
                dprintf("ms-");
1238
            if (s->mode_ext & MODE_EXT_I_STEREO)
1239
                dprintf("i-");
1240
        }
1241
        dprintf("stereo");
1242
    } else {
1243
        dprintf("mono");
1244
    }
1245
    dprintf("\n");
1246
#endif
1247
    return 0;
1248
}
1249

    
1250
/* useful helper to get mpeg audio stream infos. Return -1 if error in
1251
   header, otherwise the coded frame size in bytes */
1252
int mpa_decode_header(AVCodecContext *avctx, uint32_t head)
1253
{
1254
    MPADecodeContext s1, *s = &s1;
1255
    memset( s, 0, sizeof(MPADecodeContext) );
1256

    
1257
    if (ff_mpa_check_header(head) != 0)
1258
        return -1;
1259

    
1260
    if (decode_header(s, head) != 0) {
1261
        return -1;
1262
    }
1263

    
1264
    switch(s->layer) {
1265
    case 1:
1266
        avctx->frame_size = 384;
1267
        break;
1268
    case 2:
1269
        avctx->frame_size = 1152;
1270
        break;
1271
    default:
1272
    case 3:
1273
        if (s->lsf)
1274
            avctx->frame_size = 576;
1275
        else
1276
            avctx->frame_size = 1152;
1277
        break;
1278
    }
1279

    
1280
    avctx->sample_rate = s->sample_rate;
1281
    avctx->channels = s->nb_channels;
1282
    avctx->bit_rate = s->bit_rate;
1283
    avctx->sub_id = s->layer;
1284
    return s->frame_size;
1285
}
1286

    
1287
/* return the number of decoded frames */
1288
static int mp_decode_layer1(MPADecodeContext *s)
1289
{
1290
    int bound, i, v, n, ch, j, mant;
1291
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1292
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1293

    
1294
    if (s->mode == MPA_JSTEREO)
1295
        bound = (s->mode_ext + 1) * 4;
1296
    else
1297
        bound = SBLIMIT;
1298

    
1299
    /* allocation bits */
1300
    for(i=0;i<bound;i++) {
1301
        for(ch=0;ch<s->nb_channels;ch++) {
1302
            allocation[ch][i] = get_bits(&s->gb, 4);
1303
        }
1304
    }
1305
    for(i=bound;i<SBLIMIT;i++) {
1306
        allocation[0][i] = get_bits(&s->gb, 4);
1307
    }
1308

    
1309
    /* scale factors */
1310
    for(i=0;i<bound;i++) {
1311
        for(ch=0;ch<s->nb_channels;ch++) {
1312
            if (allocation[ch][i])
1313
                scale_factors[ch][i] = get_bits(&s->gb, 6);
1314
        }
1315
    }
1316
    for(i=bound;i<SBLIMIT;i++) {
1317
        if (allocation[0][i]) {
1318
            scale_factors[0][i] = get_bits(&s->gb, 6);
1319
            scale_factors[1][i] = get_bits(&s->gb, 6);
1320
        }
1321
    }
1322

    
1323
    /* compute samples */
1324
    for(j=0;j<12;j++) {
1325
        for(i=0;i<bound;i++) {
1326
            for(ch=0;ch<s->nb_channels;ch++) {
1327
                n = allocation[ch][i];
1328
                if (n) {
1329
                    mant = get_bits(&s->gb, n + 1);
1330
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
1331
                } else {
1332
                    v = 0;
1333
                }
1334
                s->sb_samples[ch][j][i] = v;
1335
            }
1336
        }
1337
        for(i=bound;i<SBLIMIT;i++) {
1338
            n = allocation[0][i];
1339
            if (n) {
1340
                mant = get_bits(&s->gb, n + 1);
1341
                v = l1_unscale(n, mant, scale_factors[0][i]);
1342
                s->sb_samples[0][j][i] = v;
1343
                v = l1_unscale(n, mant, scale_factors[1][i]);
1344
                s->sb_samples[1][j][i] = v;
1345
            } else {
1346
                s->sb_samples[0][j][i] = 0;
1347
                s->sb_samples[1][j][i] = 0;
1348
            }
1349
        }
1350
    }
1351
    return 12;
1352
}
1353

    
1354
/* bitrate is in kb/s */
1355
int l2_select_table(int bitrate, int nb_channels, int freq, int lsf)
1356
{
1357
    int ch_bitrate, table;
1358

    
1359
    ch_bitrate = bitrate / nb_channels;
1360
    if (!lsf) {
1361
        if ((freq == 48000 && ch_bitrate >= 56) ||
1362
            (ch_bitrate >= 56 && ch_bitrate <= 80))
1363
            table = 0;
1364
        else if (freq != 48000 && ch_bitrate >= 96)
1365
            table = 1;
1366
        else if (freq != 32000 && ch_bitrate <= 48)
1367
            table = 2;
1368
        else
1369
            table = 3;
1370
    } else {
1371
        table = 4;
1372
    }
1373
    return table;
1374
}
1375

    
1376
static int mp_decode_layer2(MPADecodeContext *s)
1377
{
1378
    int sblimit; /* number of used subbands */
1379
    const unsigned char *alloc_table;
1380
    int table, bit_alloc_bits, i, j, ch, bound, v;
1381
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1382
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1383
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1384
    int scale, qindex, bits, steps, k, l, m, b;
1385

    
1386
    /* select decoding table */
1387
    table = l2_select_table(s->bit_rate / 1000, s->nb_channels,
1388
                            s->sample_rate, s->lsf);
1389
    sblimit = sblimit_table[table];
1390
    alloc_table = alloc_tables[table];
1391

    
1392
    if (s->mode == MPA_JSTEREO)
1393
        bound = (s->mode_ext + 1) * 4;
1394
    else
1395
        bound = sblimit;
1396

    
1397
    dprintf("bound=%d sblimit=%d\n", bound, sblimit);
1398

    
1399
    /* sanity check */
1400
    if( bound > sblimit ) bound = sblimit;
1401

    
1402
    /* parse bit allocation */
1403
    j = 0;
1404
    for(i=0;i<bound;i++) {
1405
        bit_alloc_bits = alloc_table[j];
1406
        for(ch=0;ch<s->nb_channels;ch++) {
1407
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1408
        }
1409
        j += 1 << bit_alloc_bits;
1410
    }
1411
    for(i=bound;i<sblimit;i++) {
1412
        bit_alloc_bits = alloc_table[j];
1413
        v = get_bits(&s->gb, bit_alloc_bits);
1414
        bit_alloc[0][i] = v;
1415
        bit_alloc[1][i] = v;
1416
        j += 1 << bit_alloc_bits;
1417
    }
1418

    
1419
#ifdef DEBUG
1420
    {
1421
        for(ch=0;ch<s->nb_channels;ch++) {
1422
            for(i=0;i<sblimit;i++)
1423
                dprintf(" %d", bit_alloc[ch][i]);
1424
            dprintf("\n");
1425
        }
1426
    }
1427
#endif
1428

    
1429
    /* scale codes */
1430
    for(i=0;i<sblimit;i++) {
1431
        for(ch=0;ch<s->nb_channels;ch++) {
1432
            if (bit_alloc[ch][i])
1433
                scale_code[ch][i] = get_bits(&s->gb, 2);
1434
        }
1435
    }
1436

    
1437
    /* scale factors */
1438
    for(i=0;i<sblimit;i++) {
1439
        for(ch=0;ch<s->nb_channels;ch++) {
1440
            if (bit_alloc[ch][i]) {
1441
                sf = scale_factors[ch][i];
1442
                switch(scale_code[ch][i]) {
1443
                default:
1444
                case 0:
1445
                    sf[0] = get_bits(&s->gb, 6);
1446
                    sf[1] = get_bits(&s->gb, 6);
1447
                    sf[2] = get_bits(&s->gb, 6);
1448
                    break;
1449
                case 2:
1450
                    sf[0] = get_bits(&s->gb, 6);
1451
                    sf[1] = sf[0];
1452
                    sf[2] = sf[0];
1453
                    break;
1454
                case 1:
1455
                    sf[0] = get_bits(&s->gb, 6);
1456
                    sf[2] = get_bits(&s->gb, 6);
1457
                    sf[1] = sf[0];
1458
                    break;
1459
                case 3:
1460
                    sf[0] = get_bits(&s->gb, 6);
1461
                    sf[2] = get_bits(&s->gb, 6);
1462
                    sf[1] = sf[2];
1463
                    break;
1464
                }
1465
            }
1466
        }
1467
    }
1468

    
1469
#ifdef DEBUG
1470
    for(ch=0;ch<s->nb_channels;ch++) {
1471
        for(i=0;i<sblimit;i++) {
1472
            if (bit_alloc[ch][i]) {
1473
                sf = scale_factors[ch][i];
1474
                dprintf(" %d %d %d", sf[0], sf[1], sf[2]);
1475
            } else {
1476
                dprintf(" -");
1477
            }
1478
        }
1479
        dprintf("\n");
1480
    }
1481
#endif
1482

    
1483
    /* samples */
1484
    for(k=0;k<3;k++) {
1485
        for(l=0;l<12;l+=3) {
1486
            j = 0;
1487
            for(i=0;i<bound;i++) {
1488
                bit_alloc_bits = alloc_table[j];
1489
                for(ch=0;ch<s->nb_channels;ch++) {
1490
                    b = bit_alloc[ch][i];
1491
                    if (b) {
1492
                        scale = scale_factors[ch][i][k];
1493
                        qindex = alloc_table[j+b];
1494
                        bits = quant_bits[qindex];
1495
                        if (bits < 0) {
1496
                            /* 3 values at the same time */
1497
                            v = get_bits(&s->gb, -bits);
1498
                            steps = quant_steps[qindex];
1499
                            s->sb_samples[ch][k * 12 + l + 0][i] =
1500
                                l2_unscale_group(steps, v % steps, scale);
1501
                            v = v / steps;
1502
                            s->sb_samples[ch][k * 12 + l + 1][i] =
1503
                                l2_unscale_group(steps, v % steps, scale);
1504
                            v = v / steps;
1505
                            s->sb_samples[ch][k * 12 + l + 2][i] =
1506
                                l2_unscale_group(steps, v, scale);
1507
                        } else {
1508
                            for(m=0;m<3;m++) {
1509
                                v = get_bits(&s->gb, bits);
1510
                                v = l1_unscale(bits - 1, v, scale);
1511
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
1512
                            }
1513
                        }
1514
                    } else {
1515
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1516
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1517
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1518
                    }
1519
                }
1520
                /* next subband in alloc table */
1521
                j += 1 << bit_alloc_bits;
1522
            }
1523
            /* XXX: find a way to avoid this duplication of code */
1524
            for(i=bound;i<sblimit;i++) {
1525
                bit_alloc_bits = alloc_table[j];
1526
                b = bit_alloc[0][i];
1527
                if (b) {
1528
                    int mant, scale0, scale1;
1529
                    scale0 = scale_factors[0][i][k];
1530
                    scale1 = scale_factors[1][i][k];
1531
                    qindex = alloc_table[j+b];
1532
                    bits = quant_bits[qindex];
1533
                    if (bits < 0) {
1534
                        /* 3 values at the same time */
1535
                        v = get_bits(&s->gb, -bits);
1536
                        steps = quant_steps[qindex];
1537
                        mant = v % steps;
1538
                        v = v / steps;
1539
                        s->sb_samples[0][k * 12 + l + 0][i] =
1540
                            l2_unscale_group(steps, mant, scale0);
1541
                        s->sb_samples[1][k * 12 + l + 0][i] =
1542
                            l2_unscale_group(steps, mant, scale1);
1543
                        mant = v % steps;
1544
                        v = v / steps;
1545
                        s->sb_samples[0][k * 12 + l + 1][i] =
1546
                            l2_unscale_group(steps, mant, scale0);
1547
                        s->sb_samples[1][k * 12 + l + 1][i] =
1548
                            l2_unscale_group(steps, mant, scale1);
1549
                        s->sb_samples[0][k * 12 + l + 2][i] =
1550
                            l2_unscale_group(steps, v, scale0);
1551
                        s->sb_samples[1][k * 12 + l + 2][i] =
1552
                            l2_unscale_group(steps, v, scale1);
1553
                    } else {
1554
                        for(m=0;m<3;m++) {
1555
                            mant = get_bits(&s->gb, bits);
1556
                            s->sb_samples[0][k * 12 + l + m][i] =
1557
                                l1_unscale(bits - 1, mant, scale0);
1558
                            s->sb_samples[1][k * 12 + l + m][i] =
1559
                                l1_unscale(bits - 1, mant, scale1);
1560
                        }
1561
                    }
1562
                } else {
1563
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
1564
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
1565
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
1566
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
1567
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
1568
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
1569
                }
1570
                /* next subband in alloc table */
1571
                j += 1 << bit_alloc_bits;
1572
            }
1573
            /* fill remaining samples to zero */
1574
            for(i=sblimit;i<SBLIMIT;i++) {
1575
                for(ch=0;ch<s->nb_channels;ch++) {
1576
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1577
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1578
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1579
                }
1580
            }
1581
        }
1582
    }
1583
    return 3 * 12;
1584
}
1585

    
1586
static inline void lsf_sf_expand(int *slen,
1587
                                 int sf, int n1, int n2, int n3)
1588
{
1589
    if (n3) {
1590
        slen[3] = sf % n3;
1591
        sf /= n3;
1592
    } else {
1593
        slen[3] = 0;
1594
    }
1595
    if (n2) {
1596
        slen[2] = sf % n2;
1597
        sf /= n2;
1598
    } else {
1599
        slen[2] = 0;
1600
    }
1601
    slen[1] = sf % n1;
1602
    sf /= n1;
1603
    slen[0] = sf;
1604
}
1605

    
1606
static void exponents_from_scale_factors(MPADecodeContext *s,
1607
                                         GranuleDef *g,
1608
                                         int16_t *exponents)
1609
{
1610
    const uint8_t *bstab, *pretab;
1611
    int len, i, j, k, l, v0, shift, gain, gains[3];
1612
    int16_t *exp_ptr;
1613

    
1614
    exp_ptr = exponents;
1615
    gain = g->global_gain - 210;
1616
    shift = g->scalefac_scale + 1;
1617

    
1618
    bstab = band_size_long[s->sample_rate_index];
1619
    pretab = mpa_pretab[g->preflag];
1620
    for(i=0;i<g->long_end;i++) {
1621
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1622
        len = bstab[i];
1623
        for(j=len;j>0;j--)
1624
            *exp_ptr++ = v0;
1625
    }
1626

    
1627
    if (g->short_start < 13) {
1628
        bstab = band_size_short[s->sample_rate_index];
1629
        gains[0] = gain - (g->subblock_gain[0] << 3);
1630
        gains[1] = gain - (g->subblock_gain[1] << 3);
1631
        gains[2] = gain - (g->subblock_gain[2] << 3);
1632
        k = g->long_end;
1633
        for(i=g->short_start;i<13;i++) {
1634
            len = bstab[i];
1635
            for(l=0;l<3;l++) {
1636
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1637
                for(j=len;j>0;j--)
1638
                *exp_ptr++ = v0;
1639
            }
1640
        }
1641
    }
1642
}
1643

    
1644
/* handle n = 0 too */
1645
static inline int get_bitsz(GetBitContext *s, int n)
1646
{
1647
    if (n == 0)
1648
        return 0;
1649
    else
1650
        return get_bits(s, n);
1651
}
1652

    
1653
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1654
                          int16_t *exponents, int end_pos2)
1655
{
1656
    int s_index;
1657
    int i;
1658
    int last_pos, bits_left;
1659
    VLC *vlc;
1660
    int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1661

    
1662
    /* low frequencies (called big values) */
1663
    s_index = 0;
1664
    for(i=0;i<3;i++) {
1665
        int j, k, l, linbits;
1666
        j = g->region_size[i];
1667
        if (j == 0)
1668
            continue;
1669
        /* select vlc table */
1670
        k = g->table_select[i];
1671
        l = mpa_huff_data[k][0];
1672
        linbits = mpa_huff_data[k][1];
1673
        vlc = &huff_vlc[l];
1674

    
1675
        if(!l){
1676
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*j);
1677
            s_index += 2*j;
1678
            continue;
1679
        }
1680

    
1681
        /* read huffcode and compute each couple */
1682
        for(;j>0;j--) {
1683
            int exponent, x, y, v;
1684
            int pos= get_bits_count(&s->gb);
1685

    
1686
            if (pos >= end_pos){
1687
//                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1688
                if(s->in_gb.buffer && pos >= s->gb.size_in_bits){
1689
                    s->gb= s->in_gb;
1690
                    s->in_gb.buffer=NULL;
1691
                    assert((get_bits_count(&s->gb) & 7) == 0);
1692
                    skip_bits_long(&s->gb, pos - end_pos);
1693
                    end_pos= end_pos2 + get_bits_count(&s->gb) - pos;
1694
                    pos= get_bits_count(&s->gb);
1695
                }
1696
//                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1697
                if(pos >= end_pos)
1698
                    break;
1699
            }
1700
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
1701

    
1702
            if(!y){
1703
                g->sb_hybrid[s_index  ] =
1704
                g->sb_hybrid[s_index+1] = 0;
1705
                s_index += 2;
1706
                continue;
1707
            }
1708

    
1709
            exponent= exponents[s_index];
1710

    
1711
            dprintf("region=%d n=%d x=%d y=%d exp=%d\n",
1712
                    i, g->region_size[i] - j, x, y, exponent);
1713
            if(y&16){
1714
                x = y >> 5;
1715
                y = y & 0x0f;
1716
                if (x < 15){
1717
                    v = expval_table[ exponent ][ x ];
1718
//                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
1719
                }else{
1720
                    x += get_bitsz(&s->gb, linbits);
1721
                    v = l3_unscale(x, exponent);
1722
                }
1723
                if (get_bits1(&s->gb))
1724
                    v = -v;
1725
                g->sb_hybrid[s_index] = v;
1726
                if (y < 15){
1727
                    v = expval_table[ exponent ][ y ];
1728
                }else{
1729
                    y += get_bitsz(&s->gb, linbits);
1730
                    v = l3_unscale(y, exponent);
1731
                }
1732
                if (get_bits1(&s->gb))
1733
                    v = -v;
1734
                g->sb_hybrid[s_index+1] = v;
1735
            }else{
1736
                x = y >> 5;
1737
                y = y & 0x0f;
1738
                x += y;
1739
                if (x < 15){
1740
                    v = expval_table[ exponent ][ x ];
1741
                }else{
1742
                    x += get_bitsz(&s->gb, linbits);
1743
                    v = l3_unscale(x, exponent);
1744
                }
1745
                if (get_bits1(&s->gb))
1746
                    v = -v;
1747
                g->sb_hybrid[s_index+!!y] = v;
1748
            }
1749
            s_index+=2;
1750
        }
1751
    }
1752

    
1753
    /* high frequencies */
1754
    vlc = &huff_quad_vlc[g->count1table_select];
1755
    last_pos=0;
1756
    while (s_index <= 572) {
1757
        int pos, code;
1758
        pos = get_bits_count(&s->gb);
1759
        if (pos >= end_pos) {
1760
//                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1761
            if(s->in_gb.buffer && pos >= s->gb.size_in_bits){
1762
                s->gb= s->in_gb;
1763
                s->in_gb.buffer=NULL;
1764
                assert((get_bits_count(&s->gb) & 7) == 0);
1765
                skip_bits_long(&s->gb, pos - end_pos);
1766
                end_pos= end_pos2 + get_bits_count(&s->gb) - pos;
1767
                pos= get_bits_count(&s->gb);
1768
            }
1769
//                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1770
            if (pos > end_pos && last_pos){ //FIXME last_pos is messed if we switch buffers
1771
                /* some encoders generate an incorrect size for this
1772
                   part. We must go back into the data */
1773
                s_index -= 4;
1774
                skip_bits_long(&s->gb, last_pos - pos);
1775
                av_log(NULL, AV_LOG_ERROR, "overread, skip %d\n", last_pos&7);
1776
            }
1777
            if(pos >= end_pos)
1778
                break;
1779
        }
1780
        last_pos= pos;
1781

    
1782
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1783
        dprintf("t=%d code=%d\n", g->count1table_select, code);
1784
        g->sb_hybrid[s_index+0]=
1785
        g->sb_hybrid[s_index+1]=
1786
        g->sb_hybrid[s_index+2]=
1787
        g->sb_hybrid[s_index+3]= 0;
1788
        while(code){
1789
            const static int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1790
            int v;
1791
            int pos= s_index+idxtab[code];
1792
            code ^= 8>>idxtab[code];
1793
            v = exp_table[ exponents[pos] ];
1794
//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1795
            if(get_bits1(&s->gb))
1796
                v = -v;
1797
            g->sb_hybrid[pos] = v;
1798
        }
1799
        s_index+=4;
1800
    }
1801
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1802

    
1803
    /* skip extension bits */
1804
    bits_left = end_pos - get_bits_count(&s->gb);
1805
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1806
    if (bits_left < 0) {
1807
        dprintf("bits_left=%d\n", bits_left);
1808
        return -1;
1809
    }
1810
    skip_bits_long(&s->gb, bits_left);
1811

    
1812
    return 0;
1813
}
1814

    
1815
/* Reorder short blocks from bitstream order to interleaved order. It
1816
   would be faster to do it in parsing, but the code would be far more
1817
   complicated */
1818
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1819
{
1820
    int i, j, len;
1821
    int32_t *ptr, *dst, *ptr1;
1822
    int32_t tmp[576];
1823

    
1824
    if (g->block_type != 2)
1825
        return;
1826

    
1827
    if (g->switch_point) {
1828
        if (s->sample_rate_index != 8) {
1829
            ptr = g->sb_hybrid + 36;
1830
        } else {
1831
            ptr = g->sb_hybrid + 48;
1832
        }
1833
    } else {
1834
        ptr = g->sb_hybrid;
1835
    }
1836

    
1837
    for(i=g->short_start;i<13;i++) {
1838
        len = band_size_short[s->sample_rate_index][i];
1839
        ptr1 = ptr;
1840
        dst = tmp;
1841
        for(j=len;j>0;j--) {
1842
            *dst++ = ptr[0*len];
1843
            *dst++ = ptr[1*len];
1844
            *dst++ = ptr[2*len];
1845
            ptr++;
1846
        }
1847
        ptr+=2*len;
1848
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1849
    }
1850
}
1851

    
1852
#define ISQRT2 FIXR(0.70710678118654752440)
1853

    
1854
static void compute_stereo(MPADecodeContext *s,
1855
                           GranuleDef *g0, GranuleDef *g1)
1856
{
1857
    int i, j, k, l;
1858
    int32_t v1, v2;
1859
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1860
    int32_t (*is_tab)[16];
1861
    int32_t *tab0, *tab1;
1862
    int non_zero_found_short[3];
1863

    
1864
    /* intensity stereo */
1865
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1866
        if (!s->lsf) {
1867
            is_tab = is_table;
1868
            sf_max = 7;
1869
        } else {
1870
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1871
            sf_max = 16;
1872
        }
1873

    
1874
        tab0 = g0->sb_hybrid + 576;
1875
        tab1 = g1->sb_hybrid + 576;
1876

    
1877
        non_zero_found_short[0] = 0;
1878
        non_zero_found_short[1] = 0;
1879
        non_zero_found_short[2] = 0;
1880
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1881
        for(i = 12;i >= g1->short_start;i--) {
1882
            /* for last band, use previous scale factor */
1883
            if (i != 11)
1884
                k -= 3;
1885
            len = band_size_short[s->sample_rate_index][i];
1886
            for(l=2;l>=0;l--) {
1887
                tab0 -= len;
1888
                tab1 -= len;
1889
                if (!non_zero_found_short[l]) {
1890
                    /* test if non zero band. if so, stop doing i-stereo */
1891
                    for(j=0;j<len;j++) {
1892
                        if (tab1[j] != 0) {
1893
                            non_zero_found_short[l] = 1;
1894
                            goto found1;
1895
                        }
1896
                    }
1897
                    sf = g1->scale_factors[k + l];
1898
                    if (sf >= sf_max)
1899
                        goto found1;
1900

    
1901
                    v1 = is_tab[0][sf];
1902
                    v2 = is_tab[1][sf];
1903
                    for(j=0;j<len;j++) {
1904
                        tmp0 = tab0[j];
1905
                        tab0[j] = MULL(tmp0, v1);
1906
                        tab1[j] = MULL(tmp0, v2);
1907
                    }
1908
                } else {
1909
                found1:
1910
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1911
                        /* lower part of the spectrum : do ms stereo
1912
                           if enabled */
1913
                        for(j=0;j<len;j++) {
1914
                            tmp0 = tab0[j];
1915
                            tmp1 = tab1[j];
1916
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1917
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1918
                        }
1919
                    }
1920
                }
1921
            }
1922
        }
1923

    
1924
        non_zero_found = non_zero_found_short[0] |
1925
            non_zero_found_short[1] |
1926
            non_zero_found_short[2];
1927

    
1928
        for(i = g1->long_end - 1;i >= 0;i--) {
1929
            len = band_size_long[s->sample_rate_index][i];
1930
            tab0 -= len;
1931
            tab1 -= len;
1932
            /* test if non zero band. if so, stop doing i-stereo */
1933
            if (!non_zero_found) {
1934
                for(j=0;j<len;j++) {
1935
                    if (tab1[j] != 0) {
1936
                        non_zero_found = 1;
1937
                        goto found2;
1938
                    }
1939
                }
1940
                /* for last band, use previous scale factor */
1941
                k = (i == 21) ? 20 : i;
1942
                sf = g1->scale_factors[k];
1943
                if (sf >= sf_max)
1944
                    goto found2;
1945
                v1 = is_tab[0][sf];
1946
                v2 = is_tab[1][sf];
1947
                for(j=0;j<len;j++) {
1948
                    tmp0 = tab0[j];
1949
                    tab0[j] = MULL(tmp0, v1);
1950
                    tab1[j] = MULL(tmp0, v2);
1951
                }
1952
            } else {
1953
            found2:
1954
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1955
                    /* lower part of the spectrum : do ms stereo
1956
                       if enabled */
1957
                    for(j=0;j<len;j++) {
1958
                        tmp0 = tab0[j];
1959
                        tmp1 = tab1[j];
1960
                        tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1961
                        tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1962
                    }
1963
                }
1964
            }
1965
        }
1966
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1967
        /* ms stereo ONLY */
1968
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1969
           global gain */
1970
        tab0 = g0->sb_hybrid;
1971
        tab1 = g1->sb_hybrid;
1972
        for(i=0;i<576;i++) {
1973
            tmp0 = tab0[i];
1974
            tmp1 = tab1[i];
1975
            tab0[i] = tmp0 + tmp1;
1976
            tab1[i] = tmp0 - tmp1;
1977
        }
1978
    }
1979
}
1980

    
1981
static void compute_antialias_integer(MPADecodeContext *s,
1982
                              GranuleDef *g)
1983
{
1984
    int32_t *ptr, *csa;
1985
    int n, i;
1986

    
1987
    /* we antialias only "long" bands */
1988
    if (g->block_type == 2) {
1989
        if (!g->switch_point)
1990
            return;
1991
        /* XXX: check this for 8000Hz case */
1992
        n = 1;
1993
    } else {
1994
        n = SBLIMIT - 1;
1995
    }
1996

    
1997
    ptr = g->sb_hybrid + 18;
1998
    for(i = n;i > 0;i--) {
1999
        int tmp0, tmp1, tmp2;
2000
        csa = &csa_table[0][0];
2001
#define INT_AA(j) \
2002
            tmp0 = ptr[-1-j];\
2003
            tmp1 = ptr[   j];\
2004
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
2005
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
2006
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
2007

    
2008
        INT_AA(0)
2009
        INT_AA(1)
2010
        INT_AA(2)
2011
        INT_AA(3)
2012
        INT_AA(4)
2013
        INT_AA(5)
2014
        INT_AA(6)
2015
        INT_AA(7)
2016

    
2017
        ptr += 18;
2018
    }
2019
}
2020

    
2021
static void compute_antialias_float(MPADecodeContext *s,
2022
                              GranuleDef *g)
2023
{
2024
    int32_t *ptr;
2025
    int n, i;
2026

    
2027
    /* we antialias only "long" bands */
2028
    if (g->block_type == 2) {
2029
        if (!g->switch_point)
2030
            return;
2031
        /* XXX: check this for 8000Hz case */
2032
        n = 1;
2033
    } else {
2034
        n = SBLIMIT - 1;
2035
    }
2036

    
2037
    ptr = g->sb_hybrid + 18;
2038
    for(i = n;i > 0;i--) {
2039
        float tmp0, tmp1;
2040
        float *csa = &csa_table_float[0][0];
2041
#define FLOAT_AA(j)\
2042
        tmp0= ptr[-1-j];\
2043
        tmp1= ptr[   j];\
2044
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
2045
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
2046

    
2047
        FLOAT_AA(0)
2048
        FLOAT_AA(1)
2049
        FLOAT_AA(2)
2050
        FLOAT_AA(3)
2051
        FLOAT_AA(4)
2052
        FLOAT_AA(5)
2053
        FLOAT_AA(6)
2054
        FLOAT_AA(7)
2055

    
2056
        ptr += 18;
2057
    }
2058
}
2059

    
2060
static void compute_imdct(MPADecodeContext *s,
2061
                          GranuleDef *g,
2062
                          int32_t *sb_samples,
2063
                          int32_t *mdct_buf)
2064
{
2065
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
2066
    int32_t out2[12];
2067
    int i, j, mdct_long_end, v, sblimit;
2068

    
2069
    /* find last non zero block */
2070
    ptr = g->sb_hybrid + 576;
2071
    ptr1 = g->sb_hybrid + 2 * 18;
2072
    while (ptr >= ptr1) {
2073
        ptr -= 6;
2074
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
2075
        if (v != 0)
2076
            break;
2077
    }
2078
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
2079

    
2080
    if (g->block_type == 2) {
2081
        /* XXX: check for 8000 Hz */
2082
        if (g->switch_point)
2083
            mdct_long_end = 2;
2084
        else
2085
            mdct_long_end = 0;
2086
    } else {
2087
        mdct_long_end = sblimit;
2088
    }
2089

    
2090
    buf = mdct_buf;
2091
    ptr = g->sb_hybrid;
2092
    for(j=0;j<mdct_long_end;j++) {
2093
        /* apply window & overlap with previous buffer */
2094
        out_ptr = sb_samples + j;
2095
        /* select window */
2096
        if (g->switch_point && j < 2)
2097
            win1 = mdct_win[0];
2098
        else
2099
            win1 = mdct_win[g->block_type];
2100
        /* select frequency inversion */
2101
        win = win1 + ((4 * 36) & -(j & 1));
2102
        imdct36(out_ptr, buf, ptr, win);
2103
        out_ptr += 18*SBLIMIT;
2104
        ptr += 18;
2105
        buf += 18;
2106
    }
2107
    for(j=mdct_long_end;j<sblimit;j++) {
2108
        /* select frequency inversion */
2109
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
2110
        out_ptr = sb_samples + j;
2111

    
2112
        for(i=0; i<6; i++){
2113
            *out_ptr = buf[i];
2114
            out_ptr += SBLIMIT;
2115
        }
2116
        imdct12(out2, ptr + 0);
2117
        for(i=0;i<6;i++) {
2118
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
2119
            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
2120
            out_ptr += SBLIMIT;
2121
        }
2122
        imdct12(out2, ptr + 1);
2123
        for(i=0;i<6;i++) {
2124
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
2125
            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
2126
            out_ptr += SBLIMIT;
2127
        }
2128
        imdct12(out2, ptr + 2);
2129
        for(i=0;i<6;i++) {
2130
            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
2131
            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
2132
            buf[i + 6*2] = 0;
2133
        }
2134
        ptr += 18;
2135
        buf += 18;
2136
    }
2137
    /* zero bands */
2138
    for(j=sblimit;j<SBLIMIT;j++) {
2139
        /* overlap */
2140
        out_ptr = sb_samples + j;
2141
        for(i=0;i<18;i++) {
2142
            *out_ptr = buf[i];
2143
            buf[i] = 0;
2144
            out_ptr += SBLIMIT;
2145
        }
2146
        buf += 18;
2147
    }
2148
}
2149

    
2150
#if defined(DEBUG)
2151
void sample_dump(int fnum, int32_t *tab, int n)
2152
{
2153
    static FILE *files[16], *f;
2154
    char buf[512];
2155
    int i;
2156
    int32_t v;
2157

    
2158
    f = files[fnum];
2159
    if (!f) {
2160
        snprintf(buf, sizeof(buf), "/tmp/out%d.%s.pcm",
2161
                fnum,
2162
#ifdef USE_HIGHPRECISION
2163
                "hp"
2164
#else
2165
                "lp"
2166
#endif
2167
                );
2168
        f = fopen(buf, "w");
2169
        if (!f)
2170
            return;
2171
        files[fnum] = f;
2172
    }
2173

    
2174
    if (fnum == 0) {
2175
        static int pos = 0;
2176
        av_log(NULL, AV_LOG_DEBUG, "pos=%d\n", pos);
2177
        for(i=0;i<n;i++) {
2178
            av_log(NULL, AV_LOG_DEBUG, " %0.4f", (double)tab[i] / FRAC_ONE);
2179
            if ((i % 18) == 17)
2180
                av_log(NULL, AV_LOG_DEBUG, "\n");
2181
        }
2182
        pos += n;
2183
    }
2184
    for(i=0;i<n;i++) {
2185
        /* normalize to 23 frac bits */
2186
        v = tab[i] << (23 - FRAC_BITS);
2187
        fwrite(&v, 1, sizeof(int32_t), f);
2188
    }
2189
}
2190
#endif
2191

    
2192

    
2193
/* main layer3 decoding function */
2194
static int mp_decode_layer3(MPADecodeContext *s)
2195
{
2196
    int nb_granules, main_data_begin, private_bits;
2197
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
2198
    GranuleDef granules[2][2], *g;
2199
    int16_t exponents[576];
2200

    
2201
    /* read side info */
2202
    if (s->lsf) {
2203
        main_data_begin = get_bits(&s->gb, 8);
2204
        private_bits = get_bits(&s->gb, s->nb_channels);
2205
        nb_granules = 1;
2206
    } else {
2207
        main_data_begin = get_bits(&s->gb, 9);
2208
        if (s->nb_channels == 2)
2209
            private_bits = get_bits(&s->gb, 3);
2210
        else
2211
            private_bits = get_bits(&s->gb, 5);
2212
        nb_granules = 2;
2213
        for(ch=0;ch<s->nb_channels;ch++) {
2214
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
2215
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
2216
        }
2217
    }
2218

    
2219
    for(gr=0;gr<nb_granules;gr++) {
2220
        for(ch=0;ch<s->nb_channels;ch++) {
2221
            dprintf("gr=%d ch=%d: side_info\n", gr, ch);
2222
            g = &granules[ch][gr];
2223
            g->part2_3_length = get_bits(&s->gb, 12);
2224
            g->big_values = get_bits(&s->gb, 9);
2225
            g->global_gain = get_bits(&s->gb, 8);
2226
            /* if MS stereo only is selected, we precompute the
2227
               1/sqrt(2) renormalization factor */
2228
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
2229
                MODE_EXT_MS_STEREO)
2230
                g->global_gain -= 2;
2231
            if (s->lsf)
2232
                g->scalefac_compress = get_bits(&s->gb, 9);
2233
            else
2234
                g->scalefac_compress = get_bits(&s->gb, 4);
2235
            blocksplit_flag = get_bits(&s->gb, 1);
2236
            if (blocksplit_flag) {
2237
                g->block_type = get_bits(&s->gb, 2);
2238
                if (g->block_type == 0)
2239
                    return -1;
2240
                g->switch_point = get_bits(&s->gb, 1);
2241
                for(i=0;i<2;i++)
2242
                    g->table_select[i] = get_bits(&s->gb, 5);
2243
                for(i=0;i<3;i++)
2244
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
2245
                /* compute huffman coded region sizes */
2246
                if (g->block_type == 2)
2247
                    g->region_size[0] = (36 / 2);
2248
                else {
2249
                    if (s->sample_rate_index <= 2)
2250
                        g->region_size[0] = (36 / 2);
2251
                    else if (s->sample_rate_index != 8)
2252
                        g->region_size[0] = (54 / 2);
2253
                    else
2254
                        g->region_size[0] = (108 / 2);
2255
                }
2256
                g->region_size[1] = (576 / 2);
2257
            } else {
2258
                int region_address1, region_address2, l;
2259
                g->block_type = 0;
2260
                g->switch_point = 0;
2261
                for(i=0;i<3;i++)
2262
                    g->table_select[i] = get_bits(&s->gb, 5);
2263
                /* compute huffman coded region sizes */
2264
                region_address1 = get_bits(&s->gb, 4);
2265
                region_address2 = get_bits(&s->gb, 3);
2266
                dprintf("region1=%d region2=%d\n",
2267
                        region_address1, region_address2);
2268
                g->region_size[0] =
2269
                    band_index_long[s->sample_rate_index][region_address1 + 1] >> 1;
2270
                l = region_address1 + region_address2 + 2;
2271
                /* should not overflow */
2272
                if (l > 22)
2273
                    l = 22;
2274
                g->region_size[1] =
2275
                    band_index_long[s->sample_rate_index][l] >> 1;
2276
            }
2277
            /* convert region offsets to region sizes and truncate
2278
               size to big_values */
2279
            g->region_size[2] = (576 / 2);
2280
            j = 0;
2281
            for(i=0;i<3;i++) {
2282
                k = FFMIN(g->region_size[i], g->big_values);
2283
                g->region_size[i] = k - j;
2284
                j = k;
2285
            }
2286

    
2287
            /* compute band indexes */
2288
            if (g->block_type == 2) {
2289
                if (g->switch_point) {
2290
                    /* if switched mode, we handle the 36 first samples as
2291
                       long blocks.  For 8000Hz, we handle the 48 first
2292
                       exponents as long blocks (XXX: check this!) */
2293
                    if (s->sample_rate_index <= 2)
2294
                        g->long_end = 8;
2295
                    else if (s->sample_rate_index != 8)
2296
                        g->long_end = 6;
2297
                    else
2298
                        g->long_end = 4; /* 8000 Hz */
2299

    
2300
                    g->short_start = 2 + (s->sample_rate_index != 8);
2301
                } else {
2302
                    g->long_end = 0;
2303
                    g->short_start = 0;
2304
                }
2305
            } else {
2306
                g->short_start = 13;
2307
                g->long_end = 22;
2308
            }
2309

    
2310
            g->preflag = 0;
2311
            if (!s->lsf)
2312
                g->preflag = get_bits(&s->gb, 1);
2313
            g->scalefac_scale = get_bits(&s->gb, 1);
2314
            g->count1table_select = get_bits(&s->gb, 1);
2315
            dprintf("block_type=%d switch_point=%d\n",
2316
                    g->block_type, g->switch_point);
2317
        }
2318
    }
2319

    
2320
  if (!s->adu_mode) {
2321
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2322
    /* now we get bits from the main_data_begin offset */
2323
    dprintf("seekback: %d\n", main_data_begin);
2324
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2325
    if(main_data_begin > s->last_buf_size)
2326
        s->last_buf_size= main_data_begin;
2327

    
2328
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2329
    s->in_gb= s->gb;
2330
    init_get_bits(&s->gb, s->last_buf + s->last_buf_size - main_data_begin, main_data_begin*8);
2331
    /* prepare next buffer */
2332
    s->old_frame_size = s->frame_size;
2333
  }
2334

    
2335
    for(gr=0;gr<nb_granules;gr++) {
2336
        for(ch=0;ch<s->nb_channels;ch++) {
2337
            g = &granules[ch][gr];
2338

    
2339
            bits_pos = get_bits_count(&s->gb);
2340

    
2341
            if (!s->lsf) {
2342
                uint8_t *sc;
2343
                int slen, slen1, slen2;
2344

    
2345
                /* MPEG1 scale factors */
2346
                slen1 = slen_table[0][g->scalefac_compress];
2347
                slen2 = slen_table[1][g->scalefac_compress];
2348
                dprintf("slen1=%d slen2=%d\n", slen1, slen2);
2349
                if (g->block_type == 2) {
2350
                    n = g->switch_point ? 17 : 18;
2351
                    j = 0;
2352
                    if(slen1){
2353
                        for(i=0;i<n;i++)
2354
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
2355
                    }else{
2356
                        for(i=0;i<n;i++)
2357
                            g->scale_factors[j++] = 0;
2358
                    }
2359
                    if(slen2){
2360
                        for(i=0;i<18;i++)
2361
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
2362
                        for(i=0;i<3;i++)
2363
                            g->scale_factors[j++] = 0;
2364
                    }else{
2365
                        for(i=0;i<21;i++)
2366
                            g->scale_factors[j++] = 0;
2367
                    }
2368
                } else {
2369
                    sc = granules[ch][0].scale_factors;
2370
                    j = 0;
2371
                    for(k=0;k<4;k++) {
2372
                        n = (k == 0 ? 6 : 5);
2373
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2374
                            slen = (k < 2) ? slen1 : slen2;
2375
                            if(slen){
2376
                                for(i=0;i<n;i++)
2377
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
2378
                            }else{
2379
                                for(i=0;i<n;i++)
2380
                                    g->scale_factors[j++] = 0;
2381
                            }
2382
                        } else {
2383
                            /* simply copy from last granule */
2384
                            for(i=0;i<n;i++) {
2385
                                g->scale_factors[j] = sc[j];
2386
                                j++;
2387
                            }
2388
                        }
2389
                    }
2390
                    g->scale_factors[j++] = 0;
2391
                }
2392
#if defined(DEBUG)
2393
                {
2394
                    dprintf("scfsi=%x gr=%d ch=%d scale_factors:\n",
2395
                           g->scfsi, gr, ch);
2396
                    for(i=0;i<j;i++)
2397
                        dprintf(" %d", g->scale_factors[i]);
2398
                    dprintf("\n");
2399
                }
2400
#endif
2401
            } else {
2402
                int tindex, tindex2, slen[4], sl, sf;
2403

    
2404
                /* LSF scale factors */
2405
                if (g->block_type == 2) {
2406
                    tindex = g->switch_point ? 2 : 1;
2407
                } else {
2408
                    tindex = 0;
2409
                }
2410
                sf = g->scalefac_compress;
2411
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2412
                    /* intensity stereo case */
2413
                    sf >>= 1;
2414
                    if (sf < 180) {
2415
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2416
                        tindex2 = 3;
2417
                    } else if (sf < 244) {
2418
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2419
                        tindex2 = 4;
2420
                    } else {
2421
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2422
                        tindex2 = 5;
2423
                    }
2424
                } else {
2425
                    /* normal case */
2426
                    if (sf < 400) {
2427
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2428
                        tindex2 = 0;
2429
                    } else if (sf < 500) {
2430
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2431
                        tindex2 = 1;
2432
                    } else {
2433
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2434
                        tindex2 = 2;
2435
                        g->preflag = 1;
2436
                    }
2437
                }
2438

    
2439
                j = 0;
2440
                for(k=0;k<4;k++) {
2441
                    n = lsf_nsf_table[tindex2][tindex][k];
2442
                    sl = slen[k];
2443
                    if(sl){
2444
                        for(i=0;i<n;i++)
2445
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
2446
                    }else{
2447
                        for(i=0;i<n;i++)
2448
                            g->scale_factors[j++] = 0;
2449
                    }
2450
                }
2451
                /* XXX: should compute exact size */
2452
                for(;j<40;j++)
2453
                    g->scale_factors[j] = 0;
2454
#if defined(DEBUG)
2455
                {
2456
                    dprintf("gr=%d ch=%d scale_factors:\n",
2457
                           gr, ch);
2458
                    for(i=0;i<40;i++)
2459
                        dprintf(" %d", g->scale_factors[i]);
2460
                    dprintf("\n");
2461
                }
2462
#endif
2463
            }
2464

    
2465
            exponents_from_scale_factors(s, g, exponents);
2466

    
2467
            /* read Huffman coded residue */
2468
            if (huffman_decode(s, g, exponents,
2469
                               bits_pos + g->part2_3_length) < 0)
2470
                return -1;
2471
#if defined(DEBUG)
2472
            sample_dump(0, g->sb_hybrid, 576);
2473
#endif
2474
        } /* ch */
2475

    
2476
        if (s->nb_channels == 2)
2477
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2478

    
2479
        for(ch=0;ch<s->nb_channels;ch++) {
2480
            g = &granules[ch][gr];
2481

    
2482
            reorder_block(s, g);
2483
#if defined(DEBUG)
2484
            sample_dump(0, g->sb_hybrid, 576);
2485
#endif
2486
            s->compute_antialias(s, g);
2487
#if defined(DEBUG)
2488
            sample_dump(1, g->sb_hybrid, 576);
2489
#endif
2490
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2491
#if defined(DEBUG)
2492
            sample_dump(2, &s->sb_samples[ch][18 * gr][0], 576);
2493
#endif
2494
        }
2495
    } /* gr */
2496
    return nb_granules * 18;
2497
}
2498

    
2499
static int mp_decode_frame(MPADecodeContext *s,
2500
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
2501
{
2502
    int i, nb_frames, ch;
2503
    OUT_INT *samples_ptr;
2504

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

    
2507
    /* skip error protection field */
2508
    if (s->error_protection)
2509
        get_bits(&s->gb, 16);
2510

    
2511
    dprintf("frame %d:\n", s->frame_count);
2512
    switch(s->layer) {
2513
    case 1:
2514
        nb_frames = mp_decode_layer1(s);
2515
        break;
2516
    case 2:
2517
        nb_frames = mp_decode_layer2(s);
2518
        break;
2519
    case 3:
2520
    default:
2521
        nb_frames = mp_decode_layer3(s);
2522

    
2523
        if(s->in_gb.buffer)
2524
            s->gb= s->in_gb;
2525
        align_get_bits(&s->gb);
2526
        assert((get_bits_count(&s->gb) & 7) == 0);
2527
        s->last_buf_size= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2528
        memcpy(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), s->last_buf_size);
2529

    
2530
        break;
2531
    }
2532
#if defined(DEBUG)
2533
    for(i=0;i<nb_frames;i++) {
2534
        for(ch=0;ch<s->nb_channels;ch++) {
2535
            int j;
2536
            dprintf("%d-%d:", i, ch);
2537
            for(j=0;j<SBLIMIT;j++)
2538
                dprintf(" %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);
2539
            dprintf("\n");
2540
        }
2541
    }
2542
#endif
2543
    /* apply the synthesis filter */
2544
    for(ch=0;ch<s->nb_channels;ch++) {
2545
        samples_ptr = samples + ch;
2546
        for(i=0;i<nb_frames;i++) {
2547
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2548
                         window, &s->dither_state,
2549
                         samples_ptr, s->nb_channels,
2550
                         s->sb_samples[ch][i]);
2551
            samples_ptr += 32 * s->nb_channels;
2552
        }
2553
    }
2554
#ifdef DEBUG
2555
    s->frame_count++;
2556
#endif
2557
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2558
}
2559

    
2560
static int decode_frame(AVCodecContext * avctx,
2561
                        void *data, int *data_size,
2562
                        uint8_t * buf, int buf_size)
2563
{
2564
    MPADecodeContext *s = avctx->priv_data;
2565
    uint32_t header;
2566
    int out_size;
2567
    OUT_INT *out_samples = data;
2568

    
2569
retry:
2570
    if(buf_size < HEADER_SIZE)
2571
        return -1;
2572

    
2573
    header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
2574
    if(ff_mpa_check_header(header) < 0){
2575
        buf++;
2576
//        buf_size--;
2577
        av_log(avctx, AV_LOG_ERROR, "header missing skiping one byte\n");
2578
        goto retry;
2579
    }
2580

    
2581
    if (decode_header(s, header) == 1) {
2582
        /* free format: prepare to compute frame size */
2583
        s->frame_size = -1;
2584
        return -1;
2585
    }
2586
    /* update codec info */
2587
    avctx->sample_rate = s->sample_rate;
2588
    avctx->channels = s->nb_channels;
2589
    avctx->bit_rate = s->bit_rate;
2590
    avctx->sub_id = s->layer;
2591
    switch(s->layer) {
2592
    case 1:
2593
        avctx->frame_size = 384;
2594
        break;
2595
    case 2:
2596
        avctx->frame_size = 1152;
2597
        break;
2598
    case 3:
2599
        if (s->lsf)
2600
            avctx->frame_size = 576;
2601
        else
2602
            avctx->frame_size = 1152;
2603
        break;
2604
    }
2605

    
2606
    if(s->frame_size<=0 || s->frame_size < buf_size){
2607
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2608
        return -1;
2609
    }
2610

    
2611
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2612
    if(out_size>=0)
2613
        *data_size = out_size;
2614
    else
2615
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding mpeg audio frame\n"); //FIXME return -1 / but also return the number of bytes consumed
2616
    s->frame_size = 0;
2617
    return buf_size;
2618
}
2619

    
2620

    
2621
static int decode_frame_adu(AVCodecContext * avctx,
2622
                        void *data, int *data_size,
2623
                        uint8_t * buf, int buf_size)
2624
{
2625
    MPADecodeContext *s = avctx->priv_data;
2626
    uint32_t header;
2627
    int len, out_size;
2628
    OUT_INT *out_samples = data;
2629

    
2630
    len = buf_size;
2631

    
2632
    // Discard too short frames
2633
    if (buf_size < HEADER_SIZE) {
2634
        *data_size = 0;
2635
        return buf_size;
2636
    }
2637

    
2638

    
2639
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2640
        len = MPA_MAX_CODED_FRAME_SIZE;
2641

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

    
2645
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2646
        *data_size = 0;
2647
        return buf_size;
2648
    }
2649

    
2650
    decode_header(s, header);
2651
    /* update codec info */
2652
    avctx->sample_rate = s->sample_rate;
2653
    avctx->channels = s->nb_channels;
2654
    avctx->bit_rate = s->bit_rate;
2655
    avctx->sub_id = s->layer;
2656

    
2657
    avctx->frame_size=s->frame_size = len;
2658

    
2659
    if (avctx->parse_only) {
2660
        out_size = buf_size;
2661
    } else {
2662
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2663
    }
2664

    
2665
    *data_size = out_size;
2666
    return buf_size;
2667
}
2668

    
2669

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

    
2686

    
2687
static int decode_init_mp3on4(AVCodecContext * avctx)
2688
{
2689
    MP3On4DecodeContext *s = avctx->priv_data;
2690
    int i;
2691

    
2692
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2693
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2694
        return -1;
2695
    }
2696

    
2697
    s->chan_cfg = (((unsigned char *)avctx->extradata)[1] >> 3) & 0x0f;
2698
    s->frames = mp3Frames[s->chan_cfg];
2699
    if(!s->frames) {
2700
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2701
        return -1;
2702
    }
2703
    avctx->channels = mp3Channels[s->chan_cfg];
2704

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

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

    
2728
    return 0;
2729
}
2730

    
2731

    
2732
static int decode_close_mp3on4(AVCodecContext * avctx)
2733
{
2734
    MP3On4DecodeContext *s = avctx->priv_data;
2735
    int i;
2736

    
2737
    for (i = 0; i < s->frames; i++)
2738
        if (s->mp3decctx[i])
2739
            av_free(s->mp3decctx[i]);
2740

    
2741
    return 0;
2742
}
2743

    
2744

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

    
2762
    len = buf_size;
2763

    
2764
    // Discard too short frames
2765
    if (buf_size < HEADER_SIZE) {
2766
        *data_size = 0;
2767
        return buf_size;
2768
    }
2769

    
2770
    // If only one decoder interleave is not needed
2771
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2772

    
2773
    for (fr = 0; fr < s->frames; fr++) {
2774
        start = start2;
2775
        fsize = (start[0] << 4) | (start[1] >> 4);
2776
        start2 += fsize;
2777
        if (fsize > len)
2778
            fsize = len;
2779
        len -= fsize;
2780
        if (fsize > MPA_MAX_CODED_FRAME_SIZE)
2781
            fsize = MPA_MAX_CODED_FRAME_SIZE;
2782
        m = s->mp3decctx[fr];
2783
        assert (m != NULL);
2784

    
2785
        // Get header
2786
        header = (start[0] << 24) | (start[1] << 16) | (start[2] << 8) | start[3] | 0xfff00000;
2787

    
2788
        if (ff_mpa_check_header(header) < 0) { // Bad header, discard block
2789
            *data_size = 0;
2790
            return buf_size;
2791
        }
2792

    
2793
        decode_header(m, header);
2794
        mp_decode_frame(m, decoded_buf, start, fsize);
2795

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

    
2816
    /* update codec info */
2817
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2818
    avctx->frame_size= buf_size;
2819
    avctx->bit_rate = 0;
2820
    for (i = 0; i < s->frames; i++)
2821
        avctx->bit_rate += s->mp3decctx[i]->bit_rate;
2822

    
2823
    *data_size = out_size;
2824
    return buf_size;
2825
}
2826

    
2827

    
2828
AVCodec mp2_decoder =
2829
{
2830
    "mp2",
2831
    CODEC_TYPE_AUDIO,
2832
    CODEC_ID_MP2,
2833
    sizeof(MPADecodeContext),
2834
    decode_init,
2835
    NULL,
2836
    NULL,
2837
    decode_frame,
2838
    CODEC_CAP_PARSE_ONLY,
2839
};
2840

    
2841
AVCodec mp3_decoder =
2842
{
2843
    "mp3",
2844
    CODEC_TYPE_AUDIO,
2845
    CODEC_ID_MP3,
2846
    sizeof(MPADecodeContext),
2847
    decode_init,
2848
    NULL,
2849
    NULL,
2850
    decode_frame,
2851
    CODEC_CAP_PARSE_ONLY,
2852
};
2853

    
2854
AVCodec mp3adu_decoder =
2855
{
2856
    "mp3adu",
2857
    CODEC_TYPE_AUDIO,
2858
    CODEC_ID_MP3ADU,
2859
    sizeof(MPADecodeContext),
2860
    decode_init,
2861
    NULL,
2862
    NULL,
2863
    decode_frame_adu,
2864
    CODEC_CAP_PARSE_ONLY,
2865
};
2866

    
2867
AVCodec mp3on4_decoder =
2868
{
2869
    "mp3on4",
2870
    CODEC_TYPE_AUDIO,
2871
    CODEC_ID_MP3ON4,
2872
    sizeof(MP3On4DecodeContext),
2873
    decode_init_mp3on4,
2874
    NULL,
2875
    decode_close_mp3on4,
2876
    decode_frame_mp3on4,
2877
    0
2878
};