Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3dec.c @ 5aefe3eb

History | View | Annotate | Download (35.1 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

    
56
/** tables for ungrouping mantissas */
57
static float b1_mantissas[32][3];
58
static float b2_mantissas[128][3];
59
static float b3_mantissas[8];
60
static float b4_mantissas[128][2];
61
static float b5_mantissas[16];
62

    
63
/**
64
 * Quantization table: levels for symmetric. bits for asymmetric.
65
 * reference: Table 7.18 Mapping of bap to Quantizer
66
 */
67
static const uint8_t qntztab[16] = {
68
    0, 3, 5, 7, 11, 15,
69
    5, 6, 7, 8, 9, 10, 11, 12, 14, 16
70
};
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 dither_all;
96
    int cplinu;
97
    int chincpl[AC3_MAX_CHANNELS];
98
    int phsflginu;
99
    int cplcoe;
100
    uint32_t cplbndstrc;
101
    int rematstr;
102
    int nrematbnd;
103
    int rematflg[AC3_MAX_CHANNELS];
104
    int cplexpstr;
105
    int lfeexpstr;
106
    int chexpstr[5];
107
    int cplsnroffst;
108
    int cplfgain;
109
    int snroffst[5];
110
    int fgain[5];
111
    int lfesnroffst;
112
    int lfefgain;
113
    int cpldeltbae;
114
    int deltbae[5];
115
    int cpldeltnseg;
116
    uint8_t  cpldeltoffst[8];
117
    uint8_t  cpldeltlen[8];
118
    uint8_t  cpldeltba[8];
119
    int deltnseg[5];
120
    uint8_t  deltoffst[5][8];
121
    uint8_t  deltlen[5][8];
122
    uint8_t  deltba[5][8];
123

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

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

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

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

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

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

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

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

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

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

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

    
196
static inline float
197
symmetric_dequant(int code, int levels)
198
{
199
    return (code - (levels >> 1)) * (2.0f / levels);
200
}
201

    
202
/*
203
 * Initialize tables at runtime.
204
 */
205
static void ac3_tables_init(void)
206
{
207
    int i;
208

    
209
    /* generate grouped mantissa tables
210
       reference: Section 7.3.5 Ungrouping of Mantissas */
211
    for(i=0; i<32; i++) {
212
        /* bap=1 mantissas */
213
        b1_mantissas[i][0] = symmetric_dequant( i / 9     , 3);
214
        b1_mantissas[i][1] = symmetric_dequant((i % 9) / 3, 3);
215
        b1_mantissas[i][2] = symmetric_dequant((i % 9) % 3, 3);
216
    }
217
    for(i=0; i<128; i++) {
218
        /* bap=2 mantissas */
219
        b2_mantissas[i][0] = symmetric_dequant( i / 25     , 5);
220
        b2_mantissas[i][1] = symmetric_dequant((i % 25) / 5, 5);
221
        b2_mantissas[i][2] = symmetric_dequant((i % 25) % 5, 5);
222

    
223
        /* bap=4 mantissas */
224
        b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
225
        b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
226
    }
227
    /* generate ungrouped mantissa tables
228
       reference: Tables 7.21 and 7.23 */
229
    for(i=0; i<7; i++) {
230
        /* bap=3 mantissas */
231
        b3_mantissas[i] = symmetric_dequant(i, 7);
232
    }
233
    for(i=0; i<15; i++) {
234
        /* bap=5 mantissas */
235
        b5_mantissas[i] = symmetric_dequant(i, 15);
236
    }
237

    
238
    //generate scale factors
239
    for (i = 0; i < 25; i++)
240
        scale_factors[i] = pow(2.0, -i);
241

    
242
    /* generate exponent tables
243
       reference: Section 7.1.3 Exponent Decoding */
244
    for(i=0; i<128; i++) {
245
        exp_ungroup_tbl[i][0] =  i / 25;
246
        exp_ungroup_tbl[i][1] = (i % 25) / 5;
247
        exp_ungroup_tbl[i][2] = (i % 25) % 5;
248
    }
249
}
250

    
251

    
252
static int ac3_decode_init(AVCodecContext *avctx)
253
{
254
    AC3DecodeContext *ctx = avctx->priv_data;
255

    
256
    ac3_common_init();
257
    ac3_tables_init();
258
    ff_mdct_init(&ctx->imdct_256, 8, 1);
259
    ff_mdct_init(&ctx->imdct_512, 9, 1);
260
    ac3_window_init(ctx->window);
261
    dsputil_init(&ctx->dsp, avctx);
262
    av_init_random(0, &ctx->dith_state);
263

    
264
    return 0;
265
}
266
/*********** END INIT FUNCTIONS ***********/
267

    
268
/**
269
 * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
270
 * GetBitContext within AC3DecodeContext must point to
271
 * start of the synchronized ac3 bitstream.
272
 */
273
static int ac3_parse_header(AC3DecodeContext *ctx)
274
{
275
    AC3HeaderInfo hdr;
276
    GetBitContext *gb = &ctx->gb;
277
    int err, i;
278

    
279
    err = ff_ac3_parse_header(gb->buffer, &hdr);
280
    if(err)
281
        return err;
282

    
283
    /* get decoding parameters from header info */
284
    ctx->bit_alloc_params.fscod       = hdr.fscod;
285
    ctx->acmod                        = hdr.acmod;
286
    ctx->cmixlev                      = hdr.cmixlev;
287
    ctx->surmixlev                    = hdr.surmixlev;
288
    ctx->dsurmod                      = hdr.dsurmod;
289
    ctx->lfeon                        = hdr.lfeon;
290
    ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
291
    ctx->sampling_rate                = hdr.sample_rate;
292
    ctx->bit_rate                     = hdr.bit_rate;
293
    ctx->nchans                       = hdr.channels;
294
    ctx->nfchans                      = ctx->nchans - ctx->lfeon;
295
    ctx->frame_size                   = hdr.frame_size;
296

    
297
    /* set default output to all source channels */
298
    ctx->out_channels = ctx->nchans;
299
    ctx->output_mode = ctx->acmod;
300
    if(ctx->lfeon)
301
        ctx->output_mode |= AC3_OUTPUT_LFEON;
302

    
303
    /* skip over portion of header which has already been read */
304
    skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
305
    skip_bits(gb, 16); // skip crc1
306
    skip_bits(gb, 8);  // skip fscod and frmsizecod
307
    skip_bits(gb, 11); // skip bsid, bsmod, and acmod
308
    if(ctx->acmod == AC3_ACMOD_STEREO) {
309
        skip_bits(gb, 2); // skip dsurmod
310
    } else {
311
        if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
312
            skip_bits(gb, 2); // skip cmixlev
313
        if(ctx->acmod & 4)
314
            skip_bits(gb, 2); // skip surmixlev
315
    }
316
    skip_bits1(gb); // skip lfeon
317

    
318
    /* read the rest of the bsi. read twice for dual mono mode. */
319
    i = !(ctx->acmod);
320
    do {
321
        skip_bits(gb, 5); //skip dialog normalization
322
        if (get_bits1(gb))
323
            skip_bits(gb, 8); //skip compression
324
        if (get_bits1(gb))
325
            skip_bits(gb, 8); //skip language code
326
        if (get_bits1(gb))
327
            skip_bits(gb, 7); //skip audio production information
328
    } while (i--);
329

    
330
    skip_bits(gb, 2); //skip copyright bit and original bitstream bit
331

    
332
    /* FIXME: read & use the xbsi1 downmix levels */
333
    if (get_bits1(gb))
334
        skip_bits(gb, 14); //skip timecode1
335
    if (get_bits1(gb))
336
        skip_bits(gb, 14); //skip timecode2
337

    
338
    if (get_bits1(gb)) {
339
        i = get_bits(gb, 6); //additional bsi length
340
        do {
341
            skip_bits(gb, 8);
342
        } while(i--);
343
    }
344

    
345
    return 0;
346
}
347

    
348
/**
349
 * Decodes the grouped exponents.
350
 * This function decodes the coded exponents according to exponent strategy
351
 * and stores them in the decoded exponents buffer.
352
 *
353
 * @param[in]  gb      GetBitContext which points to start of coded exponents
354
 * @param[in]  expstr  Exponent coding strategy
355
 * @param[in]  ngrps   Number of grouped exponents
356
 * @param[in]  absexp  Absolute exponent or DC exponent
357
 * @param[out] dexps   Decoded exponents are stored in dexps
358
 */
359
static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
360
                             uint8_t absexp, int8_t *dexps)
361
{
362
    int i, j, grp, grpsize;
363
    int dexp[256];
364
    int expacc, prevexp;
365

    
366
    /* unpack groups */
367
    grpsize = expstr + (expstr == EXP_D45);
368
    for(grp=0,i=0; grp<ngrps; grp++) {
369
        expacc = get_bits(gb, 7);
370
        dexp[i++] = exp_ungroup_tbl[expacc][0];
371
        dexp[i++] = exp_ungroup_tbl[expacc][1];
372
        dexp[i++] = exp_ungroup_tbl[expacc][2];
373
    }
374

    
375
    /* convert to absolute exps and expand groups */
376
    prevexp = absexp;
377
    for(i=0; i<ngrps*3; i++) {
378
        prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
379
        for(j=0; j<grpsize; j++) {
380
            dexps[(i*grpsize)+j] = prevexp;
381
        }
382
    }
383
}
384

    
385
/**
386
 * Generates transform coefficients for each coupled channel in the coupling
387
 * range using the coupling coefficients and coupling coordinates.
388
 * reference: Section 7.4.3 Coupling Coordinate Format
389
 */
390
static void uncouple_channels(AC3DecodeContext *ctx)
391
{
392
    int i, j, ch, bnd, subbnd;
393

    
394
    subbnd = -1;
395
    i = ctx->cplstrtmant;
396
    for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
397
        do {
398
            subbnd++;
399
            for(j=0; j<12; j++) {
400
                for(ch=1; ch<=ctx->nfchans; ch++) {
401
                    if(ctx->chincpl[ch-1])
402
                        ctx->transform_coeffs[ch][i] = ctx->transform_coeffs_cpl[i] * ctx->cplco[ch-1][bnd] * 8.0f;
403
                }
404
                i++;
405
            }
406
        } while((ctx->cplbndstrc >> subbnd) & 1);
407
    }
408
}
409

    
410
typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
411
    float b1_mant[3];
412
    float b2_mant[3];
413
    float b4_mant[2];
414
    int b1ptr;
415
    int b2ptr;
416
    int b4ptr;
417
} mant_groups;
418

    
419
/* Get the transform coefficients for particular channel */
420
static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
421
{
422
    GetBitContext *gb = &ctx->gb;
423
    int i, gcode, tbap, start, end;
424
    uint8_t *exps;
425
    uint8_t *bap;
426
    float *coeffs;
427

    
428
    if (ch_index >= 0) { /* fbw channels */
429
        exps = ctx->dexps[ch_index];
430
        bap = ctx->bap[ch_index];
431
        coeffs = ctx->transform_coeffs[ch_index + 1];
432
        start = 0;
433
        end = ctx->endmant[ch_index];
434
    } else if (ch_index == -1) {
435
        exps = ctx->dlfeexps;
436
        bap = ctx->lfebap;
437
        coeffs = ctx->transform_coeffs[0];
438
        start = 0;
439
        end = 7;
440
    } else {
441
        exps = ctx->dcplexps;
442
        bap = ctx->cplbap;
443
        coeffs = ctx->transform_coeffs_cpl;
444
        start = ctx->cplstrtmant;
445
        end = ctx->cplendmant;
446
    }
447

    
448

    
449
    for (i = start; i < end; i++) {
450
        tbap = bap[i];
451
        switch (tbap) {
452
            case 0:
453
                coeffs[i] = ((av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB) / 32768.0f;
454
                break;
455

    
456
            case 1:
457
                if(m->b1ptr > 2) {
458
                    gcode = get_bits(gb, 5);
459
                    m->b1_mant[0] = b1_mantissas[gcode][0];
460
                    m->b1_mant[1] = b1_mantissas[gcode][1];
461
                    m->b1_mant[2] = b1_mantissas[gcode][2];
462
                    m->b1ptr = 0;
463
                }
464
                coeffs[i] = m->b1_mant[m->b1ptr++];
465
                break;
466

    
467
            case 2:
468
                if(m->b2ptr > 2) {
469
                    gcode = get_bits(gb, 7);
470
                    m->b2_mant[0] = b2_mantissas[gcode][0];
471
                    m->b2_mant[1] = b2_mantissas[gcode][1];
472
                    m->b2_mant[2] = b2_mantissas[gcode][2];
473
                    m->b2ptr = 0;
474
                }
475
                coeffs[i] = m->b2_mant[m->b2ptr++];
476
                break;
477

    
478
            case 3:
479
                coeffs[i] = b3_mantissas[get_bits(gb, 3)];
480
                break;
481

    
482
            case 4:
483
                if(m->b4ptr > 1) {
484
                    gcode = get_bits(gb, 7);
485
                    m->b4_mant[0] = b4_mantissas[gcode][0];
486
                    m->b4_mant[1] = b4_mantissas[gcode][1];
487
                    m->b4ptr = 0;
488
                }
489
                coeffs[i] = m->b4_mant[m->b4ptr++];
490
                break;
491

    
492
            case 5:
493
                coeffs[i] = b5_mantissas[get_bits(gb, 4)];
494
                break;
495

    
496
            default:
497
                coeffs[i] = get_sbits(gb, qntztab[tbap]) * scale_factors[qntztab[tbap]-1];
498
                break;
499
        }
500
        coeffs[i] *= scale_factors[exps[i]];
501
    }
502

    
503
    return 0;
504
}
505

    
506
/**
507
 * Removes random dithering from coefficients with zero-bit mantissas
508
 * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
509
 */
510
static void remove_dithering(AC3DecodeContext *ctx) {
511
    int ch, i;
512
    int end=0;
513
    float *coeffs;
514
    uint8_t *bap;
515

    
516
    for(ch=1; ch<=ctx->nfchans; ch++) {
517
        if(!ctx->dithflag[ch-1]) {
518
            coeffs = ctx->transform_coeffs[ch];
519
            bap = ctx->bap[ch-1];
520
            if(ctx->chincpl[ch-1])
521
                end = ctx->cplstrtmant;
522
            else
523
                end = ctx->endmant[ch-1];
524
            for(i=0; i<end; i++) {
525
                if(bap[i] == 0)
526
                    coeffs[i] = 0.0f;
527
            }
528
            if(ctx->chincpl[ch-1]) {
529
                bap = ctx->cplbap;
530
                for(; i<ctx->cplendmant; i++) {
531
                    if(bap[i] == 0)
532
                        coeffs[i] = 0.0f;
533
                }
534
            }
535
        }
536
    }
537
}
538

    
539
/* Get the transform coefficients.
540
 * This function extracts the tranform coefficients form the ac3 bitstream.
541
 * This function is called after bit allocation is performed.
542
 */
543
static int get_transform_coeffs(AC3DecodeContext * ctx)
544
{
545
    int i, end;
546
    int got_cplchan = 0;
547
    mant_groups m;
548

    
549
    m.b1ptr = m.b2ptr = m.b4ptr = 3;
550

    
551
    for (i = 0; i < ctx->nfchans; i++) {
552
        /* transform coefficients for individual channel */
553
        if (get_transform_coeffs_ch(ctx, i, &m))
554
            return -1;
555
        /* tranform coefficients for coupling channels */
556
        if (ctx->chincpl[i])  {
557
            if (!got_cplchan) {
558
                if (get_transform_coeffs_ch(ctx, -2, &m)) {
559
                    av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
560
                    return -1;
561
                }
562
                uncouple_channels(ctx);
563
                got_cplchan = 1;
564
            }
565
            end = ctx->cplendmant;
566
        } else
567
            end = ctx->endmant[i];
568
        do
569
            ctx->transform_coeffs[i + 1][end] = 0;
570
        while(++end < 256);
571
    }
572
    if (ctx->lfeon) {
573
        if (get_transform_coeffs_ch(ctx, -1, &m))
574
                return -1;
575
        for (i = 7; i < 256; i++) {
576
            ctx->transform_coeffs[0][i] = 0;
577
        }
578
    }
579

    
580
    /* if any channel doesn't use dithering, zero appropriate coefficients */
581
    if(!ctx->dither_all)
582
        remove_dithering(ctx);
583

    
584
    return 0;
585
}
586

    
587
/**
588
 * Performs stereo rematrixing.
589
 * reference: Section 7.5.4 Rematrixing : Decoding Technique
590
 */
591
static void do_rematrixing(AC3DecodeContext *ctx)
592
{
593
    int bnd, i;
594
    int end, bndend;
595
    float tmp0, tmp1;
596

    
597
    end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
598

    
599
    for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
600
        if(ctx->rematflg[bnd]) {
601
            bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
602
            for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
603
                tmp0 = ctx->transform_coeffs[1][i];
604
                tmp1 = ctx->transform_coeffs[2][i];
605
                ctx->transform_coeffs[1][i] = tmp0 + tmp1;
606
                ctx->transform_coeffs[2][i] = tmp0 - tmp1;
607
            }
608
        }
609
    }
610
}
611

    
612
/* This function performs the imdct on 256 sample transform
613
 * coefficients.
614
 */
615
static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
616
{
617
    int i, k;
618
    DECLARE_ALIGNED_16(float, x[128]);
619
    FFTComplex z[2][64];
620
    float *o_ptr = ctx->tmp_output;
621

    
622
    for(i=0; i<2; i++) {
623
        /* de-interleave coefficients */
624
        for(k=0; k<128; k++) {
625
            x[k] = ctx->transform_coeffs[chindex][2*k+i];
626
        }
627

    
628
        /* run standard IMDCT */
629
        ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
630

    
631
        /* reverse the post-rotation & reordering from standard IMDCT */
632
        for(k=0; k<32; k++) {
633
            z[i][32+k].re = -o_ptr[128+2*k];
634
            z[i][32+k].im = -o_ptr[2*k];
635
            z[i][31-k].re =  o_ptr[2*k+1];
636
            z[i][31-k].im =  o_ptr[128+2*k+1];
637
        }
638
    }
639

    
640
    /* apply AC-3 post-rotation & reordering */
641
    for(k=0; k<64; k++) {
642
        o_ptr[    2*k  ] = -z[0][   k].im;
643
        o_ptr[    2*k+1] =  z[0][63-k].re;
644
        o_ptr[128+2*k  ] = -z[0][   k].re;
645
        o_ptr[128+2*k+1] =  z[0][63-k].im;
646
        o_ptr[256+2*k  ] = -z[1][   k].re;
647
        o_ptr[256+2*k+1] =  z[1][63-k].im;
648
        o_ptr[384+2*k  ] =  z[1][   k].im;
649
        o_ptr[384+2*k+1] = -z[1][63-k].re;
650
    }
651
}
652

    
653
/* IMDCT Transform. */
654
static inline void do_imdct(AC3DecodeContext *ctx)
655
{
656
    int ch;
657

    
658
    if (ctx->output_mode & AC3_OUTPUT_LFEON) {
659
        ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
660
                                      ctx->transform_coeffs[0], ctx->tmp_imdct);
661
        ctx->dsp.vector_fmul_add_add(ctx->output[0], ctx->tmp_output,
662
                                     ctx->window, ctx->delay[0], 384, 256, 1);
663
        ctx->dsp.vector_fmul_reverse(ctx->delay[0], ctx->tmp_output+256,
664
                                     ctx->window, 256);
665
    }
666
    for (ch=1; ch<=ctx->nfchans; ch++) {
667
        if (ctx->blksw[ch-1])
668
            do_imdct_256(ctx, ch);
669
        else
670
            ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
671
                                          ctx->transform_coeffs[ch],
672
                                          ctx->tmp_imdct);
673

    
674
        ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
675
                                     ctx->window, ctx->delay[ch], 384, 256, 1);
676
        ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
677
                                     ctx->window, 256);
678
    }
679
}
680

    
681
/* Parse the audio block from ac3 bitstream.
682
 * This function extract the audio block from the ac3 bitstream
683
 * and produces the output for the block. This function must
684
 * be called for each of the six audio block in the ac3 bitstream.
685
 */
686
static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
687
{
688
    int nfchans = ctx->nfchans;
689
    int acmod = ctx->acmod;
690
    int i, bnd, seg, grpsize, ch;
691
    GetBitContext *gb = &ctx->gb;
692
    int bit_alloc_flags = 0;
693
    int8_t *dexps;
694
    int mstrcplco, cplcoexp, cplcomant;
695
    int dynrng, chbwcod, ngrps, cplabsexp, skipl;
696

    
697
    for (i = 0; i < nfchans; i++) /*block switch flag */
698
        ctx->blksw[i] = get_bits1(gb);
699

    
700
    ctx->dither_all = 1;
701
    for (i = 0; i < nfchans; i++) { /* dithering flag */
702
        ctx->dithflag[i] = get_bits1(gb);
703
        if(!ctx->dithflag[i])
704
            ctx->dither_all = 0;
705
    }
706

    
707
    if (get_bits1(gb)) { /* dynamic range */
708
        dynrng = get_sbits(gb, 8);
709
        ctx->dynrng = (((dynrng & 0x1f) | 0x20) << 13) * pow(2.0, -(18 - (dynrng >> 5)));
710
    } else if(blk == 0) {
711
        ctx->dynrng = 1.0;
712
    }
713

    
714
    if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
715
        if(get_bits1(gb)) {
716
            dynrng = get_sbits(gb, 8);
717
            ctx->dynrng2 = (((dynrng & 0x1f) | 0x20) << 13) * pow(2.0, -(18 - (dynrng >> 5)));
718
        } else if(blk == 0) {
719
            ctx->dynrng2 = 1.0;
720
        }
721
    }
722

    
723
    if (get_bits1(gb)) { /* coupling strategy */
724
        ctx->cplinu = get_bits1(gb);
725
        ctx->cplbndstrc = 0;
726
        if (ctx->cplinu) { /* coupling in use */
727
            int cplbegf, cplendf;
728

    
729
            for (i = 0; i < nfchans; i++)
730
                ctx->chincpl[i] = get_bits1(gb);
731

    
732
            if (acmod == AC3_ACMOD_STEREO)
733
                ctx->phsflginu = get_bits1(gb); //phase flag in use
734

    
735
            cplbegf = get_bits(gb, 4);
736
            cplendf = get_bits(gb, 4);
737

    
738
            if (3 + cplendf - cplbegf < 0) {
739
                av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
740
                return -1;
741
            }
742

    
743
            ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
744
            ctx->cplstrtmant = cplbegf * 12 + 37;
745
            ctx->cplendmant = cplendf * 12 + 73;
746
            for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
747
                if (get_bits1(gb)) {
748
                    ctx->cplbndstrc |= 1 << i;
749
                    ctx->ncplbnd--;
750
                }
751
        } else {
752
            for (i = 0; i < nfchans; i++)
753
                ctx->chincpl[i] = 0;
754
        }
755
    }
756

    
757
    if (ctx->cplinu) {
758
        ctx->cplcoe = 0;
759

    
760
        for (i = 0; i < nfchans; i++)
761
            if (ctx->chincpl[i])
762
                if (get_bits1(gb)) { /* coupling co-ordinates */
763
                    ctx->cplcoe |= 1 << i;
764
                    mstrcplco = 3 * get_bits(gb, 2);
765
                    for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
766
                        cplcoexp = get_bits(gb, 4);
767
                        cplcomant = get_bits(gb, 4);
768
                        if (cplcoexp == 15)
769
                            ctx->cplco[i][bnd] = cplcomant / 16.0f;
770
                        else
771
                            ctx->cplco[i][bnd] = (cplcomant + 16.0f) / 32.0f;
772
                        ctx->cplco[i][bnd] *= scale_factors[cplcoexp + mstrcplco];
773
                    }
774
                }
775

    
776
        if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
777
            for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
778
                if (get_bits1(gb))
779
                    ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
780
    }
781

    
782
    if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
783
        ctx->rematstr = get_bits1(gb);
784
        if (ctx->rematstr) {
785
            ctx->nrematbnd = 4;
786
            if(ctx->cplinu && ctx->cplstrtmant <= 61)
787
                ctx->nrematbnd -= 1 + (ctx->cplstrtmant == 37);
788
            for(bnd=0; bnd<ctx->nrematbnd; bnd++)
789
                ctx->rematflg[bnd] = get_bits1(gb);
790
        }
791
    }
792

    
793
    ctx->cplexpstr = EXP_REUSE;
794
    ctx->lfeexpstr = EXP_REUSE;
795
    if (ctx->cplinu) /* coupling exponent strategy */
796
        ctx->cplexpstr = get_bits(gb, 2);
797
    for (i = 0; i < nfchans; i++)  /* channel exponent strategy */
798
        ctx->chexpstr[i] = get_bits(gb, 2);
799
    if (ctx->lfeon)  /* lfe exponent strategy */
800
        ctx->lfeexpstr = get_bits1(gb);
801

    
802
    for (i = 0; i < nfchans; i++) /* channel bandwidth code */
803
        if (ctx->chexpstr[i] != EXP_REUSE) {
804
            if (ctx->chincpl[i])
805
                ctx->endmant[i] = ctx->cplstrtmant;
806
            else {
807
                chbwcod = get_bits(gb, 6);
808
                if (chbwcod > 60) {
809
                    av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
810
                    return -1;
811
                }
812
                ctx->endmant[i] = chbwcod * 3 + 73;
813
            }
814
        }
815

    
816
    if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
817
        bit_alloc_flags = 64;
818
        cplabsexp = get_bits(gb, 4) << 1;
819
        ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
820
        decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
821
    }
822

    
823
    for (i = 0; i < nfchans; i++) /* fbw channel exponents */
824
        if (ctx->chexpstr[i] != EXP_REUSE) {
825
            bit_alloc_flags |= 1 << i;
826
            grpsize = 3 << (ctx->chexpstr[i] - 1);
827
            ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
828
            dexps = ctx->dexps[i];
829
            dexps[0] = get_bits(gb, 4);
830
            decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
831
            skip_bits(gb, 2); /* skip gainrng */
832
        }
833

    
834
    if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
835
        bit_alloc_flags |= 32;
836
        ctx->dlfeexps[0] = get_bits(gb, 4);
837
        decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
838
    }
839

    
840
    if (get_bits1(gb)) { /* bit allocation information */
841
        bit_alloc_flags = 127;
842
        ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
843
        ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
844
        ctx->bit_alloc_params.sgain  = ff_sgaintab[get_bits(gb, 2)];
845
        ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
846
        ctx->bit_alloc_params.floor  = ff_floortab[get_bits(gb, 3)];
847
    }
848

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

    
867
    if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
868
        bit_alloc_flags |= 64;
869
        ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
870
        ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
871
    }
872

    
873
    if (get_bits1(gb)) { /* delta bit allocation information */
874
        bit_alloc_flags = 127;
875

    
876
        if (ctx->cplinu) {
877
            ctx->cpldeltbae = get_bits(gb, 2);
878
            if (ctx->cpldeltbae == DBA_RESERVED) {
879
                av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
880
                return -1;
881
            }
882
        }
883

    
884
        for (i = 0; i < nfchans; i++) {
885
            ctx->deltbae[i] = get_bits(gb, 2);
886
            if (ctx->deltbae[i] == DBA_RESERVED) {
887
                av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
888
                return -1;
889
            }
890
        }
891

    
892
        if (ctx->cplinu)
893
            if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
894
                ctx->cpldeltnseg = get_bits(gb, 3);
895
                for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
896
                    ctx->cpldeltoffst[seg] = get_bits(gb, 5);
897
                    ctx->cpldeltlen[seg] = get_bits(gb, 4);
898
                    ctx->cpldeltba[seg] = get_bits(gb, 3);
899
                }
900
            }
901

    
902
        for (i = 0; i < nfchans; i++)
903
            if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
904
                ctx->deltnseg[i] = get_bits(gb, 3);
905
                for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
906
                    ctx->deltoffst[i][seg] = get_bits(gb, 5);
907
                    ctx->deltlen[i][seg] = get_bits(gb, 4);
908
                    ctx->deltba[i][seg] = get_bits(gb, 3);
909
                }
910
            }
911
    } else if(blk == 0) {
912
        if(ctx->cplinu)
913
            ctx->cpldeltbae = DBA_NONE;
914
        for(i=0; i<nfchans; i++) {
915
            ctx->deltbae[i] = DBA_NONE;
916
        }
917
    }
918

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

    
943
    if (get_bits1(gb)) { /* unused dummy data */
944
        skipl = get_bits(gb, 9);
945
        while(skipl--)
946
            skip_bits(gb, 8);
947
    }
948
    /* unpack the transform coefficients
949
     * * this also uncouples channels if coupling is in use.
950
     */
951
    if (get_transform_coeffs(ctx)) {
952
        av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
953
        return -1;
954
    }
955

    
956
    /* recover coefficients if rematrixing is in use */
957
    if(ctx->acmod == AC3_ACMOD_STEREO)
958
        do_rematrixing(ctx);
959

    
960
    /* apply scaling to coefficients (headroom, dynrng) */
961
    if(ctx->lfeon) {
962
        for(i=0; i<7; i++) {
963
            ctx->transform_coeffs[0][i] *= 2.0f * ctx->dynrng;
964
        }
965
    }
966
    for(ch=1; ch<=ctx->nfchans; ch++) {
967
        float gain = 2.0f;
968
        if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
969
            gain *= ctx->dynrng2;
970
        } else {
971
            gain *= ctx->dynrng;
972
        }
973
        for(i=0; i<ctx->endmant[ch-1]; i++) {
974
            ctx->transform_coeffs[ch][i] *= gain;
975
        }
976
    }
977

    
978
    do_imdct(ctx);
979

    
980
    return 0;
981
}
982

    
983
static inline int16_t convert(int32_t i)
984
{
985
    if (i > 0x43c07fff)
986
        return 32767;
987
    else if (i <= 0x43bf8000)
988
        return -32768;
989
    else
990
        return (i - 0x43c00000);
991
}
992

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

    
1008
    for (i = 0; i < 6; i++)
1009
        int_ptr[i] = (int32_t *)(&ctx->output[i]);
1010

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

    
1014
    //Parse the syncinfo.
1015
    if (ac3_parse_header(ctx)) {
1016
        av_log(avctx, AV_LOG_ERROR, "\n");
1017
        *data_size = 0;
1018
        return buf_size;
1019
    }
1020

    
1021
    avctx->sample_rate = ctx->sampling_rate;
1022
    avctx->bit_rate = ctx->bit_rate;
1023

    
1024
    /* channel config */
1025
    if (avctx->channels == 0) {
1026
        avctx->channels = ctx->out_channels;
1027
    }
1028
    if(avctx->channels != ctx->out_channels) {
1029
        av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
1030
               avctx->channels);
1031
        return -1;
1032
    }
1033

    
1034
    //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);
1035

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

    
1052
/* Uninitialize ac3 decoder.
1053
 */
1054
static int ac3_decode_end(AVCodecContext *avctx)
1055
{
1056
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1057
    ff_mdct_end(&ctx->imdct_512);
1058
    ff_mdct_end(&ctx->imdct_256);
1059

    
1060
    return 0;
1061
}
1062

    
1063
AVCodec ac3_decoder = {
1064
    .name = "ac3",
1065
    .type = CODEC_TYPE_AUDIO,
1066
    .id = CODEC_ID_AC3,
1067
    .priv_data_size = sizeof (AC3DecodeContext),
1068
    .init = ac3_decode_init,
1069
    .close = ac3_decode_end,
1070
    .decode = ac3_decode_frame,
1071
};
1072