Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3dec.c @ 7b4076a7

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

    
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
/** dynamic range table. converts codes to scale factors. */
73
static float dynrng_tbl[256];
74

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

    
83
static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
84
    LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
85

    
86
static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
87

    
88
/* override ac3.h to include coupling channel */
89
#undef AC3_MAX_CHANNELS
90
#define AC3_MAX_CHANNELS 7
91
#define CPL_CH 0
92

    
93
#define AC3_OUTPUT_LFEON  8
94

    
95
typedef struct {
96
    int acmod;
97
    int cmixlev;
98
    int surmixlev;
99
    int dsurmod;
100

    
101
    int blksw[AC3_MAX_CHANNELS];
102
    int dithflag[AC3_MAX_CHANNELS];
103
    int dither_all;
104
    int cplinu;
105
    int chincpl[AC3_MAX_CHANNELS];
106
    int phsflginu;
107
    int cplbndstrc[18];
108
    int rematstr;
109
    int nrematbnd;
110
    int rematflg[4];
111
    int expstr[AC3_MAX_CHANNELS];
112
    int snroffst[AC3_MAX_CHANNELS];
113
    int fgain[AC3_MAX_CHANNELS];
114
    int deltbae[AC3_MAX_CHANNELS];
115
    int deltnseg[AC3_MAX_CHANNELS];
116
    uint8_t  deltoffst[AC3_MAX_CHANNELS][8];
117
    uint8_t  deltlen[AC3_MAX_CHANNELS][8];
118
    uint8_t  deltba[AC3_MAX_CHANNELS][8];
119

    
120
    /* Derived Attributes. */
121
    int      sampling_rate;
122
    int      bit_rate;
123
    int      frame_size;
124

    
125
    int      nchans;            //number of total channels
126
    int      nfchans;           //number of full-bandwidth channels
127
    int      lfeon;             //lfe channel in use
128
    int      lfe_ch;            ///< index of LFE channel
129
    int      output_mode;       ///< output channel configuration
130
    int      out_channels;      ///< number of output channels
131

    
132
    float    dynrng;            //dynamic range gain
133
    float    dynrng2;           //dynamic range gain for 1+1 mode
134
    float    cplco[AC3_MAX_CHANNELS][18];   //coupling coordinates
135
    int      ncplbnd;           //number of coupling bands
136
    int      ncplsubnd;         //number of coupling sub bands
137
    int      startmant[AC3_MAX_CHANNELS];   ///< start frequency bin
138
    int      endmant[AC3_MAX_CHANNELS];     //channel end mantissas
139
    AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
140

    
141
    int8_t   dexps[AC3_MAX_CHANNELS][256];  ///< decoded exponents
142
    uint8_t  bap[AC3_MAX_CHANNELS][256];    ///< bit allocation pointers
143
    int16_t  psd[AC3_MAX_CHANNELS][256];    ///< scaled exponents
144
    int16_t  bndpsd[AC3_MAX_CHANNELS][50];  ///< interpolated exponents
145
    int16_t  mask[AC3_MAX_CHANNELS][50];    ///< masking curve values
146

    
147
    DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]);  //transform coefficients
148

    
149
    /* For IMDCT. */
150
    MDCTContext imdct_512;  //for 512 sample imdct transform
151
    MDCTContext imdct_256;  //for 256 sample imdct transform
152
    DSPContext  dsp;        //for optimization
153

    
154
    DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS-1][256]); //output after imdct transform and windowing
155
    DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS-1][256]);  //delay - added to the next block
156
    DECLARE_ALIGNED_16(float, tmp_imdct[256]);                  //temporary storage for imdct transform
157
    DECLARE_ALIGNED_16(float, tmp_output[512]);                 //temporary storage for output before windowing
158
    DECLARE_ALIGNED_16(float, window[256]);                     //window coefficients
159

    
160
    /* Miscellaneous. */
161
    GetBitContext gb;
162
    AVRandomState dith_state;   //for dither generation
163
} AC3DecodeContext;
164

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

    
176
   for (i = 0; i < 256; i++) {
177
       tmp = i * (256 - i) * alpha2;
178
       bessel = 1.0;
179
       for (j = 100; j > 0; j--) /* defaul to 100 iterations */
180
           bessel = bessel * tmp / (j * j) + 1;
181
       sum += bessel;
182
       local_window[i] = sum;
183
   }
184

    
185
   sum++;
186
   for (i = 0; i < 256; i++)
187
       window[i] = sqrt(local_window[i] / sum);
188
}
189

    
190
static inline float
191
symmetric_dequant(int code, int levels)
192
{
193
    return (code - (levels >> 1)) * (2.0f / levels);
194
}
195

    
196
/*
197
 * Initialize tables at runtime.
198
 */
199
static void ac3_tables_init(void)
200
{
201
    int i;
202

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

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

    
232
    /* generate dynamic range table
233
       reference: Section 7.7.1 Dynamic Range Control */
234
    for(i=0; i<256; i++) {
235
        int v = (i >> 5) - ((i >> 7) << 3) - 5;
236
        dynrng_tbl[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
237
    }
238

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

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

    
252

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

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

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

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

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

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

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

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

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

    
332
    skip_bits(gb, 2); //skip copyright bit and original bitstream bit
333

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

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

    
347
    return 0;
348
}
349

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

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

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

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

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

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

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

    
430
        exps = ctx->dexps[ch_index];
431
        bap = ctx->bap[ch_index];
432
        coeffs = ctx->transform_coeffs[ch_index];
433
        start = ctx->startmant[ch_index];
434
        end = ctx->endmant[ch_index];
435

    
436

    
437
    for (i = start; i < end; i++) {
438
        tbap = bap[i];
439
        switch (tbap) {
440
            case 0:
441
                coeffs[i] = ((av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB) / 32768.0f;
442
                break;
443

    
444
            case 1:
445
                if(m->b1ptr > 2) {
446
                    gcode = get_bits(gb, 5);
447
                    m->b1_mant[0] = b1_mantissas[gcode][0];
448
                    m->b1_mant[1] = b1_mantissas[gcode][1];
449
                    m->b1_mant[2] = b1_mantissas[gcode][2];
450
                    m->b1ptr = 0;
451
                }
452
                coeffs[i] = m->b1_mant[m->b1ptr++];
453
                break;
454

    
455
            case 2:
456
                if(m->b2ptr > 2) {
457
                    gcode = get_bits(gb, 7);
458
                    m->b2_mant[0] = b2_mantissas[gcode][0];
459
                    m->b2_mant[1] = b2_mantissas[gcode][1];
460
                    m->b2_mant[2] = b2_mantissas[gcode][2];
461
                    m->b2ptr = 0;
462
                }
463
                coeffs[i] = m->b2_mant[m->b2ptr++];
464
                break;
465

    
466
            case 3:
467
                coeffs[i] = b3_mantissas[get_bits(gb, 3)];
468
                break;
469

    
470
            case 4:
471
                if(m->b4ptr > 1) {
472
                    gcode = get_bits(gb, 7);
473
                    m->b4_mant[0] = b4_mantissas[gcode][0];
474
                    m->b4_mant[1] = b4_mantissas[gcode][1];
475
                    m->b4ptr = 0;
476
                }
477
                coeffs[i] = m->b4_mant[m->b4ptr++];
478
                break;
479

    
480
            case 5:
481
                coeffs[i] = b5_mantissas[get_bits(gb, 4)];
482
                break;
483

    
484
            default:
485
                coeffs[i] = get_sbits(gb, qntztab[tbap]) * scale_factors[qntztab[tbap]-1];
486
                break;
487
        }
488
        coeffs[i] *= scale_factors[exps[i]];
489
    }
490

    
491
    return 0;
492
}
493

    
494
/**
495
 * Removes random dithering from coefficients with zero-bit mantissas
496
 * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
497
 */
498
static void remove_dithering(AC3DecodeContext *ctx) {
499
    int ch, i;
500
    int end=0;
501
    float *coeffs;
502
    uint8_t *bap;
503

    
504
    for(ch=1; ch<=ctx->nfchans; ch++) {
505
        if(!ctx->dithflag[ch]) {
506
            coeffs = ctx->transform_coeffs[ch];
507
            bap = ctx->bap[ch];
508
            if(ctx->chincpl[ch])
509
                end = ctx->startmant[CPL_CH];
510
            else
511
                end = ctx->endmant[ch];
512
            for(i=0; i<end; i++) {
513
                if(bap[i] == 0)
514
                    coeffs[i] = 0.0f;
515
            }
516
            if(ctx->chincpl[ch]) {
517
                bap = ctx->bap[CPL_CH];
518
                for(; i<ctx->endmant[CPL_CH]; i++) {
519
                    if(bap[i] == 0)
520
                        coeffs[i] = 0.0f;
521
                }
522
            }
523
        }
524
    }
525
}
526

    
527
/* Get the transform coefficients.
528
 * This function extracts the tranform coefficients form the ac3 bitstream.
529
 * This function is called after bit allocation is performed.
530
 */
531
static int get_transform_coeffs(AC3DecodeContext * ctx)
532
{
533
    int ch, end;
534
    int got_cplchan = 0;
535
    mant_groups m;
536

    
537
    m.b1ptr = m.b2ptr = m.b4ptr = 3;
538

    
539
    for (ch = 1; ch <= ctx->nchans; ch++) {
540
        /* transform coefficients for individual channel */
541
        if (get_transform_coeffs_ch(ctx, ch, &m))
542
            return -1;
543
        /* tranform coefficients for coupling channels */
544
        if (ctx->chincpl[ch])  {
545
            if (!got_cplchan) {
546
                if (get_transform_coeffs_ch(ctx, CPL_CH, &m)) {
547
                    av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
548
                    return -1;
549
                }
550
                uncouple_channels(ctx);
551
                got_cplchan = 1;
552
            }
553
            end = ctx->endmant[CPL_CH];
554
        } else {
555
            end = ctx->endmant[ch];
556
        }
557
        do
558
            ctx->transform_coeffs[ch][end] = 0;
559
        while(++end < 256);
560
    }
561

    
562
    /* if any channel doesn't use dithering, zero appropriate coefficients */
563
    if(!ctx->dither_all)
564
        remove_dithering(ctx);
565

    
566
    return 0;
567
}
568

    
569
/**
570
 * Performs stereo rematrixing.
571
 * reference: Section 7.5.4 Rematrixing : Decoding Technique
572
 */
573
static void do_rematrixing(AC3DecodeContext *ctx)
574
{
575
    int bnd, i;
576
    int end, bndend;
577
    float tmp0, tmp1;
578

    
579
    end = FFMIN(ctx->endmant[1], ctx->endmant[2]);
580

    
581
    for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
582
        if(ctx->rematflg[bnd]) {
583
            bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
584
            for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
585
                tmp0 = ctx->transform_coeffs[1][i];
586
                tmp1 = ctx->transform_coeffs[2][i];
587
                ctx->transform_coeffs[1][i] = tmp0 + tmp1;
588
                ctx->transform_coeffs[2][i] = tmp0 - tmp1;
589
            }
590
        }
591
    }
592
}
593

    
594
/* This function performs the imdct on 256 sample transform
595
 * coefficients.
596
 */
597
static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
598
{
599
    int i, k;
600
    DECLARE_ALIGNED_16(float, x[128]);
601
    FFTComplex z[2][64];
602
    float *o_ptr = ctx->tmp_output;
603

    
604
    for(i=0; i<2; i++) {
605
        /* de-interleave coefficients */
606
        for(k=0; k<128; k++) {
607
            x[k] = ctx->transform_coeffs[chindex][2*k+i];
608
        }
609

    
610
        /* run standard IMDCT */
611
        ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
612

    
613
        /* reverse the post-rotation & reordering from standard IMDCT */
614
        for(k=0; k<32; k++) {
615
            z[i][32+k].re = -o_ptr[128+2*k];
616
            z[i][32+k].im = -o_ptr[2*k];
617
            z[i][31-k].re =  o_ptr[2*k+1];
618
            z[i][31-k].im =  o_ptr[128+2*k+1];
619
        }
620
    }
621

    
622
    /* apply AC-3 post-rotation & reordering */
623
    for(k=0; k<64; k++) {
624
        o_ptr[    2*k  ] = -z[0][   k].im;
625
        o_ptr[    2*k+1] =  z[0][63-k].re;
626
        o_ptr[128+2*k  ] = -z[0][   k].re;
627
        o_ptr[128+2*k+1] =  z[0][63-k].im;
628
        o_ptr[256+2*k  ] = -z[1][   k].re;
629
        o_ptr[256+2*k+1] =  z[1][63-k].im;
630
        o_ptr[384+2*k  ] =  z[1][   k].im;
631
        o_ptr[384+2*k+1] = -z[1][63-k].re;
632
    }
633
}
634

    
635
/* IMDCT Transform. */
636
static inline void do_imdct(AC3DecodeContext *ctx)
637
{
638
    int ch;
639
    int nchans;
640

    
641
    nchans = ctx->nfchans;
642
    if(ctx->output_mode & AC3_OUTPUT_LFEON)
643
        nchans++;
644

    
645
    for (ch=1; ch<=nchans; ch++) {
646
        if (ctx->blksw[ch]) {
647
            do_imdct_256(ctx, ch);
648
        } else {
649
            ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
650
                                          ctx->transform_coeffs[ch],
651
                                          ctx->tmp_imdct);
652
        }
653
        ctx->dsp.vector_fmul_add_add(ctx->output[ch-1], ctx->tmp_output,
654
                                     ctx->window, ctx->delay[ch-1], 384, 256, 1);
655
        ctx->dsp.vector_fmul_reverse(ctx->delay[ch-1], ctx->tmp_output+256,
656
                                     ctx->window, 256);
657
    }
658
}
659

    
660
/* Parse the audio block from ac3 bitstream.
661
 * This function extract the audio block from the ac3 bitstream
662
 * and produces the output for the block. This function must
663
 * be called for each of the six audio block in the ac3 bitstream.
664
 */
665
static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
666
{
667
    int nfchans = ctx->nfchans;
668
    int acmod = ctx->acmod;
669
    int i, bnd, seg, ch;
670
    GetBitContext *gb = &ctx->gb;
671
    uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
672

    
673
    memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
674

    
675
    for (ch = 1; ch <= nfchans; ch++) /*block switch flag */
676
        ctx->blksw[ch] = get_bits1(gb);
677

    
678
    ctx->dither_all = 1;
679
    for (ch = 1; ch <= nfchans; ch++) { /* dithering flag */
680
        ctx->dithflag[ch] = get_bits1(gb);
681
        if(!ctx->dithflag[ch])
682
            ctx->dither_all = 0;
683
    }
684

    
685
    if (get_bits1(gb)) { /* dynamic range */
686
        ctx->dynrng = dynrng_tbl[get_bits(gb, 8)];
687
    } else if(blk == 0) {
688
        ctx->dynrng = 1.0;
689
    }
690

    
691
    if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
692
        if(get_bits1(gb)) {
693
            ctx->dynrng2 = dynrng_tbl[get_bits(gb, 8)];
694
        } else if(blk == 0) {
695
            ctx->dynrng2 = 1.0;
696
        }
697
    }
698

    
699
    if (get_bits1(gb)) { /* coupling strategy */
700
        memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
701
        ctx->cplinu = get_bits1(gb);
702
        if (ctx->cplinu) { /* coupling in use */
703
            int cplbegf, cplendf;
704

    
705
            for (ch = 1; ch <= nfchans; ch++)
706
                ctx->chincpl[ch] = get_bits1(gb);
707

    
708
            if (acmod == AC3_ACMOD_STEREO)
709
                ctx->phsflginu = get_bits1(gb); //phase flag in use
710

    
711
            cplbegf = get_bits(gb, 4);
712
            cplendf = get_bits(gb, 4);
713

    
714
            if (3 + cplendf - cplbegf < 0) {
715
                av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
716
                return -1;
717
            }
718

    
719
            ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
720
            ctx->startmant[CPL_CH] = cplbegf * 12 + 37;
721
            ctx->endmant[CPL_CH] = cplendf * 12 + 73;
722
            for (bnd = 0; bnd < ctx->ncplsubnd - 1; bnd++) { /* coupling band structure */
723
                if (get_bits1(gb)) {
724
                    ctx->cplbndstrc[bnd] = 1;
725
                    ctx->ncplbnd--;
726
                }
727
            }
728
        } else {
729
            for (ch = 1; ch <= nfchans; ch++)
730
                ctx->chincpl[ch] = 0;
731
        }
732
    }
733

    
734
    if (ctx->cplinu) {
735
        int cplcoe = 0;
736

    
737
        for (ch = 1; ch <= nfchans; ch++) {
738
            if (ctx->chincpl[ch]) {
739
                if (get_bits1(gb)) { /* coupling co-ordinates */
740
                    int mstrcplco, cplcoexp, cplcomant;
741
                    cplcoe = 1;
742
                    mstrcplco = 3 * get_bits(gb, 2);
743
                    for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
744
                        cplcoexp = get_bits(gb, 4);
745
                        cplcomant = get_bits(gb, 4);
746
                        if (cplcoexp == 15)
747
                            ctx->cplco[ch][bnd] = cplcomant / 16.0f;
748
                        else
749
                            ctx->cplco[ch][bnd] = (cplcomant + 16.0f) / 32.0f;
750
                        ctx->cplco[ch][bnd] *= scale_factors[cplcoexp + mstrcplco];
751
                    }
752
                }
753
            }
754
        }
755

    
756
        if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && cplcoe) {
757
            for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
758
                if (get_bits1(gb))
759
                    ctx->cplco[2][bnd] = -ctx->cplco[2][bnd];
760
            }
761
        }
762
    }
763

    
764
    if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
765
        ctx->rematstr = get_bits1(gb);
766
        if (ctx->rematstr) {
767
            ctx->nrematbnd = 4;
768
            if(ctx->cplinu && ctx->startmant[CPL_CH] <= 61)
769
                ctx->nrematbnd -= 1 + (ctx->startmant[CPL_CH] == 37);
770
            for(bnd=0; bnd<ctx->nrematbnd; bnd++)
771
                ctx->rematflg[bnd] = get_bits1(gb);
772
        }
773
    }
774

    
775
    ctx->expstr[CPL_CH] = EXP_REUSE;
776
    ctx->expstr[ctx->lfe_ch] = EXP_REUSE;
777
    for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
778
        if(ch == ctx->lfe_ch)
779
            ctx->expstr[ch] = get_bits(gb, 1);
780
        else
781
            ctx->expstr[ch] = get_bits(gb, 2);
782
        if(ctx->expstr[ch] != EXP_REUSE)
783
            bit_alloc_stages[ch] = 3;
784
    }
785

    
786
    for (ch = 1; ch <= nfchans; ch++) { /* channel bandwidth code */
787
        ctx->startmant[ch] = 0;
788
        if (ctx->expstr[ch] != EXP_REUSE) {
789
            int prev = ctx->endmant[ch];
790
            if (ctx->chincpl[ch])
791
                ctx->endmant[ch] = ctx->startmant[CPL_CH];
792
            else {
793
                int chbwcod = get_bits(gb, 6);
794
                if (chbwcod > 60) {
795
                    av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
796
                    return -1;
797
                }
798
                ctx->endmant[ch] = chbwcod * 3 + 73;
799
            }
800
            if(blk > 0 && ctx->endmant[ch] != prev)
801
                memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
802
        }
803
    }
804
    ctx->startmant[ctx->lfe_ch] = 0;
805
    ctx->endmant[ctx->lfe_ch] = 7;
806

    
807
    for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
808
        if (ctx->expstr[ch] != EXP_REUSE) {
809
            int grpsize, ngrps;
810
            grpsize = 3 << (ctx->expstr[ch] - 1);
811
            if(ch == CPL_CH)
812
                ngrps = (ctx->endmant[ch] - ctx->startmant[ch]) / grpsize;
813
            else if(ch == ctx->lfe_ch)
814
                ngrps = 2;
815
            else
816
            ngrps = (ctx->endmant[ch] + grpsize - 4) / grpsize;
817
            ctx->dexps[ch][0] = get_bits(gb, 4) << !ch;
818
            decode_exponents(gb, ctx->expstr[ch], ngrps, ctx->dexps[ch][0],
819
                             &ctx->dexps[ch][ctx->startmant[ch]+!!ch]);
820
            if(ch != CPL_CH && ch != ctx->lfe_ch)
821
            skip_bits(gb, 2); /* skip gainrng */
822
        }
823
    }
824

    
825
    if (get_bits1(gb)) { /* bit allocation information */
826
        ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
827
        ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
828
        ctx->bit_alloc_params.sgain  = ff_sgaintab[get_bits(gb, 2)];
829
        ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
830
        ctx->bit_alloc_params.floor  = ff_floortab[get_bits(gb, 3)];
831
        for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
832
            bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
833
        }
834
    }
835

    
836
    if (get_bits1(gb)) { /* snroffset */
837
        int csnr;
838
        csnr = (get_bits(gb, 6) - 15) << 4;
839
        for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) { /* snr offset and fast gain */
840
            ctx->snroffst[ch] = (csnr + get_bits(gb, 4)) << 2;
841
            ctx->fgain[ch] = ff_fgaintab[get_bits(gb, 3)];
842
        }
843
        memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
844
    }
845

    
846
    if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
847
        ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
848
        ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
849
        bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
850
    }
851

    
852
    if (get_bits1(gb)) { /* delta bit allocation information */
853
        for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
854
            ctx->deltbae[ch] = get_bits(gb, 2);
855
            if (ctx->deltbae[ch] == DBA_RESERVED) {
856
                av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
857
                return -1;
858
            }
859
            bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
860
        }
861

    
862
        for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
863
            if (ctx->deltbae[ch] == DBA_NEW) {/*channel delta offset, len and bit allocation */
864
                ctx->deltnseg[ch] = get_bits(gb, 3);
865
                for (seg = 0; seg <= ctx->deltnseg[ch]; seg++) {
866
                    ctx->deltoffst[ch][seg] = get_bits(gb, 5);
867
                    ctx->deltlen[ch][seg] = get_bits(gb, 4);
868
                    ctx->deltba[ch][seg] = get_bits(gb, 3);
869
                }
870
            }
871
        }
872
    } else if(blk == 0) {
873
        for(ch=0; ch<=ctx->nchans; ch++) {
874
            ctx->deltbae[ch] = DBA_NONE;
875
        }
876
    }
877

    
878
    for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
879
        if(bit_alloc_stages[ch] > 2) {
880
            /* Exponent mapping into PSD and PSD integration */
881
            ff_ac3_bit_alloc_calc_psd(ctx->dexps[ch],
882
                                      ctx->startmant[ch], ctx->endmant[ch],
883
                                      ctx->psd[ch], ctx->bndpsd[ch]);
884
        }
885
        if(bit_alloc_stages[ch] > 1) {
886
            /* Compute excitation function, Compute masking curve, and
887
               Apply delta bit allocation */
888
            ff_ac3_bit_alloc_calc_mask(&ctx->bit_alloc_params, ctx->bndpsd[ch],
889
                                       ctx->startmant[ch], ctx->endmant[ch],
890
                                       ctx->fgain[ch], (ch == ctx->lfe_ch),
891
                                       ctx->deltbae[ch], ctx->deltnseg[ch],
892
                                       ctx->deltoffst[ch], ctx->deltlen[ch],
893
                                       ctx->deltba[ch], ctx->mask[ch]);
894
        }
895
        if(bit_alloc_stages[ch] > 0) {
896
            /* Compute bit allocation */
897
            ff_ac3_bit_alloc_calc_bap(ctx->mask[ch], ctx->psd[ch],
898
                                      ctx->startmant[ch], ctx->endmant[ch],
899
                                      ctx->snroffst[ch],
900
                                      ctx->bit_alloc_params.floor,
901
                                      ctx->bap[ch]);
902
        }
903
    }
904

    
905
    if (get_bits1(gb)) { /* unused dummy data */
906
        int skipl = get_bits(gb, 9);
907
        while(skipl--)
908
            skip_bits(gb, 8);
909
    }
910
    /* unpack the transform coefficients
911
     * * this also uncouples channels if coupling is in use.
912
     */
913
    if (get_transform_coeffs(ctx)) {
914
        av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
915
        return -1;
916
    }
917

    
918
    /* recover coefficients if rematrixing is in use */
919
    if(ctx->acmod == AC3_ACMOD_STEREO)
920
        do_rematrixing(ctx);
921

    
922
    /* apply scaling to coefficients (headroom, dynrng) */
923
    for(ch=1; ch<=ctx->nchans; ch++) {
924
        float gain = 2.0f;
925
        if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
926
            gain *= ctx->dynrng2;
927
        } else {
928
            gain *= ctx->dynrng;
929
        }
930
        for(i=0; i<ctx->endmant[ch]; i++) {
931
            ctx->transform_coeffs[ch][i] *= gain;
932
        }
933
    }
934

    
935
    do_imdct(ctx);
936

    
937
    return 0;
938
}
939

    
940
static inline int16_t convert(int32_t i)
941
{
942
    if (i > 0x43c07fff)
943
        return 32767;
944
    else if (i <= 0x43bf8000)
945
        return -32768;
946
    else
947
        return (i - 0x43c00000);
948
}
949

    
950
/* Decode ac3 frame.
951
 *
952
 * @param avctx Pointer to AVCodecContext
953
 * @param data Pointer to pcm smaples
954
 * @param data_size Set to number of pcm samples produced by decoding
955
 * @param buf Data to be decoded
956
 * @param buf_size Size of the buffer
957
 */
958
static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
959
{
960
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
961
    int16_t *out_samples = (int16_t *)data;
962
    int i, blk, ch;
963
    int32_t *int_ptr[6];
964

    
965
    for (ch = 0; ch < 6; ch++)
966
        int_ptr[ch] = (int32_t *)(&ctx->output[ch]);
967

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

    
971
    //Parse the syncinfo.
972
    if (ac3_parse_header(ctx)) {
973
        av_log(avctx, AV_LOG_ERROR, "\n");
974
        *data_size = 0;
975
        return buf_size;
976
    }
977

    
978
    avctx->sample_rate = ctx->sampling_rate;
979
    avctx->bit_rate = ctx->bit_rate;
980

    
981
    /* channel config */
982
    if (avctx->channels == 0) {
983
        avctx->channels = ctx->out_channels;
984
    }
985
    if(avctx->channels != ctx->out_channels) {
986
        av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
987
               avctx->channels);
988
        return -1;
989
    }
990

    
991
    //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);
992

    
993
    //Parse the Audio Blocks.
994
    for (blk = 0; blk < NB_BLOCKS; blk++) {
995
        if (ac3_parse_audio_block(ctx, blk)) {
996
            av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
997
            *data_size = 0;
998
            return ctx->frame_size;
999
        }
1000
        for (i = 0; i < 256; i++)
1001
            for (ch = 0; ch < ctx->out_channels; ch++)
1002
                *(out_samples++) = convert(int_ptr[ch][i]);
1003
    }
1004
    *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
1005
    return ctx->frame_size;
1006
}
1007

    
1008
/* Uninitialize ac3 decoder.
1009
 */
1010
static int ac3_decode_end(AVCodecContext *avctx)
1011
{
1012
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1013
    ff_mdct_end(&ctx->imdct_512);
1014
    ff_mdct_end(&ctx->imdct_256);
1015

    
1016
    return 0;
1017
}
1018

    
1019
AVCodec ac3_decoder = {
1020
    .name = "ac3",
1021
    .type = CODEC_TYPE_AUDIO,
1022
    .id = CODEC_ID_AC3,
1023
    .priv_data_size = sizeof (AC3DecodeContext),
1024
    .init = ac3_decode_init,
1025
    .close = ac3_decode_end,
1026
    .decode = ac3_decode_frame,
1027
};
1028