Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3dec.c @ d63f6fea

History | View | Annotate | Download (35.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
/**
42
 * Table of bin locations for rematrixing bands
43
 * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
44
 */
45
static const uint8_t rematrix_band_tbl[5] = { 13, 25, 37, 61, 253 };
46

    
47
/* table for exponent to scale_factor mapping
48
 * scale_factor[i] = 2 ^ -(i + 15)
49
 */
50
static float scale_factors[25];
51

    
52
/** table for grouping exponents */
53
static uint8_t exp_ungroup_tbl[128][3];
54

    
55
static int16_t l3_quantizers_1[32];
56
static int16_t l3_quantizers_2[32];
57
static int16_t l3_quantizers_3[32];
58

    
59
static int16_t l5_quantizers_1[128];
60
static int16_t l5_quantizers_2[128];
61
static int16_t l5_quantizers_3[128];
62

    
63
static int16_t l7_quantizers[7];
64

    
65
static int16_t l11_quantizers_1[128];
66
static int16_t l11_quantizers_2[128];
67

    
68
static int16_t l15_quantizers[15];
69

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

    
72
/* Adjustmens in dB gain */
73
#define LEVEL_MINUS_3DB         0.7071067811865476
74
#define LEVEL_MINUS_4POINT5DB   0.5946035575013605
75
#define LEVEL_MINUS_6DB         0.5000000000000000
76
#define LEVEL_PLUS_3DB          1.4142135623730951
77
#define LEVEL_PLUS_6DB          2.0000000000000000
78
#define LEVEL_ZERO              0.0000000000000000
79

    
80
static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
81
    LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
82

    
83
static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
84

    
85
#define AC3_OUTPUT_LFEON  8
86

    
87
typedef struct {
88
    int acmod;
89
    int cmixlev;
90
    int surmixlev;
91
    int dsurmod;
92

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

    
123
    /* Derived Attributes. */
124
    int      sampling_rate;
125
    int      bit_rate;
126
    int      frame_size;
127

    
128
    int      nchans;            //number of total channels
129
    int      nfchans;           //number of full-bandwidth channels
130
    int      lfeon;             //lfe channel in use
131
    int      output_mode;       ///< output channel configuration
132
    int      out_channels;      ///< number of output channels
133

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

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

    
151
    float transform_coeffs_cpl[256];
152
    DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]);  //transform coefficients
153

    
154
    /* For IMDCT. */
155
    MDCTContext imdct_512;  //for 512 sample imdct transform
156
    MDCTContext imdct_256;  //for 256 sample imdct transform
157
    DSPContext  dsp;        //for optimization
158

    
159
    DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS][256]);   //output after imdct transform and windowing
160
    DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS][256]);    //delay - added to the next block
161
    DECLARE_ALIGNED_16(float, tmp_imdct[256]);                  //temporary storage for imdct transform
162
    DECLARE_ALIGNED_16(float, tmp_output[512]);                 //temporary storage for output before windowing
163
    DECLARE_ALIGNED_16(float, window[256]);                     //window coefficients
164

    
165
    /* Miscellaneous. */
166
    GetBitContext gb;
167
    AVRandomState dith_state;   //for dither generation
168
} AC3DecodeContext;
169

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

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

    
190
   sum++;
191
   for (i = 0; i < 256; i++)
192
       window[i] = sqrt(local_window[i] / sum);
193
}
194

    
195
/*
196
 * Generate quantizer tables.
197
 */
198
static void generate_quantizers_table(int16_t quantizers[], int level, int length)
199
{
200
    int i;
201

    
202
    for (i = 0; i < length; i++)
203
        quantizers[i] = ((2 * i - level + 1) << 15) / level;
204
}
205

    
206
static void generate_quantizers_table_1(int16_t quantizers[], int level, int length1, int length2, int size)
207
{
208
    int i, j;
209
    int16_t v;
210

    
211
    for (i = 0; i < length1; i++) {
212
        v = ((2 * i - level + 1) << 15) / level;
213
        for (j = 0; j < length2; j++)
214
            quantizers[i * length2 + j] = v;
215
    }
216

    
217
    for (i = length1 * length2; i < size; i++)
218
        quantizers[i] = 0;
219
}
220

    
221
static void generate_quantizers_table_2(int16_t quantizers[], int level, int length1, int length2, int size)
222
{
223
    int i, j;
224
    int16_t v;
225

    
226
    for (i = 0; i < length1; i++) {
227
        v = ((2 * (i % level) - level + 1) << 15) / level;
228
        for (j = 0; j < length2; j++)
229
            quantizers[i * length2 + j] = v;
230
    }
231

    
232
    for (i = length1 * length2; i < size; i++)
233
        quantizers[i] = 0;
234

    
235
}
236

    
237
static void generate_quantizers_table_3(int16_t quantizers[], int level, int length1, int length2, int size)
238
{
239
    int i, j;
240

    
241
    for (i = 0; i < length1; i++)
242
        for (j = 0; j < length2; j++)
243
            quantizers[i * length2 + j] = ((2 * (j % level) - level + 1) << 15) / level;
244

    
245
    for (i = length1 * length2; i < size; i++)
246
        quantizers[i] = 0;
247
}
248

    
249
/*
250
 * Initialize tables at runtime.
251
 */
252
static void ac3_tables_init(void)
253
{
254
    int i;
255

    
256
    /* Quantizer ungrouping tables. */
257
    // for level-3 quantizers
258
    generate_quantizers_table_1(l3_quantizers_1, 3, 3, 9, 32);
259
    generate_quantizers_table_2(l3_quantizers_2, 3, 9, 3, 32);
260
    generate_quantizers_table_3(l3_quantizers_3, 3, 9, 3, 32);
261

    
262
    //for level-5 quantizers
263
    generate_quantizers_table_1(l5_quantizers_1, 5, 5, 25, 128);
264
    generate_quantizers_table_2(l5_quantizers_2, 5, 25, 5, 128);
265
    generate_quantizers_table_3(l5_quantizers_3, 5, 25, 5, 128);
266

    
267
    //for level-7 quantizers
268
    generate_quantizers_table(l7_quantizers, 7, 7);
269

    
270
    //for level-4 quantizers
271
    generate_quantizers_table_2(l11_quantizers_1, 11, 11, 11, 128);
272
    generate_quantizers_table_3(l11_quantizers_2, 11, 11, 11, 128);
273

    
274
    //for level-15 quantizers
275
    generate_quantizers_table(l15_quantizers, 15, 15);
276
    /* End Quantizer ungrouping tables. */
277

    
278
    //generate scale factors
279
    for (i = 0; i < 25; i++)
280
        scale_factors[i] = pow(2.0, -(i + 15));
281

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

    
291

    
292
static int ac3_decode_init(AVCodecContext *avctx)
293
{
294
    AC3DecodeContext *ctx = avctx->priv_data;
295

    
296
    ac3_common_init();
297
    ac3_tables_init();
298
    ff_mdct_init(&ctx->imdct_256, 8, 1);
299
    ff_mdct_init(&ctx->imdct_512, 9, 1);
300
    ac3_window_init(ctx->window);
301
    dsputil_init(&ctx->dsp, avctx);
302
    av_init_random(0, &ctx->dith_state);
303

    
304
    return 0;
305
}
306
/*********** END INIT FUNCTIONS ***********/
307

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

    
319
    err = ff_ac3_parse_header(gb->buffer, &hdr);
320
    if(err)
321
        return err;
322

    
323
    /* get decoding parameters from header info */
324
    ctx->bit_alloc_params.fscod       = hdr.fscod;
325
    ctx->acmod                        = hdr.acmod;
326
    ctx->cmixlev                      = hdr.cmixlev;
327
    ctx->surmixlev                    = hdr.surmixlev;
328
    ctx->dsurmod                      = hdr.dsurmod;
329
    ctx->lfeon                        = hdr.lfeon;
330
    ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
331
    ctx->sampling_rate                = hdr.sample_rate;
332
    ctx->bit_rate                     = hdr.bit_rate;
333
    ctx->nchans                       = hdr.channels;
334
    ctx->nfchans                      = ctx->nchans - ctx->lfeon;
335
    ctx->frame_size                   = hdr.frame_size;
336

    
337
    /* set default output to all source channels */
338
    ctx->out_channels = ctx->nchans;
339
    ctx->output_mode = ctx->acmod;
340
    if(ctx->lfeon)
341
        ctx->output_mode |= AC3_OUTPUT_LFEON;
342

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

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

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

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

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

    
385
    return 0;
386
}
387

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

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

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

    
425
/**
426
 * Generates transform coefficients for each coupled channel in the coupling
427
 * range using the coupling coefficients and coupling coordinates.
428
 * reference: Section 7.4.3 Coupling Coordinate Format
429
 */
430
static void uncouple_channels(AC3DecodeContext *ctx)
431
{
432
    int i, j, ch, bnd, subbnd;
433

    
434
    subbnd = -1;
435
    i = ctx->cplstrtmant;
436
    for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
437
        do {
438
            subbnd++;
439
            for(j=0; j<12; j++) {
440
                for(ch=1; ch<=ctx->nfchans; ch++) {
441
                    if(ctx->chincpl[ch-1])
442
                        ctx->transform_coeffs[ch][i] = ctx->transform_coeffs_cpl[i] * ctx->cplco[ch-1][bnd];
443
                }
444
                i++;
445
            }
446
        } while((ctx->cplbndstrc >> subbnd) & 1);
447
    }
448
}
449

    
450
typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
451
    int16_t l3_quantizers[3];
452
    int16_t l5_quantizers[3];
453
    int16_t l11_quantizers[2];
454
    int l3ptr;
455
    int l5ptr;
456
    int l11ptr;
457
} mant_groups;
458

    
459
/* Get the transform coefficients for particular channel */
460
static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
461
{
462
    GetBitContext *gb = &ctx->gb;
463
    int i, gcode, tbap, dithflag, start, end;
464
    uint8_t *exps;
465
    uint8_t *bap;
466
    float *coeffs;
467

    
468
    if (ch_index >= 0) { /* fbw channels */
469
        dithflag = ctx->dithflag[ch_index];
470
        exps = ctx->dexps[ch_index];
471
        bap = ctx->bap[ch_index];
472
        coeffs = ctx->transform_coeffs[ch_index + 1];
473
        start = 0;
474
        end = ctx->endmant[ch_index];
475
    } else if (ch_index == -1) {
476
        dithflag = 0;
477
        exps = ctx->dlfeexps;
478
        bap = ctx->lfebap;
479
        coeffs = ctx->transform_coeffs[0];
480
        start = 0;
481
        end = 7;
482
    } else {
483
        dithflag = 0;
484
        exps = ctx->dcplexps;
485
        bap = ctx->cplbap;
486
        coeffs = ctx->transform_coeffs_cpl;
487
        start = ctx->cplstrtmant;
488
        end = ctx->cplendmant;
489
    }
490

    
491

    
492
    for (i = start; i < end; i++) {
493
        tbap = bap[i];
494
        switch (tbap) {
495
            case 0:
496
                if (!dithflag) {
497
                    coeffs[i] = 0;
498
                }
499
                else {
500
                    coeffs[i] = (av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB;
501
                }
502
                break;
503

    
504
            case 1:
505
                if (m->l3ptr > 2) {
506
                    gcode = get_bits(gb, 5);
507
                    m->l3_quantizers[0] = l3_quantizers_1[gcode];
508
                    m->l3_quantizers[1] = l3_quantizers_2[gcode];
509
                    m->l3_quantizers[2] = l3_quantizers_3[gcode];
510
                    m->l3ptr = 0;
511
                }
512
                coeffs[i] = m->l3_quantizers[m->l3ptr++];
513
                break;
514

    
515
            case 2:
516
                if (m->l5ptr > 2) {
517
                    gcode = get_bits(gb, 7);
518
                    m->l5_quantizers[0] = l5_quantizers_1[gcode];
519
                    m->l5_quantizers[1] = l5_quantizers_2[gcode];
520
                    m->l5_quantizers[2] = l5_quantizers_3[gcode];
521
                    m->l5ptr = 0;
522
                }
523
                coeffs[i] = m->l5_quantizers[m->l5ptr++];
524
                break;
525

    
526
            case 3:
527
                coeffs[i] = l7_quantizers[get_bits(gb, 3)];
528
                break;
529

    
530
            case 4:
531
                if (m->l11ptr > 1) {
532
                    gcode = get_bits(gb, 7);
533
                    m->l11_quantizers[0] = l11_quantizers_1[gcode];
534
                    m->l11_quantizers[1] = l11_quantizers_2[gcode];
535
                    m->l11ptr = 0;
536
                }
537
                coeffs[i] = m->l11_quantizers[m->l11ptr++];
538
                break;
539

    
540
            case 5:
541
                coeffs[i] = l15_quantizers[get_bits(gb, 4)];
542
                break;
543

    
544
            default:
545
                coeffs[i] = get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap]);
546
                break;
547
        }
548
        coeffs[i] *= scale_factors[exps[i]];
549
    }
550

    
551
    return 0;
552
}
553

    
554
/* Get the transform coefficients.
555
 * This function extracts the tranform coefficients form the ac3 bitstream.
556
 * This function is called after bit allocation is performed.
557
 */
558
static int get_transform_coeffs(AC3DecodeContext * ctx)
559
{
560
    int i, end;
561
    int got_cplchan = 0;
562
    mant_groups m;
563

    
564
    m.l3ptr = m.l5ptr = m.l11ptr = 3;
565

    
566
    for (i = 0; i < ctx->nfchans; i++) {
567
        /* transform coefficients for individual channel */
568
        if (get_transform_coeffs_ch(ctx, i, &m))
569
            return -1;
570
        /* tranform coefficients for coupling channels */
571
        if (ctx->chincpl[i])  {
572
            if (!got_cplchan) {
573
                if (get_transform_coeffs_ch(ctx, -2, &m)) {
574
                    av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
575
                    return -1;
576
                }
577
                uncouple_channels(ctx);
578
                got_cplchan = 1;
579
            }
580
            end = ctx->cplendmant;
581
        } else
582
            end = ctx->endmant[i];
583
        do
584
            ctx->transform_coeffs[i + 1][end] = 0;
585
        while(++end < 256);
586
    }
587
    if (ctx->lfeon) {
588
        if (get_transform_coeffs_ch(ctx, -1, &m))
589
                return -1;
590
        for (i = 7; i < 256; i++) {
591
            ctx->transform_coeffs[0][i] = 0;
592
        }
593
    }
594

    
595
    return 0;
596
}
597

    
598
/**
599
 * Performs stereo rematrixing.
600
 * reference: Section 7.5.4 Rematrixing : Decoding Technique
601
 */
602
static void do_rematrixing(AC3DecodeContext *ctx)
603
{
604
    int bnd, i;
605
    int end, bndend;
606
    float tmp0, tmp1;
607

    
608
    end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
609

    
610
    for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
611
        if(ctx->rematflg[bnd]) {
612
            bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
613
            for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
614
                tmp0 = ctx->transform_coeffs[1][i];
615
                tmp1 = ctx->transform_coeffs[2][i];
616
                ctx->transform_coeffs[1][i] = tmp0 + tmp1;
617
                ctx->transform_coeffs[2][i] = tmp0 - tmp1;
618
            }
619
        }
620
    }
621
}
622

    
623
/* This function performs the imdct on 256 sample transform
624
 * coefficients.
625
 */
626
static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
627
{
628
    int i, k;
629
    DECLARE_ALIGNED_16(float, x[128]);
630
    FFTComplex z[2][64];
631
    float *o_ptr = ctx->tmp_output;
632

    
633
    for(i=0; i<2; i++) {
634
        /* de-interleave coefficients */
635
        for(k=0; k<128; k++) {
636
            x[k] = ctx->transform_coeffs[chindex][2*k+i];
637
        }
638

    
639
        /* run standard IMDCT */
640
        ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
641

    
642
        /* reverse the post-rotation & reordering from standard IMDCT */
643
        for(k=0; k<32; k++) {
644
            z[i][32+k].re = -o_ptr[128+2*k];
645
            z[i][32+k].im = -o_ptr[2*k];
646
            z[i][31-k].re =  o_ptr[2*k+1];
647
            z[i][31-k].im =  o_ptr[128+2*k+1];
648
        }
649
    }
650

    
651
    /* apply AC-3 post-rotation & reordering */
652
    for(k=0; k<64; k++) {
653
        o_ptr[    2*k  ] = -z[0][   k].im;
654
        o_ptr[    2*k+1] =  z[0][63-k].re;
655
        o_ptr[128+2*k  ] = -z[0][   k].re;
656
        o_ptr[128+2*k+1] =  z[0][63-k].im;
657
        o_ptr[256+2*k  ] = -z[1][   k].re;
658
        o_ptr[256+2*k+1] =  z[1][63-k].im;
659
        o_ptr[384+2*k  ] =  z[1][   k].im;
660
        o_ptr[384+2*k+1] = -z[1][63-k].re;
661
    }
662
}
663

    
664
/* IMDCT Transform. */
665
static inline void do_imdct(AC3DecodeContext *ctx)
666
{
667
    int ch;
668

    
669
    if (ctx->output_mode & AC3_OUTPUT_LFEON) {
670
        ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
671
                                      ctx->transform_coeffs[0], ctx->tmp_imdct);
672
        ctx->dsp.vector_fmul_add_add(ctx->output[0], ctx->tmp_output,
673
                                     ctx->window, ctx->delay[0], 384, 256, 1);
674
        ctx->dsp.vector_fmul_reverse(ctx->delay[0], ctx->tmp_output+256,
675
                                     ctx->window, 256);
676
    }
677
    for (ch=1; ch<=ctx->nfchans; ch++) {
678
        if (ctx->blksw[ch-1])
679
            do_imdct_256(ctx, ch);
680
        else
681
            ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
682
                                          ctx->transform_coeffs[ch],
683
                                          ctx->tmp_imdct);
684

    
685
        ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
686
                                     ctx->window, ctx->delay[ch], 384, 256, 1);
687
        ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
688
                                     ctx->window, 256);
689
    }
690
}
691

    
692
/* Parse the audio block from ac3 bitstream.
693
 * This function extract the audio block from the ac3 bitstream
694
 * and produces the output for the block. This function must
695
 * be called for each of the six audio block in the ac3 bitstream.
696
 */
697
static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
698
{
699
    int nfchans = ctx->nfchans;
700
    int acmod = ctx->acmod;
701
    int i, bnd, seg, grpsize, ch;
702
    GetBitContext *gb = &ctx->gb;
703
    int bit_alloc_flags = 0;
704
    int8_t *dexps;
705
    int mstrcplco, cplcoexp, cplcomant;
706
    int dynrng, chbwcod, ngrps, cplabsexp, skipl;
707

    
708
    for (i = 0; i < nfchans; i++) /*block switch flag */
709
        ctx->blksw[i] = get_bits1(gb);
710

    
711
    for (i = 0; i < nfchans; i++) /* dithering flag */
712
        ctx->dithflag[i] = get_bits1(gb);
713

    
714
    if (get_bits1(gb)) { /* dynamic range */
715
        dynrng = get_sbits(gb, 8);
716
        ctx->dynrng = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
717
    } else if(blk == 0) {
718
        ctx->dynrng = 1.0;
719
    }
720

    
721
    if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
722
        if(get_bits1(gb)) {
723
            dynrng = get_sbits(gb, 8);
724
            ctx->dynrng2 = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
725
        } else if(blk == 0) {
726
            ctx->dynrng2 = 1.0;
727
        }
728
    }
729

    
730
    if (get_bits1(gb)) { /* coupling strategy */
731
        ctx->cplinu = get_bits1(gb);
732
        ctx->cplbndstrc = 0;
733
        if (ctx->cplinu) { /* coupling in use */
734
            int cplbegf, cplendf;
735

    
736
            for (i = 0; i < nfchans; i++)
737
                ctx->chincpl[i] = get_bits1(gb);
738

    
739
            if (acmod == AC3_ACMOD_STEREO)
740
                ctx->phsflginu = get_bits1(gb); //phase flag in use
741

    
742
            cplbegf = get_bits(gb, 4);
743
            cplendf = get_bits(gb, 4);
744

    
745
            if (3 + cplendf - cplbegf < 0) {
746
                av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
747
                return -1;
748
            }
749

    
750
            ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
751
            ctx->cplstrtmant = cplbegf * 12 + 37;
752
            ctx->cplendmant = cplendf * 12 + 73;
753
            for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
754
                if (get_bits1(gb)) {
755
                    ctx->cplbndstrc |= 1 << i;
756
                    ctx->ncplbnd--;
757
                }
758
        } else {
759
            for (i = 0; i < nfchans; i++)
760
                ctx->chincpl[i] = 0;
761
        }
762
    }
763

    
764
    if (ctx->cplinu) {
765
        ctx->cplcoe = 0;
766

    
767
        for (i = 0; i < nfchans; i++)
768
            if (ctx->chincpl[i])
769
                if (get_bits1(gb)) { /* coupling co-ordinates */
770
                    ctx->cplcoe |= 1 << i;
771
                    mstrcplco = 3 * get_bits(gb, 2);
772
                    for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
773
                        cplcoexp = get_bits(gb, 4);
774
                        cplcomant = get_bits(gb, 4);
775
                        if (cplcoexp == 15)
776
                            cplcomant <<= 14;
777
                        else
778
                            cplcomant = (cplcomant | 0x10) << 13;
779
                        ctx->cplco[i][bnd] = cplcomant * scale_factors[cplcoexp + mstrcplco];
780
                    }
781
                }
782

    
783
        if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
784
            for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
785
                if (get_bits1(gb))
786
                    ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
787
    }
788

    
789
    if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
790
        ctx->rematstr = get_bits1(gb);
791
        if (ctx->rematstr) {
792
            ctx->nrematbnd = 4;
793
            if(ctx->cplinu && ctx->cplstrtmant <= 61)
794
                ctx->nrematbnd -= 1 + (ctx->cplstrtmant == 37);
795
            for(bnd=0; bnd<ctx->nrematbnd; bnd++)
796
                ctx->rematflg[bnd] = get_bits1(gb);
797
        }
798
    }
799

    
800
    ctx->cplexpstr = EXP_REUSE;
801
    ctx->lfeexpstr = EXP_REUSE;
802
    if (ctx->cplinu) /* coupling exponent strategy */
803
        ctx->cplexpstr = get_bits(gb, 2);
804
    for (i = 0; i < nfchans; i++)  /* channel exponent strategy */
805
        ctx->chexpstr[i] = get_bits(gb, 2);
806
    if (ctx->lfeon)  /* lfe exponent strategy */
807
        ctx->lfeexpstr = get_bits1(gb);
808

    
809
    for (i = 0; i < nfchans; i++) /* channel bandwidth code */
810
        if (ctx->chexpstr[i] != EXP_REUSE) {
811
            if (ctx->chincpl[i])
812
                ctx->endmant[i] = ctx->cplstrtmant;
813
            else {
814
                chbwcod = get_bits(gb, 6);
815
                if (chbwcod > 60) {
816
                    av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
817
                    return -1;
818
                }
819
                ctx->endmant[i] = chbwcod * 3 + 73;
820
            }
821
        }
822

    
823
    if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
824
        bit_alloc_flags = 64;
825
        cplabsexp = get_bits(gb, 4) << 1;
826
        ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
827
        decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
828
    }
829

    
830
    for (i = 0; i < nfchans; i++) /* fbw channel exponents */
831
        if (ctx->chexpstr[i] != EXP_REUSE) {
832
            bit_alloc_flags |= 1 << i;
833
            grpsize = 3 << (ctx->chexpstr[i] - 1);
834
            ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
835
            dexps = ctx->dexps[i];
836
            dexps[0] = get_bits(gb, 4);
837
            decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
838
            skip_bits(gb, 2); /* skip gainrng */
839
        }
840

    
841
    if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
842
        bit_alloc_flags |= 32;
843
        ctx->dlfeexps[0] = get_bits(gb, 4);
844
        decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
845
    }
846

    
847
    if (get_bits1(gb)) { /* bit allocation information */
848
        bit_alloc_flags = 127;
849
        ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
850
        ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
851
        ctx->bit_alloc_params.sgain  = ff_sgaintab[get_bits(gb, 2)];
852
        ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
853
        ctx->bit_alloc_params.floor  = ff_floortab[get_bits(gb, 3)];
854
    }
855

    
856
    if (get_bits1(gb)) { /* snroffset */
857
        int csnr;
858
        bit_alloc_flags = 127;
859
        csnr = (get_bits(gb, 6) - 15) << 4;
860
        if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
861
            ctx->cplsnroffst = (csnr + get_bits(gb, 4)) << 2;
862
            ctx->cplfgain = ff_fgaintab[get_bits(gb, 3)];
863
        }
864
        for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
865
            ctx->snroffst[i] = (csnr + get_bits(gb, 4)) << 2;
866
            ctx->fgain[i] = ff_fgaintab[get_bits(gb, 3)];
867
        }
868
        if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
869
            ctx->lfesnroffst = (csnr + get_bits(gb, 4)) << 2;
870
            ctx->lfefgain = ff_fgaintab[get_bits(gb, 3)];
871
        }
872
    }
873

    
874
    if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
875
        bit_alloc_flags |= 64;
876
        ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
877
        ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
878
    }
879

    
880
    if (get_bits1(gb)) { /* delta bit allocation information */
881
        bit_alloc_flags = 127;
882

    
883
        if (ctx->cplinu) {
884
            ctx->cpldeltbae = get_bits(gb, 2);
885
            if (ctx->cpldeltbae == DBA_RESERVED) {
886
                av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
887
                return -1;
888
            }
889
        }
890

    
891
        for (i = 0; i < nfchans; i++) {
892
            ctx->deltbae[i] = get_bits(gb, 2);
893
            if (ctx->deltbae[i] == DBA_RESERVED) {
894
                av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
895
                return -1;
896
            }
897
        }
898

    
899
        if (ctx->cplinu)
900
            if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
901
                ctx->cpldeltnseg = get_bits(gb, 3);
902
                for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
903
                    ctx->cpldeltoffst[seg] = get_bits(gb, 5);
904
                    ctx->cpldeltlen[seg] = get_bits(gb, 4);
905
                    ctx->cpldeltba[seg] = get_bits(gb, 3);
906
                }
907
            }
908

    
909
        for (i = 0; i < nfchans; i++)
910
            if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
911
                ctx->deltnseg[i] = get_bits(gb, 3);
912
                for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
913
                    ctx->deltoffst[i][seg] = get_bits(gb, 5);
914
                    ctx->deltlen[i][seg] = get_bits(gb, 4);
915
                    ctx->deltba[i][seg] = get_bits(gb, 3);
916
                }
917
            }
918
    } else if(blk == 0) {
919
        if(ctx->cplinu)
920
            ctx->cpldeltbae = DBA_NONE;
921
        for(i=0; i<nfchans; i++) {
922
            ctx->deltbae[i] = DBA_NONE;
923
        }
924
    }
925

    
926
    if (bit_alloc_flags) {
927
        if (ctx->cplinu && (bit_alloc_flags & 64))
928
            ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->cplbap,
929
                                          ctx->dcplexps, ctx->cplstrtmant,
930
                                          ctx->cplendmant, ctx->cplsnroffst,
931
                                          ctx->cplfgain, 0,
932
                                          ctx->cpldeltbae, ctx->cpldeltnseg,
933
                                          ctx->cpldeltoffst, ctx->cpldeltlen,
934
                                          ctx->cpldeltba);
935
        for (i = 0; i < nfchans; i++)
936
            if ((bit_alloc_flags >> i) & 1)
937
                ac3_parametric_bit_allocation(&ctx->bit_alloc_params,
938
                                              ctx->bap[i], ctx->dexps[i], 0,
939
                                              ctx->endmant[i], ctx->snroffst[i],
940
                                              ctx->fgain[i], 0, ctx->deltbae[i],
941
                                              ctx->deltnseg[i], ctx->deltoffst[i],
942
                                              ctx->deltlen[i], ctx->deltba[i]);
943
        if (ctx->lfeon && (bit_alloc_flags & 32))
944
            ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->lfebap,
945
                                          ctx->dlfeexps, 0, 7, ctx->lfesnroffst,
946
                                          ctx->lfefgain, 1,
947
                                          DBA_NONE, 0, NULL, NULL, NULL);
948
    }
949

    
950
    if (get_bits1(gb)) { /* unused dummy data */
951
        skipl = get_bits(gb, 9);
952
        while(skipl--)
953
            skip_bits(gb, 8);
954
    }
955
    /* unpack the transform coefficients
956
     * * this also uncouples channels if coupling is in use.
957
     */
958
    if (get_transform_coeffs(ctx)) {
959
        av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
960
        return -1;
961
    }
962

    
963
    /* recover coefficients if rematrixing is in use */
964
    if(ctx->acmod == AC3_ACMOD_STEREO)
965
        do_rematrixing(ctx);
966

    
967
    /* apply scaling to coefficients (headroom, dynrng) */
968
    if(ctx->lfeon) {
969
        for(i=0; i<7; i++) {
970
            ctx->transform_coeffs[0][i] *= 2.0f * ctx->dynrng;
971
        }
972
    }
973
    for(ch=1; ch<=ctx->nfchans; ch++) {
974
        float gain = 2.0f;
975
        if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
976
            gain *= ctx->dynrng2;
977
        } else {
978
            gain *= ctx->dynrng;
979
        }
980
        for(i=0; i<ctx->endmant[ch-1]; i++) {
981
            ctx->transform_coeffs[ch][i] *= gain;
982
        }
983
    }
984

    
985
    do_imdct(ctx);
986

    
987
    return 0;
988
}
989

    
990
static inline int16_t convert(int32_t i)
991
{
992
    if (i > 0x43c07fff)
993
        return 32767;
994
    else if (i <= 0x43bf8000)
995
        return -32768;
996
    else
997
        return (i - 0x43c00000);
998
}
999

    
1000
/* Decode ac3 frame.
1001
 *
1002
 * @param avctx Pointer to AVCodecContext
1003
 * @param data Pointer to pcm smaples
1004
 * @param data_size Set to number of pcm samples produced by decoding
1005
 * @param buf Data to be decoded
1006
 * @param buf_size Size of the buffer
1007
 */
1008
static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1009
{
1010
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1011
    int16_t *out_samples = (int16_t *)data;
1012
    int i, j, k, start;
1013
    int32_t *int_ptr[6];
1014

    
1015
    for (i = 0; i < 6; i++)
1016
        int_ptr[i] = (int32_t *)(&ctx->output[i]);
1017

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

    
1021
    //Parse the syncinfo.
1022
    if (ac3_parse_header(ctx)) {
1023
        av_log(avctx, AV_LOG_ERROR, "\n");
1024
        *data_size = 0;
1025
        return buf_size;
1026
    }
1027

    
1028
    avctx->sample_rate = ctx->sampling_rate;
1029
    avctx->bit_rate = ctx->bit_rate;
1030

    
1031
    /* channel config */
1032
    if (avctx->channels == 0) {
1033
        avctx->channels = ctx->out_channels;
1034
    }
1035
    if(avctx->channels != ctx->out_channels) {
1036
        av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
1037
               avctx->channels);
1038
        return -1;
1039
    }
1040

    
1041
    //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);
1042

    
1043
    //Parse the Audio Blocks.
1044
    for (i = 0; i < NB_BLOCKS; i++) {
1045
        if (ac3_parse_audio_block(ctx, i)) {
1046
            av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1047
            *data_size = 0;
1048
            return ctx->frame_size;
1049
        }
1050
        start = (ctx->output_mode & AC3_OUTPUT_LFEON) ? 0 : 1;
1051
        for (k = 0; k < 256; k++)
1052
            for (j = start; j <= ctx->nfchans; j++)
1053
                *(out_samples++) = convert(int_ptr[j][k]);
1054
    }
1055
    *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
1056
    return ctx->frame_size;
1057
}
1058

    
1059
/* Uninitialize ac3 decoder.
1060
 */
1061
static int ac3_decode_end(AVCodecContext *avctx)
1062
{
1063
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1064
    ff_mdct_end(&ctx->imdct_512);
1065
    ff_mdct_end(&ctx->imdct_256);
1066

    
1067
    return 0;
1068
}
1069

    
1070
AVCodec ac3_decoder = {
1071
    .name = "ac3",
1072
    .type = CODEC_TYPE_AUDIO,
1073
    .id = CODEC_ID_AC3,
1074
    .priv_data_size = sizeof (AC3DecodeContext),
1075
    .init = ac3_decode_init,
1076
    .close = ac3_decode_end,
1077
    .decode = ac3_decode_frame,
1078
};
1079