Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ bbdf8728

History | View | Annotate | Download (81.2 KB)

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

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

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

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

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

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

    
47
#include "mathops.h"
48

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

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

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

    
57
#define HEADER_SIZE 4
58

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
239
    return m;
240
}
241

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

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

    
250
static int dev_4_3_coefs[DEV_ORDER];
251

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

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

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

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

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

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

    
324
    s->avctx = avctx;
325

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

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

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

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

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

    
365
        ff_mpa_synth_init(window);
366

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
497
                if(j==2 && i%3 != 1)
498
                    continue;
499

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

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

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

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

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

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

    
551
/* cos(i*pi/64) */
552

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

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

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

    
584
#define COS3_0 FIXHR(0.54119610014619698439/2)
585
#define COS3_1 FIXHR(1.30656296487637652785/4)
586

    
587
#define COS4_0 FIXHR(0.70710678118654752439/2)
588

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

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

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

    
615
#define ADD(a, b) tab[a] += tab[b]
616

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

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

    
666

    
667

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

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

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

    
723
    /* pass 6 */
724

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

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

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

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

    
776
#if FRAC_BITS <= 15
777

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

    
790
/* signed 16x16 -> 32 multiply add accumulate */
791
#define MACS(rt, ra, rb) MAC16(rt, ra, rb)
792

    
793
/* signed 16x16 -> 32 multiply */
794
#define MULS(ra, rb) MUL16(ra, rb)
795

    
796
#define MLSS(rt, ra, rb) MLS16(rt, ra, rb)
797

    
798
#else
799

    
800
static inline int round_sample(int64_t *sum)
801
{
802
    int sum1;
803
    sum1 = (int)((*sum) >> OUT_SHIFT);
804
    *sum &= (1<<OUT_SHIFT)-1;
805
    if (sum1 < OUT_MIN)
806
        sum1 = OUT_MIN;
807
    else if (sum1 > OUT_MAX)
808
        sum1 = OUT_MAX;
809
    return sum1;
810
}
811

    
812
#   define MULS(ra, rb) MUL64(ra, rb)
813
#   define MACS(rt, ra, rb) MAC64(rt, ra, rb)
814
#   define MLSS(rt, ra, rb) MLS64(rt, ra, rb)
815
#endif
816

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

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

    
858
void ff_mpa_synth_init(MPA_INT *window)
859
{
860
    int i;
861

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

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

    
896
    dct32(tmp, sb_samples);
897

    
898
    offset = *synth_buf_offset;
899
    synth_buf = synth_buf_ptr + offset;
900

    
901
    for(j=0;j<32;j++) {
902
        v = tmp[j];
903
#if FRAC_BITS <= 15
904
        /* NOTE: can cause a loss in precision if very high amplitude
905
           sound */
906
        v = av_clip_int16(v);
907
#endif
908
        synth_buf[j] = v;
909
    }
910
    /* copy to avoid wrap */
911
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
912

    
913
    samples2 = samples + 31 * incr;
914
    w = window;
915
    w2 = window + 31;
916

    
917
    sum = *dither_state;
918
    p = synth_buf + 16;
919
    SUM8(MACS, sum, w, p);
920
    p = synth_buf + 48;
921
    SUM8(MLSS, sum, w + 32, p);
922
    *samples = round_sample(&sum);
923
    samples += incr;
924
    w++;
925

    
926
    /* we calculate two samples at the same time to avoid one memory
927
       access per two sample */
928
    for(j=1;j<16;j++) {
929
        sum2 = 0;
930
        p = synth_buf + 16 + j;
931
        SUM8P2(sum, MACS, sum2, MLSS, w, w2, p);
932
        p = synth_buf + 48 - j;
933
        SUM8P2(sum, MLSS, sum2, MLSS, w + 32, w2 + 32, p);
934

    
935
        *samples = round_sample(&sum);
936
        samples += incr;
937
        sum += sum2;
938
        *samples2 = round_sample(&sum);
939
        samples2 -= incr;
940
        w++;
941
        w2--;
942
    }
943

    
944
    p = synth_buf + 32;
945
    SUM8(MLSS, sum, w + 32, p);
946
    *samples = round_sample(&sum);
947
    *dither_state= sum;
948

    
949
    offset = (offset - 32) & 511;
950
    *synth_buf_offset = offset;
951
}
952

    
953
#define C3 FIXHR(0.86602540378443864676/2)
954

    
955
/* 0.5 / cos(pi*(2*i+1)/36) */
956
static const int icos36[9] = {
957
    FIXR(0.50190991877167369479),
958
    FIXR(0.51763809020504152469), //0
959
    FIXR(0.55168895948124587824),
960
    FIXR(0.61038729438072803416),
961
    FIXR(0.70710678118654752439), //1
962
    FIXR(0.87172339781054900991),
963
    FIXR(1.18310079157624925896),
964
    FIXR(1.93185165257813657349), //2
965
    FIXR(5.73685662283492756461),
966
};
967

    
968
/* 0.5 / cos(pi*(2*i+1)/36) */
969
static const int icos36h[9] = {
970
    FIXHR(0.50190991877167369479/2),
971
    FIXHR(0.51763809020504152469/2), //0
972
    FIXHR(0.55168895948124587824/2),
973
    FIXHR(0.61038729438072803416/2),
974
    FIXHR(0.70710678118654752439/2), //1
975
    FIXHR(0.87172339781054900991/2),
976
    FIXHR(1.18310079157624925896/4),
977
    FIXHR(1.93185165257813657349/4), //2
978
//    FIXHR(5.73685662283492756461),
979
};
980

    
981
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
982
   cases. */
983
static void imdct12(int *out, int *in)
984
{
985
    int in0, in1, in2, in3, in4, in5, t1, t2;
986

    
987
    in0= in[0*3];
988
    in1= in[1*3] + in[0*3];
989
    in2= in[2*3] + in[1*3];
990
    in3= in[3*3] + in[2*3];
991
    in4= in[4*3] + in[3*3];
992
    in5= in[5*3] + in[4*3];
993
    in5 += in3;
994
    in3 += in1;
995

    
996
    in2= MULH(2*in2, C3);
997
    in3= MULH(4*in3, C3);
998

    
999
    t1 = in0 - in4;
1000
    t2 = MULH(2*(in1 - in5), icos36h[4]);
1001

    
1002
    out[ 7]=
1003
    out[10]= t1 + t2;
1004
    out[ 1]=
1005
    out[ 4]= t1 - t2;
1006

    
1007
    in0 += in4>>1;
1008
    in4 = in0 + in2;
1009
    in5 += 2*in1;
1010
    in1 = MULH(in5 + in3, icos36h[1]);
1011
    out[ 8]=
1012
    out[ 9]= in4 + in1;
1013
    out[ 2]=
1014
    out[ 3]= in4 - in1;
1015

    
1016
    in0 -= in2;
1017
    in5 = MULH(2*(in5 - in3), icos36h[7]);
1018
    out[ 0]=
1019
    out[ 5]= in0 - in5;
1020
    out[ 6]=
1021
    out[11]= in0 + in5;
1022
}
1023

    
1024
/* cos(pi*i/18) */
1025
#define C1 FIXHR(0.98480775301220805936/2)
1026
#define C2 FIXHR(0.93969262078590838405/2)
1027
#define C3 FIXHR(0.86602540378443864676/2)
1028
#define C4 FIXHR(0.76604444311897803520/2)
1029
#define C5 FIXHR(0.64278760968653932632/2)
1030
#define C6 FIXHR(0.5/2)
1031
#define C7 FIXHR(0.34202014332566873304/2)
1032
#define C8 FIXHR(0.17364817766693034885/2)
1033

    
1034

    
1035
/* using Lee like decomposition followed by hand coded 9 points DCT */
1036
static void imdct36(int *out, int *buf, int *in, int *win)
1037
{
1038
    int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
1039
    int tmp[18], *tmp1, *in1;
1040

    
1041
    for(i=17;i>=1;i--)
1042
        in[i] += in[i-1];
1043
    for(i=17;i>=3;i-=2)
1044
        in[i] += in[i-2];
1045

    
1046
    for(j=0;j<2;j++) {
1047
        tmp1 = tmp + j;
1048
        in1 = in + j;
1049
#if 0
1050
//more accurate but slower
1051
        int64_t t0, t1, t2, t3;
1052
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1053

1054
        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
1055
        t1 = in1[2*0] - in1[2*6];
1056
        tmp1[ 6] = t1 - (t2>>1);
1057
        tmp1[16] = t1 + t2;
1058

1059
        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
1060
        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
1061
        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
1062

1063
        tmp1[10] = (t3 - t0 - t2) >> 32;
1064
        tmp1[ 2] = (t3 + t0 + t1) >> 32;
1065
        tmp1[14] = (t3 + t2 - t1) >> 32;
1066

1067
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1068
        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
1069
        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
1070
        t0 = MUL64(2*in1[2*3], C3);
1071

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

1074
        tmp1[ 0] = (t2 + t3 + t0) >> 32;
1075
        tmp1[12] = (t2 + t1 - t0) >> 32;
1076
        tmp1[ 8] = (t3 - t1 - t0) >> 32;
1077
#else
1078
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1079

    
1080
        t3 = in1[2*0] + (in1[2*6]>>1);
1081
        t1 = in1[2*0] - in1[2*6];
1082
        tmp1[ 6] = t1 - (t2>>1);
1083
        tmp1[16] = t1 + t2;
1084

    
1085
        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1086
        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1087
        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1088

    
1089
        tmp1[10] = t3 - t0 - t2;
1090
        tmp1[ 2] = t3 + t0 + t1;
1091
        tmp1[14] = t3 + t2 - t1;
1092

    
1093
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1094
        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1095
        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1096
        t0 = MULH(2*in1[2*3], C3);
1097

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

    
1100
        tmp1[ 0] = t2 + t3 + t0;
1101
        tmp1[12] = t2 + t1 - t0;
1102
        tmp1[ 8] = t3 - t1 - t0;
1103
#endif
1104
    }
1105

    
1106
    i = 0;
1107
    for(j=0;j<4;j++) {
1108
        t0 = tmp[i];
1109
        t1 = tmp[i + 2];
1110
        s0 = t1 + t0;
1111
        s2 = t1 - t0;
1112

    
1113
        t2 = tmp[i + 1];
1114
        t3 = tmp[i + 3];
1115
        s1 = MULH(2*(t3 + t2), icos36h[j]);
1116
        s3 = MULL(t3 - t2, icos36[8 - j]);
1117

    
1118
        t0 = s0 + s1;
1119
        t1 = s0 - s1;
1120
        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1121
        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1122
        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1123
        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1124

    
1125
        t0 = s2 + s3;
1126
        t1 = s2 - s3;
1127
        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1128
        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1129
        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1130
        buf[      + j] = MULH(t0, win[18         + j]);
1131
        i += 4;
1132
    }
1133

    
1134
    s0 = tmp[16];
1135
    s1 = MULH(2*tmp[17], icos36h[4]);
1136
    t0 = s0 + s1;
1137
    t1 = s0 - s1;
1138
    out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
1139
    out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
1140
    buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
1141
    buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
1142
}
1143

    
1144
/* return the number of decoded frames */
1145
static int mp_decode_layer1(MPADecodeContext *s)
1146
{
1147
    int bound, i, v, n, ch, j, mant;
1148
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1149
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1150

    
1151
    if (s->mode == MPA_JSTEREO)
1152
        bound = (s->mode_ext + 1) * 4;
1153
    else
1154
        bound = SBLIMIT;
1155

    
1156
    /* allocation bits */
1157
    for(i=0;i<bound;i++) {
1158
        for(ch=0;ch<s->nb_channels;ch++) {
1159
            allocation[ch][i] = get_bits(&s->gb, 4);
1160
        }
1161
    }
1162
    for(i=bound;i<SBLIMIT;i++) {
1163
        allocation[0][i] = get_bits(&s->gb, 4);
1164
    }
1165

    
1166
    /* scale factors */
1167
    for(i=0;i<bound;i++) {
1168
        for(ch=0;ch<s->nb_channels;ch++) {
1169
            if (allocation[ch][i])
1170
                scale_factors[ch][i] = get_bits(&s->gb, 6);
1171
        }
1172
    }
1173
    for(i=bound;i<SBLIMIT;i++) {
1174
        if (allocation[0][i]) {
1175
            scale_factors[0][i] = get_bits(&s->gb, 6);
1176
            scale_factors[1][i] = get_bits(&s->gb, 6);
1177
        }
1178
    }
1179

    
1180
    /* compute samples */
1181
    for(j=0;j<12;j++) {
1182
        for(i=0;i<bound;i++) {
1183
            for(ch=0;ch<s->nb_channels;ch++) {
1184
                n = allocation[ch][i];
1185
                if (n) {
1186
                    mant = get_bits(&s->gb, n + 1);
1187
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
1188
                } else {
1189
                    v = 0;
1190
                }
1191
                s->sb_samples[ch][j][i] = v;
1192
            }
1193
        }
1194
        for(i=bound;i<SBLIMIT;i++) {
1195
            n = allocation[0][i];
1196
            if (n) {
1197
                mant = get_bits(&s->gb, n + 1);
1198
                v = l1_unscale(n, mant, scale_factors[0][i]);
1199
                s->sb_samples[0][j][i] = v;
1200
                v = l1_unscale(n, mant, scale_factors[1][i]);
1201
                s->sb_samples[1][j][i] = v;
1202
            } else {
1203
                s->sb_samples[0][j][i] = 0;
1204
                s->sb_samples[1][j][i] = 0;
1205
            }
1206
        }
1207
    }
1208
    return 12;
1209
}
1210

    
1211
static int mp_decode_layer2(MPADecodeContext *s)
1212
{
1213
    int sblimit; /* number of used subbands */
1214
    const unsigned char *alloc_table;
1215
    int table, bit_alloc_bits, i, j, ch, bound, v;
1216
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1217
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1218
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1219
    int scale, qindex, bits, steps, k, l, m, b;
1220

    
1221
    /* select decoding table */
1222
    table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
1223
                            s->sample_rate, s->lsf);
1224
    sblimit = ff_mpa_sblimit_table[table];
1225
    alloc_table = ff_mpa_alloc_tables[table];
1226

    
1227
    if (s->mode == MPA_JSTEREO)
1228
        bound = (s->mode_ext + 1) * 4;
1229
    else
1230
        bound = sblimit;
1231

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

    
1234
    /* sanity check */
1235
    if( bound > sblimit ) bound = sblimit;
1236

    
1237
    /* parse bit allocation */
1238
    j = 0;
1239
    for(i=0;i<bound;i++) {
1240
        bit_alloc_bits = alloc_table[j];
1241
        for(ch=0;ch<s->nb_channels;ch++) {
1242
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1243
        }
1244
        j += 1 << bit_alloc_bits;
1245
    }
1246
    for(i=bound;i<sblimit;i++) {
1247
        bit_alloc_bits = alloc_table[j];
1248
        v = get_bits(&s->gb, bit_alloc_bits);
1249
        bit_alloc[0][i] = v;
1250
        bit_alloc[1][i] = v;
1251
        j += 1 << bit_alloc_bits;
1252
    }
1253

    
1254
#ifdef DEBUG
1255
    {
1256
        for(ch=0;ch<s->nb_channels;ch++) {
1257
            for(i=0;i<sblimit;i++)
1258
                dprintf(s->avctx, " %d", bit_alloc[ch][i]);
1259
            dprintf(s->avctx, "\n");
1260
        }
1261
    }
1262
#endif
1263

    
1264
    /* scale codes */
1265
    for(i=0;i<sblimit;i++) {
1266
        for(ch=0;ch<s->nb_channels;ch++) {
1267
            if (bit_alloc[ch][i])
1268
                scale_code[ch][i] = get_bits(&s->gb, 2);
1269
        }
1270
    }
1271

    
1272
    /* scale factors */
1273
    for(i=0;i<sblimit;i++) {
1274
        for(ch=0;ch<s->nb_channels;ch++) {
1275
            if (bit_alloc[ch][i]) {
1276
                sf = scale_factors[ch][i];
1277
                switch(scale_code[ch][i]) {
1278
                default:
1279
                case 0:
1280
                    sf[0] = get_bits(&s->gb, 6);
1281
                    sf[1] = get_bits(&s->gb, 6);
1282
                    sf[2] = get_bits(&s->gb, 6);
1283
                    break;
1284
                case 2:
1285
                    sf[0] = get_bits(&s->gb, 6);
1286
                    sf[1] = sf[0];
1287
                    sf[2] = sf[0];
1288
                    break;
1289
                case 1:
1290
                    sf[0] = get_bits(&s->gb, 6);
1291
                    sf[2] = get_bits(&s->gb, 6);
1292
                    sf[1] = sf[0];
1293
                    break;
1294
                case 3:
1295
                    sf[0] = get_bits(&s->gb, 6);
1296
                    sf[2] = get_bits(&s->gb, 6);
1297
                    sf[1] = sf[2];
1298
                    break;
1299
                }
1300
            }
1301
        }
1302
    }
1303

    
1304
#ifdef DEBUG
1305
    for(ch=0;ch<s->nb_channels;ch++) {
1306
        for(i=0;i<sblimit;i++) {
1307
            if (bit_alloc[ch][i]) {
1308
                sf = scale_factors[ch][i];
1309
                dprintf(s->avctx, " %d %d %d", sf[0], sf[1], sf[2]);
1310
            } else {
1311
                dprintf(s->avctx, " -");
1312
            }
1313
        }
1314
        dprintf(s->avctx, "\n");
1315
    }
1316
#endif
1317

    
1318
    /* samples */
1319
    for(k=0;k<3;k++) {
1320
        for(l=0;l<12;l+=3) {
1321
            j = 0;
1322
            for(i=0;i<bound;i++) {
1323
                bit_alloc_bits = alloc_table[j];
1324
                for(ch=0;ch<s->nb_channels;ch++) {
1325
                    b = bit_alloc[ch][i];
1326
                    if (b) {
1327
                        scale = scale_factors[ch][i][k];
1328
                        qindex = alloc_table[j+b];
1329
                        bits = ff_mpa_quant_bits[qindex];
1330
                        if (bits < 0) {
1331
                            /* 3 values at the same time */
1332
                            v = get_bits(&s->gb, -bits);
1333
                            steps = ff_mpa_quant_steps[qindex];
1334
                            s->sb_samples[ch][k * 12 + l + 0][i] =
1335
                                l2_unscale_group(steps, v % steps, scale);
1336
                            v = v / steps;
1337
                            s->sb_samples[ch][k * 12 + l + 1][i] =
1338
                                l2_unscale_group(steps, v % steps, scale);
1339
                            v = v / steps;
1340
                            s->sb_samples[ch][k * 12 + l + 2][i] =
1341
                                l2_unscale_group(steps, v, scale);
1342
                        } else {
1343
                            for(m=0;m<3;m++) {
1344
                                v = get_bits(&s->gb, bits);
1345
                                v = l1_unscale(bits - 1, v, scale);
1346
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
1347
                            }
1348
                        }
1349
                    } else {
1350
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1351
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1352
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1353
                    }
1354
                }
1355
                /* next subband in alloc table */
1356
                j += 1 << bit_alloc_bits;
1357
            }
1358
            /* XXX: find a way to avoid this duplication of code */
1359
            for(i=bound;i<sblimit;i++) {
1360
                bit_alloc_bits = alloc_table[j];
1361
                b = bit_alloc[0][i];
1362
                if (b) {
1363
                    int mant, scale0, scale1;
1364
                    scale0 = scale_factors[0][i][k];
1365
                    scale1 = scale_factors[1][i][k];
1366
                    qindex = alloc_table[j+b];
1367
                    bits = ff_mpa_quant_bits[qindex];
1368
                    if (bits < 0) {
1369
                        /* 3 values at the same time */
1370
                        v = get_bits(&s->gb, -bits);
1371
                        steps = ff_mpa_quant_steps[qindex];
1372
                        mant = v % steps;
1373
                        v = v / steps;
1374
                        s->sb_samples[0][k * 12 + l + 0][i] =
1375
                            l2_unscale_group(steps, mant, scale0);
1376
                        s->sb_samples[1][k * 12 + l + 0][i] =
1377
                            l2_unscale_group(steps, mant, scale1);
1378
                        mant = v % steps;
1379
                        v = v / steps;
1380
                        s->sb_samples[0][k * 12 + l + 1][i] =
1381
                            l2_unscale_group(steps, mant, scale0);
1382
                        s->sb_samples[1][k * 12 + l + 1][i] =
1383
                            l2_unscale_group(steps, mant, scale1);
1384
                        s->sb_samples[0][k * 12 + l + 2][i] =
1385
                            l2_unscale_group(steps, v, scale0);
1386
                        s->sb_samples[1][k * 12 + l + 2][i] =
1387
                            l2_unscale_group(steps, v, scale1);
1388
                    } else {
1389
                        for(m=0;m<3;m++) {
1390
                            mant = get_bits(&s->gb, bits);
1391
                            s->sb_samples[0][k * 12 + l + m][i] =
1392
                                l1_unscale(bits - 1, mant, scale0);
1393
                            s->sb_samples[1][k * 12 + l + m][i] =
1394
                                l1_unscale(bits - 1, mant, scale1);
1395
                        }
1396
                    }
1397
                } else {
1398
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
1399
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
1400
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
1401
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
1402
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
1403
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
1404
                }
1405
                /* next subband in alloc table */
1406
                j += 1 << bit_alloc_bits;
1407
            }
1408
            /* fill remaining samples to zero */
1409
            for(i=sblimit;i<SBLIMIT;i++) {
1410
                for(ch=0;ch<s->nb_channels;ch++) {
1411
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1412
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1413
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1414
                }
1415
            }
1416
        }
1417
    }
1418
    return 3 * 12;
1419
}
1420

    
1421
static inline void lsf_sf_expand(int *slen,
1422
                                 int sf, int n1, int n2, int n3)
1423
{
1424
    if (n3) {
1425
        slen[3] = sf % n3;
1426
        sf /= n3;
1427
    } else {
1428
        slen[3] = 0;
1429
    }
1430
    if (n2) {
1431
        slen[2] = sf % n2;
1432
        sf /= n2;
1433
    } else {
1434
        slen[2] = 0;
1435
    }
1436
    slen[1] = sf % n1;
1437
    sf /= n1;
1438
    slen[0] = sf;
1439
}
1440

    
1441
static void exponents_from_scale_factors(MPADecodeContext *s,
1442
                                         GranuleDef *g,
1443
                                         int16_t *exponents)
1444
{
1445
    const uint8_t *bstab, *pretab;
1446
    int len, i, j, k, l, v0, shift, gain, gains[3];
1447
    int16_t *exp_ptr;
1448

    
1449
    exp_ptr = exponents;
1450
    gain = g->global_gain - 210;
1451
    shift = g->scalefac_scale + 1;
1452

    
1453
    bstab = band_size_long[s->sample_rate_index];
1454
    pretab = mpa_pretab[g->preflag];
1455
    for(i=0;i<g->long_end;i++) {
1456
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1457
        len = bstab[i];
1458
        for(j=len;j>0;j--)
1459
            *exp_ptr++ = v0;
1460
    }
1461

    
1462
    if (g->short_start < 13) {
1463
        bstab = band_size_short[s->sample_rate_index];
1464
        gains[0] = gain - (g->subblock_gain[0] << 3);
1465
        gains[1] = gain - (g->subblock_gain[1] << 3);
1466
        gains[2] = gain - (g->subblock_gain[2] << 3);
1467
        k = g->long_end;
1468
        for(i=g->short_start;i<13;i++) {
1469
            len = bstab[i];
1470
            for(l=0;l<3;l++) {
1471
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1472
                for(j=len;j>0;j--)
1473
                *exp_ptr++ = v0;
1474
            }
1475
        }
1476
    }
1477
}
1478

    
1479
/* handle n = 0 too */
1480
static inline int get_bitsz(GetBitContext *s, int n)
1481
{
1482
    if (n == 0)
1483
        return 0;
1484
    else
1485
        return get_bits(s, n);
1486
}
1487

    
1488

    
1489
static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos, int *end_pos2){
1490
    if(s->in_gb.buffer && *pos >= s->gb.size_in_bits){
1491
        s->gb= s->in_gb;
1492
        s->in_gb.buffer=NULL;
1493
        assert((get_bits_count(&s->gb) & 7) == 0);
1494
        skip_bits_long(&s->gb, *pos - *end_pos);
1495
        *end_pos2=
1496
        *end_pos= *end_pos2 + get_bits_count(&s->gb) - *pos;
1497
        *pos= get_bits_count(&s->gb);
1498
    }
1499
}
1500

    
1501
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1502
                          int16_t *exponents, int end_pos2)
1503
{
1504
    int s_index;
1505
    int i;
1506
    int last_pos, bits_left;
1507
    VLC *vlc;
1508
    int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1509

    
1510
    /* low frequencies (called big values) */
1511
    s_index = 0;
1512
    for(i=0;i<3;i++) {
1513
        int j, k, l, linbits;
1514
        j = g->region_size[i];
1515
        if (j == 0)
1516
            continue;
1517
        /* select vlc table */
1518
        k = g->table_select[i];
1519
        l = mpa_huff_data[k][0];
1520
        linbits = mpa_huff_data[k][1];
1521
        vlc = &huff_vlc[l];
1522

    
1523
        if(!l){
1524
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1525
            s_index += 2*j;
1526
            continue;
1527
        }
1528

    
1529
        /* read huffcode and compute each couple */
1530
        for(;j>0;j--) {
1531
            int exponent, x, y, v;
1532
            int pos= get_bits_count(&s->gb);
1533

    
1534
            if (pos >= end_pos){
1535
//                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1536
                switch_buffer(s, &pos, &end_pos, &end_pos2);
1537
//                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1538
                if(pos >= end_pos)
1539
                    break;
1540
            }
1541
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
1542

    
1543
            if(!y){
1544
                g->sb_hybrid[s_index  ] =
1545
                g->sb_hybrid[s_index+1] = 0;
1546
                s_index += 2;
1547
                continue;
1548
            }
1549

    
1550
            exponent= exponents[s_index];
1551

    
1552
            dprintf(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
1553
                    i, g->region_size[i] - j, x, y, exponent);
1554
            if(y&16){
1555
                x = y >> 5;
1556
                y = y & 0x0f;
1557
                if (x < 15){
1558
                    v = expval_table[ exponent ][ x ];
1559
//                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
1560
                }else{
1561
                    x += get_bitsz(&s->gb, linbits);
1562
                    v = l3_unscale(x, exponent);
1563
                }
1564
                if (get_bits1(&s->gb))
1565
                    v = -v;
1566
                g->sb_hybrid[s_index] = v;
1567
                if (y < 15){
1568
                    v = expval_table[ exponent ][ y ];
1569
                }else{
1570
                    y += get_bitsz(&s->gb, linbits);
1571
                    v = l3_unscale(y, exponent);
1572
                }
1573
                if (get_bits1(&s->gb))
1574
                    v = -v;
1575
                g->sb_hybrid[s_index+1] = v;
1576
            }else{
1577
                x = y >> 5;
1578
                y = y & 0x0f;
1579
                x += y;
1580
                if (x < 15){
1581
                    v = expval_table[ exponent ][ x ];
1582
                }else{
1583
                    x += get_bitsz(&s->gb, linbits);
1584
                    v = l3_unscale(x, exponent);
1585
                }
1586
                if (get_bits1(&s->gb))
1587
                    v = -v;
1588
                g->sb_hybrid[s_index+!!y] = v;
1589
                g->sb_hybrid[s_index+ !y] = 0;
1590
            }
1591
            s_index+=2;
1592
        }
1593
    }
1594

    
1595
    /* high frequencies */
1596
    vlc = &huff_quad_vlc[g->count1table_select];
1597
    last_pos=0;
1598
    while (s_index <= 572) {
1599
        int pos, code;
1600
        pos = get_bits_count(&s->gb);
1601
        if (pos >= end_pos) {
1602
            if (pos > end_pos2 && last_pos){
1603
                /* some encoders generate an incorrect size for this
1604
                   part. We must go back into the data */
1605
                s_index -= 4;
1606
                skip_bits_long(&s->gb, last_pos - pos);
1607
                av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1608
                if(s->error_resilience >= FF_ER_COMPLIANT)
1609
                    s_index=0;
1610
                break;
1611
            }
1612
//                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1613
            switch_buffer(s, &pos, &end_pos, &end_pos2);
1614
//                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1615
            if(pos >= end_pos)
1616
                break;
1617
        }
1618
        last_pos= pos;
1619

    
1620
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1621
        dprintf(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1622
        g->sb_hybrid[s_index+0]=
1623
        g->sb_hybrid[s_index+1]=
1624
        g->sb_hybrid[s_index+2]=
1625
        g->sb_hybrid[s_index+3]= 0;
1626
        while(code){
1627
            static const int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1628
            int v;
1629
            int pos= s_index+idxtab[code];
1630
            code ^= 8>>idxtab[code];
1631
            v = exp_table[ exponents[pos] ];
1632
//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1633
            if(get_bits1(&s->gb))
1634
                v = -v;
1635
            g->sb_hybrid[pos] = v;
1636
        }
1637
        s_index+=4;
1638
    }
1639
    /* skip extension bits */
1640
    bits_left = end_pos2 - get_bits_count(&s->gb);
1641
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1642
    if (bits_left < 0/* || bits_left > 500*/) {
1643
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1644
        s_index=0;
1645
    }else if(bits_left > 0 && s->error_resilience >= FF_ER_AGGRESSIVE){
1646
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1647
        s_index=0;
1648
    }
1649
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1650
    skip_bits_long(&s->gb, bits_left);
1651

    
1652
    i= get_bits_count(&s->gb);
1653
    switch_buffer(s, &i, &end_pos, &end_pos2);
1654

    
1655
    return 0;
1656
}
1657

    
1658
/* Reorder short blocks from bitstream order to interleaved order. It
1659
   would be faster to do it in parsing, but the code would be far more
1660
   complicated */
1661
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1662
{
1663
    int i, j, len;
1664
    int32_t *ptr, *dst, *ptr1;
1665
    int32_t tmp[576];
1666

    
1667
    if (g->block_type != 2)
1668
        return;
1669

    
1670
    if (g->switch_point) {
1671
        if (s->sample_rate_index != 8) {
1672
            ptr = g->sb_hybrid + 36;
1673
        } else {
1674
            ptr = g->sb_hybrid + 48;
1675
        }
1676
    } else {
1677
        ptr = g->sb_hybrid;
1678
    }
1679

    
1680
    for(i=g->short_start;i<13;i++) {
1681
        len = band_size_short[s->sample_rate_index][i];
1682
        ptr1 = ptr;
1683
        dst = tmp;
1684
        for(j=len;j>0;j--) {
1685
            *dst++ = ptr[0*len];
1686
            *dst++ = ptr[1*len];
1687
            *dst++ = ptr[2*len];
1688
            ptr++;
1689
        }
1690
        ptr+=2*len;
1691
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1692
    }
1693
}
1694

    
1695
#define ISQRT2 FIXR(0.70710678118654752440)
1696

    
1697
static void compute_stereo(MPADecodeContext *s,
1698
                           GranuleDef *g0, GranuleDef *g1)
1699
{
1700
    int i, j, k, l;
1701
    int32_t v1, v2;
1702
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1703
    int32_t (*is_tab)[16];
1704
    int32_t *tab0, *tab1;
1705
    int non_zero_found_short[3];
1706

    
1707
    /* intensity stereo */
1708
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1709
        if (!s->lsf) {
1710
            is_tab = is_table;
1711
            sf_max = 7;
1712
        } else {
1713
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1714
            sf_max = 16;
1715
        }
1716

    
1717
        tab0 = g0->sb_hybrid + 576;
1718
        tab1 = g1->sb_hybrid + 576;
1719

    
1720
        non_zero_found_short[0] = 0;
1721
        non_zero_found_short[1] = 0;
1722
        non_zero_found_short[2] = 0;
1723
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1724
        for(i = 12;i >= g1->short_start;i--) {
1725
            /* for last band, use previous scale factor */
1726
            if (i != 11)
1727
                k -= 3;
1728
            len = band_size_short[s->sample_rate_index][i];
1729
            for(l=2;l>=0;l--) {
1730
                tab0 -= len;
1731
                tab1 -= len;
1732
                if (!non_zero_found_short[l]) {
1733
                    /* test if non zero band. if so, stop doing i-stereo */
1734
                    for(j=0;j<len;j++) {
1735
                        if (tab1[j] != 0) {
1736
                            non_zero_found_short[l] = 1;
1737
                            goto found1;
1738
                        }
1739
                    }
1740
                    sf = g1->scale_factors[k + l];
1741
                    if (sf >= sf_max)
1742
                        goto found1;
1743

    
1744
                    v1 = is_tab[0][sf];
1745
                    v2 = is_tab[1][sf];
1746
                    for(j=0;j<len;j++) {
1747
                        tmp0 = tab0[j];
1748
                        tab0[j] = MULL(tmp0, v1);
1749
                        tab1[j] = MULL(tmp0, v2);
1750
                    }
1751
                } else {
1752
                found1:
1753
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1754
                        /* lower part of the spectrum : do ms stereo
1755
                           if enabled */
1756
                        for(j=0;j<len;j++) {
1757
                            tmp0 = tab0[j];
1758
                            tmp1 = tab1[j];
1759
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1760
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1761
                        }
1762
                    }
1763
                }
1764
            }
1765
        }
1766

    
1767
        non_zero_found = non_zero_found_short[0] |
1768
            non_zero_found_short[1] |
1769
            non_zero_found_short[2];
1770

    
1771
        for(i = g1->long_end - 1;i >= 0;i--) {
1772
            len = band_size_long[s->sample_rate_index][i];
1773
            tab0 -= len;
1774
            tab1 -= len;
1775
            /* test if non zero band. if so, stop doing i-stereo */
1776
            if (!non_zero_found) {
1777
                for(j=0;j<len;j++) {
1778
                    if (tab1[j] != 0) {
1779
                        non_zero_found = 1;
1780
                        goto found2;
1781
                    }
1782
                }
1783
                /* for last band, use previous scale factor */
1784
                k = (i == 21) ? 20 : i;
1785
                sf = g1->scale_factors[k];
1786
                if (sf >= sf_max)
1787
                    goto found2;
1788
                v1 = is_tab[0][sf];
1789
                v2 = is_tab[1][sf];
1790
                for(j=0;j<len;j++) {
1791
                    tmp0 = tab0[j];
1792
                    tab0[j] = MULL(tmp0, v1);
1793
                    tab1[j] = MULL(tmp0, v2);
1794
                }
1795
            } else {
1796
            found2:
1797
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1798
                    /* lower part of the spectrum : do ms stereo
1799
                       if enabled */
1800
                    for(j=0;j<len;j++) {
1801
                        tmp0 = tab0[j];
1802
                        tmp1 = tab1[j];
1803
                        tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1804
                        tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1805
                    }
1806
                }
1807
            }
1808
        }
1809
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1810
        /* ms stereo ONLY */
1811
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1812
           global gain */
1813
        tab0 = g0->sb_hybrid;
1814
        tab1 = g1->sb_hybrid;
1815
        for(i=0;i<576;i++) {
1816
            tmp0 = tab0[i];
1817
            tmp1 = tab1[i];
1818
            tab0[i] = tmp0 + tmp1;
1819
            tab1[i] = tmp0 - tmp1;
1820
        }
1821
    }
1822
}
1823

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

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

    
1840
    ptr = g->sb_hybrid + 18;
1841
    for(i = n;i > 0;i--) {
1842
        int tmp0, tmp1, tmp2;
1843
        csa = &csa_table[0][0];
1844
#define INT_AA(j) \
1845
            tmp0 = ptr[-1-j];\
1846
            tmp1 = ptr[   j];\
1847
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1848
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1849
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1850

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

    
1860
        ptr += 18;
1861
    }
1862
}
1863

    
1864
static void compute_antialias_float(MPADecodeContext *s,
1865
                              GranuleDef *g)
1866
{
1867
    int32_t *ptr;
1868
    int n, i;
1869

    
1870
    /* we antialias only "long" bands */
1871
    if (g->block_type == 2) {
1872
        if (!g->switch_point)
1873
            return;
1874
        /* XXX: check this for 8000Hz case */
1875
        n = 1;
1876
    } else {
1877
        n = SBLIMIT - 1;
1878
    }
1879

    
1880
    ptr = g->sb_hybrid + 18;
1881
    for(i = n;i > 0;i--) {
1882
        float tmp0, tmp1;
1883
        float *csa = &csa_table_float[0][0];
1884
#define FLOAT_AA(j)\
1885
        tmp0= ptr[-1-j];\
1886
        tmp1= ptr[   j];\
1887
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1888
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1889

    
1890
        FLOAT_AA(0)
1891
        FLOAT_AA(1)
1892
        FLOAT_AA(2)
1893
        FLOAT_AA(3)
1894
        FLOAT_AA(4)
1895
        FLOAT_AA(5)
1896
        FLOAT_AA(6)
1897
        FLOAT_AA(7)
1898

    
1899
        ptr += 18;
1900
    }
1901
}
1902

    
1903
static void compute_imdct(MPADecodeContext *s,
1904
                          GranuleDef *g,
1905
                          int32_t *sb_samples,
1906
                          int32_t *mdct_buf)
1907
{
1908
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
1909
    int32_t out2[12];
1910
    int i, j, mdct_long_end, v, sblimit;
1911

    
1912
    /* find last non zero block */
1913
    ptr = g->sb_hybrid + 576;
1914
    ptr1 = g->sb_hybrid + 2 * 18;
1915
    while (ptr >= ptr1) {
1916
        ptr -= 6;
1917
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
1918
        if (v != 0)
1919
            break;
1920
    }
1921
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1922

    
1923
    if (g->block_type == 2) {
1924
        /* XXX: check for 8000 Hz */
1925
        if (g->switch_point)
1926
            mdct_long_end = 2;
1927
        else
1928
            mdct_long_end = 0;
1929
    } else {
1930
        mdct_long_end = sblimit;
1931
    }
1932

    
1933
    buf = mdct_buf;
1934
    ptr = g->sb_hybrid;
1935
    for(j=0;j<mdct_long_end;j++) {
1936
        /* apply window & overlap with previous buffer */
1937
        out_ptr = sb_samples + j;
1938
        /* select window */
1939
        if (g->switch_point && j < 2)
1940
            win1 = mdct_win[0];
1941
        else
1942
            win1 = mdct_win[g->block_type];
1943
        /* select frequency inversion */
1944
        win = win1 + ((4 * 36) & -(j & 1));
1945
        imdct36(out_ptr, buf, ptr, win);
1946
        out_ptr += 18*SBLIMIT;
1947
        ptr += 18;
1948
        buf += 18;
1949
    }
1950
    for(j=mdct_long_end;j<sblimit;j++) {
1951
        /* select frequency inversion */
1952
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
1953
        out_ptr = sb_samples + j;
1954

    
1955
        for(i=0; i<6; i++){
1956
            *out_ptr = buf[i];
1957
            out_ptr += SBLIMIT;
1958
        }
1959
        imdct12(out2, ptr + 0);
1960
        for(i=0;i<6;i++) {
1961
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
1962
            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
1963
            out_ptr += SBLIMIT;
1964
        }
1965
        imdct12(out2, ptr + 1);
1966
        for(i=0;i<6;i++) {
1967
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
1968
            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
1969
            out_ptr += SBLIMIT;
1970
        }
1971
        imdct12(out2, ptr + 2);
1972
        for(i=0;i<6;i++) {
1973
            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
1974
            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
1975
            buf[i + 6*2] = 0;
1976
        }
1977
        ptr += 18;
1978
        buf += 18;
1979
    }
1980
    /* zero bands */
1981
    for(j=sblimit;j<SBLIMIT;j++) {
1982
        /* overlap */
1983
        out_ptr = sb_samples + j;
1984
        for(i=0;i<18;i++) {
1985
            *out_ptr = buf[i];
1986
            buf[i] = 0;
1987
            out_ptr += SBLIMIT;
1988
        }
1989
        buf += 18;
1990
    }
1991
}
1992

    
1993
#if defined(DEBUG)
1994
void sample_dump(int fnum, int32_t *tab, int n)
1995
{
1996
    static FILE *files[16], *f;
1997
    char buf[512];
1998
    int i;
1999
    int32_t v;
2000

    
2001
    f = files[fnum];
2002
    if (!f) {
2003
        snprintf(buf, sizeof(buf), "/tmp/out%d.%s.pcm",
2004
                fnum,
2005
#ifdef USE_HIGHPRECISION
2006
                "hp"
2007
#else
2008
                "lp"
2009
#endif
2010
                );
2011
        f = fopen(buf, "w");
2012
        if (!f)
2013
            return;
2014
        files[fnum] = f;
2015
    }
2016

    
2017
    if (fnum == 0) {
2018
        static int pos = 0;
2019
        av_log(NULL, AV_LOG_DEBUG, "pos=%d\n", pos);
2020
        for(i=0;i<n;i++) {
2021
            av_log(NULL, AV_LOG_DEBUG, " %0.4f", (double)tab[i] / FRAC_ONE);
2022
            if ((i % 18) == 17)
2023
                av_log(NULL, AV_LOG_DEBUG, "\n");
2024
        }
2025
        pos += n;
2026
    }
2027
    for(i=0;i<n;i++) {
2028
        /* normalize to 23 frac bits */
2029
        v = tab[i] << (23 - FRAC_BITS);
2030
        fwrite(&v, 1, sizeof(int32_t), f);
2031
    }
2032
}
2033
#endif
2034

    
2035

    
2036
/* main layer3 decoding function */
2037
static int mp_decode_layer3(MPADecodeContext *s)
2038
{
2039
    int nb_granules, main_data_begin, private_bits;
2040
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
2041
    GranuleDef granules[2][2], *g;
2042
    int16_t exponents[576];
2043

    
2044
    /* read side info */
2045
    if (s->lsf) {
2046
        main_data_begin = get_bits(&s->gb, 8);
2047
        private_bits = get_bits(&s->gb, s->nb_channels);
2048
        nb_granules = 1;
2049
    } else {
2050
        main_data_begin = get_bits(&s->gb, 9);
2051
        if (s->nb_channels == 2)
2052
            private_bits = get_bits(&s->gb, 3);
2053
        else
2054
            private_bits = get_bits(&s->gb, 5);
2055
        nb_granules = 2;
2056
        for(ch=0;ch<s->nb_channels;ch++) {
2057
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
2058
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
2059
        }
2060
    }
2061

    
2062
    for(gr=0;gr<nb_granules;gr++) {
2063
        for(ch=0;ch<s->nb_channels;ch++) {
2064
            dprintf(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
2065
            g = &granules[ch][gr];
2066
            g->part2_3_length = get_bits(&s->gb, 12);
2067
            g->big_values = get_bits(&s->gb, 9);
2068
            if(g->big_values > 288){
2069
                av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
2070
                return -1;
2071
            }
2072

    
2073
            g->global_gain = get_bits(&s->gb, 8);
2074
            /* if MS stereo only is selected, we precompute the
2075
               1/sqrt(2) renormalization factor */
2076
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
2077
                MODE_EXT_MS_STEREO)
2078
                g->global_gain -= 2;
2079
            if (s->lsf)
2080
                g->scalefac_compress = get_bits(&s->gb, 9);
2081
            else
2082
                g->scalefac_compress = get_bits(&s->gb, 4);
2083
            blocksplit_flag = get_bits1(&s->gb);
2084
            if (blocksplit_flag) {
2085
                g->block_type = get_bits(&s->gb, 2);
2086
                if (g->block_type == 0){
2087
                    av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
2088
                    return -1;
2089
                }
2090
                g->switch_point = get_bits1(&s->gb);
2091
                for(i=0;i<2;i++)
2092
                    g->table_select[i] = get_bits(&s->gb, 5);
2093
                for(i=0;i<3;i++)
2094
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
2095
                ff_init_short_region(s, g);
2096
            } else {
2097
                int region_address1, region_address2;
2098
                g->block_type = 0;
2099
                g->switch_point = 0;
2100
                for(i=0;i<3;i++)
2101
                    g->table_select[i] = get_bits(&s->gb, 5);
2102
                /* compute huffman coded region sizes */
2103
                region_address1 = get_bits(&s->gb, 4);
2104
                region_address2 = get_bits(&s->gb, 3);
2105
                dprintf(s->avctx, "region1=%d region2=%d\n",
2106
                        region_address1, region_address2);
2107
                ff_init_long_region(s, g, region_address1, region_address2);
2108
            }
2109
            ff_region_offset2size(g);
2110
            ff_compute_band_indexes(s, g);
2111

    
2112
            g->preflag = 0;
2113
            if (!s->lsf)
2114
                g->preflag = get_bits1(&s->gb);
2115
            g->scalefac_scale = get_bits1(&s->gb);
2116
            g->count1table_select = get_bits1(&s->gb);
2117
            dprintf(s->avctx, "block_type=%d switch_point=%d\n",
2118
                    g->block_type, g->switch_point);
2119
        }
2120
    }
2121

    
2122
  if (!s->adu_mode) {
2123
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2124
    assert((get_bits_count(&s->gb) & 7) == 0);
2125
    /* now we get bits from the main_data_begin offset */
2126
    dprintf(s->avctx, "seekback: %d\n", main_data_begin);
2127
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2128

    
2129
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2130
    s->in_gb= s->gb;
2131
        init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
2132
        skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
2133
  }
2134

    
2135
    for(gr=0;gr<nb_granules;gr++) {
2136
        for(ch=0;ch<s->nb_channels;ch++) {
2137
            g = &granules[ch][gr];
2138
            if(get_bits_count(&s->gb)<0){
2139
                av_log(s->avctx, AV_LOG_ERROR, "mdb:%d, lastbuf:%d skipping granule %d\n",
2140
                                            main_data_begin, s->last_buf_size, gr);
2141
                skip_bits_long(&s->gb, g->part2_3_length);
2142
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
2143
                if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer){
2144
                    skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
2145
                    s->gb= s->in_gb;
2146
                    s->in_gb.buffer=NULL;
2147
                }
2148
                continue;
2149
            }
2150

    
2151
            bits_pos = get_bits_count(&s->gb);
2152

    
2153
            if (!s->lsf) {
2154
                uint8_t *sc;
2155
                int slen, slen1, slen2;
2156

    
2157
                /* MPEG1 scale factors */
2158
                slen1 = slen_table[0][g->scalefac_compress];
2159
                slen2 = slen_table[1][g->scalefac_compress];
2160
                dprintf(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
2161
                if (g->block_type == 2) {
2162
                    n = g->switch_point ? 17 : 18;
2163
                    j = 0;
2164
                    if(slen1){
2165
                        for(i=0;i<n;i++)
2166
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
2167
                    }else{
2168
                        for(i=0;i<n;i++)
2169
                            g->scale_factors[j++] = 0;
2170
                    }
2171
                    if(slen2){
2172
                        for(i=0;i<18;i++)
2173
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
2174
                        for(i=0;i<3;i++)
2175
                            g->scale_factors[j++] = 0;
2176
                    }else{
2177
                        for(i=0;i<21;i++)
2178
                            g->scale_factors[j++] = 0;
2179
                    }
2180
                } else {
2181
                    sc = granules[ch][0].scale_factors;
2182
                    j = 0;
2183
                    for(k=0;k<4;k++) {
2184
                        n = (k == 0 ? 6 : 5);
2185
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2186
                            slen = (k < 2) ? slen1 : slen2;
2187
                            if(slen){
2188
                                for(i=0;i<n;i++)
2189
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
2190
                            }else{
2191
                                for(i=0;i<n;i++)
2192
                                    g->scale_factors[j++] = 0;
2193
                            }
2194
                        } else {
2195
                            /* simply copy from last granule */
2196
                            for(i=0;i<n;i++) {
2197
                                g->scale_factors[j] = sc[j];
2198
                                j++;
2199
                            }
2200
                        }
2201
                    }
2202
                    g->scale_factors[j++] = 0;
2203
                }
2204
#if defined(DEBUG)
2205
                {
2206
                    dprintf(s->avctx, "scfsi=%x gr=%d ch=%d scale_factors:\n",
2207
                           g->scfsi, gr, ch);
2208
                    for(i=0;i<j;i++)
2209
                        dprintf(s->avctx, " %d", g->scale_factors[i]);
2210
                    dprintf(s->avctx, "\n");
2211
                }
2212
#endif
2213
            } else {
2214
                int tindex, tindex2, slen[4], sl, sf;
2215

    
2216
                /* LSF scale factors */
2217
                if (g->block_type == 2) {
2218
                    tindex = g->switch_point ? 2 : 1;
2219
                } else {
2220
                    tindex = 0;
2221
                }
2222
                sf = g->scalefac_compress;
2223
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2224
                    /* intensity stereo case */
2225
                    sf >>= 1;
2226
                    if (sf < 180) {
2227
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2228
                        tindex2 = 3;
2229
                    } else if (sf < 244) {
2230
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2231
                        tindex2 = 4;
2232
                    } else {
2233
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2234
                        tindex2 = 5;
2235
                    }
2236
                } else {
2237
                    /* normal case */
2238
                    if (sf < 400) {
2239
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2240
                        tindex2 = 0;
2241
                    } else if (sf < 500) {
2242
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2243
                        tindex2 = 1;
2244
                    } else {
2245
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2246
                        tindex2 = 2;
2247
                        g->preflag = 1;
2248
                    }
2249
                }
2250

    
2251
                j = 0;
2252
                for(k=0;k<4;k++) {
2253
                    n = lsf_nsf_table[tindex2][tindex][k];
2254
                    sl = slen[k];
2255
                    if(sl){
2256
                        for(i=0;i<n;i++)
2257
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
2258
                    }else{
2259
                        for(i=0;i<n;i++)
2260
                            g->scale_factors[j++] = 0;
2261
                    }
2262
                }
2263
                /* XXX: should compute exact size */
2264
                for(;j<40;j++)
2265
                    g->scale_factors[j] = 0;
2266
#if defined(DEBUG)
2267
                {
2268
                    dprintf(s->avctx, "gr=%d ch=%d scale_factors:\n",
2269
                           gr, ch);
2270
                    for(i=0;i<40;i++)
2271
                        dprintf(s->avctx, " %d", g->scale_factors[i]);
2272
                    dprintf(s->avctx, "\n");
2273
                }
2274
#endif
2275
            }
2276

    
2277
            exponents_from_scale_factors(s, g, exponents);
2278

    
2279
            /* read Huffman coded residue */
2280
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
2281
#if defined(DEBUG)
2282
            sample_dump(0, g->sb_hybrid, 576);
2283
#endif
2284
        } /* ch */
2285

    
2286
        if (s->nb_channels == 2)
2287
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2288

    
2289
        for(ch=0;ch<s->nb_channels;ch++) {
2290
            g = &granules[ch][gr];
2291

    
2292
            reorder_block(s, g);
2293
#if defined(DEBUG)
2294
            sample_dump(0, g->sb_hybrid, 576);
2295
#endif
2296
            s->compute_antialias(s, g);
2297
#if defined(DEBUG)
2298
            sample_dump(1, g->sb_hybrid, 576);
2299
#endif
2300
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2301
#if defined(DEBUG)
2302
            sample_dump(2, &s->sb_samples[ch][18 * gr][0], 576);
2303
#endif
2304
        }
2305
    } /* gr */
2306
    if(get_bits_count(&s->gb)<0)
2307
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
2308
    return nb_granules * 18;
2309
}
2310

    
2311
static int mp_decode_frame(MPADecodeContext *s,
2312
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
2313
{
2314
    int i, nb_frames, ch;
2315
    OUT_INT *samples_ptr;
2316

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

    
2319
    /* skip error protection field */
2320
    if (s->error_protection)
2321
        skip_bits(&s->gb, 16);
2322

    
2323
    dprintf(s->avctx, "frame %d:\n", s->frame_count);
2324
    switch(s->layer) {
2325
    case 1:
2326
        s->avctx->frame_size = 384;
2327
        nb_frames = mp_decode_layer1(s);
2328
        break;
2329
    case 2:
2330
        s->avctx->frame_size = 1152;
2331
        nb_frames = mp_decode_layer2(s);
2332
        break;
2333
    case 3:
2334
        s->avctx->frame_size = s->lsf ? 576 : 1152;
2335
    default:
2336
        nb_frames = mp_decode_layer3(s);
2337

    
2338
        s->last_buf_size=0;
2339
        if(s->in_gb.buffer){
2340
            align_get_bits(&s->gb);
2341
            i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2342
            if(i >= 0 && i <= BACKSTEP_SIZE){
2343
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
2344
                s->last_buf_size=i;
2345
            }else
2346
                av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
2347
            s->gb= s->in_gb;
2348
            s->in_gb.buffer= NULL;
2349
        }
2350

    
2351
        align_get_bits(&s->gb);
2352
        assert((get_bits_count(&s->gb) & 7) == 0);
2353
        i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2354

    
2355
        if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
2356
            av_log(s->avctx, AV_LOG_WARNING, "invalid new backstep %d\n", i);
2357
            i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
2358
        }
2359
        assert(i <= buf_size - HEADER_SIZE && i>= 0);
2360
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
2361
        s->last_buf_size += i;
2362

    
2363
        break;
2364
    }
2365
#if defined(DEBUG)
2366
    for(i=0;i<nb_frames;i++) {
2367
        for(ch=0;ch<s->nb_channels;ch++) {
2368
            int j;
2369
            dprintf(s->avctx, "%d-%d:", i, ch);
2370
            for(j=0;j<SBLIMIT;j++)
2371
                dprintf(s->avctx, " %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);
2372
            dprintf(s->avctx, "\n");
2373
        }
2374
    }
2375
#endif
2376
    /* apply the synthesis filter */
2377
    for(ch=0;ch<s->nb_channels;ch++) {
2378
        samples_ptr = samples + ch;
2379
        for(i=0;i<nb_frames;i++) {
2380
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2381
                         window, &s->dither_state,
2382
                         samples_ptr, s->nb_channels,
2383
                         s->sb_samples[ch][i]);
2384
            samples_ptr += 32 * s->nb_channels;
2385
        }
2386
    }
2387
#ifdef DEBUG
2388
    s->frame_count++;
2389
#endif
2390
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2391
}
2392

    
2393
static int decode_frame(AVCodecContext * avctx,
2394
                        void *data, int *data_size,
2395
                        const uint8_t * buf, int buf_size)
2396
{
2397
    MPADecodeContext *s = avctx->priv_data;
2398
    uint32_t header;
2399
    int out_size;
2400
    OUT_INT *out_samples = data;
2401

    
2402
retry:
2403
    if(buf_size < HEADER_SIZE)
2404
        return -1;
2405

    
2406
    header = AV_RB32(buf);
2407
    if(ff_mpa_check_header(header) < 0){
2408
        buf++;
2409
//        buf_size--;
2410
        av_log(avctx, AV_LOG_ERROR, "Header missing skipping one byte.\n");
2411
        goto retry;
2412
    }
2413

    
2414
    if (ff_mpegaudio_decode_header(s, header) == 1) {
2415
        /* free format: prepare to compute frame size */
2416
        s->frame_size = -1;
2417
        return -1;
2418
    }
2419
    /* update codec info */
2420
    avctx->channels = s->nb_channels;
2421
    avctx->bit_rate = s->bit_rate;
2422
    avctx->sub_id = s->layer;
2423

    
2424
    if(s->frame_size<=0 || s->frame_size > buf_size){
2425
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2426
        return -1;
2427
    }else if(s->frame_size < buf_size){
2428
        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
2429
        buf_size= s->frame_size;
2430
    }
2431

    
2432
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2433
    if(out_size>=0){
2434
        *data_size = out_size;
2435
        avctx->sample_rate = s->sample_rate;
2436
        //FIXME maybe move the other codec info stuff from above here too
2437
    }else
2438
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed
2439
    s->frame_size = 0;
2440
    return buf_size;
2441
}
2442

    
2443
static void flush(AVCodecContext *avctx){
2444
    MPADecodeContext *s = avctx->priv_data;
2445
    memset(s->synth_buf, 0, sizeof(s->synth_buf));
2446
    s->last_buf_size= 0;
2447
}
2448

    
2449
#ifdef CONFIG_MP3ADU_DECODER
2450
static int decode_frame_adu(AVCodecContext * avctx,
2451
                        void *data, int *data_size,
2452
                        const uint8_t * buf, int buf_size)
2453
{
2454
    MPADecodeContext *s = avctx->priv_data;
2455
    uint32_t header;
2456
    int len, out_size;
2457
    OUT_INT *out_samples = data;
2458

    
2459
    len = buf_size;
2460

    
2461
    // Discard too short frames
2462
    if (buf_size < HEADER_SIZE) {
2463
        *data_size = 0;
2464
        return buf_size;
2465
    }
2466

    
2467

    
2468
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2469
        len = MPA_MAX_CODED_FRAME_SIZE;
2470

    
2471
    // Get header and restore sync word
2472
    header = AV_RB32(buf) | 0xffe00000;
2473

    
2474
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2475
        *data_size = 0;
2476
        return buf_size;
2477
    }
2478

    
2479
    ff_mpegaudio_decode_header(s, header);
2480
    /* update codec info */
2481
    avctx->sample_rate = s->sample_rate;
2482
    avctx->channels = s->nb_channels;
2483
    avctx->bit_rate = s->bit_rate;
2484
    avctx->sub_id = s->layer;
2485

    
2486
    s->frame_size = len;
2487

    
2488
    if (avctx->parse_only) {
2489
        out_size = buf_size;
2490
    } else {
2491
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2492
    }
2493

    
2494
    *data_size = out_size;
2495
    return buf_size;
2496
}
2497
#endif /* CONFIG_MP3ADU_DECODER */
2498

    
2499
#ifdef CONFIG_MP3ON4_DECODER
2500

    
2501
/**
2502
 * Context for MP3On4 decoder
2503
 */
2504
typedef struct MP3On4DecodeContext {
2505
    int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
2506
    int syncword; ///< syncword patch
2507
    const uint8_t *coff; ///< channels offsets in output buffer
2508
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
2509
} MP3On4DecodeContext;
2510

    
2511
#include "mpeg4audio.h"
2512

    
2513
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2514
static const uint8_t mp3Frames[8] = {0,1,1,2,3,3,4,5};   /* number of mp3 decoder instances */
2515
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2516
static const uint8_t chan_offset[8][5] = {
2517
    {0},
2518
    {0},            // C
2519
    {0},            // FLR
2520
    {2,0},          // C FLR
2521
    {2,0,3},        // C FLR BS
2522
    {4,0,2},        // C FLR BLRS
2523
    {4,0,2,5},      // C FLR BLRS LFE
2524
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2525
};
2526

    
2527

    
2528
static int decode_init_mp3on4(AVCodecContext * avctx)
2529
{
2530
    MP3On4DecodeContext *s = avctx->priv_data;
2531
    MPEG4AudioConfig cfg;
2532
    int i;
2533

    
2534
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2535
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2536
        return -1;
2537
    }
2538

    
2539
    ff_mpeg4audio_get_config(&cfg, avctx->extradata, avctx->extradata_size);
2540
    if (!cfg.chan_config || cfg.chan_config > 7) {
2541
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2542
        return -1;
2543
    }
2544
    s->frames = mp3Frames[cfg.chan_config];
2545
    s->coff = chan_offset[cfg.chan_config];
2546
    avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
2547

    
2548
    if (cfg.sample_rate < 16000)
2549
        s->syncword = 0xffe00000;
2550
    else
2551
        s->syncword = 0xfff00000;
2552

    
2553
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2554
     * We replace avctx->priv_data with the context of the first decoder so that
2555
     * decode_init() does not have to be changed.
2556
     * Other decoders will be initialized here copying data from the first context
2557
     */
2558
    // Allocate zeroed memory for the first decoder context
2559
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2560
    // Put decoder context in place to make init_decode() happy
2561
    avctx->priv_data = s->mp3decctx[0];
2562
    decode_init(avctx);
2563
    // Restore mp3on4 context pointer
2564
    avctx->priv_data = s;
2565
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2566

    
2567
    /* Create a separate codec/context for each frame (first is already ok).
2568
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2569
     */
2570
    for (i = 1; i < s->frames; i++) {
2571
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2572
        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2573
        s->mp3decctx[i]->adu_mode = 1;
2574
        s->mp3decctx[i]->avctx = avctx;
2575
    }
2576

    
2577
    return 0;
2578
}
2579

    
2580

    
2581
static int decode_close_mp3on4(AVCodecContext * avctx)
2582
{
2583
    MP3On4DecodeContext *s = avctx->priv_data;
2584
    int i;
2585

    
2586
    for (i = 0; i < s->frames; i++)
2587
        if (s->mp3decctx[i])
2588
            av_free(s->mp3decctx[i]);
2589

    
2590
    return 0;
2591
}
2592

    
2593

    
2594
static int decode_frame_mp3on4(AVCodecContext * avctx,
2595
                        void *data, int *data_size,
2596
                        const uint8_t * buf, int buf_size)
2597
{
2598
    MP3On4DecodeContext *s = avctx->priv_data;
2599
    MPADecodeContext *m;
2600
    int fsize, len = buf_size, out_size = 0;
2601
    uint32_t header;
2602
    OUT_INT *out_samples = data;
2603
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2604
    OUT_INT *outptr, *bp;
2605
    int fr, j, n;
2606

    
2607
    *data_size = 0;
2608
    // Discard too short frames
2609
    if (buf_size < HEADER_SIZE)
2610
        return -1;
2611

    
2612
    // If only one decoder interleave is not needed
2613
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2614

    
2615
    avctx->bit_rate = 0;
2616

    
2617
    for (fr = 0; fr < s->frames; fr++) {
2618
        fsize = AV_RB16(buf) >> 4;
2619
        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
2620
        m = s->mp3decctx[fr];
2621
        assert (m != NULL);
2622

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

    
2625
        if (ff_mpa_check_header(header) < 0) // Bad header, discard block
2626
            break;
2627

    
2628
        ff_mpegaudio_decode_header(m, header);
2629
        out_size += mp_decode_frame(m, outptr, buf, fsize);
2630
        buf += fsize;
2631
        len -= fsize;
2632

    
2633
        if(s->frames > 1) {
2634
            n = m->avctx->frame_size*m->nb_channels;
2635
            /* interleave output data */
2636
            bp = out_samples + s->coff[fr];
2637
            if(m->nb_channels == 1) {
2638
                for(j = 0; j < n; j++) {
2639
                    *bp = decoded_buf[j];
2640
                    bp += avctx->channels;
2641
                }
2642
            } else {
2643
                for(j = 0; j < n; j++) {
2644
                    bp[0] = decoded_buf[j++];
2645
                    bp[1] = decoded_buf[j];
2646
                    bp += avctx->channels;
2647
                }
2648
            }
2649
        }
2650
        avctx->bit_rate += m->bit_rate;
2651
    }
2652

    
2653
    /* update codec info */
2654
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2655

    
2656
    *data_size = out_size;
2657
    return buf_size;
2658
}
2659
#endif /* CONFIG_MP3ON4_DECODER */
2660

    
2661
#ifdef CONFIG_MP2_DECODER
2662
AVCodec mp2_decoder =
2663
{
2664
    "mp2",
2665
    CODEC_TYPE_AUDIO,
2666
    CODEC_ID_MP2,
2667
    sizeof(MPADecodeContext),
2668
    decode_init,
2669
    NULL,
2670
    NULL,
2671
    decode_frame,
2672
    CODEC_CAP_PARSE_ONLY,
2673
    .flush= flush,
2674
    .long_name= NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2675
};
2676
#endif
2677
#ifdef CONFIG_MP3_DECODER
2678
AVCodec mp3_decoder =
2679
{
2680
    "mp3",
2681
    CODEC_TYPE_AUDIO,
2682
    CODEC_ID_MP3,
2683
    sizeof(MPADecodeContext),
2684
    decode_init,
2685
    NULL,
2686
    NULL,
2687
    decode_frame,
2688
    CODEC_CAP_PARSE_ONLY,
2689
    .flush= flush,
2690
    .long_name= NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2691
};
2692
#endif
2693
#ifdef CONFIG_MP3ADU_DECODER
2694
AVCodec mp3adu_decoder =
2695
{
2696
    "mp3adu",
2697
    CODEC_TYPE_AUDIO,
2698
    CODEC_ID_MP3ADU,
2699
    sizeof(MPADecodeContext),
2700
    decode_init,
2701
    NULL,
2702
    NULL,
2703
    decode_frame_adu,
2704
    CODEC_CAP_PARSE_ONLY,
2705
    .flush= flush,
2706
    .long_name= NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2707
};
2708
#endif
2709
#ifdef CONFIG_MP3ON4_DECODER
2710
AVCodec mp3on4_decoder =
2711
{
2712
    "mp3on4",
2713
    CODEC_TYPE_AUDIO,
2714
    CODEC_ID_MP3ON4,
2715
    sizeof(MP3On4DecodeContext),
2716
    decode_init_mp3on4,
2717
    NULL,
2718
    decode_close_mp3on4,
2719
    decode_frame_mp3on4,
2720
    .flush= flush,
2721
    .long_name= NULL_IF_CONFIG_SMALL("MP3onMP4"),
2722
};
2723
#endif