GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/mpegaudiodec_template.c Lines: 742 1071 69.3 %
Date: 2020-09-21 17:35:45 Branches: 390 592 65.9 %

Line Branch Exec Source
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
24
 * MPEG Audio decoder
25
 */
26
27
#include "libavutil/attributes.h"
28
#include "libavutil/avassert.h"
29
#include "libavutil/channel_layout.h"
30
#include "libavutil/crc.h"
31
#include "libavutil/float_dsp.h"
32
#include "libavutil/libm.h"
33
#include "avcodec.h"
34
#include "get_bits.h"
35
#include "internal.h"
36
#include "mathops.h"
37
#include "mpegaudiodsp.h"
38
39
/*
40
 * TODO:
41
 *  - test lsf / mpeg25 extensively.
42
 */
43
44
#include "mpegaudio.h"
45
#include "mpegaudiodecheader.h"
46
47
#define BACKSTEP_SIZE 512
48
#define EXTRABYTES 24
49
#define LAST_BUF_SIZE 2 * BACKSTEP_SIZE + EXTRABYTES
50
51
/* layer 3 "granule" */
52
typedef struct GranuleDef {
53
    uint8_t scfsi;
54
    int part2_3_length;
55
    int big_values;
56
    int global_gain;
57
    int scalefac_compress;
58
    uint8_t block_type;
59
    uint8_t switch_point;
60
    int table_select[3];
61
    int subblock_gain[3];
62
    uint8_t scalefac_scale;
63
    uint8_t count1table_select;
64
    int region_size[3]; /* number of huffman codes in each region */
65
    int preflag;
66
    int short_start, long_end; /* long/short band indexes */
67
    uint8_t scale_factors[40];
68
    DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
69
} GranuleDef;
70
71
typedef struct MPADecodeContext {
72
    MPA_DECODE_HEADER
73
    uint8_t last_buf[LAST_BUF_SIZE];
74
    int last_buf_size;
75
    int extrasize;
76
    /* next header (used in free format parsing) */
77
    uint32_t free_format_next_header;
78
    GetBitContext gb;
79
    GetBitContext in_gb;
80
    DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
81
    int synth_buf_offset[MPA_MAX_CHANNELS];
82
    DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
83
    INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
84
    GranuleDef granules[2][2]; /* Used in Layer 3 */
85
    int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
86
    int dither_state;
87
    int err_recognition;
88
    AVCodecContext* avctx;
89
    MPADSPContext mpadsp;
90
    void (*butterflies_float)(float *av_restrict v1, float *av_restrict v2, int len);
91
    AVFrame *frame;
92
    uint32_t crc;
93
} MPADecodeContext;
94
95
#define HEADER_SIZE 4
96
97
#include "mpegaudiodata.h"
98
#include "mpegaudiodectab.h"
99
100
/* vlc structure for decoding layer 3 huffman tables */
101
static VLC huff_vlc[16];
102
static VLC_TYPE huff_vlc_tables[
103
    0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
104
  142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
105
  ][2];
106
static const int huff_vlc_tables_sizes[16] = {
107
    0,  128,  128,  128,  130,  128,  154,  166,
108
  142,  204,  190,  170,  542,  460,  662,  414
109
};
110
static VLC huff_quad_vlc[2];
111
static VLC_TYPE  huff_quad_vlc_tables[128+16][2];
112
static const int huff_quad_vlc_tables_sizes[2] = { 128, 16 };
113
/* computed from band_size_long */
114
static uint16_t band_index_long[9][23];
115
#include "mpegaudio_tablegen.h"
116
/* intensity stereo coef table */
117
static INTFLOAT is_table[2][16];
118
static INTFLOAT is_table_lsf[2][2][16];
119
static INTFLOAT csa_table[8][4];
120
121
static int16_t division_tab3[1 << 6 ];
122
static int16_t division_tab5[1 << 8 ];
123
static int16_t division_tab9[1 << 11];
124
125
static int16_t * const division_tabs[4] = {
126
    division_tab3, division_tab5, NULL, division_tab9
127
};
128
129
/* lower 2 bits: modulo 3, higher bits: shift */
130
static uint16_t scale_factor_modshift[64];
131
/* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
132
static int32_t scale_factor_mult[15][3];
133
/* mult table for layer 2 group quantization */
134
135
#define SCALE_GEN(v) \
136
{ FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
137
138
static const int32_t scale_factor_mult2[3][3] = {
139
    SCALE_GEN(4.0 / 3.0), /* 3 steps */
140
    SCALE_GEN(4.0 / 5.0), /* 5 steps */
141
    SCALE_GEN(4.0 / 9.0), /* 9 steps */
142
};
143
144
/**
145
 * Convert region offsets to region sizes and truncate
146
 * size to big_values.
147
 */
148
8116
static void region_offset2size(GranuleDef *g)
149
{
150
8116
    int i, k, j = 0;
151
8116
    g->region_size[2] = 576 / 2;
152
32464
    for (i = 0; i < 3; i++) {
153
24348
        k = FFMIN(g->region_size[i], g->big_values);
154
24348
        g->region_size[i] = k - j;
155
24348
        j = k;
156
    }
157
8116
}
158
159
845
static void init_short_region(MPADecodeContext *s, GranuleDef *g)
160
{
161
845
    if (g->block_type == 2) {
162
305
        if (s->sample_rate_index != 8)
163
305
            g->region_size[0] = (36 / 2);
164
        else
165
            g->region_size[0] = (72 / 2);
166
    } else {
167
540
        if (s->sample_rate_index <= 2)
168
539
            g->region_size[0] = (36 / 2);
169
1
        else if (s->sample_rate_index != 8)
170
1
            g->region_size[0] = (54 / 2);
171
        else
172
            g->region_size[0] = (108 / 2);
173
    }
174
845
    g->region_size[1] = (576 / 2);
175
845
}
176
177
7271
static void init_long_region(MPADecodeContext *s, GranuleDef *g,
178
                             int ra1, int ra2)
179
{
180
    int l;
181
7271
    g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
182
    /* should not overflow */
183
7271
    l = FFMIN(ra1 + ra2 + 2, 22);
184
7271
    g->region_size[1] = band_index_long[s->sample_rate_index][      l] >> 1;
185
7271
}
186
187
8116
static void compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
188
{
189
8116
    if (g->block_type == 2) {
190
305
        if (g->switch_point) {
191
13
            if(s->sample_rate_index == 8)
192
                avpriv_request_sample(s->avctx, "switch point in 8khz");
193
            /* if switched mode, we handle the 36 first samples as
194
                long blocks.  For 8000Hz, we handle the 72 first
195
                exponents as long blocks */
196
13
            if (s->sample_rate_index <= 2)
197
13
                g->long_end = 8;
198
            else
199
                g->long_end = 6;
200
201
13
            g->short_start = 3;
202
        } else {
203
292
            g->long_end    = 0;
204
292
            g->short_start = 0;
205
        }
206
    } else {
207
7811
        g->short_start = 13;
208
7811
        g->long_end    = 22;
209
    }
210
8116
}
211
212
/* layer 1 unscaling */
213
/* n = number of bits of the mantissa minus 1 */
214
5010012
static inline int l1_unscale(int n, int mant, int scale_factor)
215
{
216
    int shift, mod;
217
    int64_t val;
218
219
5010012
    shift   = scale_factor_modshift[scale_factor];
220
5010012
    mod     = shift & 3;
221
5010012
    shift >>= 2;
222
5010012
    val     = MUL64((int)(mant + (-1U << n) + 1), scale_factor_mult[n-1][mod]);
223
5010012
    shift  += n;
224
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
225
5010012
    return (int)((val + (1LL << (shift - 1))) >> shift);
226
}
227
228
882756
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
229
{
230
    int shift, mod, val;
231
232
882756
    shift   = scale_factor_modshift[scale_factor];
233
882756
    mod     = shift & 3;
234
882756
    shift >>= 2;
235
236
882756
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
237
    /* NOTE: at this point, 0 <= shift <= 21 */
238
882756
    if (shift > 0)
239
882756
        val = (val + (1 << (shift - 1))) >> shift;
240
882756
    return val;
241
}
242
243
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
244
56735
static inline int l3_unscale(int value, int exponent)
245
{
246
    unsigned int m;
247
    int e;
248
249
56735
    e  = table_4_3_exp  [4 * value + (exponent & 3)];
250
56735
    m  = table_4_3_value[4 * value + (exponent & 3)];
251
56735
    e -= exponent >> 2;
252
#ifdef DEBUG
253
    if(e < 1)
254
        av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
255
#endif
256
56735
    if (e > (SUINT)31)
257
10
        return 0;
258
56725
    m = (m + ((1U << e) >> 1)) >> e;
259
260
56725
    return m;
261
}
262
263
90
static av_cold void decode_init_static(void)
264
{
265
    int i, j, k;
266
    int offset;
267
268
    /* scale factors table for layer 1/2 */
269
5850
    for (i = 0; i < 64; i++) {
270
        int shift, mod;
271
        /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
272
5760
        shift = i / 3;
273
5760
        mod   = i % 3;
274
5760
        scale_factor_modshift[i] = mod | (shift << 2);
275
    }
276
277
    /* scale factor multiply for layer 1 */
278
1440
    for (i = 0; i < 15; i++) {
279
        int n, norm;
280
1350
        n = i + 2;
281
1350
        norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
282
1350
        scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);
283
1350
        scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
284
1350
        scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
285
        ff_dlog(NULL, "%d: norm=%x s=%"PRIx32" %"PRIx32" %"PRIx32"\n", i,
286
                (unsigned)norm,
287
                scale_factor_mult[i][0],
288
                scale_factor_mult[i][1],
289
                scale_factor_mult[i][2]);
290
    }
291
292
90
    RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
293
294
    /* huffman decode tables */
295
90
    offset = 0;
296
1440
    for (i = 1; i < 16; i++) {
297
1350
        const HuffTable *h = &mpa_huff_tables[i];
298
        int xsize, x, y;
299
1350
        uint8_t  tmp_bits [512] = { 0 };
300
1350
        uint16_t tmp_codes[512] = { 0 };
301
302
1350
        xsize = h->xsize;
303
304
1350
        j = 0;
305
12330
        for (x = 0; x < xsize; x++) {
306
135000
            for (y = 0; y < xsize; y++) {
307

124020
                tmp_bits [(x << 5) | y | ((x && y) << 4)]= h->bits [j  ];
308

124020
                tmp_codes[(x << 5) | y | ((x && y) << 4)]= h->codes[j++];
309
            }
310
        }
311
312
        /* XXX: fail test */
313
1350
        huff_vlc[i].table = huff_vlc_tables+offset;
314
1350
        huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
315
1350
        init_vlc(&huff_vlc[i], 7, 512,
316
                 tmp_bits, 1, 1, tmp_codes, 2, 2,
317
                 INIT_VLC_USE_NEW_STATIC);
318
1350
        offset += huff_vlc_tables_sizes[i];
319
    }
320
90
    av_assert0(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
321
322
90
    offset = 0;
323
270
    for (i = 0; i < 2; i++) {
324
180
        huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
325
180
        huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
326
180
        init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
327
                 mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
328
                 INIT_VLC_USE_NEW_STATIC);
329
180
        offset += huff_quad_vlc_tables_sizes[i];
330
    }
331
90
    av_assert0(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
332
333
900
    for (i = 0; i < 9; i++) {
334
810
        k = 0;
335
18630
        for (j = 0; j < 22; j++) {
336
17820
            band_index_long[i][j] = k;
337
17820
            k += band_size_long[i][j];
338
        }
339
810
        band_index_long[i][22] = k;
340
    }
341
342
    /* compute n ^ (4/3) and store it in mantissa/exp format */
343
344
90
    mpegaudio_tableinit();
345
346
450
    for (i = 0; i < 4; i++) {
347
360
        if (ff_mpa_quant_bits[i] < 0) {
348
213390
            for (j = 0; j < (1 << (-ff_mpa_quant_bits[i] + 1)); j++) {
349
                int val1, val2, val3, steps;
350
213120
                int val = j;
351
213120
                steps   = ff_mpa_quant_steps[i];
352
213120
                val1    = val % steps;
353
213120
                val    /= steps;
354
213120
                val2    = val % steps;
355
213120
                val3    = val / steps;
356
213120
                division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
357
            }
358
        }
359
    }
360
361
362
720
    for (i = 0; i < 7; i++) {
363
        float f;
364
        INTFLOAT v;
365
630
        if (i != 6) {
366
540
            f = tan((double)i * M_PI / 12.0);
367
540
            v = FIXR(f / (1.0 + f));
368
        } else {
369
90
            v = FIXR(1.0);
370
        }
371
630
        is_table[0][    i] = v;
372
630
        is_table[1][6 - i] = v;
373
    }
374
    /* invalid values */
375
900
    for (i = 7; i < 16; i++)
376
810
        is_table[0][i] = is_table[1][i] = 0.0;
377
378
1530
    for (i = 0; i < 16; i++) {
379
        double f;
380
        int e, k;
381
382
4320
        for (j = 0; j < 2; j++) {
383
2880
            e = -(j + 1) * ((i + 1) >> 1);
384
2880
            f = exp2(e / 4.0);
385
2880
            k = i & 1;
386
2880
            is_table_lsf[j][k ^ 1][i] = FIXR(f);
387
2880
            is_table_lsf[j][k    ][i] = FIXR(1.0);
388
            ff_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
389
                    i, j, (float) is_table_lsf[j][0][i],
390
                    (float) is_table_lsf[j][1][i]);
391
        }
392
    }
393
394
810
    for (i = 0; i < 8; i++) {
395
        double ci, cs, ca;
396
720
        ci = ci_table[i];
397
720
        cs = 1.0 / sqrt(1.0 + ci * ci);
398
720
        ca = cs * ci;
399
#if !USE_FLOATS
400
352
        csa_table[i][0] = FIXHR(cs/4);
401
352
        csa_table[i][1] = FIXHR(ca/4);
402
352
        csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
403
352
        csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
404
#else
405
368
        csa_table[i][0] = cs;
406
368
        csa_table[i][1] = ca;
407
368
        csa_table[i][2] = ca + cs;
408
368
        csa_table[i][3] = ca - cs;
409
#endif
410
    }
411
90
}
412
413
132
static av_cold int decode_init(AVCodecContext * avctx)
414
{
415
    static int initialized_tables = 0;
416
132
    MPADecodeContext *s = avctx->priv_data;
417
418
132
    if (!initialized_tables) {
419
90
        decode_init_static();
420
90
        initialized_tables = 1;
421
    }
422
423
132
    s->avctx = avctx;
424
425
#if USE_FLOATS
426
    {
427
        AVFloatDSPContext *fdsp;
428
63
        fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
429
63
        if (!fdsp)
430
            return AVERROR(ENOMEM);
431
63
        s->butterflies_float = fdsp->butterflies_float;
432
63
        av_free(fdsp);
433
    }
434
#endif
435
436
132
    ff_mpadsp_init(&s->mpadsp);
437
438
132
    if (avctx->request_sample_fmt == OUT_FMT &&
439
        avctx->codec_id != AV_CODEC_ID_MP3ON4)
440
        avctx->sample_fmt = OUT_FMT;
441
    else
442
132
        avctx->sample_fmt = OUT_FMT_P;
443
132
    s->err_recognition = avctx->err_recognition;
444
445
132
    if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
446
        s->adu_mode = 1;
447
448
132
    return 0;
449
}
450
451
#define C3 FIXHR(0.86602540378443864676/2)
452
#define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
453
#define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
454
#define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
455
456
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
457
   cases. */
458
19371
static void imdct12(INTFLOAT *out, SUINTFLOAT *in)
459
{
460
    SUINTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
461
462
19371
    in0  = in[0*3];
463
19371
    in1  = in[1*3] + in[0*3];
464
19371
    in2  = in[2*3] + in[1*3];
465
19371
    in3  = in[3*3] + in[2*3];
466
19371
    in4  = in[4*3] + in[3*3];
467
19371
    in5  = in[5*3] + in[4*3];
468
19371
    in5 += in3;
469
19371
    in3 += in1;
470
471
19371
    in2  = MULH3(in2, C3, 2);
472
19371
    in3  = MULH3(in3, C3, 4);
473
474
19371
    t1   = in0 - in4;
475
19371
    t2   = MULH3(in1 - in5, C4, 2);
476
477
19371
    out[ 7] =
478
19371
    out[10] = t1 + t2;
479
19371
    out[ 1] =
480
19371
    out[ 4] = t1 - t2;
481
482
19371
    in0    += SHR(in4, 1);
483
19371
    in4     = in0 + in2;
484
19371
    in5    += 2*in1;
485
19371
    in1     = MULH3(in5 + in3, C5, 1);
486
19371
    out[ 8] =
487
19371
    out[ 9] = in4 + in1;
488
19371
    out[ 2] =
489
19371
    out[ 3] = in4 - in1;
490
491
19371
    in0    -= in2;
492
19371
    in5     = MULH3(in5 - in3, C6, 2);
493
19371
    out[ 0] =
494
19371
    out[ 5] = in0 - in5;
495
19371
    out[ 6] =
496
19371
    out[11] = in0 + in5;
497
19371
}
498
499
10040
static int handle_crc(MPADecodeContext *s, int sec_len)
500
{
501

10040
    if (s->error_protection && (s->err_recognition & AV_EF_CRCCHECK)) {
502
        const uint8_t *buf = s->gb.buffer - HEADER_SIZE;
503
        int sec_byte_len  = sec_len >> 3;
504
        int sec_rem_bits  = sec_len & 7;
505
        const AVCRC *crc_tab = av_crc_get_table(AV_CRC_16_ANSI);
506
        uint8_t tmp_buf[4];
507
        uint32_t crc_val = av_crc(crc_tab, UINT16_MAX, &buf[2], 2);
508
        crc_val = av_crc(crc_tab, crc_val, &buf[6], sec_byte_len);
509
510
        AV_WB32(tmp_buf,
511
                ((buf[6 + sec_byte_len] & (0xFF00 >> sec_rem_bits)) << 24) +
512
                ((s->crc << 16) >> sec_rem_bits));
513
514
        crc_val = av_crc(crc_tab, crc_val, tmp_buf, 3);
515
516
        if (crc_val) {
517
            av_log(s->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", crc_val);
518
            if (s->err_recognition & AV_EF_EXPLODE)
519
                return AVERROR_INVALIDDATA;
520
        }
521
    }
522
10040
    return 0;
523
}
524
525
/* return the number of decoded frames */
526
static int mp_decode_layer1(MPADecodeContext *s)
527
{
528
    int bound, i, v, n, ch, j, mant;
529
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
530
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
531
    int ret;
532
533
    ret = handle_crc(s, (s->nb_channels == 1) ? 8*16  : 8*32);
534
    if (ret < 0)
535
        return ret;
536
537
    if (s->mode == MPA_JSTEREO)
538
        bound = (s->mode_ext + 1) * 4;
539
    else
540
        bound = SBLIMIT;
541
542
    /* allocation bits */
543
    for (i = 0; i < bound; i++) {
544
        for (ch = 0; ch < s->nb_channels; ch++) {
545
            allocation[ch][i] = get_bits(&s->gb, 4);
546
        }
547
    }
548
    for (i = bound; i < SBLIMIT; i++)
549
        allocation[0][i] = get_bits(&s->gb, 4);
550
551
    /* scale factors */
552
    for (i = 0; i < bound; i++) {
553
        for (ch = 0; ch < s->nb_channels; ch++) {
554
            if (allocation[ch][i])
555
                scale_factors[ch][i] = get_bits(&s->gb, 6);
556
        }
557
    }
558
    for (i = bound; i < SBLIMIT; i++) {
559
        if (allocation[0][i]) {
560
            scale_factors[0][i] = get_bits(&s->gb, 6);
561
            scale_factors[1][i] = get_bits(&s->gb, 6);
562
        }
563
    }
564
565
    /* compute samples */
566
    for (j = 0; j < 12; j++) {
567
        for (i = 0; i < bound; i++) {
568
            for (ch = 0; ch < s->nb_channels; ch++) {
569
                n = allocation[ch][i];
570
                if (n) {
571
                    mant = get_bits(&s->gb, n + 1);
572
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
573
                } else {
574
                    v = 0;
575
                }
576
                s->sb_samples[ch][j][i] = v;
577
            }
578
        }
579
        for (i = bound; i < SBLIMIT; i++) {
580
            n = allocation[0][i];
581
            if (n) {
582
                mant = get_bits(&s->gb, n + 1);
583
                v = l1_unscale(n, mant, scale_factors[0][i]);
584
                s->sb_samples[0][j][i] = v;
585
                v = l1_unscale(n, mant, scale_factors[1][i]);
586
                s->sb_samples[1][j][i] = v;
587
            } else {
588
                s->sb_samples[0][j][i] = 0;
589
                s->sb_samples[1][j][i] = 0;
590
            }
591
        }
592
    }
593
    return 12;
594
}
595
596
7237
static int mp_decode_layer2(MPADecodeContext *s)
597
{
598
    int sblimit; /* number of used subbands */
599
    const unsigned char *alloc_table;
600
    int table, bit_alloc_bits, i, j, ch, bound, v;
601
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
602
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
603
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
604
    int scale, qindex, bits, steps, k, l, m, b;
605
    int ret;
606
607
    /* select decoding table */
608
7237
    table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
609
                                   s->sample_rate, s->lsf);
610
7237
    sblimit     = ff_mpa_sblimit_table[table];
611
7237
    alloc_table = ff_mpa_alloc_tables[table];
612
613
7237
    if (s->mode == MPA_JSTEREO)
614
        bound = (s->mode_ext + 1) * 4;
615
    else
616
7237
        bound = sblimit;
617
618
    ff_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
619
620
    /* sanity check */
621
7237
    if (bound > sblimit)
622
        bound = sblimit;
623
624
    /* parse bit allocation */
625
7237
    j = 0;
626
221869
    for (i = 0; i < bound; i++) {
627
214632
        bit_alloc_bits = alloc_table[j];
628
447402
        for (ch = 0; ch < s->nb_channels; ch++)
629
232770
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
630
214632
        j += 1 << bit_alloc_bits;
631
    }
632
7237
    for (i = bound; i < sblimit; i++) {
633
        bit_alloc_bits = alloc_table[j];
634
        v = get_bits(&s->gb, bit_alloc_bits);
635
        bit_alloc[0][i] = v;
636
        bit_alloc[1][i] = v;
637
        j += 1 << bit_alloc_bits;
638
    }
639
640
    /* scale codes */
641
221869
    for (i = 0; i < sblimit; i++) {
642
447402
        for (ch = 0; ch < s->nb_channels; ch++) {
643
232770
            if (bit_alloc[ch][i])
644
163688
                scale_code[ch][i] = get_bits(&s->gb, 2);
645
        }
646
    }
647
648
7237
    ret = handle_crc(s, get_bits_count(&s->gb) - 16);
649
7237
    if (ret < 0)
650
        return ret;
651
652
    /* scale factors */
653
221869
    for (i = 0; i < sblimit; i++) {
654
447402
        for (ch = 0; ch < s->nb_channels; ch++) {
655
232770
            if (bit_alloc[ch][i]) {
656
163688
                sf = scale_factors[ch][i];
657

163688
                switch (scale_code[ch][i]) {
658
2929
                default:
659
                case 0:
660
2929
                    sf[0] = get_bits(&s->gb, 6);
661
2929
                    sf[1] = get_bits(&s->gb, 6);
662
2929
                    sf[2] = get_bits(&s->gb, 6);
663
2929
                    break;
664
153192
                case 2:
665
153192
                    sf[0] = get_bits(&s->gb, 6);
666
153192
                    sf[1] = sf[0];
667
153192
                    sf[2] = sf[0];
668
153192
                    break;
669
2542
                case 1:
670
2542
                    sf[0] = get_bits(&s->gb, 6);
671
2542
                    sf[2] = get_bits(&s->gb, 6);
672
2542
                    sf[1] = sf[0];
673
2542
                    break;
674
5025
                case 3:
675
5025
                    sf[0] = get_bits(&s->gb, 6);
676
5025
                    sf[2] = get_bits(&s->gb, 6);
677
5025
                    sf[1] = sf[2];
678
5025
                    break;
679
                }
680
69082
            }
681
        }
682
    }
683
684
    /* samples */
685
28948
    for (k = 0; k < 3; k++) {
686
108555
        for (l = 0; l < 12; l += 3) {
687
86844
            j = 0;
688
2662428
            for (i = 0; i < bound; i++) {
689
2575584
                bit_alloc_bits = alloc_table[j];
690
5368824
                for (ch = 0; ch < s->nb_channels; ch++) {
691
2793240
                    b = bit_alloc[ch][i];
692
2793240
                    if (b) {
693
1964256
                        scale = scale_factors[ch][i][k];
694
1964256
                        qindex = alloc_table[j+b];
695
1964256
                        bits = ff_mpa_quant_bits[qindex];
696
1964256
                        if (bits < 0) {
697
                            int v2;
698
                            /* 3 values at the same time */
699
294252
                            v = get_bits(&s->gb, -bits);
700
294252
                            v2 = division_tabs[qindex][v];
701
294252
                            steps  = ff_mpa_quant_steps[qindex];
702
703
586416
                            s->sb_samples[ch][k * 12 + l + 0][i] =
704
294252
                                l2_unscale_group(steps,  v2       & 15, scale);
705
586416
                            s->sb_samples[ch][k * 12 + l + 1][i] =
706
294252
                                l2_unscale_group(steps, (v2 >> 4) & 15, scale);
707
294252
                            s->sb_samples[ch][k * 12 + l + 2][i] =
708
294252
                                l2_unscale_group(steps,  v2 >> 8      , scale);
709
                        } else {
710
6680016
                            for (m = 0; m < 3; m++) {
711
5010012
                                v = get_bits(&s->gb, bits);
712
5010012
                                v = l1_unscale(bits - 1, v, scale);
713
5010012
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
714
                            }
715
                        }
716
                    } else {
717
828984
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
718
828984
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
719
828984
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
720
                    }
721
                }
722
                /* next subband in alloc table */
723
2575584
                j += 1 << bit_alloc_bits;
724
            }
725
            /* XXX: find a way to avoid this duplication of code */
726
86844
            for (i = bound; i < sblimit; i++) {
727
                bit_alloc_bits = alloc_table[j];
728
                b = bit_alloc[0][i];
729
                if (b) {
730
                    int mant, scale0, scale1;
731
                    scale0 = scale_factors[0][i][k];
732
                    scale1 = scale_factors[1][i][k];
733
                    qindex = alloc_table[j + b];
734
                    bits = ff_mpa_quant_bits[qindex];
735
                    if (bits < 0) {
736
                        /* 3 values at the same time */
737
                        v = get_bits(&s->gb, -bits);
738
                        steps = ff_mpa_quant_steps[qindex];
739
                        mant = v % steps;
740
                        v = v / steps;
741
                        s->sb_samples[0][k * 12 + l + 0][i] =
742
                            l2_unscale_group(steps, mant, scale0);
743
                        s->sb_samples[1][k * 12 + l + 0][i] =
744
                            l2_unscale_group(steps, mant, scale1);
745
                        mant = v % steps;
746
                        v = v / steps;
747
                        s->sb_samples[0][k * 12 + l + 1][i] =
748
                            l2_unscale_group(steps, mant, scale0);
749
                        s->sb_samples[1][k * 12 + l + 1][i] =
750
                            l2_unscale_group(steps, mant, scale1);
751
                        s->sb_samples[0][k * 12 + l + 2][i] =
752
                            l2_unscale_group(steps, v, scale0);
753
                        s->sb_samples[1][k * 12 + l + 2][i] =
754
                            l2_unscale_group(steps, v, scale1);
755
                    } else {
756
                        for (m = 0; m < 3; m++) {
757
                            mant = get_bits(&s->gb, bits);
758
                            s->sb_samples[0][k * 12 + l + m][i] =
759
                                l1_unscale(bits - 1, mant, scale0);
760
                            s->sb_samples[1][k * 12 + l + m][i] =
761
                                l1_unscale(bits - 1, mant, scale1);
762
                        }
763
                    }
764
                } else {
765
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
766
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
767
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
768
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
769
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
770
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
771
                }
772
                /* next subband in alloc table */
773
                j += 1 << bit_alloc_bits;
774
            }
775
            /* fill remaining samples to zero */
776
290268
            for (i = sblimit; i < SBLIMIT; i++) {
777
437256
                for (ch = 0; ch < s->nb_channels; ch++) {
778
233832
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
779
233832
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
780
233832
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
781
                }
782
            }
783
        }
784
    }
785
7237
    return 3 * 12;
786
}
787
788
#define SPLIT(dst,sf,n)             \
789
    if (n == 3) {                   \
790
        int m = (sf * 171) >> 9;    \
791
        dst   = sf - 3 * m;         \
792
        sf    = m;                  \
793
    } else if (n == 4) {            \
794
        dst  = sf & 3;              \
795
        sf >>= 2;                   \
796
    } else if (n == 5) {            \
797
        int m = (sf * 205) >> 10;   \
798
        dst   = sf - 5 * m;         \
799
        sf    = m;                  \
800
    } else if (n == 6) {            \
801
        int m = (sf * 171) >> 10;   \
802
        dst   = sf - 6 * m;         \
803
        sf    = m;                  \
804
    } else {                        \
805
        dst = 0;                    \
806
    }
807
808
4
static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
809
                                           int n3)
810
{
811


4
    SPLIT(slen[3], sf, n3)
812


4
    SPLIT(slen[2], sf, n2)
813


4
    SPLIT(slen[1], sf, n1)
814
4
    slen[0] = sf;
815
4
}
816
817
8112
static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
818
                                         int16_t *exponents)
819
{
820
    const uint8_t *bstab, *pretab;
821
    int len, i, j, k, l, v0, shift, gain, gains[3];
822
    int16_t *exp_ptr;
823
824
8112
    exp_ptr = exponents;
825
8112
    gain    = g->global_gain - 210;
826
8112
    shift   = g->scalefac_scale + 1;
827
828
8112
    bstab  = band_size_long[s->sample_rate_index];
829
8112
    pretab = mpa_pretab[g->preflag];
830
179992
    for (i = 0; i < g->long_end; i++) {
831
171880
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
832
171880
        len = bstab[i];
833
4669756
        for (j = len; j > 0; j--)
834
4497876
            *exp_ptr++ = v0;
835
    }
836
837
8112
    if (g->short_start < 13) {
838
304
        bstab    = band_size_short[s->sample_rate_index];
839
304
        gains[0] = gain - (g->subblock_gain[0] << 3);
840
304
        gains[1] = gain - (g->subblock_gain[1] << 3);
841
304
        gains[2] = gain - (g->subblock_gain[2] << 3);
842
304
        k        = g->long_end;
843
4217
        for (i = g->short_start; i < 13; i++) {
844
3913
            len = bstab[i];
845
15652
            for (l = 0; l < 3; l++) {
846
11739
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
847
186375
                for (j = len; j > 0; j--)
848
174636
                    *exp_ptr++ = v0;
849
            }
850
        }
851
    }
852
8112
}
853
854
16799
static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
855
                          int *end_pos2)
856
{
857

16799
    if (s->in_gb.buffer && *pos >= s->gb.size_in_bits - s->extrasize * 8) {
858
939
        s->gb           = s->in_gb;
859
939
        s->in_gb.buffer = NULL;
860
939
        s->extrasize    = 0;
861
        av_assert2((get_bits_count(&s->gb) & 7) == 0);
862
939
        skip_bits_long(&s->gb, *pos - *end_pos);
863
939
        *end_pos2 =
864
939
        *end_pos  = *end_pos2 + get_bits_count(&s->gb) - *pos;
865
939
        *pos      = get_bits_count(&s->gb);
866
    }
867
16799
}
868
869
/* Following is an optimized code for
870
            INTFLOAT v = *src
871
            if(get_bits1(&s->gb))
872
                v = -v;
873
            *dst = v;
874
*/
875
#if USE_FLOATS
876
#define READ_FLIP_SIGN(dst,src)                     \
877
    v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31);  \
878
    AV_WN32A(dst, v);
879
#else
880
#define READ_FLIP_SIGN(dst,src)     \
881
    v      = -get_bits1(&s->gb);    \
882
    *(dst) = (*(src) ^ v) - v;
883
#endif
884
885
8112
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
886
                          int16_t *exponents, int end_pos2)
887
{
888
    int s_index;
889
    int i;
890
    int last_pos, bits_left;
891
    VLC *vlc;
892
8112
    int end_pos = FFMIN(end_pos2, s->gb.size_in_bits - s->extrasize * 8);
893
894
    /* low frequencies (called big values) */
895
8112
    s_index = 0;
896
32448
    for (i = 0; i < 3; i++) {
897
        int j, k, l, linbits;
898
24336
        j = g->region_size[i];
899
24336
        if (j == 0)
900
1292
            continue;
901
        /* select vlc table */
902
23044
        k       = g->table_select[i];
903
23044
        l       = mpa_huff_data[k][0];
904
23044
        linbits = mpa_huff_data[k][1];
905
23044
        vlc     = &huff_vlc[l];
906
907
23044
        if (!l) {
908
92
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
909
92
            s_index += 2 * j;
910
92
            continue;
911
        }
912
913
        /* read huffcode and compute each couple */
914
909472
        for (; j > 0; j--) {
915
            int exponent, x, y;
916
            int v;
917
886520
            int pos = get_bits_count(&s->gb);
918
919
886520
            if (pos >= end_pos){
920
789
                switch_buffer(s, &pos, &end_pos, &end_pos2);
921
789
                if (pos >= end_pos)
922
                    break;
923
            }
924
886520
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
925
926
886520
            if (!y) {
927
215662
                g->sb_hybrid[s_index    ] =
928
215662
                g->sb_hybrid[s_index + 1] = 0;
929
215662
                s_index += 2;
930
215662
                continue;
931
            }
932
933
670858
            exponent= exponents[s_index];
934
935
            ff_dlog(s->avctx, "region=%d n=%d y=%d exp=%d\n",
936
                    i, g->region_size[i] - j, y, exponent);
937
670858
            if (y & 16) {
938
426226
                x = y >> 5;
939
426226
                y = y & 0x0f;
940
426226
                if (x < 15) {
941
400278
                    READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
942
                } else {
943
25948
                    x += get_bitsz(&s->gb, linbits);
944
25948
                    v  = l3_unscale(x, exponent);
945
25948
                    if (get_bits1(&s->gb))
946
12440
                        v = -v;
947
25948
                    g->sb_hybrid[s_index] = v;
948
                }
949
426226
                if (y < 15) {
950
401244
                    READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
951
                } else {
952
24982
                    y += get_bitsz(&s->gb, linbits);
953
24982
                    v  = l3_unscale(y, exponent);
954
24982
                    if (get_bits1(&s->gb))
955
11889
                        v = -v;
956
24982
                    g->sb_hybrid[s_index + 1] = v;
957
                }
958
            } else {
959
244632
                x = y >> 5;
960
244632
                y = y & 0x0f;
961
244632
                x += y;
962
244632
                if (x < 15) {
963
238827
                    READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
964
                } else {
965
5805
                    x += get_bitsz(&s->gb, linbits);
966
5805
                    v  = l3_unscale(x, exponent);
967
5805
                    if (get_bits1(&s->gb))
968
2114
                        v = -v;
969
5805
                    g->sb_hybrid[s_index+!!y] = v;
970
                }
971
244632
                g->sb_hybrid[s_index + !y] = 0;
972
            }
973
670858
            s_index += 2;
974
        }
975
    }
976
977
    /* high frequencies */
978
8112
    vlc = &huff_quad_vlc[g->count1table_select];
979
8112
    last_pos = 0;
980
226739
    while (s_index <= 572) {
981
        int pos, code;
982
226438
        pos = get_bits_count(&s->gb);
983
226438
        if (pos >= end_pos) {
984

7898
            if (pos > end_pos2 && last_pos) {
985
                /* some encoders generate an incorrect size for this
986
                   part. We must go back into the data */
987
                s_index -= 4;
988
                skip_bits_long(&s->gb, last_pos - pos);
989
                av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
990
                if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
991
                    s_index=0;
992
7811
                break;
993
            }
994
7898
            switch_buffer(s, &pos, &end_pos, &end_pos2);
995
7898
            if (pos >= end_pos)
996
7811
                break;
997
        }
998
218627
        last_pos = pos;
999
1000
218627
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1001
        ff_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1002
218627
        g->sb_hybrid[s_index + 0] =
1003
218627
        g->sb_hybrid[s_index + 1] =
1004
218627
        g->sb_hybrid[s_index + 2] =
1005
218627
        g->sb_hybrid[s_index + 3] = 0;
1006
366945
        while (code) {
1007
            static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
1008
            int v;
1009
148318
            int pos = s_index + idxtab[code];
1010
148318
            code   ^= 8 >> idxtab[code];
1011
148318
            READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
1012
        }
1013
218627
        s_index += 4;
1014
    }
1015
    /* skip extension bits */
1016
8112
    bits_left = end_pos2 - get_bits_count(&s->gb);
1017

8112
    if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
1018
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1019
        s_index=0;
1020

8112
    } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
1021
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1022
        s_index = 0;
1023
    }
1024
8112
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1025
8112
    skip_bits_long(&s->gb, bits_left);
1026
1027
8112
    i = get_bits_count(&s->gb);
1028
8112
    switch_buffer(s, &i, &end_pos, &end_pos2);
1029
1030
8112
    return 0;
1031
}
1032
1033
/* Reorder short blocks from bitstream order to interleaved order. It
1034
   would be faster to do it in parsing, but the code would be far more
1035
   complicated */
1036
8112
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1037
{
1038
    int i, j, len;
1039
    INTFLOAT *ptr, *dst, *ptr1;
1040
    INTFLOAT tmp[576];
1041
1042
8112
    if (g->block_type != 2)
1043
7808
        return;
1044
1045
304
    if (g->switch_point) {
1046
13
        if (s->sample_rate_index != 8)
1047
13
            ptr = g->sb_hybrid + 36;
1048
        else
1049
            ptr = g->sb_hybrid + 72;
1050
    } else {
1051
291
        ptr = g->sb_hybrid;
1052
    }
1053
1054
4217
    for (i = g->short_start; i < 13; i++) {
1055
3913
        len  = band_size_short[s->sample_rate_index][i];
1056
3913
        ptr1 = ptr;
1057
3913
        dst  = tmp;
1058
62125
        for (j = len; j > 0; j--) {
1059
58212
            *dst++ = ptr[0*len];
1060
58212
            *dst++ = ptr[1*len];
1061
58212
            *dst++ = ptr[2*len];
1062
58212
            ptr++;
1063
        }
1064
3913
        ptr += 2 * len;
1065
3913
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1066
    }
1067
}
1068
1069
#define ISQRT2 FIXR(0.70710678118654752440)
1070
1071
2447
static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1072
{
1073
    int i, j, k, l;
1074
    int sf_max, sf, len, non_zero_found;
1075
    INTFLOAT (*is_tab)[16], *tab0, *tab1, v1, v2;
1076
    SUINTFLOAT tmp0, tmp1;
1077
    int non_zero_found_short[3];
1078
1079
    /* intensity stereo */
1080
2447
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1081
1
        if (!s->lsf) {
1082
            is_tab = is_table;
1083
            sf_max = 7;
1084
        } else {
1085
1
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1086
1
            sf_max = 16;
1087
        }
1088
1089
1
        tab0 = g0->sb_hybrid + 576;
1090
1
        tab1 = g1->sb_hybrid + 576;
1091
1092
1
        non_zero_found_short[0] = 0;
1093
1
        non_zero_found_short[1] = 0;
1094
1
        non_zero_found_short[2] = 0;
1095
1
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1096
1
        for (i = 12; i >= g1->short_start; i--) {
1097
            /* for last band, use previous scale factor */
1098
            if (i != 11)
1099
                k -= 3;
1100
            len = band_size_short[s->sample_rate_index][i];
1101
            for (l = 2; l >= 0; l--) {
1102
                tab0 -= len;
1103
                tab1 -= len;
1104
                if (!non_zero_found_short[l]) {
1105
                    /* test if non zero band. if so, stop doing i-stereo */
1106
                    for (j = 0; j < len; j++) {
1107
                        if (tab1[j] != 0) {
1108
                            non_zero_found_short[l] = 1;
1109
                            goto found1;
1110
                        }
1111
                    }
1112
                    sf = g1->scale_factors[k + l];
1113
                    if (sf >= sf_max)
1114
                        goto found1;
1115
1116
                    v1 = is_tab[0][sf];
1117
                    v2 = is_tab[1][sf];
1118
                    for (j = 0; j < len; j++) {
1119
                        tmp0    = tab0[j];
1120
                        tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1121
                        tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1122
                    }
1123
                } else {
1124
found1:
1125
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1126
                        /* lower part of the spectrum : do ms stereo
1127
                           if enabled */
1128
                        for (j = 0; j < len; j++) {
1129
                            tmp0    = tab0[j];
1130
                            tmp1    = tab1[j];
1131
                            tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1132
                            tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1133
                        }
1134
                    }
1135
                }
1136
            }
1137
        }
1138
1139
1
        non_zero_found = non_zero_found_short[0] |
1140
1
                         non_zero_found_short[1] |
1141
1
                         non_zero_found_short[2];
1142
1143
23
        for (i = g1->long_end - 1;i >= 0;i--) {
1144
22
            len   = band_size_long[s->sample_rate_index][i];
1145
22
            tab0 -= len;
1146
22
            tab1 -= len;
1147
            /* test if non zero band. if so, stop doing i-stereo */
1148
22
            if (!non_zero_found) {
1149
598
                for (j = 0; j < len; j++) {
1150
576
                    if (tab1[j] != 0) {
1151
                        non_zero_found = 1;
1152
                        goto found2;
1153
                    }
1154
                }
1155
                /* for last band, use previous scale factor */
1156
22
                k  = (i == 21) ? 20 : i;
1157
22
                sf = g1->scale_factors[k];
1158
22
                if (sf >= sf_max)
1159
                    goto found2;
1160
22
                v1 = is_tab[0][sf];
1161
22
                v2 = is_tab[1][sf];
1162
598
                for (j = 0; j < len; j++) {
1163
576
                    tmp0    = tab0[j];
1164
576
                    tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1165
576
                    tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1166
                }
1167
            } else {
1168
found2:
1169
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1170
                    /* lower part of the spectrum : do ms stereo
1171
                       if enabled */
1172
                    for (j = 0; j < len; j++) {
1173
                        tmp0    = tab0[j];
1174
                        tmp1    = tab1[j];
1175
                        tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1176
                        tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1177
                    }
1178
                }
1179
            }
1180
        }
1181
2446
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1182
        /* ms stereo ONLY */
1183
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1184
           global gain */
1185
#if USE_FLOATS
1186
52
       s->butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1187
#else
1188
2176
        tab0 = g0->sb_hybrid;
1189
2176
        tab1 = g1->sb_hybrid;
1190
1255552
        for (i = 0; i < 576; i++) {
1191
1253376
            tmp0    = tab0[i];
1192
1253376
            tmp1    = tab1[i];
1193
1253376
            tab0[i] = tmp0 + tmp1;
1194
1253376
            tab1[i] = tmp0 - tmp1;
1195
        }
1196
#endif
1197
    }
1198
2447
}
1199
1200
#if USE_FLOATS
1201
#if HAVE_MIPSFPU
1202
#   include "mips/compute_antialias_float.h"
1203
#endif /* HAVE_MIPSFPU */
1204
#else
1205
#if HAVE_MIPSDSP
1206
#   include "mips/compute_antialias_fixed.h"
1207
#endif /* HAVE_MIPSDSP */
1208
#endif /* USE_FLOATS */
1209
1210
#ifndef compute_antialias
1211
#if USE_FLOATS
1212
#define AA(j) do {                                                      \
1213
        float tmp0 = ptr[-1-j];                                         \
1214
        float tmp1 = ptr[   j];                                         \
1215
        ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1];    \
1216
        ptr[   j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0];    \
1217
    } while (0)
1218
#else
1219
#define AA(j) do {                                              \
1220
        SUINT tmp0 = ptr[-1-j];                                   \
1221
        SUINT tmp1 = ptr[   j];                                   \
1222
        SUINT tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]);          \
1223
        ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2]));   \
1224
        ptr[   j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3]));   \
1225
    } while (0)
1226
#endif
1227
1228
8112
static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1229
{
1230
    INTFLOAT *ptr;
1231
    int n, i;
1232
1233
    /* we antialias only "long" bands */
1234
8112
    if (g->block_type == 2) {
1235
304
        if (!g->switch_point)
1236
291
            return;
1237
        /* XXX: check this for 8000Hz case */
1238
13
        n = 1;
1239
    } else {
1240
7808
        n = SBLIMIT - 1;
1241
    }
1242
1243
7821
    ptr = g->sb_hybrid + 18;
1244
249882
    for (i = n; i > 0; i--) {
1245
242061
        AA(0);
1246
242061
        AA(1);
1247
242061
        AA(2);
1248
242061
        AA(3);
1249
242061
        AA(4);
1250
242061
        AA(5);
1251
242061
        AA(6);
1252
242061
        AA(7);
1253
1254
242061
        ptr += 18;
1255
    }
1256
}
1257
#endif /* compute_antialias */
1258
1259
8116
static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1260
                          INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1261
{
1262
    INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1263
    INTFLOAT out2[12];
1264
    int i, j, mdct_long_end, sblimit;
1265
1266
    /* find last non zero block */
1267
8116
    ptr  = g->sb_hybrid + 576;
1268
8116
    ptr1 = g->sb_hybrid + 2 * 18;
1269
312005
    while (ptr >= ptr1) {
1270
        int32_t *p;
1271
311823
        ptr -= 6;
1272
311823
        p    = (int32_t*)ptr;
1273
311823
        if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1274
7934
            break;
1275
    }
1276
8116
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1277
1278
8116
    if (g->block_type == 2) {
1279
        /* XXX: check for 8000 Hz */
1280
305
        if (g->switch_point)
1281
13
            mdct_long_end = 2;
1282
        else
1283
292
            mdct_long_end = 0;
1284
    } else {
1285
7811
        mdct_long_end = sblimit;
1286
    }
1287
1288
8116
    s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1289
8116
                                     mdct_long_end, g->switch_point,
1290
8116
                                     g->block_type);
1291
1292
8116
    buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1293
8116
    ptr = g->sb_hybrid + 18 * mdct_long_end;
1294
1295
14573
    for (j = mdct_long_end; j < sblimit; j++) {
1296
        /* select frequency inversion */
1297
6457
        win     = RENAME(ff_mdct_win)[2 + (4  & -(j & 1))];
1298
6457
        out_ptr = sb_samples + j;
1299
1300
45199
        for (i = 0; i < 6; i++) {
1301
38742
            *out_ptr = buf[4*i];
1302
38742
            out_ptr += SBLIMIT;
1303
        }
1304
6457
        imdct12(out2, ptr + 0);
1305
45199
        for (i = 0; i < 6; i++) {
1306
38742
            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*1)];
1307
38742
            buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1308
38742
            out_ptr += SBLIMIT;
1309
        }
1310
6457
        imdct12(out2, ptr + 1);
1311
45199
        for (i = 0; i < 6; i++) {
1312
38742
            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*2)];
1313
38742
            buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1314
38742
            out_ptr += SBLIMIT;
1315
        }
1316
6457
        imdct12(out2, ptr + 2);
1317
45199
        for (i = 0; i < 6; i++) {
1318
38742
            buf[4*(i + 6*0)] = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*0)];
1319
38742
            buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1320
38742
            buf[4*(i + 6*2)] = 0;
1321
        }
1322
6457
        ptr += 18;
1323
6457
        buf += (j&3) != 3 ? 1 : (4*18-3);
1324
    }
1325
    /* zero bands */
1326
105676
    for (j = sblimit; j < SBLIMIT; j++) {
1327
        /* overlap */
1328
97560
        out_ptr = sb_samples + j;
1329
1853640
        for (i = 0; i < 18; i++) {
1330
1756080
            *out_ptr = buf[4*i];
1331
1756080
            buf[4*i]   = 0;
1332
1756080
            out_ptr += SBLIMIT;
1333
        }
1334
97560
        buf += (j&3) != 3 ? 1 : (4*18-3);
1335
    }
1336
8116
}
1337
1338
/* main layer3 decoding function */
1339
2803
static int mp_decode_layer3(MPADecodeContext *s)
1340
{
1341
    int nb_granules, main_data_begin;
1342
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1343
    GranuleDef *g;
1344
    int16_t exponents[576]; //FIXME try INTFLOAT
1345
    int ret;
1346
1347
    /* read side info */
1348
2803
    if (s->lsf) {
1349
3
        ret = handle_crc(s, ((s->nb_channels == 1) ? 8*9  : 8*17));
1350
3
        main_data_begin = get_bits(&s->gb, 8);
1351
3
        skip_bits(&s->gb, s->nb_channels);
1352
3
        nb_granules = 1;
1353
    } else {
1354
2800
        ret = handle_crc(s, ((s->nb_channels == 1) ? 8*17 : 8*32));
1355
2800
        main_data_begin = get_bits(&s->gb, 9);
1356
2800
        if (s->nb_channels == 2)
1357
1256
            skip_bits(&s->gb, 3);
1358
        else
1359
1544
            skip_bits(&s->gb, 5);
1360
2800
        nb_granules = 2;
1361
6856
        for (ch = 0; ch < s->nb_channels; ch++) {
1362
4056
            s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1363
4056
            s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1364
        }
1365
    }
1366
2803
    if (ret < 0)
1367
        return ret;
1368
1369
8406
    for (gr = 0; gr < nb_granules; gr++) {
1370
13719
        for (ch = 0; ch < s->nb_channels; ch++) {
1371
            ff_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1372
8116
            g = &s->granules[ch][gr];
1373
8116
            g->part2_3_length = get_bits(&s->gb, 12);
1374
8116
            g->big_values     = get_bits(&s->gb,  9);
1375
8116
            if (g->big_values > 288) {
1376
                av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1377
                return AVERROR_INVALIDDATA;
1378
            }
1379
1380
8116
            g->global_gain = get_bits(&s->gb, 8);
1381
            /* if MS stereo only is selected, we precompute the
1382
               1/sqrt(2) renormalization factor */
1383
8116
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1384
                MODE_EXT_MS_STEREO)
1385
4456
                g->global_gain -= 2;
1386
8116
            if (s->lsf)
1387
4
                g->scalefac_compress = get_bits(&s->gb, 9);
1388
            else
1389
8112
                g->scalefac_compress = get_bits(&s->gb, 4);
1390
8116
            blocksplit_flag = get_bits1(&s->gb);
1391
8116
            if (blocksplit_flag) {
1392
845
                g->block_type = get_bits(&s->gb, 2);
1393
845
                if (g->block_type == 0) {
1394
                    av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1395
                    return AVERROR_INVALIDDATA;
1396
                }
1397
845
                g->switch_point = get_bits1(&s->gb);
1398
2535
                for (i = 0; i < 2; i++)
1399
1690
                    g->table_select[i] = get_bits(&s->gb, 5);
1400
3380
                for (i = 0; i < 3; i++)
1401
2535
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
1402
845
                init_short_region(s, g);
1403
            } else {
1404
                int region_address1, region_address2;
1405
7271
                g->block_type = 0;
1406
7271
                g->switch_point = 0;
1407
29084
                for (i = 0; i < 3; i++)
1408
21813
                    g->table_select[i] = get_bits(&s->gb, 5);
1409
                /* compute huffman coded region sizes */
1410
7271
                region_address1 = get_bits(&s->gb, 4);
1411
7271
                region_address2 = get_bits(&s->gb, 3);
1412
                ff_dlog(s->avctx, "region1=%d region2=%d\n",
1413
                        region_address1, region_address2);
1414
7271
                init_long_region(s, g, region_address1, region_address2);
1415
            }
1416
8116
            region_offset2size(g);
1417
8116
            compute_band_indexes(s, g);
1418
1419
8116
            g->preflag = 0;
1420
8116
            if (!s->lsf)
1421
8112
                g->preflag = get_bits1(&s->gb);
1422
8116
            g->scalefac_scale     = get_bits1(&s->gb);
1423
8116
            g->count1table_select = get_bits1(&s->gb);
1424
            ff_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1425
                    g->block_type, g->switch_point);
1426
        }
1427
    }
1428
1429
2803
    if (!s->adu_mode) {
1430
        int skip;
1431
2803
        const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb) >> 3);
1432
2803
        s->extrasize = av_clip((get_bits_left(&s->gb) >> 3) - s->extrasize, 0,
1433
2803
                               FFMAX(0, LAST_BUF_SIZE - s->last_buf_size));
1434
        av_assert1((get_bits_count(&s->gb) & 7) == 0);
1435
        /* now we get bits from the main_data_begin offset */
1436
        ff_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1437
                main_data_begin, s->last_buf_size);
1438
1439
2803
        memcpy(s->last_buf + s->last_buf_size, ptr, s->extrasize);
1440
2803
        s->in_gb = s->gb;
1441
2803
        init_get_bits(&s->gb, s->last_buf, (s->last_buf_size + s->extrasize) * 8);
1442
2803
        s->last_buf_size <<= 3;
1443

2807
        for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1444
8
            for (ch = 0; ch < s->nb_channels; ch++) {
1445
4
                g = &s->granules[ch][gr];
1446
4
                s->last_buf_size += g->part2_3_length;
1447
4
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1448
4
                compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1449
            }
1450
        }
1451
2803
        skip = s->last_buf_size - 8 * main_data_begin;
1452

2803
        if (skip >= s->gb.size_in_bits - s->extrasize * 8 && s->in_gb.buffer) {
1453
145
            skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits + s->extrasize * 8);
1454
145
            s->gb           = s->in_gb;
1455
145
            s->in_gb.buffer = NULL;
1456
145
            s->extrasize    = 0;
1457
        } else {
1458
2658
            skip_bits_long(&s->gb, skip);
1459
        }
1460
    } else {
1461
        gr = 0;
1462
        s->extrasize = 0;
1463
    }
1464
1465
8402
    for (; gr < nb_granules; gr++) {
1466
13711
        for (ch = 0; ch < s->nb_channels; ch++) {
1467
8112
            g = &s->granules[ch][gr];
1468
8112
            bits_pos = get_bits_count(&s->gb);
1469
1470
8112
            if (!s->lsf) {
1471
                uint8_t *sc;
1472
                int slen, slen1, slen2;
1473
1474
                /* MPEG-1 scale factors */
1475
8108
                slen1 = slen_table[0][g->scalefac_compress];
1476
8108
                slen2 = slen_table[1][g->scalefac_compress];
1477
                ff_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1478
8108
                if (g->block_type == 2) {
1479
304
                    n = g->switch_point ? 17 : 18;
1480
304
                    j = 0;
1481
304
                    if (slen1) {
1482
756
                        for (i = 0; i < n; i++)
1483
716
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
1484
                    } else {
1485
5007
                        for (i = 0; i < n; i++)
1486
4743
                            g->scale_factors[j++] = 0;
1487
                    }
1488
304
                    if (slen2) {
1489
4826
                        for (i = 0; i < 18; i++)
1490
4572
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
1491
1016
                        for (i = 0; i < 3; i++)
1492
762
                            g->scale_factors[j++] = 0;
1493
                    } else {
1494
1100
                        for (i = 0; i < 21; i++)
1495
1050
                            g->scale_factors[j++] = 0;
1496
                    }
1497
                } else {
1498
7804
                    sc = s->granules[ch][0].scale_factors;
1499
7804
                    j = 0;
1500
39020
                    for (k = 0; k < 4; k++) {
1501
31216
                        n = k == 0 ? 6 : 5;
1502
31216
                        if ((g->scfsi & (0x8 >> k)) == 0) {
1503
26870
                            slen = (k < 2) ? slen1 : slen2;
1504
26870
                            if (slen) {
1505
88829
                                for (i = 0; i < n; i++)
1506
74467
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
1507
                            } else {
1508
78786
                                for (i = 0; i < n; i++)
1509
66278
                                    g->scale_factors[j++] = 0;
1510
                            }
1511
                        } else {
1512
                            /* simply copy from last granule */
1513
27485
                            for (i = 0; i < n; i++) {
1514
23139
                                g->scale_factors[j] = sc[j];
1515
23139
                                j++;
1516
                            }
1517
                        }
1518
                    }
1519
7804
                    g->scale_factors[j++] = 0;
1520
                }
1521
            } else {
1522
                int tindex, tindex2, slen[4], sl, sf;
1523
1524
                /* LSF scale factors */
1525
4
                if (g->block_type == 2)
1526
                    tindex = g->switch_point ? 2 : 1;
1527
                else
1528
4
                    tindex = 0;
1529
1530
4
                sf = g->scalefac_compress;
1531

4
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1532
                    /* intensity stereo case */
1533
1
                    sf >>= 1;
1534
1
                    if (sf < 180) {
1535
1
                        lsf_sf_expand(slen, sf, 6, 6, 0);
1536
1
                        tindex2 = 3;
1537
                    } else if (sf < 244) {
1538
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1539
                        tindex2 = 4;
1540
                    } else {
1541
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1542
                        tindex2 = 5;
1543
                    }
1544
                } else {
1545
                    /* normal case */
1546
3
                    if (sf < 400) {
1547
1
                        lsf_sf_expand(slen, sf, 5, 4, 4);
1548
1
                        tindex2 = 0;
1549
2
                    } else if (sf < 500) {
1550
2
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1551
2
                        tindex2 = 1;
1552
                    } else {
1553
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1554
                        tindex2 = 2;
1555
                        g->preflag = 1;
1556
                    }
1557
                }
1558
1559
4
                j = 0;
1560
20
                for (k = 0; k < 4; k++) {
1561
16
                    n  = lsf_nsf_table[tindex2][tindex][k];
1562
16
                    sl = slen[k];
1563
16
                    if (sl) {
1564
45
                        for (i = 0; i < n; i++)
1565
39
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
1566
                    } else {
1567
55
                        for (i = 0; i < n; i++)
1568
45
                            g->scale_factors[j++] = 0;
1569
                    }
1570
                }
1571
                /* XXX: should compute exact size */
1572
80
                for (; j < 40; j++)
1573
76
                    g->scale_factors[j] = 0;
1574
            }
1575
1576
8112
            exponents_from_scale_factors(s, g, exponents);
1577
1578
            /* read Huffman coded residue */
1579
8112
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1580
        } /* ch */
1581
1582
5599
        if (s->mode == MPA_JSTEREO)
1583
2447
            compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1584
1585
13711
        for (ch = 0; ch < s->nb_channels; ch++) {
1586
8112
            g = &s->granules[ch][gr];
1587
1588
8112
            reorder_block(s, g);
1589
8112
            compute_antialias(s, g);
1590
8112
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1591
        }
1592
    } /* gr */
1593
2803
    if (get_bits_count(&s->gb) < 0)
1594
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1595
2803
    return nb_granules * 18;
1596
}
1597
1598
10040
static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1599
                           const uint8_t *buf, int buf_size)
1600
{
1601
    int i, nb_frames, ch, ret;
1602
    OUT_INT *samples_ptr;
1603
1604
10040
    init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1605
10040
    if (s->error_protection)
1606
117
        s->crc = get_bits(&s->gb, 16);
1607
1608

10040
    switch(s->layer) {
1609
    case 1:
1610
        s->avctx->frame_size = 384;
1611
        nb_frames = mp_decode_layer1(s);
1612
        break;
1613
7237
    case 2:
1614
7237
        s->avctx->frame_size = 1152;
1615
7237
        nb_frames = mp_decode_layer2(s);
1616
7237
        break;
1617
2803
    case 3:
1618
2803
        s->avctx->frame_size = s->lsf ? 576 : 1152;
1619
2803
    default:
1620
2803
        nb_frames = mp_decode_layer3(s);
1621
1622
2803
        s->last_buf_size=0;
1623
2803
        if (s->in_gb.buffer) {
1624
1719
            align_get_bits(&s->gb);
1625
1719
            i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1626

1719
            if (i >= 0 && i <= BACKSTEP_SIZE) {
1627
1719
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb) >> 3), i);
1628
1719
                s->last_buf_size=i;
1629
            } else
1630
                av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1631
1719
            s->gb           = s->in_gb;
1632
1719
            s->in_gb.buffer = NULL;
1633
1719
            s->extrasize    = 0;
1634
        }
1635
1636
2803
        align_get_bits(&s->gb);
1637
        av_assert1((get_bits_count(&s->gb) & 7) == 0);
1638
2803
        i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1639

2803
        if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1640
230
            if (i < 0)
1641
                av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1642
230
            i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1643
        }
1644
        av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1645
2803
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1646
2803
        s->last_buf_size += i;
1647
    }
1648
1649
10040
    if(nb_frames < 0)
1650
        return nb_frames;
1651
1652
    /* get output buffer */
1653
10040
    if (!samples) {
1654
10040
        av_assert0(s->frame);
1655
10040
        s->frame->nb_samples = s->avctx->frame_size;
1656
10040
        if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0)
1657
            return ret;
1658
10040
        samples = (OUT_INT **)s->frame->extended_data;
1659
    }
1660
1661
    /* apply the synthesis filter */
1662
21983
    for (ch = 0; ch < s->nb_channels; ch++) {
1663
        int sample_stride;
1664
11943
        if (s->avctx->sample_fmt == OUT_FMT_P) {
1665
11943
            samples_ptr   = samples[ch];
1666
11943
            sample_stride = 1;
1667
        } else {
1668
            samples_ptr   = samples[0] + ch;
1669
            sample_stride = s->nb_channels;
1670
        }
1671
441819
        for (i = 0; i < nb_frames; i++) {
1672
429876
            RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1673
                                        &(s->synth_buf_offset[ch]),
1674
                                        RENAME(ff_mpa_synth_window),
1675
                                        &s->dither_state, samples_ptr,
1676
429876
                                        sample_stride, s->sb_samples[ch][i]);
1677
429876
            samples_ptr += 32 * sample_stride;
1678
        }
1679
    }
1680
1681
10040
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1682
}
1683
1684
10042
static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1685
                        AVPacket *avpkt)
1686
{
1687
10042
    const uint8_t *buf  = avpkt->data;
1688
10042
    int buf_size        = avpkt->size;
1689
10042
    MPADecodeContext *s = avctx->priv_data;
1690
    uint32_t header;
1691
    int ret;
1692
1693
10042
    int skipped = 0;
1694

10042
    while(buf_size && !*buf){
1695
        buf++;
1696
        buf_size--;
1697
        skipped++;
1698
    }
1699
1700
10042
    if (buf_size < HEADER_SIZE)
1701
        return AVERROR_INVALIDDATA;
1702
1703
10042
    header = AV_RB32(buf);
1704
10042
    if (header >> 8 == AV_RB32("TAG") >> 8) {
1705
        av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
1706
        return buf_size + skipped;
1707
    }
1708
10042
    ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1709
10042
    if (ret < 0) {
1710
2
        av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1711
2
        return AVERROR_INVALIDDATA;
1712
10040
    } else if (ret == 1) {
1713
        /* free format: prepare to compute frame size */
1714
        s->frame_size = -1;
1715
        return AVERROR_INVALIDDATA;
1716
    }
1717
    /* update codec info */
1718
10040
    avctx->channels       = s->nb_channels;
1719
10040
    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1720
10040
    if (!avctx->bit_rate)
1721
4
        avctx->bit_rate = s->bit_rate;
1722
1723
10040
    if (s->frame_size <= 0) {
1724
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1725
        return AVERROR_INVALIDDATA;
1726
10040
    } else if (s->frame_size < buf_size) {
1727
        av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1728
        buf_size= s->frame_size;
1729
    }
1730
1731
10040
    s->frame = data;
1732
1733
10040
    ret = mp_decode_frame(s, NULL, buf, buf_size);
1734
10040
    if (ret >= 0) {
1735
10040
        s->frame->nb_samples = avctx->frame_size;
1736
10040
        *got_frame_ptr       = 1;
1737
10040
        avctx->sample_rate   = s->sample_rate;
1738
        //FIXME maybe move the other codec info stuff from above here too
1739
    } else {
1740
        av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1741
        /* Only return an error if the bad frame makes up the whole packet or
1742
         * the error is related to buffer management.
1743
         * If there is more data in the packet, just consume the bad frame
1744
         * instead of returning an error, which would discard the whole
1745
         * packet. */
1746
        *got_frame_ptr = 0;
1747
        if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1748
            return ret;
1749
    }
1750
10040
    s->frame_size = 0;
1751
10040
    return buf_size + skipped;
1752
}
1753
1754
static void mp_flush(MPADecodeContext *ctx)
1755
{
1756
    memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1757
    memset(ctx->mdct_buf, 0, sizeof(ctx->mdct_buf));
1758
    ctx->last_buf_size = 0;
1759
    ctx->dither_state = 0;
1760
}
1761
1762
static void flush(AVCodecContext *avctx)
1763
{
1764
    mp_flush(avctx->priv_data);
1765
}
1766
1767
#if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1768
static int decode_frame_adu(AVCodecContext *avctx, void *data,
1769
                            int *got_frame_ptr, AVPacket *avpkt)
1770
{
1771
    const uint8_t *buf  = avpkt->data;
1772
    int buf_size        = avpkt->size;
1773
    MPADecodeContext *s = avctx->priv_data;
1774
    uint32_t header;
1775
    int len, ret;
1776
    int av_unused out_size;
1777
1778
    len = buf_size;
1779
1780
    // Discard too short frames
1781
    if (buf_size < HEADER_SIZE) {
1782
        av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1783
        return AVERROR_INVALIDDATA;
1784
    }
1785
1786
1787
    if (len > MPA_MAX_CODED_FRAME_SIZE)
1788
        len = MPA_MAX_CODED_FRAME_SIZE;
1789
1790
    // Get header and restore sync word
1791
    header = AV_RB32(buf) | 0xffe00000;
1792
1793
    ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1794
    if (ret < 0) {
1795
        av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1796
        return ret;
1797
    }
1798
    /* update codec info */
1799
    avctx->sample_rate = s->sample_rate;
1800
    avctx->channels    = s->nb_channels;
1801
    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1802
    if (!avctx->bit_rate)
1803
        avctx->bit_rate = s->bit_rate;
1804
1805
    s->frame_size = len;
1806
1807
    s->frame = data;
1808
1809
    ret = mp_decode_frame(s, NULL, buf, buf_size);
1810
    if (ret < 0) {
1811
        av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1812
        return ret;
1813
    }
1814
1815
    *got_frame_ptr = 1;
1816
1817
    return buf_size;
1818
}
1819
#endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1820
1821
#if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1822
1823
/**
1824
 * Context for MP3On4 decoder
1825
 */
1826
typedef struct MP3On4DecodeContext {
1827
    int frames;                     ///< number of mp3 frames per block (number of mp3 decoder instances)
1828
    int syncword;                   ///< syncword patch
1829
    const uint8_t *coff;            ///< channel offsets in output buffer
1830
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1831
} MP3On4DecodeContext;
1832
1833
#include "mpeg4audio.h"
1834
1835
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1836
1837
/* number of mp3 decoder instances */
1838
static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1839
1840
/* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1841
static const uint8_t chan_offset[8][5] = {
1842
    { 0             },
1843
    { 0             },  // C
1844
    { 0             },  // FLR
1845
    { 2, 0          },  // C FLR
1846
    { 2, 0, 3       },  // C FLR BS
1847
    { 2, 0, 3       },  // C FLR BLRS
1848
    { 2, 0, 4, 3    },  // C FLR BLRS LFE
1849
    { 2, 0, 6, 4, 3 },  // C FLR BLRS BLR LFE
1850
};
1851
1852
/* mp3on4 channel layouts */
1853
static const int16_t chan_layout[8] = {
1854
    0,
1855
    AV_CH_LAYOUT_MONO,
1856
    AV_CH_LAYOUT_STEREO,
1857
    AV_CH_LAYOUT_SURROUND,
1858
    AV_CH_LAYOUT_4POINT0,
1859
    AV_CH_LAYOUT_5POINT0,
1860
    AV_CH_LAYOUT_5POINT1,
1861
    AV_CH_LAYOUT_7POINT1
1862
};
1863
1864
static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1865
{
1866
    MP3On4DecodeContext *s = avctx->priv_data;
1867
    int i;
1868
1869
    for (i = 0; i < s->frames; i++)
1870
        av_freep(&s->mp3decctx[i]);
1871
1872
    return 0;
1873
}
1874
1875
1876
static av_cold int decode_init_mp3on4(AVCodecContext * avctx)
1877
{
1878
    MP3On4DecodeContext *s = avctx->priv_data;
1879
    MPEG4AudioConfig cfg;
1880
    int i, ret;
1881
1882
    if ((avctx->extradata_size < 2) || !avctx->extradata) {
1883
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1884
        return AVERROR_INVALIDDATA;
1885
    }
1886
1887
    avpriv_mpeg4audio_get_config2(&cfg, avctx->extradata,
1888
                                  avctx->extradata_size, 1, avctx);
1889
    if (!cfg.chan_config || cfg.chan_config > 7) {
1890
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1891
        return AVERROR_INVALIDDATA;
1892
    }
1893
    s->frames             = mp3Frames[cfg.chan_config];
1894
    s->coff               = chan_offset[cfg.chan_config];
1895
    avctx->channels       = ff_mpeg4audio_channels[cfg.chan_config];
1896
    avctx->channel_layout = chan_layout[cfg.chan_config];
1897
1898
    if (cfg.sample_rate < 16000)
1899
        s->syncword = 0xffe00000;
1900
    else
1901
        s->syncword = 0xfff00000;
1902
1903
    /* Init the first mp3 decoder in standard way, so that all tables get builded
1904
     * We replace avctx->priv_data with the context of the first decoder so that
1905
     * decode_init() does not have to be changed.
1906
     * Other decoders will be initialized here copying data from the first context
1907
     */
1908
    // Allocate zeroed memory for the first decoder context
1909
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1910
    if (!s->mp3decctx[0])
1911
        return AVERROR(ENOMEM);
1912
    // Put decoder context in place to make init_decode() happy
1913
    avctx->priv_data = s->mp3decctx[0];
1914
    ret = decode_init(avctx);
1915
    // Restore mp3on4 context pointer
1916
    avctx->priv_data = s;
1917
    if (ret < 0)
1918
        return ret;
1919
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1920
1921
    /* Create a separate codec/context for each frame (first is already ok).
1922
     * Each frame is 1 or 2 channels - up to 5 frames allowed
1923
     */
1924
    for (i = 1; i < s->frames; i++) {
1925
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1926
        if (!s->mp3decctx[i])
1927
            return AVERROR(ENOMEM);
1928
        s->mp3decctx[i]->adu_mode = 1;
1929
        s->mp3decctx[i]->avctx = avctx;
1930
        s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1931
        s->mp3decctx[i]->butterflies_float = s->mp3decctx[0]->butterflies_float;
1932
    }
1933
1934
    return 0;
1935
}
1936
1937
1938
static void flush_mp3on4(AVCodecContext *avctx)
1939
{
1940
    int i;
1941
    MP3On4DecodeContext *s = avctx->priv_data;
1942
1943
    for (i = 0; i < s->frames; i++)
1944
        mp_flush(s->mp3decctx[i]);
1945
}
1946
1947
1948
static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1949
                               int *got_frame_ptr, AVPacket *avpkt)
1950
{
1951
    AVFrame *frame         = data;
1952
    const uint8_t *buf     = avpkt->data;
1953
    int buf_size           = avpkt->size;
1954
    MP3On4DecodeContext *s = avctx->priv_data;
1955
    MPADecodeContext *m;
1956
    int fsize, len = buf_size, out_size = 0;
1957
    uint32_t header;
1958
    OUT_INT **out_samples;
1959
    OUT_INT *outptr[2];
1960
    int fr, ch, ret;
1961
1962
    /* get output buffer */
1963
    frame->nb_samples = MPA_FRAME_SIZE;
1964
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1965
        return ret;
1966
    out_samples = (OUT_INT **)frame->extended_data;
1967
1968
    // Discard too short frames
1969
    if (buf_size < HEADER_SIZE)
1970
        return AVERROR_INVALIDDATA;
1971
1972
    avctx->bit_rate = 0;
1973
1974
    ch = 0;
1975
    for (fr = 0; fr < s->frames; fr++) {
1976
        fsize = AV_RB16(buf) >> 4;
1977
        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1978
        m     = s->mp3decctx[fr];
1979
        av_assert1(m);
1980
1981
        if (fsize < HEADER_SIZE) {
1982
            av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1983
            return AVERROR_INVALIDDATA;
1984
        }
1985
        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1986
1987
        ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1988
        if (ret < 0) {
1989
            av_log(avctx, AV_LOG_ERROR, "Bad header, discard block\n");
1990
            return AVERROR_INVALIDDATA;
1991
        }
1992
1993
        if (ch + m->nb_channels > avctx->channels ||
1994
            s->coff[fr] + m->nb_channels > avctx->channels) {
1995
            av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1996
                                        "channel count\n");
1997
            return AVERROR_INVALIDDATA;
1998
        }
1999
        ch += m->nb_channels;
2000
2001
        outptr[0] = out_samples[s->coff[fr]];
2002
        if (m->nb_channels > 1)
2003
            outptr[1] = out_samples[s->coff[fr] + 1];
2004
2005
        if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0) {
2006
            av_log(avctx, AV_LOG_ERROR, "failed to decode channel %d\n", ch);
2007
            memset(outptr[0], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2008
            if (m->nb_channels > 1)
2009
                memset(outptr[1], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2010
            ret = m->nb_channels * MPA_FRAME_SIZE*sizeof(OUT_INT);
2011
        }
2012
2013
        out_size += ret;
2014
        buf      += fsize;
2015
        len      -= fsize;
2016
2017
        avctx->bit_rate += m->bit_rate;
2018
    }
2019
    if (ch != avctx->channels) {
2020
        av_log(avctx, AV_LOG_ERROR, "failed to decode all channels\n");
2021
        return AVERROR_INVALIDDATA;
2022
    }
2023
2024
    /* update codec info */
2025
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2026
2027
    frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
2028
    *got_frame_ptr    = 1;
2029
2030
    return buf_size;
2031
}
2032
#endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */