Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3dec.c @ 60f07fad

History | View | Annotate | Download (36.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 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
/*
197
 * Generate quantizer tables.
198
 */
199
static void generate_quantizers_table(int16_t quantizers[], int level, int length)
200
{
201
    int i;
202

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

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

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

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

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

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

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

    
236
}
237

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

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

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

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

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

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

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

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

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

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

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

    
292

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

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

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

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

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

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

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

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

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

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

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

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

    
386
    return 0;
387
}
388

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

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

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

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

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

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

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

    
469
    if (ch_index >= 0) { /* fbw channels */
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
        exps = ctx->dlfeexps;
477
        bap = ctx->lfebap;
478
        coeffs = ctx->transform_coeffs[0];
479
        start = 0;
480
        end = 7;
481
    } else {
482
        exps = ctx->dcplexps;
483
        bap = ctx->cplbap;
484
        coeffs = ctx->transform_coeffs_cpl;
485
        start = ctx->cplstrtmant;
486
        end = ctx->cplendmant;
487
    }
488

    
489

    
490
    for (i = start; i < end; i++) {
491
        tbap = bap[i];
492
        switch (tbap) {
493
            case 0:
494
                    coeffs[i] = (av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB;
495
                break;
496

    
497
            case 1:
498
                if (m->l3ptr > 2) {
499
                    gcode = get_bits(gb, 5);
500
                    m->l3_quantizers[0] = l3_quantizers_1[gcode];
501
                    m->l3_quantizers[1] = l3_quantizers_2[gcode];
502
                    m->l3_quantizers[2] = l3_quantizers_3[gcode];
503
                    m->l3ptr = 0;
504
                }
505
                coeffs[i] = m->l3_quantizers[m->l3ptr++];
506
                break;
507

    
508
            case 2:
509
                if (m->l5ptr > 2) {
510
                    gcode = get_bits(gb, 7);
511
                    m->l5_quantizers[0] = l5_quantizers_1[gcode];
512
                    m->l5_quantizers[1] = l5_quantizers_2[gcode];
513
                    m->l5_quantizers[2] = l5_quantizers_3[gcode];
514
                    m->l5ptr = 0;
515
                }
516
                coeffs[i] = m->l5_quantizers[m->l5ptr++];
517
                break;
518

    
519
            case 3:
520
                coeffs[i] = l7_quantizers[get_bits(gb, 3)];
521
                break;
522

    
523
            case 4:
524
                if (m->l11ptr > 1) {
525
                    gcode = get_bits(gb, 7);
526
                    m->l11_quantizers[0] = l11_quantizers_1[gcode];
527
                    m->l11_quantizers[1] = l11_quantizers_2[gcode];
528
                    m->l11ptr = 0;
529
                }
530
                coeffs[i] = m->l11_quantizers[m->l11ptr++];
531
                break;
532

    
533
            case 5:
534
                coeffs[i] = l15_quantizers[get_bits(gb, 4)];
535
                break;
536

    
537
            default:
538
                coeffs[i] = get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap]);
539
                break;
540
        }
541
        coeffs[i] *= scale_factors[exps[i]];
542
    }
543

    
544
    return 0;
545
}
546

    
547
/**
548
 * Removes random dithering from coefficients with zero-bit mantissas
549
 * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
550
 */
551
static void remove_dithering(AC3DecodeContext *ctx) {
552
    int ch, i;
553
    int end=0;
554
    float *coeffs;
555
    uint8_t *bap;
556

    
557
    for(ch=1; ch<=ctx->nfchans; ch++) {
558
        if(!ctx->dithflag[ch-1]) {
559
            coeffs = ctx->transform_coeffs[ch];
560
            bap = ctx->bap[ch-1];
561
            if(ctx->chincpl[ch-1])
562
                end = ctx->cplstrtmant;
563
            else
564
                end = ctx->endmant[ch-1];
565
            for(i=0; i<end; i++) {
566
                if(bap[i] == 0)
567
                    coeffs[i] = 0.0f;
568
            }
569
            if(ctx->chincpl[ch-1]) {
570
                bap = ctx->cplbap;
571
                for(; i<ctx->cplendmant; i++) {
572
                    if(bap[i] == 0)
573
                        coeffs[i] = 0.0f;
574
                }
575
            }
576
        }
577
    }
578
}
579

    
580
/* Get the transform coefficients.
581
 * This function extracts the tranform coefficients form the ac3 bitstream.
582
 * This function is called after bit allocation is performed.
583
 */
584
static int get_transform_coeffs(AC3DecodeContext * ctx)
585
{
586
    int i, end;
587
    int got_cplchan = 0;
588
    mant_groups m;
589

    
590
    m.l3ptr = m.l5ptr = m.l11ptr = 3;
591

    
592
    for (i = 0; i < ctx->nfchans; i++) {
593
        /* transform coefficients for individual channel */
594
        if (get_transform_coeffs_ch(ctx, i, &m))
595
            return -1;
596
        /* tranform coefficients for coupling channels */
597
        if (ctx->chincpl[i])  {
598
            if (!got_cplchan) {
599
                if (get_transform_coeffs_ch(ctx, -2, &m)) {
600
                    av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
601
                    return -1;
602
                }
603
                uncouple_channels(ctx);
604
                got_cplchan = 1;
605
            }
606
            end = ctx->cplendmant;
607
        } else
608
            end = ctx->endmant[i];
609
        do
610
            ctx->transform_coeffs[i + 1][end] = 0;
611
        while(++end < 256);
612
    }
613
    if (ctx->lfeon) {
614
        if (get_transform_coeffs_ch(ctx, -1, &m))
615
                return -1;
616
        for (i = 7; i < 256; i++) {
617
            ctx->transform_coeffs[0][i] = 0;
618
        }
619
    }
620

    
621
    /* if any channel doesn't use dithering, zero appropriate coefficients */
622
    if(!ctx->dither_all)
623
        remove_dithering(ctx);
624

    
625
    return 0;
626
}
627

    
628
/**
629
 * Performs stereo rematrixing.
630
 * reference: Section 7.5.4 Rematrixing : Decoding Technique
631
 */
632
static void do_rematrixing(AC3DecodeContext *ctx)
633
{
634
    int bnd, i;
635
    int end, bndend;
636
    float tmp0, tmp1;
637

    
638
    end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
639

    
640
    for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
641
        if(ctx->rematflg[bnd]) {
642
            bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
643
            for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
644
                tmp0 = ctx->transform_coeffs[1][i];
645
                tmp1 = ctx->transform_coeffs[2][i];
646
                ctx->transform_coeffs[1][i] = tmp0 + tmp1;
647
                ctx->transform_coeffs[2][i] = tmp0 - tmp1;
648
            }
649
        }
650
    }
651
}
652

    
653
/* This function performs the imdct on 256 sample transform
654
 * coefficients.
655
 */
656
static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
657
{
658
    int i, k;
659
    DECLARE_ALIGNED_16(float, x[128]);
660
    FFTComplex z[2][64];
661
    float *o_ptr = ctx->tmp_output;
662

    
663
    for(i=0; i<2; i++) {
664
        /* de-interleave coefficients */
665
        for(k=0; k<128; k++) {
666
            x[k] = ctx->transform_coeffs[chindex][2*k+i];
667
        }
668

    
669
        /* run standard IMDCT */
670
        ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
671

    
672
        /* reverse the post-rotation & reordering from standard IMDCT */
673
        for(k=0; k<32; k++) {
674
            z[i][32+k].re = -o_ptr[128+2*k];
675
            z[i][32+k].im = -o_ptr[2*k];
676
            z[i][31-k].re =  o_ptr[2*k+1];
677
            z[i][31-k].im =  o_ptr[128+2*k+1];
678
        }
679
    }
680

    
681
    /* apply AC-3 post-rotation & reordering */
682
    for(k=0; k<64; k++) {
683
        o_ptr[    2*k  ] = -z[0][   k].im;
684
        o_ptr[    2*k+1] =  z[0][63-k].re;
685
        o_ptr[128+2*k  ] = -z[0][   k].re;
686
        o_ptr[128+2*k+1] =  z[0][63-k].im;
687
        o_ptr[256+2*k  ] = -z[1][   k].re;
688
        o_ptr[256+2*k+1] =  z[1][63-k].im;
689
        o_ptr[384+2*k  ] =  z[1][   k].im;
690
        o_ptr[384+2*k+1] = -z[1][63-k].re;
691
    }
692
}
693

    
694
/* IMDCT Transform. */
695
static inline void do_imdct(AC3DecodeContext *ctx)
696
{
697
    int ch;
698

    
699
    if (ctx->output_mode & AC3_OUTPUT_LFEON) {
700
        ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
701
                                      ctx->transform_coeffs[0], ctx->tmp_imdct);
702
        ctx->dsp.vector_fmul_add_add(ctx->output[0], ctx->tmp_output,
703
                                     ctx->window, ctx->delay[0], 384, 256, 1);
704
        ctx->dsp.vector_fmul_reverse(ctx->delay[0], ctx->tmp_output+256,
705
                                     ctx->window, 256);
706
    }
707
    for (ch=1; ch<=ctx->nfchans; ch++) {
708
        if (ctx->blksw[ch-1])
709
            do_imdct_256(ctx, ch);
710
        else
711
            ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
712
                                          ctx->transform_coeffs[ch],
713
                                          ctx->tmp_imdct);
714

    
715
        ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
716
                                     ctx->window, ctx->delay[ch], 384, 256, 1);
717
        ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
718
                                     ctx->window, 256);
719
    }
720
}
721

    
722
/* Parse the audio block from ac3 bitstream.
723
 * This function extract the audio block from the ac3 bitstream
724
 * and produces the output for the block. This function must
725
 * be called for each of the six audio block in the ac3 bitstream.
726
 */
727
static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
728
{
729
    int nfchans = ctx->nfchans;
730
    int acmod = ctx->acmod;
731
    int i, bnd, seg, grpsize, ch;
732
    GetBitContext *gb = &ctx->gb;
733
    int bit_alloc_flags = 0;
734
    int8_t *dexps;
735
    int mstrcplco, cplcoexp, cplcomant;
736
    int dynrng, chbwcod, ngrps, cplabsexp, skipl;
737

    
738
    for (i = 0; i < nfchans; i++) /*block switch flag */
739
        ctx->blksw[i] = get_bits1(gb);
740

    
741
    ctx->dither_all = 1;
742
    for (i = 0; i < nfchans; i++) { /* dithering flag */
743
        ctx->dithflag[i] = get_bits1(gb);
744
        if(!ctx->dithflag[i])
745
            ctx->dither_all = 0;
746
    }
747

    
748
    if (get_bits1(gb)) { /* dynamic range */
749
        dynrng = get_sbits(gb, 8);
750
        ctx->dynrng = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
751
    } else if(blk == 0) {
752
        ctx->dynrng = 1.0;
753
    }
754

    
755
    if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
756
        if(get_bits1(gb)) {
757
            dynrng = get_sbits(gb, 8);
758
            ctx->dynrng2 = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
759
        } else if(blk == 0) {
760
            ctx->dynrng2 = 1.0;
761
        }
762
    }
763

    
764
    if (get_bits1(gb)) { /* coupling strategy */
765
        ctx->cplinu = get_bits1(gb);
766
        ctx->cplbndstrc = 0;
767
        if (ctx->cplinu) { /* coupling in use */
768
            int cplbegf, cplendf;
769

    
770
            for (i = 0; i < nfchans; i++)
771
                ctx->chincpl[i] = get_bits1(gb);
772

    
773
            if (acmod == AC3_ACMOD_STEREO)
774
                ctx->phsflginu = get_bits1(gb); //phase flag in use
775

    
776
            cplbegf = get_bits(gb, 4);
777
            cplendf = get_bits(gb, 4);
778

    
779
            if (3 + cplendf - cplbegf < 0) {
780
                av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
781
                return -1;
782
            }
783

    
784
            ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
785
            ctx->cplstrtmant = cplbegf * 12 + 37;
786
            ctx->cplendmant = cplendf * 12 + 73;
787
            for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
788
                if (get_bits1(gb)) {
789
                    ctx->cplbndstrc |= 1 << i;
790
                    ctx->ncplbnd--;
791
                }
792
        } else {
793
            for (i = 0; i < nfchans; i++)
794
                ctx->chincpl[i] = 0;
795
        }
796
    }
797

    
798
    if (ctx->cplinu) {
799
        ctx->cplcoe = 0;
800

    
801
        for (i = 0; i < nfchans; i++)
802
            if (ctx->chincpl[i])
803
                if (get_bits1(gb)) { /* coupling co-ordinates */
804
                    ctx->cplcoe |= 1 << i;
805
                    mstrcplco = 3 * get_bits(gb, 2);
806
                    for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
807
                        cplcoexp = get_bits(gb, 4);
808
                        cplcomant = get_bits(gb, 4);
809
                        if (cplcoexp == 15)
810
                            cplcomant <<= 14;
811
                        else
812
                            cplcomant = (cplcomant | 0x10) << 13;
813
                        ctx->cplco[i][bnd] = cplcomant * scale_factors[cplcoexp + mstrcplco];
814
                    }
815
                }
816

    
817
        if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
818
            for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
819
                if (get_bits1(gb))
820
                    ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
821
    }
822

    
823
    if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
824
        ctx->rematstr = get_bits1(gb);
825
        if (ctx->rematstr) {
826
            ctx->nrematbnd = 4;
827
            if(ctx->cplinu && ctx->cplstrtmant <= 61)
828
                ctx->nrematbnd -= 1 + (ctx->cplstrtmant == 37);
829
            for(bnd=0; bnd<ctx->nrematbnd; bnd++)
830
                ctx->rematflg[bnd] = get_bits1(gb);
831
        }
832
    }
833

    
834
    ctx->cplexpstr = EXP_REUSE;
835
    ctx->lfeexpstr = EXP_REUSE;
836
    if (ctx->cplinu) /* coupling exponent strategy */
837
        ctx->cplexpstr = get_bits(gb, 2);
838
    for (i = 0; i < nfchans; i++)  /* channel exponent strategy */
839
        ctx->chexpstr[i] = get_bits(gb, 2);
840
    if (ctx->lfeon)  /* lfe exponent strategy */
841
        ctx->lfeexpstr = get_bits1(gb);
842

    
843
    for (i = 0; i < nfchans; i++) /* channel bandwidth code */
844
        if (ctx->chexpstr[i] != EXP_REUSE) {
845
            if (ctx->chincpl[i])
846
                ctx->endmant[i] = ctx->cplstrtmant;
847
            else {
848
                chbwcod = get_bits(gb, 6);
849
                if (chbwcod > 60) {
850
                    av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
851
                    return -1;
852
                }
853
                ctx->endmant[i] = chbwcod * 3 + 73;
854
            }
855
        }
856

    
857
    if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
858
        bit_alloc_flags = 64;
859
        cplabsexp = get_bits(gb, 4) << 1;
860
        ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
861
        decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
862
    }
863

    
864
    for (i = 0; i < nfchans; i++) /* fbw channel exponents */
865
        if (ctx->chexpstr[i] != EXP_REUSE) {
866
            bit_alloc_flags |= 1 << i;
867
            grpsize = 3 << (ctx->chexpstr[i] - 1);
868
            ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
869
            dexps = ctx->dexps[i];
870
            dexps[0] = get_bits(gb, 4);
871
            decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
872
            skip_bits(gb, 2); /* skip gainrng */
873
        }
874

    
875
    if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
876
        bit_alloc_flags |= 32;
877
        ctx->dlfeexps[0] = get_bits(gb, 4);
878
        decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
879
    }
880

    
881
    if (get_bits1(gb)) { /* bit allocation information */
882
        bit_alloc_flags = 127;
883
        ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
884
        ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
885
        ctx->bit_alloc_params.sgain  = ff_sgaintab[get_bits(gb, 2)];
886
        ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
887
        ctx->bit_alloc_params.floor  = ff_floortab[get_bits(gb, 3)];
888
    }
889

    
890
    if (get_bits1(gb)) { /* snroffset */
891
        int csnr;
892
        bit_alloc_flags = 127;
893
        csnr = (get_bits(gb, 6) - 15) << 4;
894
        if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
895
            ctx->cplsnroffst = (csnr + get_bits(gb, 4)) << 2;
896
            ctx->cplfgain = ff_fgaintab[get_bits(gb, 3)];
897
        }
898
        for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
899
            ctx->snroffst[i] = (csnr + get_bits(gb, 4)) << 2;
900
            ctx->fgain[i] = ff_fgaintab[get_bits(gb, 3)];
901
        }
902
        if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
903
            ctx->lfesnroffst = (csnr + get_bits(gb, 4)) << 2;
904
            ctx->lfefgain = ff_fgaintab[get_bits(gb, 3)];
905
        }
906
    }
907

    
908
    if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
909
        bit_alloc_flags |= 64;
910
        ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
911
        ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
912
    }
913

    
914
    if (get_bits1(gb)) { /* delta bit allocation information */
915
        bit_alloc_flags = 127;
916

    
917
        if (ctx->cplinu) {
918
            ctx->cpldeltbae = get_bits(gb, 2);
919
            if (ctx->cpldeltbae == DBA_RESERVED) {
920
                av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
921
                return -1;
922
            }
923
        }
924

    
925
        for (i = 0; i < nfchans; i++) {
926
            ctx->deltbae[i] = get_bits(gb, 2);
927
            if (ctx->deltbae[i] == DBA_RESERVED) {
928
                av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
929
                return -1;
930
            }
931
        }
932

    
933
        if (ctx->cplinu)
934
            if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
935
                ctx->cpldeltnseg = get_bits(gb, 3);
936
                for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
937
                    ctx->cpldeltoffst[seg] = get_bits(gb, 5);
938
                    ctx->cpldeltlen[seg] = get_bits(gb, 4);
939
                    ctx->cpldeltba[seg] = get_bits(gb, 3);
940
                }
941
            }
942

    
943
        for (i = 0; i < nfchans; i++)
944
            if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
945
                ctx->deltnseg[i] = get_bits(gb, 3);
946
                for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
947
                    ctx->deltoffst[i][seg] = get_bits(gb, 5);
948
                    ctx->deltlen[i][seg] = get_bits(gb, 4);
949
                    ctx->deltba[i][seg] = get_bits(gb, 3);
950
                }
951
            }
952
    } else if(blk == 0) {
953
        if(ctx->cplinu)
954
            ctx->cpldeltbae = DBA_NONE;
955
        for(i=0; i<nfchans; i++) {
956
            ctx->deltbae[i] = DBA_NONE;
957
        }
958
    }
959

    
960
    if (bit_alloc_flags) {
961
        if (ctx->cplinu && (bit_alloc_flags & 64))
962
            ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->cplbap,
963
                                          ctx->dcplexps, ctx->cplstrtmant,
964
                                          ctx->cplendmant, ctx->cplsnroffst,
965
                                          ctx->cplfgain, 0,
966
                                          ctx->cpldeltbae, ctx->cpldeltnseg,
967
                                          ctx->cpldeltoffst, ctx->cpldeltlen,
968
                                          ctx->cpldeltba);
969
        for (i = 0; i < nfchans; i++)
970
            if ((bit_alloc_flags >> i) & 1)
971
                ac3_parametric_bit_allocation(&ctx->bit_alloc_params,
972
                                              ctx->bap[i], ctx->dexps[i], 0,
973
                                              ctx->endmant[i], ctx->snroffst[i],
974
                                              ctx->fgain[i], 0, ctx->deltbae[i],
975
                                              ctx->deltnseg[i], ctx->deltoffst[i],
976
                                              ctx->deltlen[i], ctx->deltba[i]);
977
        if (ctx->lfeon && (bit_alloc_flags & 32))
978
            ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->lfebap,
979
                                          ctx->dlfeexps, 0, 7, ctx->lfesnroffst,
980
                                          ctx->lfefgain, 1,
981
                                          DBA_NONE, 0, NULL, NULL, NULL);
982
    }
983

    
984
    if (get_bits1(gb)) { /* unused dummy data */
985
        skipl = get_bits(gb, 9);
986
        while(skipl--)
987
            skip_bits(gb, 8);
988
    }
989
    /* unpack the transform coefficients
990
     * * this also uncouples channels if coupling is in use.
991
     */
992
    if (get_transform_coeffs(ctx)) {
993
        av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
994
        return -1;
995
    }
996

    
997
    /* recover coefficients if rematrixing is in use */
998
    if(ctx->acmod == AC3_ACMOD_STEREO)
999
        do_rematrixing(ctx);
1000

    
1001
    /* apply scaling to coefficients (headroom, dynrng) */
1002
    if(ctx->lfeon) {
1003
        for(i=0; i<7; i++) {
1004
            ctx->transform_coeffs[0][i] *= 2.0f * ctx->dynrng;
1005
        }
1006
    }
1007
    for(ch=1; ch<=ctx->nfchans; ch++) {
1008
        float gain = 2.0f;
1009
        if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
1010
            gain *= ctx->dynrng2;
1011
        } else {
1012
            gain *= ctx->dynrng;
1013
        }
1014
        for(i=0; i<ctx->endmant[ch-1]; i++) {
1015
            ctx->transform_coeffs[ch][i] *= gain;
1016
        }
1017
    }
1018

    
1019
    do_imdct(ctx);
1020

    
1021
    return 0;
1022
}
1023

    
1024
static inline int16_t convert(int32_t i)
1025
{
1026
    if (i > 0x43c07fff)
1027
        return 32767;
1028
    else if (i <= 0x43bf8000)
1029
        return -32768;
1030
    else
1031
        return (i - 0x43c00000);
1032
}
1033

    
1034
/* Decode ac3 frame.
1035
 *
1036
 * @param avctx Pointer to AVCodecContext
1037
 * @param data Pointer to pcm smaples
1038
 * @param data_size Set to number of pcm samples produced by decoding
1039
 * @param buf Data to be decoded
1040
 * @param buf_size Size of the buffer
1041
 */
1042
static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1043
{
1044
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1045
    int16_t *out_samples = (int16_t *)data;
1046
    int i, j, k, start;
1047
    int32_t *int_ptr[6];
1048

    
1049
    for (i = 0; i < 6; i++)
1050
        int_ptr[i] = (int32_t *)(&ctx->output[i]);
1051

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

    
1055
    //Parse the syncinfo.
1056
    if (ac3_parse_header(ctx)) {
1057
        av_log(avctx, AV_LOG_ERROR, "\n");
1058
        *data_size = 0;
1059
        return buf_size;
1060
    }
1061

    
1062
    avctx->sample_rate = ctx->sampling_rate;
1063
    avctx->bit_rate = ctx->bit_rate;
1064

    
1065
    /* channel config */
1066
    if (avctx->channels == 0) {
1067
        avctx->channels = ctx->out_channels;
1068
    }
1069
    if(avctx->channels != ctx->out_channels) {
1070
        av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
1071
               avctx->channels);
1072
        return -1;
1073
    }
1074

    
1075
    //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);
1076

    
1077
    //Parse the Audio Blocks.
1078
    for (i = 0; i < NB_BLOCKS; i++) {
1079
        if (ac3_parse_audio_block(ctx, i)) {
1080
            av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1081
            *data_size = 0;
1082
            return ctx->frame_size;
1083
        }
1084
        start = (ctx->output_mode & AC3_OUTPUT_LFEON) ? 0 : 1;
1085
        for (k = 0; k < 256; k++)
1086
            for (j = start; j <= ctx->nfchans; j++)
1087
                *(out_samples++) = convert(int_ptr[j][k]);
1088
    }
1089
    *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
1090
    return ctx->frame_size;
1091
}
1092

    
1093
/* Uninitialize ac3 decoder.
1094
 */
1095
static int ac3_decode_end(AVCodecContext *avctx)
1096
{
1097
    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1098
    ff_mdct_end(&ctx->imdct_512);
1099
    ff_mdct_end(&ctx->imdct_256);
1100

    
1101
    return 0;
1102
}
1103

    
1104
AVCodec ac3_decoder = {
1105
    .name = "ac3",
1106
    .type = CODEC_TYPE_AUDIO,
1107
    .id = CODEC_ID_AC3,
1108
    .priv_data_size = sizeof (AC3DecodeContext),
1109
    .init = ac3_decode_init,
1110
    .close = ac3_decode_end,
1111
    .decode = ac3_decode_frame,
1112
};
1113