Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3dec.c @ 285bf28c

History | View | Annotate | Download (35.5 KB)

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

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

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

    
41
/**
42
 * Table of bin locations for rematrixing bands
43
 * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
44
 */
45
static const uint8_t rematrix_band_tbl[5] = { 13, 25, 37, 61, 253 };
46

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

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

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

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

    
63
static int16_t l7_quantizers[7];
64

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

    
68
static int16_t l15_quantizers[15];
69

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

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

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

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

    
85
#define AC3_OUTPUT_LFEON  8
86

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
235
}
236

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

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

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

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

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

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

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

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

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

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

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

    
291

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

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

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

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

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

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

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

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

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

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

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

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

    
385
    return 0;
386
}
387

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

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

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

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

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

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

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

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

    
491

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

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

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

    
528
            case 3:
529
                coeffs[i] = l7_quantizers[get_bits(gb, 3)] * scale_factors[exps[i]];
530
                continue;
531

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

    
542
            case 5:
543
                coeffs[i] = l15_quantizers[get_bits(gb, 4)] * scale_factors[exps[i]];
544
                continue;
545

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

    
552
    return 0;
553
}
554

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

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

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

    
596
    return 0;
597
}
598

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
986
    do_imdct(ctx);
987

    
988
    return 0;
989
}
990

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

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

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

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

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

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

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

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

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

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

    
1068
    return 0;
1069
}
1070

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