Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3dec.c @ 4611b64e

History | View | Annotate | Download (54.3 KB)

1
/*
2
 * AC-3 Audio Decoder
3
 * This code is developed as part of Google Summer of Code 2006 Program.
4
 *
5
 * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com).
6
 * Copyright (c) 2007 Justin Ruggles
7
 *
8
 * Portions of this code are derived from liba52
9
 * http://liba52.sourceforge.net
10
 * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
11
 * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
12
 *
13
 * This file is part of FFmpeg.
14
 *
15
 * FFmpeg is free software; you can redistribute it and/or
16
 * modify it under the terms of the GNU General Public
17
 * License as published by the Free Software Foundation; either
18
 * version 2 of the License, or (at your option) any later version.
19
 *
20
 * FFmpeg is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23
 * General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public
26
 * License along with FFmpeg; if not, write to the Free Software
27
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28
 */
29

    
30
#include <stdio.h>
31
#include <stddef.h>
32
#include <math.h>
33
#include <string.h>
34

    
35
#include "avcodec.h"
36
#include "ac3_parser.h"
37
#include "bitstream.h"
38
#include "dsputil.h"
39
#include "random.h"
40

    
41
static const int nfchans_tbl[8] = { 2, 1, 2, 3, 3, 4, 4, 5 };
42

    
43
/* table for exponent to scale_factor mapping
44
 * scale_factor[i] = 2 ^ -(i + 15)
45
 */
46
static float scale_factors[25];
47

    
48
/** table for grouping exponents */
49
static uint8_t exp_ungroup_tbl[128][3];
50

    
51
static int16_t l3_quantizers_1[32];
52
static int16_t l3_quantizers_2[32];
53
static int16_t l3_quantizers_3[32];
54

    
55
static int16_t l5_quantizers_1[128];
56
static int16_t l5_quantizers_2[128];
57
static int16_t l5_quantizers_3[128];
58

    
59
static int16_t l7_quantizers[7];
60

    
61
static int16_t l11_quantizers_1[128];
62
static int16_t l11_quantizers_2[128];
63

    
64
static int16_t l15_quantizers[15];
65

    
66
static const uint8_t qntztab[16] = { 0, 5, 7, 3, 7, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16 };
67

    
68
/* Adjustmens in dB gain */
69
#define LEVEL_MINUS_3DB         0.7071067811865476
70
#define LEVEL_MINUS_4POINT5DB   0.5946035575013605
71
#define LEVEL_MINUS_6DB         0.5000000000000000
72
#define LEVEL_PLUS_3DB          1.4142135623730951
73
#define LEVEL_PLUS_6DB          2.0000000000000000
74
#define LEVEL_ZERO              0.0000000000000000
75

    
76
static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
77
    LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
78

    
79
static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
80

    
81
#define BLOCK_SIZE    256
82

    
83
/* Output and input configurations. */
84
#define AC3_OUTPUT_UNMODIFIED   0x01
85
#define AC3_OUTPUT_MONO         0x02
86
#define AC3_OUTPUT_STEREO       0x04
87
#define AC3_OUTPUT_DOLBY        0x08
88
#define AC3_OUTPUT_LFEON        0x10
89

    
90
typedef struct {
91
    int acmod;
92
    int cmixlev;
93
    int surmixlev;
94
    int dsurmod;
95

    
96
    int blksw[AC3_MAX_CHANNELS];
97
    int dithflag[AC3_MAX_CHANNELS];
98
    int cplinu;
99
    int chincpl[AC3_MAX_CHANNELS];
100
    int phsflginu;
101
    int cplbegf;
102
    int cplendf;
103
    int cplcoe;
104
    uint32_t cplbndstrc;
105
    int rematstr;
106
    int rematflg[AC3_MAX_CHANNELS];
107
    int cplexpstr;
108
    int lfeexpstr;
109
    int chexpstr[5];
110
    int cplsnroffst;
111
    int cplfgain;
112
    int snroffst[5];
113
    int fgain[5];
114
    int lfesnroffst;
115
    int lfefgain;
116
    int cpldeltbae;
117
    int deltbae[5];
118
    int cpldeltnseg;
119
    uint8_t  cpldeltoffst[8];
120
    uint8_t  cpldeltlen[8];
121
    uint8_t  cpldeltba[8];
122
    int deltnseg[5];
123
    uint8_t  deltoffst[5][8];
124
    uint8_t  deltlen[5][8];
125
    uint8_t  deltba[5][8];
126

    
127
    /* Derived Attributes. */
128
    int      sampling_rate;
129
    int      bit_rate;
130
    int      frame_size;
131

    
132
    int      nchans;            //number of total channels
133
    int      nfchans;           //number of full-bandwidth channels
134
    int      lfeon;             //lfe channel in use
135

    
136
    float    dynrng;            //dynamic range gain
137
    float    dynrng2;           //dynamic range gain for 1+1 mode
138
    float    chcoeffs[6];       //normalized channel coefficients
139
    float    cplco[5][18];      //coupling coordinates
140
    int      ncplbnd;           //number of coupling bands
141
    int      ncplsubnd;         //number of coupling sub bands
142
    int      cplstrtmant;       //coupling start mantissa
143
    int      cplendmant;        //coupling end mantissa
144
    int      endmant[5];        //channel end mantissas
145
    AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
146

    
147
    int8_t   dcplexps[256];     //decoded coupling exponents
148
    int8_t   dexps[5][256];     //decoded fbw channel exponents
149
    int8_t   dlfeexps[256];     //decoded lfe channel exponents
150
    uint8_t  cplbap[256];       //coupling bit allocation pointers
151
    uint8_t  bap[5][256];       //fbw channel bit allocation pointers
152
    uint8_t  lfebap[256];       //lfe channel bit allocation pointers
153

    
154
    int      blkoutput;         //output configuration for block
155

    
156
    DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][BLOCK_SIZE]);  //transform coefficients
157

    
158
    /* For IMDCT. */
159
    MDCTContext imdct_512;  //for 512 sample imdct transform
160
    MDCTContext imdct_256;  //for 256 sample imdct transform
161
    DSPContext  dsp;        //for optimization
162

    
163
    DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS][BLOCK_SIZE]);    //output after imdct transform and windowing
164
    DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS][BLOCK_SIZE]);     //delay - added to the next block
165
    DECLARE_ALIGNED_16(float, tmp_imdct[BLOCK_SIZE]);               //temporary storage for imdct transform
166
    DECLARE_ALIGNED_16(float, tmp_output[BLOCK_SIZE * 2]);          //temporary storage for output before windowing
167
    DECLARE_ALIGNED_16(float, window[BLOCK_SIZE]);                  //window coefficients
168

    
169
    /* Miscellaneous. */
170
    GetBitContext gb;
171
    AVRandomState dith_state;   //for dither generation
172
} AC3DecodeContext;
173

    
174
/*********** BEGIN INIT HELPER FUNCTIONS ***********/
175
/**
176
 * Generate a Kaiser-Bessel Derived Window.
177
 */
178
static void ac3_window_init(float *window)
179
{
180
   int i, j;
181
   double sum = 0.0, bessel, tmp;
182
   double local_window[256];
183
   double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
184

    
185
   for (i = 0; i < 256; i++) {
186
       tmp = i * (256 - i) * alpha2;
187
       bessel = 1.0;
188
       for (j = 100; j > 0; j--) /* defaul to 100 iterations */
189
           bessel = bessel * tmp / (j * j) + 1;
190
       sum += bessel;
191
       local_window[i] = sum;
192
   }
193

    
194
   sum++;
195
   for (i = 0; i < 256; i++)
196
       window[i] = sqrt(local_window[i] / sum);
197
}
198

    
199
/*
200
 * Generate quantizer tables.
201
 */
202
static void generate_quantizers_table(int16_t quantizers[], int level, int length)
203
{
204
    int i;
205

    
206
    for (i = 0; i < length; i++)
207
        quantizers[i] = ((2 * i - level + 1) << 15) / level;
208
}
209

    
210
static void generate_quantizers_table_1(int16_t quantizers[], int level, int length1, int length2, int size)
211
{
212
    int i, j;
213
    int16_t v;
214

    
215
    for (i = 0; i < length1; i++) {
216
        v = ((2 * i - level + 1) << 15) / level;
217
        for (j = 0; j < length2; j++)
218
            quantizers[i * length2 + j] = v;
219
    }
220

    
221
    for (i = length1 * length2; i < size; i++)
222
        quantizers[i] = 0;
223
}
224

    
225
static void generate_quantizers_table_2(int16_t quantizers[], int level, int length1, int length2, int size)
226
{
227
    int i, j;
228
    int16_t v;
229

    
230
    for (i = 0; i < length1; i++) {
231
        v = ((2 * (i % level) - level + 1) << 15) / level;
232
        for (j = 0; j < length2; j++)
233
            quantizers[i * length2 + j] = v;
234
    }
235

    
236
    for (i = length1 * length2; i < size; i++)
237
        quantizers[i] = 0;
238

    
239
}
240

    
241
static void generate_quantizers_table_3(int16_t quantizers[], int level, int length1, int length2, int size)
242
{
243
    int i, j;
244

    
245
    for (i = 0; i < length1; i++)
246
        for (j = 0; j < length2; j++)
247
            quantizers[i * length2 + j] = ((2 * (j % level) - level + 1) << 15) / level;
248

    
249
    for (i = length1 * length2; i < size; i++)
250
        quantizers[i] = 0;
251
}
252

    
253
/*
254
 * Initialize tables at runtime.
255
 */
256
static void ac3_tables_init(void)
257
{
258
    int i;
259

    
260
    /* Quantizer ungrouping tables. */
261
    // for level-3 quantizers
262
    generate_quantizers_table_1(l3_quantizers_1, 3, 3, 9, 32);
263
    generate_quantizers_table_2(l3_quantizers_2, 3, 9, 3, 32);
264
    generate_quantizers_table_3(l3_quantizers_3, 3, 9, 3, 32);
265

    
266
    //for level-5 quantizers
267
    generate_quantizers_table_1(l5_quantizers_1, 5, 5, 25, 128);
268
    generate_quantizers_table_2(l5_quantizers_2, 5, 25, 5, 128);
269
    generate_quantizers_table_3(l5_quantizers_3, 5, 25, 5, 128);
270

    
271
    //for level-7 quantizers
272
    generate_quantizers_table(l7_quantizers, 7, 7);
273

    
274
    //for level-4 quantizers
275
    generate_quantizers_table_2(l11_quantizers_1, 11, 11, 11, 128);
276
    generate_quantizers_table_3(l11_quantizers_2, 11, 11, 11, 128);
277

    
278
    //for level-15 quantizers
279
    generate_quantizers_table(l15_quantizers, 15, 15);
280
    /* End Quantizer ungrouping tables. */
281

    
282
    //generate scale factors
283
    for (i = 0; i < 25; i++)
284
        scale_factors[i] = pow(2.0, -(i + 15));
285

    
286
    /* generate exponent tables
287
       reference: Section 7.1.3 Exponent Decoding */
288
    for(i=0; i<128; i++) {
289
        exp_ungroup_tbl[i][0] =  i / 25;
290
        exp_ungroup_tbl[i][1] = (i % 25) / 5;
291
        exp_ungroup_tbl[i][2] = (i % 25) % 5;
292
    }
293
}
294

    
295

    
296
static int ac3_decode_init(AVCodecContext *avctx)
297
{
298
    AC3DecodeContext *ctx = avctx->priv_data;
299

    
300
    ac3_common_init();
301
    ac3_tables_init();
302
    ff_mdct_init(&ctx->imdct_256, 8, 1);
303
    ff_mdct_init(&ctx->imdct_512, 9, 1);
304
    ac3_window_init(ctx->window);
305
    dsputil_init(&ctx->dsp, avctx);
306
    av_init_random(0, &ctx->dith_state);
307

    
308
    return 0;
309
}
310
/*********** END INIT FUNCTIONS ***********/
311

    
312
/**
313
 * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
314
 * GetBitContext within AC3DecodeContext must point to
315
 * start of the synchronized ac3 bitstream.
316
 */
317
static int ac3_parse_header(AC3DecodeContext *ctx)
318
{
319
    AC3HeaderInfo hdr;
320
    GetBitContext *gb = &ctx->gb;
321
    int err, i;
322

    
323
    err = ff_ac3_parse_header(gb->buffer, &hdr);
324
    if(err)
325
        return err;
326

    
327
    /* get decoding parameters from header info */
328
    ctx->bit_alloc_params.fscod       = hdr.fscod;
329
    ctx->acmod                        = hdr.acmod;
330
    ctx->cmixlev                      = hdr.cmixlev;
331
    ctx->surmixlev                    = hdr.surmixlev;
332
    ctx->dsurmod                      = hdr.dsurmod;
333
    ctx->lfeon                        = hdr.lfeon;
334
    ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
335
    ctx->sampling_rate                = hdr.sample_rate;
336
    ctx->bit_rate                     = hdr.bit_rate;
337
    ctx->nchans                       = hdr.channels;
338
    ctx->nfchans                      = ctx->nchans - ctx->lfeon;
339
    ctx->frame_size                   = hdr.frame_size;
340
    ctx->blkoutput                    = nfchans_tbl[ctx->acmod];
341
    if(ctx->lfeon)
342
        ctx->blkoutput |= AC3_OUTPUT_LFEON;
343

    
344
    /* skip over portion of header which has already been read */
345
    skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
346
    skip_bits(gb, 16); // skip crc1
347
    skip_bits(gb, 8);  // skip fscod and frmsizecod
348
    skip_bits(gb, 11); // skip bsid, bsmod, and acmod
349
    if(ctx->acmod == AC3_ACMOD_STEREO) {
350
        skip_bits(gb, 2); // skip dsurmod
351
    } else {
352
        if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
353
            skip_bits(gb, 2); // skip cmixlev
354
        if(ctx->acmod & 4)
355
            skip_bits(gb, 2); // skip surmixlev
356
    }
357
    skip_bits1(gb); // skip lfeon
358

    
359
    /* read the rest of the bsi. read twice for dual mono mode. */
360
    i = !(ctx->acmod);
361
    do {
362
        skip_bits(gb, 5); //skip dialog normalization
363
        if (get_bits1(gb))
364
            skip_bits(gb, 8); //skip compression
365
        if (get_bits1(gb))
366
            skip_bits(gb, 8); //skip language code
367
        if (get_bits1(gb))
368
            skip_bits(gb, 7); //skip audio production information
369
    } while (i--);
370

    
371
    skip_bits(gb, 2); //skip copyright bit and original bitstream bit
372

    
373
    /* FIXME: read & use the xbsi1 downmix levels */
374
    if (get_bits1(gb))
375
        skip_bits(gb, 14); //skip timecode1
376
    if (get_bits1(gb))
377
        skip_bits(gb, 14); //skip timecode2
378

    
379
    if (get_bits1(gb)) {
380
        i = get_bits(gb, 6); //additional bsi length
381
        do {
382
            skip_bits(gb, 8);
383
        } while(i--);
384
    }
385

    
386
    return 0;
387
}
388

    
389
/**
390
 * Decodes the grouped exponents.
391
 * This function decodes the coded exponents according to exponent strategy
392
 * and stores them in the decoded exponents buffer.
393
 *
394
 * @param[in]  gb      GetBitContext which points to start of coded exponents
395
 * @param[in]  expstr  Exponent coding strategy
396
 * @param[in]  ngrps   Number of grouped exponents
397
 * @param[in]  absexp  Absolute exponent or DC exponent
398
 * @param[out] dexps   Decoded exponents are stored in dexps
399
 */
400
static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
401
                             uint8_t absexp, int8_t *dexps)
402
{
403
    int i, j, grp, grpsize;
404
    int dexp[256];
405
    int expacc, prevexp;
406

    
407
    /* unpack groups */
408
    grpsize = expstr + (expstr == EXP_D45);
409
    for(grp=0,i=0; grp<ngrps; grp++) {
410
        expacc = get_bits(gb, 7);
411
        dexp[i++] = exp_ungroup_tbl[expacc][0];
412
        dexp[i++] = exp_ungroup_tbl[expacc][1];
413
        dexp[i++] = exp_ungroup_tbl[expacc][2];
414
    }
415

    
416
    /* convert to absolute exps and expand groups */
417
    prevexp = absexp;
418
    for(i=0; i<ngrps*3; i++) {
419
        prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
420
        for(j=0; j<grpsize; j++) {
421
            dexps[(i*grpsize)+j] = prevexp;
422
        }
423
    }
424
}
425

    
426
typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
427
    int16_t l3_quantizers[3];
428
    int16_t l5_quantizers[3];
429
    int16_t l11_quantizers[2];
430
    int l3ptr;
431
    int l5ptr;
432
    int l11ptr;
433
} mant_groups;
434

    
435
/* Get the transform coefficients for coupling channel and uncouple channels.
436
 * The coupling transform coefficients starts at the the cplstrtmant, which is
437
 * equal to endmant[ch] for fbw channels. Hence we can uncouple channels before
438
 * getting transform coefficients for the channel.
439
 */
440
static int get_transform_coeffs_cpling(AC3DecodeContext *ctx, mant_groups *m)
441
{
442
    GetBitContext *gb = &ctx->gb;
443
    int ch, start, end, cplbndstrc, bnd, gcode, tbap;
444
    float cplcos[5], cplcoeff;
445
    uint8_t *exps = ctx->dcplexps;
446
    uint8_t *bap = ctx->cplbap;
447

    
448
    cplbndstrc = ctx->cplbndstrc;
449
    start = ctx->cplstrtmant;
450
    bnd = 0;
451

    
452
    while (start < ctx->cplendmant) {
453
        end = start + 12;
454
        while (cplbndstrc & 1) {
455
            end += 12;
456
            cplbndstrc >>= 1;
457
        }
458
        cplbndstrc >>= 1;
459
        for (ch = 0; ch < ctx->nfchans; ch++)
460
            cplcos[ch] = ctx->chcoeffs[ch] * ctx->cplco[ch][bnd];
461
        bnd++;
462

    
463
        while (start < end) {
464
            tbap = bap[start];
465
            switch(tbap) {
466
                case 0:
467
                    for (ch = 0; ch < ctx->nfchans; ch++)
468
                        if (ctx->chincpl[ch]) {
469
                            if (ctx->dithflag[ch]) {
470
                                cplcoeff = (av_random(&ctx->dith_state) & 0xFFFF) * scale_factors[exps[start]];
471
                                ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch] * LEVEL_MINUS_3DB;
472
                            } else
473
                                ctx->transform_coeffs[ch + 1][start] = 0;
474
                        }
475
                    start++;
476
                    continue;
477
                case 1:
478
                    if (m->l3ptr > 2) {
479
                        gcode = get_bits(gb, 5);
480
                        m->l3_quantizers[0] = l3_quantizers_1[gcode];
481
                        m->l3_quantizers[1] = l3_quantizers_2[gcode];
482
                        m->l3_quantizers[2] = l3_quantizers_3[gcode];
483
                        m->l3ptr = 0;
484
                    }
485
                    cplcoeff = m->l3_quantizers[m->l3ptr++] * scale_factors[exps[start]];
486
                    break;
487

    
488
                case 2:
489
                    if (m->l5ptr > 2) {
490
                        gcode = get_bits(gb, 7);
491
                        m->l5_quantizers[0] = l5_quantizers_1[gcode];
492
                        m->l5_quantizers[1] = l5_quantizers_2[gcode];
493
                        m->l5_quantizers[2] = l5_quantizers_3[gcode];
494
                        m->l5ptr = 0;
495
                    }
496
                    cplcoeff = m->l5_quantizers[m->l5ptr++] * scale_factors[exps[start]];
497
                    break;
498

    
499
                case 3:
500
                    cplcoeff = l7_quantizers[get_bits(gb, 3)] * scale_factors[exps[start]];
501
                    break;
502

    
503
                case 4:
504
                    if (m->l11ptr > 1) {
505
                        gcode = get_bits(gb, 7);
506
                        m->l11_quantizers[0] = l11_quantizers_1[gcode];
507
                        m->l11_quantizers[1] = l11_quantizers_2[gcode];
508
                        m->l11ptr = 0;
509
                    }
510
                    cplcoeff = m->l11_quantizers[m->l11ptr++] * scale_factors[exps[start]];
511
                    break;
512

    
513
                case 5:
514
                    cplcoeff = l15_quantizers[get_bits(gb, 4)] * scale_factors[exps[start]];
515
                    break;
516

    
517
                default:
518
                    cplcoeff = (get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap])) * scale_factors[exps[start]];
519
            }
520
            for (ch = 0; ch < ctx->nfchans; ch++)
521
                if (ctx->chincpl[ch])
522
                    ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch];
523
            start++;
524
        }
525
    }
526

    
527
    return 0;
528
}
529

    
530
/* Get the transform coefficients for particular channel */
531
static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
532
{
533
    GetBitContext *gb = &ctx->gb;
534
    int i, gcode, tbap, dithflag, end;
535
    uint8_t *exps;
536
    uint8_t *bap;
537
    float *coeffs;
538
    float factors[25];
539

    
540
    for (i = 0; i < 25; i++)
541
        factors[i] = scale_factors[i] * ctx->chcoeffs[ch_index];
542

    
543
    if (ch_index != -1) { /* fbw channels */
544
        dithflag = ctx->dithflag[ch_index];
545
        exps = ctx->dexps[ch_index];
546
        bap = ctx->bap[ch_index];
547
        coeffs = ctx->transform_coeffs[ch_index + 1];
548
        end = ctx->endmant[ch_index];
549
    } else if (ch_index == -1) {
550
        dithflag = 0;
551
        exps = ctx->dlfeexps;
552
        bap = ctx->lfebap;
553
        coeffs = ctx->transform_coeffs[0];
554
        end = 7;
555
    }
556

    
557

    
558
    for (i = 0; i < end; i++) {
559
        tbap = bap[i];
560
        switch (tbap) {
561
            case 0:
562
                if (!dithflag) {
563
                    coeffs[i] = 0;
564
                    continue;
565
                }
566
                else {
567
                    coeffs[i] = (av_random(&ctx->dith_state) & 0xFFFF) * factors[exps[i]];
568
                    coeffs[i] *= LEVEL_MINUS_3DB;
569
                    continue;
570
                }
571

    
572
            case 1:
573
                if (m->l3ptr > 2) {
574
                    gcode = get_bits(gb, 5);
575
                    m->l3_quantizers[0] = l3_quantizers_1[gcode];
576
                    m->l3_quantizers[1] = l3_quantizers_2[gcode];
577
                    m->l3_quantizers[2] = l3_quantizers_3[gcode];
578
                    m->l3ptr = 0;
579
                }
580
                coeffs[i] = m->l3_quantizers[m->l3ptr++] * factors[exps[i]];
581
                continue;
582

    
583
            case 2:
584
                if (m->l5ptr > 2) {
585
                    gcode = get_bits(gb, 7);
586
                    m->l5_quantizers[0] = l5_quantizers_1[gcode];
587
                    m->l5_quantizers[1] = l5_quantizers_2[gcode];
588
                    m->l5_quantizers[2] = l5_quantizers_3[gcode];
589
                    m->l5ptr = 0;
590
                }
591
                coeffs[i] = m->l5_quantizers[m->l5ptr++] * factors[exps[i]];
592
                continue;
593

    
594
            case 3:
595
                coeffs[i] = l7_quantizers[get_bits(gb, 3)] * factors[exps[i]];
596
                continue;
597

    
598
            case 4:
599
                if (m->l11ptr > 1) {
600
                    gcode = get_bits(gb, 7);
601
                    m->l11_quantizers[0] = l11_quantizers_1[gcode];
602
                    m->l11_quantizers[1] = l11_quantizers_2[gcode];
603
                    m->l11ptr = 0;
604
                }
605
                coeffs[i] = m->l11_quantizers[m->l11ptr++] * factors[exps[i]];
606
                continue;
607

    
608
            case 5:
609
                coeffs[i] = l15_quantizers[get_bits(gb, 4)] * factors[exps[i]];
610
                continue;
611

    
612
            default:
613
                coeffs[i] = (get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap])) * factors[exps[i]];
614
                continue;
615
        }
616
    }
617

    
618
    return 0;
619
}
620

    
621
/* Get the transform coefficients.
622
 * This function extracts the tranform coefficients form the ac3 bitstream.
623
 * This function is called after bit allocation is performed.
624
 */
625
static int get_transform_coeffs(AC3DecodeContext * ctx)
626
{
627
    int i, end;
628
    int got_cplchan = 0;
629
    mant_groups m;
630

    
631
    m.l3ptr = m.l5ptr = m.l11ptr = 3;
632

    
633
    for (i = 0; i < ctx->nfchans; i++) {
634
        /* transform coefficients for individual channel */
635
        if (get_transform_coeffs_ch(ctx, i, &m))
636
            return -1;
637
        /* tranform coefficients for coupling channels */
638
        if (ctx->chincpl[i])  {
639
            if (!got_cplchan) {
640
                if (get_transform_coeffs_cpling(ctx, &m)) {
641
                    av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
642
                    return -1;
643
                }
644
                got_cplchan = 1;
645
            }
646
            end = ctx->cplendmant;
647
        } else
648
            end = ctx->endmant[i];
649
        do
650
            ctx->transform_coeffs[i + 1][end] = 0;
651
        while(++end < 256);
652
    }
653
    if (ctx->lfeon) {
654
        if (get_transform_coeffs_ch(ctx, -1, &m))
655
                return -1;
656
        for (i = 7; i < 256; i++) {
657
            ctx->transform_coeffs[0][i] = 0;
658
        }
659
    }
660

    
661
    return 0;
662
}
663

    
664
/* Rematrixing routines. */
665
static void do_rematrixing1(AC3DecodeContext *ctx, int start, int end)
666
{
667
    float tmp0, tmp1;
668

    
669
    while (start < end) {
670
        tmp0 = ctx->transform_coeffs[1][start];
671
        tmp1 = ctx->transform_coeffs[2][start];
672
        ctx->transform_coeffs[1][start] = tmp0 + tmp1;
673
        ctx->transform_coeffs[2][start] = tmp0 - tmp1;
674
        start++;
675
    }
676
}
677

    
678
static void do_rematrixing(AC3DecodeContext *ctx)
679
{
680
    int bnd1 = 13, bnd2 = 25, bnd3 = 37, bnd4 = 61;
681
    int end, bndend;
682

    
683
    end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
684

    
685
    if (ctx->rematflg[0])
686
        do_rematrixing1(ctx, bnd1, bnd2);
687

    
688
    if (ctx->rematflg[1])
689
        do_rematrixing1(ctx, bnd2, bnd3);
690

    
691
    bndend = bnd4;
692
    if (bndend > end) {
693
        bndend = end;
694
        if (ctx->rematflg[2])
695
            do_rematrixing1(ctx, bnd3, bndend);
696
    } else {
697
        if (ctx->rematflg[2])
698
            do_rematrixing1(ctx, bnd3, bnd4);
699
        if (ctx->rematflg[3])
700
            do_rematrixing1(ctx, bnd4, end);
701
    }
702
}
703

    
704
/* This function sets the normalized channel coefficients.
705
 * Transform coefficients are multipllied by the channel
706
 * coefficients to get normalized transform coefficients.
707
 */
708
static void get_downmix_coeffs(AC3DecodeContext *ctx)
709
{
710
    int from = ctx->acmod;
711
    int to = ctx->blkoutput;
712
    float clev = clevs[ctx->cmixlev];
713
    float slev = slevs[ctx->surmixlev];
714
    float nf = 1.0; //normalization factor for downmix coeffs
715
    int i;
716

    
717
    if (!ctx->acmod) {
718
        ctx->chcoeffs[0] = 2 * ctx->dynrng;
719
        ctx->chcoeffs[1] = 2 * ctx->dynrng2;
720
    } else {
721
        for (i = 0; i < ctx->nfchans; i++)
722
            ctx->chcoeffs[i] = 2 * ctx->dynrng;
723
    }
724

    
725
    if (to == AC3_OUTPUT_UNMODIFIED)
726
        return;
727

    
728
    switch (from) {
729
        case AC3_ACMOD_DUALMONO:
730
            switch (to) {
731
                case AC3_OUTPUT_MONO:
732
                case AC3_OUTPUT_STEREO: /* We Assume that sum of both mono channels is requested */
733
                    nf = 0.5;
734
                    ctx->chcoeffs[0] *= nf;
735
                    ctx->chcoeffs[1] *= nf;
736
                    break;
737
            }
738
            break;
739
        case AC3_ACMOD_MONO:
740
            switch (to) {
741
                case AC3_OUTPUT_STEREO:
742
                    nf = LEVEL_MINUS_3DB;
743
                    ctx->chcoeffs[0] *= nf;
744
                    break;
745
            }
746
            break;
747
        case AC3_ACMOD_STEREO:
748
            switch (to) {
749
                case AC3_OUTPUT_MONO:
750
                    nf = LEVEL_MINUS_3DB;
751
                    ctx->chcoeffs[0] *= nf;
752
                    ctx->chcoeffs[1] *= nf;
753
                    break;
754
            }
755
            break;
756
        case AC3_ACMOD_3F:
757
            switch (to) {
758
                case AC3_OUTPUT_MONO:
759
                    nf = LEVEL_MINUS_3DB / (1.0 + clev);
760
                    ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
761
                    ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
762
                    ctx->chcoeffs[1] *= ((nf * clev * LEVEL_MINUS_3DB) / 2.0);
763
                    break;
764
                case AC3_OUTPUT_STEREO:
765
                    nf = 1.0 / (1.0 + clev);
766
                    ctx->chcoeffs[0] *= nf;
767
                    ctx->chcoeffs[2] *= nf;
768
                    ctx->chcoeffs[1] *= (nf * clev);
769
                    break;
770
            }
771
            break;
772
        case AC3_ACMOD_2F1R:
773
            switch (to) {
774
                case AC3_OUTPUT_MONO:
775
                    nf = 2.0 * LEVEL_MINUS_3DB / (2.0 + slev);
776
                    ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
777
                    ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
778
                    ctx->chcoeffs[2] *= (nf * slev * LEVEL_MINUS_3DB);
779
                    break;
780
                case AC3_OUTPUT_STEREO:
781
                    nf = 1.0 / (1.0 + (slev * LEVEL_MINUS_3DB));
782
                    ctx->chcoeffs[0] *= nf;
783
                    ctx->chcoeffs[1] *= nf;
784
                    ctx->chcoeffs[2] *= (nf * slev * LEVEL_MINUS_3DB);
785
                    break;
786
                case AC3_OUTPUT_DOLBY:
787
                    nf = 1.0 / (1.0 + LEVEL_MINUS_3DB);
788
                    ctx->chcoeffs[0] *= nf;
789
                    ctx->chcoeffs[1] *= nf;
790
                    ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
791
                    break;
792
            }
793
            break;
794
        case AC3_ACMOD_3F1R:
795
            switch (to) {
796
                case AC3_OUTPUT_MONO:
797
                    nf = LEVEL_MINUS_3DB / (1.0 + clev + (slev / 2.0));
798
                    ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
799
                    ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
800
                    ctx->chcoeffs[1] *= (nf * clev * LEVEL_PLUS_3DB);
801
                    ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
802
                    break;
803
                case AC3_OUTPUT_STEREO:
804
                    nf = 1.0 / (1.0 + clev + (slev * LEVEL_MINUS_3DB));
805
                    ctx->chcoeffs[0] *= nf;
806
                    ctx->chcoeffs[2] *= nf;
807
                    ctx->chcoeffs[1] *= (nf * clev);
808
                    ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
809
                    break;
810
                case AC3_OUTPUT_DOLBY:
811
                    nf = 1.0 / (1.0 + (2.0 * LEVEL_MINUS_3DB));
812
                    ctx->chcoeffs[0] *= nf;
813
                    ctx->chcoeffs[1] *= nf;
814
                    ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
815
                    ctx->chcoeffs[3] *= (nf * LEVEL_MINUS_3DB);
816
                    break;
817
            }
818
            break;
819
        case AC3_ACMOD_2F2R:
820
            switch (to) {
821
                case AC3_OUTPUT_MONO:
822
                    nf = LEVEL_MINUS_3DB / (1.0 + slev);
823
                    ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
824
                    ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
825
                    ctx->chcoeffs[2] *= (nf * slev * LEVEL_MINUS_3DB);
826
                    ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
827
                    break;
828
                case AC3_OUTPUT_STEREO:
829
                    nf = 1.0 / (1.0 + slev);
830
                    ctx->chcoeffs[0] *= nf;
831
                    ctx->chcoeffs[1] *= nf;
832
                    ctx->chcoeffs[2] *= (nf * slev);
833
                    ctx->chcoeffs[3] *= (nf * slev);
834
                    break;
835
                case AC3_OUTPUT_DOLBY:
836
                    nf = 1.0 / (1.0 + (2.0 * LEVEL_MINUS_3DB));
837
                    ctx->chcoeffs[0] *= nf;
838
                    ctx->chcoeffs[1] *= nf;
839
                    ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
840
                    ctx->chcoeffs[3] *= (nf * LEVEL_MINUS_3DB);
841
                    break;
842
            }
843
            break;
844
        case AC3_ACMOD_3F2R:
845
            switch (to) {
846
                case AC3_OUTPUT_MONO:
847
                    nf = LEVEL_MINUS_3DB / (1.0 + clev + slev);
848
                    ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
849
                    ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
850
                    ctx->chcoeffs[1] *= (nf * clev * LEVEL_PLUS_3DB);
851
                    ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
852
                    ctx->chcoeffs[4] *= (nf * slev * LEVEL_MINUS_3DB);
853
                    break;
854
                case AC3_OUTPUT_STEREO:
855
                    nf = 1.0 / (1.0 + clev + slev);
856
                    ctx->chcoeffs[0] *= nf;
857
                    ctx->chcoeffs[2] *= nf;
858
                    ctx->chcoeffs[1] *= (nf * clev);
859
                    ctx->chcoeffs[3] *= (nf * slev);
860
                    ctx->chcoeffs[4] *= (nf * slev);
861
                    break;
862
                case AC3_OUTPUT_DOLBY:
863
                    nf = 1.0 / (1.0 + (3.0 * LEVEL_MINUS_3DB));
864
                    ctx->chcoeffs[0] *= nf;
865
                    ctx->chcoeffs[1] *= nf;
866
                    ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
867
                    ctx->chcoeffs[3] *= (nf * LEVEL_MINUS_3DB);
868
                    ctx->chcoeffs[4] *= (nf * LEVEL_MINUS_3DB);
869
                    break;
870
            }
871
            break;
872
    }
873
}
874

    
875
/*********** BEGIN DOWNMIX FUNCTIONS ***********/
876
static inline void mix_dualmono_to_mono(AC3DecodeContext *ctx)
877
{
878
    int i;
879
    float (*output)[BLOCK_SIZE] = ctx->output;
880

    
881
    for (i = 0; i < 256; i++)
882
        output[1][i] += output[2][i];
883
    memset(output[2], 0, sizeof(output[2]));
884
}
885

    
886
static inline void mix_dualmono_to_stereo(AC3DecodeContext *ctx)
887
{
888
    int i;
889
    float tmp;
890
    float (*output)[BLOCK_SIZE] = ctx->output;
891

    
892
    for (i = 0; i < 256; i++) {
893
        tmp = output[1][i] + output[2][i];
894
        output[1][i] = output[2][i] = tmp;
895
    }
896
}
897

    
898
static inline void upmix_mono_to_stereo(AC3DecodeContext *ctx)
899
{
900
    int i;
901
    float (*output)[BLOCK_SIZE] = ctx->output;
902

    
903
    for (i = 0; i < 256; i++)
904
        output[2][i] = output[1][i];
905
}
906

    
907
static inline void mix_stereo_to_mono(AC3DecodeContext *ctx)
908
{
909
    int i;
910
    float (*output)[BLOCK_SIZE] = ctx->output;
911

    
912
    for (i = 0; i < 256; i++)
913
        output[1][i] += output[2][i];
914
    memset(output[2], 0, sizeof(output[2]));
915
}
916

    
917
static inline void mix_3f_to_mono(AC3DecodeContext *ctx)
918
{
919
    int i;
920
    float (*output)[BLOCK_SIZE] = ctx->output;
921

    
922
    for (i = 0; i < 256; i++)
923
        output[1][i] += (output[2][i] + output[3][i]);
924
    memset(output[2], 0, sizeof(output[2]));
925
    memset(output[3], 0, sizeof(output[3]));
926
}
927

    
928
static inline void mix_3f_to_stereo(AC3DecodeContext *ctx)
929
{
930
    int i;
931
    float (*output)[BLOCK_SIZE] = ctx->output;
932

    
933
    for (i = 0; i < 256; i++) {
934
        output[1][i] += output[2][i];
935
        output[2][i] += output[3][i];
936
    }
937
    memset(output[3], 0, sizeof(output[3]));
938
}
939

    
940
static inline void mix_2f_1r_to_mono(AC3DecodeContext *ctx)
941
{
942
    int i;
943
    float (*output)[BLOCK_SIZE] = ctx->output;
944

    
945
    for (i = 0; i < 256; i++)
946
        output[1][i] += (output[2][i] + output[3][i]);
947
    memset(output[2], 0, sizeof(output[2]));
948
    memset(output[3], 0, sizeof(output[3]));
949

    
950
}
951

    
952
static inline void mix_2f_1r_to_stereo(AC3DecodeContext *ctx)
953
{
954
    int i;
955
    float (*output)[BLOCK_SIZE] = ctx->output;
956

    
957
    for (i = 0; i < 256; i++) {
958
        output[1][i] += output[2][i];
959
        output[2][i] += output[3][i];
960
    }
961
    memset(output[3], 0, sizeof(output[3]));
962
}
963

    
964
static inline void mix_2f_1r_to_dolby(AC3DecodeContext *ctx)
965
{
966
    int i;
967
    float (*output)[BLOCK_SIZE] = ctx->output;
968

    
969
    for (i = 0; i < 256; i++) {
970
        output[1][i] -= output[3][i];
971
        output[2][i] += output[3][i];
972
    }
973
    memset(output[3], 0, sizeof(output[3]));
974
}
975

    
976
static inline void mix_3f_1r_to_mono(AC3DecodeContext *ctx)
977
{
978
    int i;
979
    float (*output)[BLOCK_SIZE] = ctx->output;
980

    
981
    for (i = 0; i < 256; i++)
982
        output[1][i] = (output[2][i] + output[3][i] + output[4][i]);
983
    memset(output[2], 0, sizeof(output[2]));
984
    memset(output[3], 0, sizeof(output[3]));
985
    memset(output[4], 0, sizeof(output[4]));
986
}
987

    
988
static inline void mix_3f_1r_to_stereo(AC3DecodeContext *ctx)
989
{
990
    int i;
991
    float (*output)[BLOCK_SIZE] = ctx->output;
992

    
993
    for (i = 0; i < 256; i++) {
994
        output[1][i] += (output[2][i] + output[4][i]);
995
        output[2][i] += (output[3][i] + output[4][i]);
996
    }
997
    memset(output[3], 0, sizeof(output[3]));
998
    memset(output[4], 0, sizeof(output[4]));
999
}
1000

    
1001
static inline void mix_3f_1r_to_dolby(AC3DecodeContext *ctx)
1002
{
1003
    int i;
1004
    float (*output)[BLOCK_SIZE] = ctx->output;
1005

    
1006
    for (i = 0; i < 256; i++) {
1007
        output[1][i] += (output[2][i] - output[4][i]);
1008
        output[2][i] += (output[3][i] + output[4][i]);
1009
    }
1010
    memset(output[3], 0, sizeof(output[3]));
1011
    memset(output[4], 0, sizeof(output[4]));
1012
}
1013

    
1014
static inline void mix_2f_2r_to_mono(AC3DecodeContext *ctx)
1015
{
1016
    int i;
1017
    float (*output)[BLOCK_SIZE] = ctx->output;
1018

    
1019
    for (i = 0; i < 256; i++)
1020
        output[1][i] = (output[2][i] + output[3][i] + output[4][i]);
1021
    memset(output[2], 0, sizeof(output[2]));
1022
    memset(output[3], 0, sizeof(output[3]));
1023
    memset(output[4], 0, sizeof(output[4]));
1024
}
1025

    
1026
static inline void mix_2f_2r_to_stereo(AC3DecodeContext *ctx)
1027
{
1028
    int i;
1029
    float (*output)[BLOCK_SIZE] = ctx->output;
1030

    
1031
    for (i = 0; i < 256; i++) {
1032
        output[1][i] += output[3][i];
1033
        output[2][i] += output[4][i];
1034
    }
1035
    memset(output[3], 0, sizeof(output[3]));
1036
    memset(output[4], 0, sizeof(output[4]));
1037
}
1038

    
1039
static inline void mix_2f_2r_to_dolby(AC3DecodeContext *ctx)
1040
{
1041
    int i;
1042
    float (*output)[BLOCK_SIZE] = ctx->output;
1043

    
1044
    for (i = 0; i < 256; i++) {
1045
        output[1][i] -= output[3][i];
1046
        output[2][i] += output[4][i];
1047
    }
1048
    memset(output[3], 0, sizeof(output[3]));
1049
    memset(output[4], 0, sizeof(output[4]));
1050
}
1051

    
1052
static inline void mix_3f_2r_to_mono(AC3DecodeContext *ctx)
1053
{
1054
    int i;
1055
    float (*output)[BLOCK_SIZE] = ctx->output;
1056

    
1057
    for (i = 0; i < 256; i++)
1058
        output[1][i] += (output[2][i] + output[3][i] + output[4][i] + output[5][i]);
1059
    memset(output[2], 0, sizeof(output[2]));
1060
    memset(output[3], 0, sizeof(output[3]));
1061
    memset(output[4], 0, sizeof(output[4]));
1062
    memset(output[5], 0, sizeof(output[5]));
1063
}
1064

    
1065
static inline void mix_3f_2r_to_stereo(AC3DecodeContext *ctx)
1066
{
1067
    int i;
1068
    float (*output)[BLOCK_SIZE] = ctx->output;
1069

    
1070
    for (i = 0; i < 256; i++) {
1071
        output[1][i] += (output[2][i] + output[4][i]);
1072
        output[2][i] += (output[3][i] + output[5][i]);
1073
    }
1074
    memset(output[3], 0, sizeof(output[3]));
1075
    memset(output[4], 0, sizeof(output[4]));
1076
    memset(output[5], 0, sizeof(output[5]));
1077
}
1078

    
1079
static inline void mix_3f_2r_to_dolby(AC3DecodeContext *ctx)
1080
{
1081
    int i;
1082
    float (*output)[BLOCK_SIZE] = ctx->output;
1083

    
1084
    for (i = 0; i < 256; i++) {
1085
        output[1][i] += (output[2][i] - output[4][i] - output[5][i]);
1086
        output[2][i] += (output[3][i] + output[4][i] + output[5][i]);
1087
    }
1088
    memset(output[3], 0, sizeof(output[3]));
1089
    memset(output[4], 0, sizeof(output[4]));
1090
    memset(output[5], 0, sizeof(output[5]));
1091
}
1092
/*********** END DOWNMIX FUNCTIONS ***********/
1093

    
1094
/* Downmix the output.
1095
 * This function downmixes the output when the number of input
1096
 * channels is not equal to the number of output channels requested.
1097
 */
1098
static void do_downmix(AC3DecodeContext *ctx)
1099
{
1100
    int from = ctx->acmod;
1101
    int to = ctx->blkoutput;
1102

    
1103
    if (to == AC3_OUTPUT_UNMODIFIED)
1104
        return;
1105

    
1106
    switch (from) {
1107
        case AC3_ACMOD_DUALMONO:
1108
            switch (to) {
1109
                case AC3_OUTPUT_MONO:
1110
                    mix_dualmono_to_mono(ctx);
1111
                    break;
1112
                case AC3_OUTPUT_STEREO: /* We assume that sum of both mono channels is requested */
1113
                    mix_dualmono_to_stereo(ctx);
1114
                    break;
1115
            }
1116
            break;
1117
        case AC3_ACMOD_MONO:
1118
            switch (to) {
1119
                case AC3_OUTPUT_STEREO:
1120
                    upmix_mono_to_stereo(ctx);
1121
                    break;
1122
            }
1123
            break;
1124
        case AC3_ACMOD_STEREO:
1125
            switch (to) {
1126
                case AC3_OUTPUT_MONO:
1127
                    mix_stereo_to_mono(ctx);
1128
                    break;
1129
            }
1130
            break;
1131
        case AC3_ACMOD_3F:
1132
            switch (to) {
1133
                case AC3_OUTPUT_MONO:
1134
                    mix_3f_to_mono(ctx);
1135
                    break;
1136
                case AC3_OUTPUT_STEREO:
1137
                    mix_3f_to_stereo(ctx);
1138
                    break;
1139
            }
1140
            break;
1141
        case AC3_ACMOD_2F1R:
1142
            switch (to) {
1143
                case AC3_OUTPUT_MONO:
1144
                    mix_2f_1r_to_mono(ctx);
1145
                    break;
1146
                case AC3_OUTPUT_STEREO:
1147
                    mix_2f_1r_to_stereo(ctx);
1148
                    break;
1149
                case AC3_OUTPUT_DOLBY:
1150
                    mix_2f_1r_to_dolby(ctx);
1151
                    break;
1152
            }
1153
            break;
1154
        case AC3_ACMOD_3F1R:
1155
            switch (to) {
1156
                case AC3_OUTPUT_MONO:
1157
                    mix_3f_1r_to_mono(ctx);
1158
                    break;
1159
                case AC3_OUTPUT_STEREO:
1160
                    mix_3f_1r_to_stereo(ctx);
1161
                    break;
1162
                case AC3_OUTPUT_DOLBY:
1163
                    mix_3f_1r_to_dolby(ctx);
1164
                    break;
1165
            }
1166
            break;
1167
        case AC3_ACMOD_2F2R:
1168
            switch (to) {
1169
                case AC3_OUTPUT_MONO:
1170
                    mix_2f_2r_to_mono(ctx);
1171
                    break;
1172
                case AC3_OUTPUT_STEREO:
1173
                    mix_2f_2r_to_stereo(ctx);
1174
                    break;
1175
                case AC3_OUTPUT_DOLBY:
1176
                    mix_2f_2r_to_dolby(ctx);
1177
                    break;
1178
            }
1179
            break;
1180
        case AC3_ACMOD_3F2R:
1181
            switch (to) {
1182
                case AC3_OUTPUT_MONO:
1183
                    mix_3f_2r_to_mono(ctx);
1184
                    break;
1185
                case AC3_OUTPUT_STEREO:
1186
                    mix_3f_2r_to_stereo(ctx);
1187
                    break;
1188
                case AC3_OUTPUT_DOLBY:
1189
                    mix_3f_2r_to_dolby(ctx);
1190
                    break;
1191
            }
1192
            break;
1193
    }
1194
}
1195

    
1196
/* This function performs the imdct on 256 sample transform
1197
 * coefficients.
1198
 */
1199
static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
1200
{
1201
    int i, k;
1202
    float x[128];
1203
    FFTComplex z[2][64];
1204
    float *o_ptr = ctx->tmp_output;
1205

    
1206
    for(i=0; i<2; i++) {
1207
        /* de-interleave coefficients */
1208
        for(k=0; k<128; k++) {
1209
            x[k] = ctx->transform_coeffs[chindex][2*k+i];
1210
        }
1211

    
1212
        /* run standard IMDCT */
1213
        ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
1214

    
1215
        /* reverse the post-rotation & reordering from standard IMDCT */
1216
        for(k=0; k<32; k++) {
1217
            z[i][32+k].re = -o_ptr[128+2*k];
1218
            z[i][32+k].im = -o_ptr[2*k];
1219
            z[i][31-k].re =  o_ptr[2*k+1];
1220
            z[i][31-k].im =  o_ptr[128+2*k+1];
1221
        }
1222
    }
1223

    
1224
    /* apply AC-3 post-rotation & reordering */
1225
    for(k=0; k<64; k++) {
1226
        o_ptr[    2*k  ] = -z[0][   k].im;
1227
        o_ptr[    2*k+1] =  z[0][63-k].re;
1228
        o_ptr[128+2*k  ] = -z[0][   k].re;
1229
        o_ptr[128+2*k+1] =  z[0][63-k].im;
1230
        o_ptr[256+2*k  ] = -z[1][   k].re;
1231
        o_ptr[256+2*k+1] =  z[1][63-k].im;
1232
        o_ptr[384+2*k  ] =  z[1][   k].im;
1233
        o_ptr[384+2*k+1] = -z[1][63-k].re;
1234
    }
1235
}
1236

    
1237
/* IMDCT Transform. */
1238
static inline void do_imdct(AC3DecodeContext *ctx)
1239
{
1240
    int ch;
1241

    
1242
    if (ctx->blkoutput & AC3_OUTPUT_LFEON) {
1243
        ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
1244
                                      ctx->transform_coeffs[0], ctx->tmp_imdct);
1245
    }
1246
    for (ch=1; ch<=ctx->nfchans; ch++) {
1247
        if (ctx->blksw[ch-1])
1248
            do_imdct_256(ctx, ch);
1249
        else
1250
            ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
1251
                                          ctx->transform_coeffs[ch],
1252
                                          ctx->tmp_imdct);
1253

    
1254
        ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
1255
                                     ctx->window, ctx->delay[ch], 384, 256, 1);
1256
        ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
1257
                                     ctx->window, 256);
1258
    }
1259
}
1260

    
1261
/* Parse the audio block from ac3 bitstream.
1262
 * This function extract the audio block from the ac3 bitstream
1263
 * and produces the output for the block. This function must
1264
 * be called for each of the six audio block in the ac3 bitstream.
1265
 */
1266
static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
1267
{
1268
    int nfchans = ctx->nfchans;
1269
    int acmod = ctx->acmod;
1270
    int i, bnd, rbnd, seg, grpsize;
1271
    GetBitContext *gb = &ctx->gb;
1272
    int bit_alloc_flags = 0;
1273
    int8_t *dexps;
1274
    int mstrcplco, cplcoexp, cplcomant;
1275
    int dynrng, chbwcod, ngrps, cplabsexp, skipl;
1276

    
1277
    for (i = 0; i < nfchans; i++) /*block switch flag */
1278
        ctx->blksw[i] = get_bits1(gb);
1279

    
1280
    for (i = 0; i < nfchans; i++) /* dithering flag */
1281
        ctx->dithflag[i] = get_bits1(gb);
1282

    
1283
    if (get_bits1(gb)) { /* dynamic range */
1284
        dynrng = get_sbits(gb, 8);
1285
        ctx->dynrng = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
1286
    } else if(blk == 0) {
1287
        ctx->dynrng = 1.0;
1288
    }
1289

    
1290
    if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
1291
        if(get_bits1(gb)) {
1292
            dynrng = get_sbits(gb, 8);
1293
            ctx->dynrng2 = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
1294
        } else if(blk == 0) {
1295
            ctx->dynrng2 = 1.0;
1296
        }
1297
    }
1298

    
1299
    get_downmix_coeffs(ctx);
1300

    
1301
    if (get_bits1(gb)) { /* coupling strategy */
1302
        ctx->cplinu = get_bits1(gb);
1303
        ctx->cplbndstrc = 0;
1304
        if (ctx->cplinu) { /* coupling in use */
1305
            for (i = 0; i < nfchans; i++)
1306
                ctx->chincpl[i] = get_bits1(gb);
1307

    
1308
            if (acmod == AC3_ACMOD_STEREO)
1309
                ctx->phsflginu = get_bits1(gb); //phase flag in use
1310

    
1311
            ctx->cplbegf = get_bits(gb, 4);
1312
            ctx->cplendf = get_bits(gb, 4);
1313

    
1314
            if (3 + ctx->cplendf - ctx->cplbegf < 0) {
1315
                av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", ctx->cplendf, ctx->cplbegf);
1316
                return -1;
1317
            }
1318

    
1319
            ctx->ncplbnd = ctx->ncplsubnd = 3 + ctx->cplendf - ctx->cplbegf;
1320
            ctx->cplstrtmant = ctx->cplbegf * 12 + 37;
1321
            ctx->cplendmant = ctx->cplendf * 12 + 73;
1322
            for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
1323
                if (get_bits1(gb)) {
1324
                    ctx->cplbndstrc |= 1 << i;
1325
                    ctx->ncplbnd--;
1326
                }
1327
        } else {
1328
            for (i = 0; i < nfchans; i++)
1329
                ctx->chincpl[i] = 0;
1330
        }
1331
    }
1332

    
1333
    if (ctx->cplinu) {
1334
        ctx->cplcoe = 0;
1335

    
1336
        for (i = 0; i < nfchans; i++)
1337
            if (ctx->chincpl[i])
1338
                if (get_bits1(gb)) { /* coupling co-ordinates */
1339
                    ctx->cplcoe |= 1 << i;
1340
                    mstrcplco = 3 * get_bits(gb, 2);
1341
                    for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
1342
                        cplcoexp = get_bits(gb, 4);
1343
                        cplcomant = get_bits(gb, 4);
1344
                        if (cplcoexp == 15)
1345
                            cplcomant <<= 14;
1346
                        else
1347
                            cplcomant = (cplcomant | 0x10) << 13;
1348
                        ctx->cplco[i][bnd] = cplcomant * scale_factors[cplcoexp + mstrcplco];
1349
                    }
1350
                }
1351

    
1352
        if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
1353
            for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
1354
                if (get_bits1(gb))
1355
                    ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
1356
    }
1357

    
1358
    if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
1359
        ctx->rematstr = get_bits1(gb);
1360
        if (ctx->rematstr) {
1361
            if (!(ctx->cplinu) || ctx->cplbegf > 2)
1362
                for (rbnd = 0; rbnd < 4; rbnd++)
1363
                    ctx->rematflg[rbnd] = get_bits1(gb);
1364
            if (ctx->cplbegf > 0 && ctx->cplbegf <= 2 && ctx->cplinu)
1365
                for (rbnd = 0; rbnd < 3; rbnd++)
1366
                    ctx->rematflg[rbnd] = get_bits1(gb);
1367
            if (ctx->cplbegf == 0 && ctx->cplinu)
1368
                for (rbnd = 0; rbnd < 2; rbnd++)
1369
                    ctx->rematflg[rbnd] = get_bits1(gb);
1370
        }
1371
    }
1372

    
1373
    ctx->cplexpstr = EXP_REUSE;
1374
    ctx->lfeexpstr = EXP_REUSE;
1375
    if (ctx->cplinu) /* coupling exponent strategy */
1376
        ctx->cplexpstr = get_bits(gb, 2);
1377
    for (i = 0; i < nfchans; i++)  /* channel exponent strategy */
1378
        ctx->chexpstr[i] = get_bits(gb, 2);
1379
    if (ctx->lfeon)  /* lfe exponent strategy */
1380
        ctx->lfeexpstr = get_bits1(gb);
1381

    
1382
    for (i = 0; i < nfchans; i++) /* channel bandwidth code */
1383
        if (ctx->chexpstr[i] != EXP_REUSE) {
1384
            if (ctx->chincpl[i])
1385
                ctx->endmant[i] = ctx->cplstrtmant;
1386
            else {
1387
                chbwcod = get_bits(gb, 6);
1388
                if (chbwcod > 60) {
1389
                    av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
1390
                    return -1;
1391
                }
1392
                ctx->endmant[i] = chbwcod * 3 + 73;
1393
            }
1394
        }
1395

    
1396
    if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
1397
        bit_alloc_flags = 64;
1398
        cplabsexp = get_bits(gb, 4) << 1;
1399
        ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
1400
        decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
1401
    }
1402

    
1403
    for (i = 0; i < nfchans; i++) /* fbw channel exponents */
1404
        if (ctx->chexpstr[i] != EXP_REUSE) {
1405
            bit_alloc_flags |= 1 << i;
1406
            grpsize = 3 << (ctx->chexpstr[i] - 1);
1407
            ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
1408
            dexps = ctx->dexps[i];
1409
            dexps[0] = get_bits(gb, 4);
1410
            decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
1411
            skip_bits(gb, 2); /* skip gainrng */
1412
        }
1413

    
1414
    if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
1415
        bit_alloc_flags |= 32;
1416
        ctx->dlfeexps[0] = get_bits(gb, 4);
1417
        decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
1418
    }
1419

    
1420
    if (get_bits1(gb)) { /* bit allocation information */
1421
        bit_alloc_flags = 127;
1422
        ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
1423
        ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
1424
        ctx->bit_alloc_params.sgain  = ff_sgaintab[get_bits(gb, 2)];
1425
        ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
1426
        ctx->bit_alloc_params.floor  = ff_floortab[get_bits(gb, 3)];
1427
    }
1428

    
1429
    if (get_bits1(gb)) { /* snroffset */
1430
        int csnr;
1431
        bit_alloc_flags = 127;
1432
        csnr = (get_bits(gb, 6) - 15) << 4;
1433
        if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
1434
            ctx->cplsnroffst = (csnr + get_bits(gb, 4)) << 2;
1435
            ctx->cplfgain = ff_fgaintab[get_bits(gb, 3)];
1436
        }
1437
        for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
1438
            ctx->snroffst[i] = (csnr + get_bits(gb, 4)) << 2;
1439
            ctx->fgain[i] = ff_fgaintab[get_bits(gb, 3)];
1440
        }
1441
        if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
1442
            ctx->lfesnroffst = (csnr + get_bits(gb, 4)) << 2;
1443
            ctx->lfefgain = ff_fgaintab[get_bits(gb, 3)];
1444
        }
1445
    }
1446

    
1447
    if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
1448
        bit_alloc_flags |= 64;
1449
        ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
1450
        ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
1451
    }
1452

    
1453
    if (get_bits1(gb)) { /* delta bit allocation information */
1454
        bit_alloc_flags = 127;
1455

    
1456
        if (ctx->cplinu) {
1457
            ctx->cpldeltbae = get_bits(gb, 2);
1458
            if (ctx->cpldeltbae == DBA_RESERVED) {
1459
                av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
1460
                return -1;
1461
            }
1462
        }
1463

    
1464
        for (i = 0; i < nfchans; i++) {
1465
            ctx->deltbae[i] = get_bits(gb, 2);
1466
            if (ctx->deltbae[i] == DBA_RESERVED) {
1467
                av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
1468
                return -1;
1469
            }
1470
        }
1471

    
1472
        if (ctx->cplinu)
1473
            if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
1474
                ctx->cpldeltnseg = get_bits(gb, 3);
1475
                for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
1476
                    ctx->cpldeltoffst[seg] = get_bits(gb, 5);
1477
                    ctx->cpldeltlen[seg] = get_bits(gb, 4);
1478
                    ctx->cpldeltba[seg] = get_bits(gb, 3);
1479
                }
1480
            }
1481

    
1482
        for (i = 0; i < nfchans; i++)
1483
            if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
1484
                ctx->deltnseg[i] = get_bits(gb, 3);
1485
                for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
1486
                    ctx->deltoffst[i][seg] = get_bits(gb, 5);
1487
                    ctx->deltlen[i][seg] = get_bits(gb, 4);
1488
                    ctx->deltba[i][seg] = get_bits(gb, 3);
1489
                }
1490
            }
1491
    } else if(blk == 0) {
1492
        if(ctx->cplinu)
1493
            ctx->cpldeltbae = DBA_NONE;
1494
        for(i=0; i<nfchans; i++) {
1495
            ctx->deltbae[i] = DBA_NONE;
1496
        }
1497
    }
1498

    
1499
    if (bit_alloc_flags) {
1500
        if (ctx->cplinu && (bit_alloc_flags & 64))
1501
            ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->cplbap,
1502
                                          ctx->dcplexps, ctx->cplstrtmant,
1503
                                          ctx->cplendmant, ctx->cplsnroffst,
1504
                                          ctx->cplfgain, 0,
1505
                                          ctx->cpldeltbae, ctx->cpldeltnseg,
1506
                                          ctx->cpldeltoffst, ctx->cpldeltlen,
1507
                                          ctx->cpldeltba);
1508
        for (i = 0; i < nfchans; i++)
1509
            if ((bit_alloc_flags >> i) & 1)
1510
                ac3_parametric_bit_allocation(&ctx->bit_alloc_params,
1511
                                              ctx->bap[i], ctx->dexps[i], 0,
1512
                                              ctx->endmant[i], ctx->snroffst[i],
1513
                                              ctx->fgain[i], 0, ctx->deltbae[i],
1514
                                              ctx->deltnseg[i], ctx->deltoffst[i],
1515
                                              ctx->deltlen[i], ctx->deltba[i]);
1516
        if (ctx->lfeon && (bit_alloc_flags & 32))
1517
            ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->lfebap,
1518
                                          ctx->dlfeexps, 0, 7, ctx->lfesnroffst,
1519
                                          ctx->lfefgain, 1,
1520
                                          DBA_NONE, 0, NULL, NULL, NULL);
1521
    }
1522

    
1523
    if (get_bits1(gb)) { /* unused dummy data */
1524
        skipl = get_bits(gb, 9);
1525
        while(skipl--)
1526
            skip_bits(gb, 8);
1527
    }
1528
    /* unpack the transform coefficients
1529
     * * this also uncouples channels if coupling is in use.
1530
     */
1531
    if (get_transform_coeffs(ctx)) {
1532
        av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
1533
        return -1;
1534
    }
1535

    
1536
    /* recover coefficients if rematrixing is in use */
1537
    if(ctx->acmod == AC3_ACMOD_STEREO)
1538
        do_rematrixing(ctx);
1539

    
1540
    do_downmix(ctx);
1541

    
1542
    do_imdct(ctx);
1543

    
1544
    return 0;
1545
}
1546

    
1547
static inline int16_t convert(int32_t i)
1548
{
1549
    if (i > 0x43c07fff)
1550
        return 32767;
1551
    else if (i <= 0x43bf8000)
1552
        return -32768;
1553
    else
1554
        return (i - 0x43c00000);
1555
}
1556

    
1557
/* Decode ac3 frame.
1558
 *
1559
 * @param avctx Pointer to AVCodecContext
1560
 * @param data Pointer to pcm smaples
1561
 * @param data_size Set to number of pcm samples produced by decoding
1562
 * @param buf Data to be decoded
1563
 * @param buf_size Size of the buffer
1564
 */
1565
static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1566
{
1567
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1568
    int16_t *out_samples = (int16_t *)data;
1569
    int i, j, k, start;
1570
    int32_t *int_ptr[6];
1571

    
1572
    for (i = 0; i < 6; i++)
1573
        int_ptr[i] = (int32_t *)(&ctx->output[i]);
1574

    
1575
    //Initialize the GetBitContext with the start of valid AC3 Frame.
1576
    init_get_bits(&ctx->gb, buf, buf_size * 8);
1577

    
1578
    //Parse the syncinfo.
1579
    if (ac3_parse_header(ctx)) {
1580
        av_log(avctx, AV_LOG_ERROR, "\n");
1581
        *data_size = 0;
1582
        return buf_size;
1583
    }
1584

    
1585
    avctx->sample_rate = ctx->sampling_rate;
1586
    avctx->bit_rate = ctx->bit_rate;
1587

    
1588
    if (avctx->channels == 0) {
1589
        ctx->blkoutput |= AC3_OUTPUT_UNMODIFIED;
1590
        if (ctx->lfeon)
1591
            ctx->blkoutput |= AC3_OUTPUT_LFEON;
1592
        avctx->channels = ctx->nfchans + ctx->lfeon;
1593
    }
1594
    else if (avctx->channels == 1)
1595
        ctx->blkoutput |= AC3_OUTPUT_MONO;
1596
    else if (avctx->channels == 2) {
1597
        if (ctx->dsurmod == 0x02)
1598
            ctx->blkoutput |= AC3_OUTPUT_DOLBY;
1599
        else
1600
            ctx->blkoutput |= AC3_OUTPUT_STEREO;
1601
    }
1602
    else {
1603
        if (avctx->channels < (ctx->nfchans + ctx->lfeon))
1604
            av_log(avctx, AV_LOG_INFO, "ac3_decoder: AC3 Source Channels Are Less Then Specified %d: Output to %d Channels\n",avctx->channels, ctx->nfchans + ctx->lfeon);
1605
        ctx->blkoutput |= AC3_OUTPUT_UNMODIFIED;
1606
        if (ctx->lfeon)
1607
            ctx->blkoutput |= AC3_OUTPUT_LFEON;
1608
        avctx->channels = ctx->nfchans + ctx->lfeon;
1609
    }
1610

    
1611
    //av_log(avctx, AV_LOG_INFO, "channels = %d \t bit rate = %d \t sampling rate = %d \n", avctx->channels, avctx->bit_rate * 1000, avctx->sample_rate);
1612

    
1613
    //Parse the Audio Blocks.
1614
    for (i = 0; i < NB_BLOCKS; i++) {
1615
        if (ac3_parse_audio_block(ctx, i)) {
1616
            av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1617
            *data_size = 0;
1618
            return ctx->frame_size;
1619
        }
1620
        start = (ctx->blkoutput & AC3_OUTPUT_LFEON) ? 0 : 1;
1621
        for (k = 0; k < BLOCK_SIZE; k++)
1622
            for (j = start; j <= avctx->channels; j++)
1623
                *(out_samples++) = convert(int_ptr[j][k]);
1624
    }
1625
    *data_size = NB_BLOCKS * BLOCK_SIZE * avctx->channels * sizeof (int16_t);
1626
    return ctx->frame_size;
1627
}
1628

    
1629
/* Uninitialize ac3 decoder.
1630
 */
1631
static int ac3_decode_end(AVCodecContext *avctx)
1632
{
1633
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1634
    ff_mdct_end(&ctx->imdct_512);
1635
    ff_mdct_end(&ctx->imdct_256);
1636

    
1637
    return 0;
1638
}
1639

    
1640
AVCodec ac3_decoder = {
1641
    .name = "ac3",
1642
    .type = CODEC_TYPE_AUDIO,
1643
    .id = CODEC_ID_AC3,
1644
    .priv_data_size = sizeof (AC3DecodeContext),
1645
    .init = ac3_decode_init,
1646
    .close = ac3_decode_end,
1647
    .decode = ac3_decode_frame,
1648
};
1649