]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3dec.c
add support for downmixing to stereo or mono
[ffmpeg] / libavcodec / ac3dec.c
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_MINUS_9DB         0.3535533905932738
80 #define LEVEL_ZERO              0.0000000000000000
81 #define LEVEL_ONE               1.0000000000000000
82
83 static const float gain_levels[6] = {
84     LEVEL_ZERO,
85     LEVEL_ONE,
86     LEVEL_MINUS_3DB,
87     LEVEL_MINUS_4POINT5DB,
88     LEVEL_MINUS_6DB,
89     LEVEL_MINUS_9DB
90 };
91
92 /**
93  * Table for center mix levels
94  * reference: Section 5.4.2.4 cmixlev
95  */
96 static const uint8_t clevs[4] = { 2, 3, 4, 3 };
97
98 /**
99  * Table for surround mix levels
100  * reference: Section 5.4.2.5 surmixlev
101  */
102 static const uint8_t slevs[4] = { 2, 4, 0, 4 };
103
104 /**
105  * Table for default stereo downmixing coefficients
106  * reference: Section 7.8.2 Downmixing Into Two Channels
107  */
108 static const uint8_t ac3_default_coeffs[8][5][2] = {
109     { { 1, 0 }, { 0, 1 },                               },
110     { { 2, 2 },                                         },
111     { { 1, 0 }, { 0, 1 },                               },
112     { { 1, 0 }, { 3, 3 }, { 0, 1 },                     },
113     { { 1, 0 }, { 0, 1 }, { 4, 4 },                     },
114     { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 5, 5 },           },
115     { { 1, 0 }, { 0, 1 }, { 4, 0 }, { 0, 4 },           },
116     { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 4, 0 }, { 0, 4 }, },
117 };
118
119 /* override ac3.h to include coupling channel */
120 #undef AC3_MAX_CHANNELS
121 #define AC3_MAX_CHANNELS 7
122 #define CPL_CH 0
123
124 #define AC3_OUTPUT_LFEON  8
125
126 typedef struct {
127     int acmod;
128     int dsurmod;
129
130     int blksw[AC3_MAX_CHANNELS];
131     int dithflag[AC3_MAX_CHANNELS];
132     int dither_all;
133     int cplinu;
134     int chincpl[AC3_MAX_CHANNELS];
135     int phsflginu;
136     int cplbndstrc[18];
137     int rematstr;
138     int nrematbnd;
139     int rematflg[4];
140     int expstr[AC3_MAX_CHANNELS];
141     int snroffst[AC3_MAX_CHANNELS];
142     int fgain[AC3_MAX_CHANNELS];
143     int deltbae[AC3_MAX_CHANNELS];
144     int deltnseg[AC3_MAX_CHANNELS];
145     uint8_t  deltoffst[AC3_MAX_CHANNELS][8];
146     uint8_t  deltlen[AC3_MAX_CHANNELS][8];
147     uint8_t  deltba[AC3_MAX_CHANNELS][8];
148
149     /* Derived Attributes. */
150     int      sampling_rate;
151     int      bit_rate;
152     int      frame_size;
153
154     int      nchans;            //number of total channels
155     int      nfchans;           //number of full-bandwidth channels
156     int      lfeon;             //lfe channel in use
157     int      lfe_ch;            ///< index of LFE channel
158     int      output_mode;       ///< output channel configuration
159     int      out_channels;      ///< number of output channels
160
161     float    downmix_coeffs[AC3_MAX_CHANNELS][2];   ///< stereo downmix coefficients
162     float    dynrng;            //dynamic range gain
163     float    dynrng2;           //dynamic range gain for 1+1 mode
164     float    cplco[AC3_MAX_CHANNELS][18];   //coupling coordinates
165     int      ncplbnd;           //number of coupling bands
166     int      ncplsubnd;         //number of coupling sub bands
167     int      startmant[AC3_MAX_CHANNELS];   ///< start frequency bin
168     int      endmant[AC3_MAX_CHANNELS];     //channel end mantissas
169     AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
170
171     int8_t   dexps[AC3_MAX_CHANNELS][256];  ///< decoded exponents
172     uint8_t  bap[AC3_MAX_CHANNELS][256];    ///< bit allocation pointers
173     int16_t  psd[AC3_MAX_CHANNELS][256];    ///< scaled exponents
174     int16_t  bndpsd[AC3_MAX_CHANNELS][50];  ///< interpolated exponents
175     int16_t  mask[AC3_MAX_CHANNELS][50];    ///< masking curve values
176
177     DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]);  //transform coefficients
178
179     /* For IMDCT. */
180     MDCTContext imdct_512;  //for 512 sample imdct transform
181     MDCTContext imdct_256;  //for 256 sample imdct transform
182     DSPContext  dsp;        //for optimization
183     float       add_bias;   ///< offset for float_to_int16 conversion
184     float       mul_bias;   ///< scaling for float_to_int16 conversion
185
186     DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS-1][256]); //output after imdct transform and windowing
187     DECLARE_ALIGNED_16(short, int_output[AC3_MAX_CHANNELS-1][256]); ///< final 16-bit integer output
188     DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS-1][256]);  //delay - added to the next block
189     DECLARE_ALIGNED_16(float, tmp_imdct[256]);                  //temporary storage for imdct transform
190     DECLARE_ALIGNED_16(float, tmp_output[512]);                 //temporary storage for output before windowing
191     DECLARE_ALIGNED_16(float, window[256]);                     //window coefficients
192
193     /* Miscellaneous. */
194     GetBitContext gb;
195     AVRandomState dith_state;   //for dither generation
196 } AC3DecodeContext;
197
198 /*********** BEGIN INIT HELPER FUNCTIONS ***********/
199 /**
200  * Generate a Kaiser-Bessel Derived Window.
201  */
202 static void ac3_window_init(float *window)
203 {
204    int i, j;
205    double sum = 0.0, bessel, tmp;
206    double local_window[256];
207    double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
208
209    for (i = 0; i < 256; i++) {
210        tmp = i * (256 - i) * alpha2;
211        bessel = 1.0;
212        for (j = 100; j > 0; j--) /* defaul to 100 iterations */
213            bessel = bessel * tmp / (j * j) + 1;
214        sum += bessel;
215        local_window[i] = sum;
216    }
217
218    sum++;
219    for (i = 0; i < 256; i++)
220        window[i] = sqrt(local_window[i] / sum);
221 }
222
223 static inline float
224 symmetric_dequant(int code, int levels)
225 {
226     return (code - (levels >> 1)) * (2.0f / levels);
227 }
228
229 /*
230  * Initialize tables at runtime.
231  */
232 static void ac3_tables_init(void)
233 {
234     int i;
235
236     /* generate grouped mantissa tables
237        reference: Section 7.3.5 Ungrouping of Mantissas */
238     for(i=0; i<32; i++) {
239         /* bap=1 mantissas */
240         b1_mantissas[i][0] = symmetric_dequant( i / 9     , 3);
241         b1_mantissas[i][1] = symmetric_dequant((i % 9) / 3, 3);
242         b1_mantissas[i][2] = symmetric_dequant((i % 9) % 3, 3);
243     }
244     for(i=0; i<128; i++) {
245         /* bap=2 mantissas */
246         b2_mantissas[i][0] = symmetric_dequant( i / 25     , 5);
247         b2_mantissas[i][1] = symmetric_dequant((i % 25) / 5, 5);
248         b2_mantissas[i][2] = symmetric_dequant((i % 25) % 5, 5);
249
250         /* bap=4 mantissas */
251         b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
252         b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
253     }
254     /* generate ungrouped mantissa tables
255        reference: Tables 7.21 and 7.23 */
256     for(i=0; i<7; i++) {
257         /* bap=3 mantissas */
258         b3_mantissas[i] = symmetric_dequant(i, 7);
259     }
260     for(i=0; i<15; i++) {
261         /* bap=5 mantissas */
262         b5_mantissas[i] = symmetric_dequant(i, 15);
263     }
264
265     /* generate dynamic range table
266        reference: Section 7.7.1 Dynamic Range Control */
267     for(i=0; i<256; i++) {
268         int v = (i >> 5) - ((i >> 7) << 3) - 5;
269         dynrng_tbl[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
270     }
271
272     //generate scale factors
273     for (i = 0; i < 25; i++)
274         scale_factors[i] = pow(2.0, -i);
275
276     /* generate exponent tables
277        reference: Section 7.1.3 Exponent Decoding */
278     for(i=0; i<128; i++) {
279         exp_ungroup_tbl[i][0] =  i / 25;
280         exp_ungroup_tbl[i][1] = (i % 25) / 5;
281         exp_ungroup_tbl[i][2] = (i % 25) % 5;
282     }
283 }
284
285
286 static int ac3_decode_init(AVCodecContext *avctx)
287 {
288     AC3DecodeContext *ctx = avctx->priv_data;
289
290     ac3_common_init();
291     ac3_tables_init();
292     ff_mdct_init(&ctx->imdct_256, 8, 1);
293     ff_mdct_init(&ctx->imdct_512, 9, 1);
294     ac3_window_init(ctx->window);
295     dsputil_init(&ctx->dsp, avctx);
296     av_init_random(0, &ctx->dith_state);
297
298     if(ctx->dsp.float_to_int16 == ff_float_to_int16_c) {
299         ctx->add_bias = 385.0f;
300         ctx->mul_bias = 1.0f;
301     } else {
302         ctx->add_bias = 0.0f;
303         ctx->mul_bias = 32767.0f;
304     }
305
306     return 0;
307 }
308 /*********** END INIT FUNCTIONS ***********/
309
310 /**
311  * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
312  * GetBitContext within AC3DecodeContext must point to
313  * start of the synchronized ac3 bitstream.
314  */
315 static int ac3_parse_header(AC3DecodeContext *ctx)
316 {
317     AC3HeaderInfo hdr;
318     GetBitContext *gb = &ctx->gb;
319     float cmixlev, surmixlev;
320     int err, i;
321
322     err = ff_ac3_parse_header(gb->buffer, &hdr);
323     if(err)
324         return err;
325
326     /* get decoding parameters from header info */
327     ctx->bit_alloc_params.fscod       = hdr.fscod;
328     ctx->acmod                        = hdr.acmod;
329     cmixlev                           = gain_levels[clevs[hdr.cmixlev]];
330     surmixlev                         = gain_levels[slevs[hdr.surmixlev]];
331     ctx->dsurmod                      = hdr.dsurmod;
332     ctx->lfeon                        = hdr.lfeon;
333     ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
334     ctx->sampling_rate                = hdr.sample_rate;
335     ctx->bit_rate                     = hdr.bit_rate;
336     ctx->nchans                       = hdr.channels;
337     ctx->nfchans                      = ctx->nchans - ctx->lfeon;
338     ctx->lfe_ch                       = ctx->nfchans + 1;
339     ctx->frame_size                   = hdr.frame_size;
340
341     /* set default output to all source channels */
342     ctx->out_channels = ctx->nchans;
343     ctx->output_mode = ctx->acmod;
344     if(ctx->lfeon)
345         ctx->output_mode |= AC3_OUTPUT_LFEON;
346
347     /* skip over portion of header which has already been read */
348     skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
349     skip_bits(gb, 16); // skip crc1
350     skip_bits(gb, 8);  // skip fscod and frmsizecod
351     skip_bits(gb, 11); // skip bsid, bsmod, and acmod
352     if(ctx->acmod == AC3_ACMOD_STEREO) {
353         skip_bits(gb, 2); // skip dsurmod
354     } else {
355         if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
356             skip_bits(gb, 2); // skip cmixlev
357         if(ctx->acmod & 4)
358             skip_bits(gb, 2); // skip surmixlev
359     }
360     skip_bits1(gb); // skip lfeon
361
362     /* read the rest of the bsi. read twice for dual mono mode. */
363     i = !(ctx->acmod);
364     do {
365         skip_bits(gb, 5); //skip dialog normalization
366         if (get_bits1(gb))
367             skip_bits(gb, 8); //skip compression
368         if (get_bits1(gb))
369             skip_bits(gb, 8); //skip language code
370         if (get_bits1(gb))
371             skip_bits(gb, 7); //skip audio production information
372     } while (i--);
373
374     skip_bits(gb, 2); //skip copyright bit and original bitstream bit
375
376     /* FIXME: read & use the xbsi1 downmix levels */
377     if (get_bits1(gb))
378         skip_bits(gb, 14); //skip timecode1
379     if (get_bits1(gb))
380         skip_bits(gb, 14); //skip timecode2
381
382     if (get_bits1(gb)) {
383         i = get_bits(gb, 6); //additional bsi length
384         do {
385             skip_bits(gb, 8);
386         } while(i--);
387     }
388
389     /* set stereo downmixing coefficients
390        reference: Section 7.8.2 Downmixing Into Two Channels */
391     for(i=0; i<ctx->nfchans; i++) {
392         ctx->downmix_coeffs[i][0] = gain_levels[ac3_default_coeffs[ctx->acmod][i][0]];
393         ctx->downmix_coeffs[i][1] = gain_levels[ac3_default_coeffs[ctx->acmod][i][1]];
394     }
395     if(ctx->acmod > 1 && ctx->acmod & 1) {
396         ctx->downmix_coeffs[1][0] = ctx->downmix_coeffs[1][1] = cmixlev;
397     }
398     if(ctx->acmod == AC3_ACMOD_2F1R || ctx->acmod == AC3_ACMOD_3F1R) {
399         int nf = ctx->acmod - 2;
400         ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf][1] = surmixlev * LEVEL_MINUS_3DB;
401     }
402     if(ctx->acmod == AC3_ACMOD_2F2R || ctx->acmod == AC3_ACMOD_3F2R) {
403         int nf = ctx->acmod - 4;
404         ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf+1][1] = surmixlev;
405     }
406
407     return 0;
408 }
409
410 /**
411  * Decodes the grouped exponents.
412  * This function decodes the coded exponents according to exponent strategy
413  * and stores them in the decoded exponents buffer.
414  *
415  * @param[in]  gb      GetBitContext which points to start of coded exponents
416  * @param[in]  expstr  Exponent coding strategy
417  * @param[in]  ngrps   Number of grouped exponents
418  * @param[in]  absexp  Absolute exponent or DC exponent
419  * @param[out] dexps   Decoded exponents are stored in dexps
420  */
421 static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
422                              uint8_t absexp, int8_t *dexps)
423 {
424     int i, j, grp, grpsize;
425     int dexp[256];
426     int expacc, prevexp;
427
428     /* unpack groups */
429     grpsize = expstr + (expstr == EXP_D45);
430     for(grp=0,i=0; grp<ngrps; grp++) {
431         expacc = get_bits(gb, 7);
432         dexp[i++] = exp_ungroup_tbl[expacc][0];
433         dexp[i++] = exp_ungroup_tbl[expacc][1];
434         dexp[i++] = exp_ungroup_tbl[expacc][2];
435     }
436
437     /* convert to absolute exps and expand groups */
438     prevexp = absexp;
439     for(i=0; i<ngrps*3; i++) {
440         prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
441         for(j=0; j<grpsize; j++) {
442             dexps[(i*grpsize)+j] = prevexp;
443         }
444     }
445 }
446
447 /**
448  * Generates transform coefficients for each coupled channel in the coupling
449  * range using the coupling coefficients and coupling coordinates.
450  * reference: Section 7.4.3 Coupling Coordinate Format
451  */
452 static void uncouple_channels(AC3DecodeContext *ctx)
453 {
454     int i, j, ch, bnd, subbnd;
455
456     subbnd = -1;
457     i = ctx->startmant[CPL_CH];
458     for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
459         do {
460             subbnd++;
461             for(j=0; j<12; j++) {
462                 for(ch=1; ch<=ctx->nfchans; ch++) {
463                     if(ctx->chincpl[ch])
464                         ctx->transform_coeffs[ch][i] = ctx->transform_coeffs[CPL_CH][i] * ctx->cplco[ch][bnd] * 8.0f;
465                 }
466                 i++;
467             }
468         } while(ctx->cplbndstrc[subbnd]);
469     }
470 }
471
472 typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
473     float b1_mant[3];
474     float b2_mant[3];
475     float b4_mant[2];
476     int b1ptr;
477     int b2ptr;
478     int b4ptr;
479 } mant_groups;
480
481 /* Get the transform coefficients for particular channel */
482 static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
483 {
484     GetBitContext *gb = &ctx->gb;
485     int i, gcode, tbap, start, end;
486     uint8_t *exps;
487     uint8_t *bap;
488     float *coeffs;
489
490     exps = ctx->dexps[ch_index];
491     bap = ctx->bap[ch_index];
492     coeffs = ctx->transform_coeffs[ch_index];
493     start = ctx->startmant[ch_index];
494     end = ctx->endmant[ch_index];
495
496
497     for (i = start; i < end; i++) {
498         tbap = bap[i];
499         switch (tbap) {
500             case 0:
501                 coeffs[i] = ((av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB) / 32768.0f;
502                 break;
503
504             case 1:
505                 if(m->b1ptr > 2) {
506                     gcode = get_bits(gb, 5);
507                     m->b1_mant[0] = b1_mantissas[gcode][0];
508                     m->b1_mant[1] = b1_mantissas[gcode][1];
509                     m->b1_mant[2] = b1_mantissas[gcode][2];
510                     m->b1ptr = 0;
511                 }
512                 coeffs[i] = m->b1_mant[m->b1ptr++];
513                 break;
514
515             case 2:
516                 if(m->b2ptr > 2) {
517                     gcode = get_bits(gb, 7);
518                     m->b2_mant[0] = b2_mantissas[gcode][0];
519                     m->b2_mant[1] = b2_mantissas[gcode][1];
520                     m->b2_mant[2] = b2_mantissas[gcode][2];
521                     m->b2ptr = 0;
522                 }
523                 coeffs[i] = m->b2_mant[m->b2ptr++];
524                 break;
525
526             case 3:
527                 coeffs[i] = b3_mantissas[get_bits(gb, 3)];
528                 break;
529
530             case 4:
531                 if(m->b4ptr > 1) {
532                     gcode = get_bits(gb, 7);
533                     m->b4_mant[0] = b4_mantissas[gcode][0];
534                     m->b4_mant[1] = b4_mantissas[gcode][1];
535                     m->b4ptr = 0;
536                 }
537                 coeffs[i] = m->b4_mant[m->b4ptr++];
538                 break;
539
540             case 5:
541                 coeffs[i] = b5_mantissas[get_bits(gb, 4)];
542                 break;
543
544             default:
545                 coeffs[i] = get_sbits(gb, qntztab[tbap]) * scale_factors[qntztab[tbap]-1];
546                 break;
547         }
548         coeffs[i] *= scale_factors[exps[i]];
549     }
550
551     return 0;
552 }
553
554 /**
555  * Removes random dithering from coefficients with zero-bit mantissas
556  * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
557  */
558 static void remove_dithering(AC3DecodeContext *ctx) {
559     int ch, i;
560     int end=0;
561     float *coeffs;
562     uint8_t *bap;
563
564     for(ch=1; ch<=ctx->nfchans; ch++) {
565         if(!ctx->dithflag[ch]) {
566             coeffs = ctx->transform_coeffs[ch];
567             bap = ctx->bap[ch];
568             if(ctx->chincpl[ch])
569                 end = ctx->startmant[CPL_CH];
570             else
571                 end = ctx->endmant[ch];
572             for(i=0; i<end; i++) {
573                 if(bap[i] == 0)
574                     coeffs[i] = 0.0f;
575             }
576             if(ctx->chincpl[ch]) {
577                 bap = ctx->bap[CPL_CH];
578                 for(; i<ctx->endmant[CPL_CH]; i++) {
579                     if(bap[i] == 0)
580                         coeffs[i] = 0.0f;
581                 }
582             }
583         }
584     }
585 }
586
587 /* Get the transform coefficients.
588  * This function extracts the tranform coefficients form the ac3 bitstream.
589  * This function is called after bit allocation is performed.
590  */
591 static int get_transform_coeffs(AC3DecodeContext * ctx)
592 {
593     int ch, end;
594     int got_cplchan = 0;
595     mant_groups m;
596
597     m.b1ptr = m.b2ptr = m.b4ptr = 3;
598
599     for (ch = 1; ch <= ctx->nchans; ch++) {
600         /* transform coefficients for individual channel */
601         if (get_transform_coeffs_ch(ctx, ch, &m))
602             return -1;
603         /* tranform coefficients for coupling channels */
604         if (ctx->chincpl[ch])  {
605             if (!got_cplchan) {
606                 if (get_transform_coeffs_ch(ctx, CPL_CH, &m)) {
607                     av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
608                     return -1;
609                 }
610                 uncouple_channels(ctx);
611                 got_cplchan = 1;
612             }
613             end = ctx->endmant[CPL_CH];
614         } else {
615             end = ctx->endmant[ch];
616         }
617         do
618             ctx->transform_coeffs[ch][end] = 0;
619         while(++end < 256);
620     }
621
622     /* if any channel doesn't use dithering, zero appropriate coefficients */
623     if(!ctx->dither_all)
624         remove_dithering(ctx);
625
626     return 0;
627 }
628
629 /**
630  * Performs stereo rematrixing.
631  * reference: Section 7.5.4 Rematrixing : Decoding Technique
632  */
633 static void do_rematrixing(AC3DecodeContext *ctx)
634 {
635     int bnd, i;
636     int end, bndend;
637     float tmp0, tmp1;
638
639     end = FFMIN(ctx->endmant[1], ctx->endmant[2]);
640
641     for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
642         if(ctx->rematflg[bnd]) {
643             bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
644             for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
645                 tmp0 = ctx->transform_coeffs[1][i];
646                 tmp1 = ctx->transform_coeffs[2][i];
647                 ctx->transform_coeffs[1][i] = tmp0 + tmp1;
648                 ctx->transform_coeffs[2][i] = tmp0 - tmp1;
649             }
650         }
651     }
652 }
653
654 /* This function performs the imdct on 256 sample transform
655  * coefficients.
656  */
657 static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
658 {
659     int i, k;
660     DECLARE_ALIGNED_16(float, x[128]);
661     FFTComplex z[2][64];
662     float *o_ptr = ctx->tmp_output;
663
664     for(i=0; i<2; i++) {
665         /* de-interleave coefficients */
666         for(k=0; k<128; k++) {
667             x[k] = ctx->transform_coeffs[chindex][2*k+i];
668         }
669
670         /* run standard IMDCT */
671         ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
672
673         /* reverse the post-rotation & reordering from standard IMDCT */
674         for(k=0; k<32; k++) {
675             z[i][32+k].re = -o_ptr[128+2*k];
676             z[i][32+k].im = -o_ptr[2*k];
677             z[i][31-k].re =  o_ptr[2*k+1];
678             z[i][31-k].im =  o_ptr[128+2*k+1];
679         }
680     }
681
682     /* apply AC-3 post-rotation & reordering */
683     for(k=0; k<64; k++) {
684         o_ptr[    2*k  ] = -z[0][   k].im;
685         o_ptr[    2*k+1] =  z[0][63-k].re;
686         o_ptr[128+2*k  ] = -z[0][   k].re;
687         o_ptr[128+2*k+1] =  z[0][63-k].im;
688         o_ptr[256+2*k  ] = -z[1][   k].re;
689         o_ptr[256+2*k+1] =  z[1][63-k].im;
690         o_ptr[384+2*k  ] =  z[1][   k].im;
691         o_ptr[384+2*k+1] = -z[1][63-k].re;
692     }
693 }
694
695 /* IMDCT Transform. */
696 static inline void do_imdct(AC3DecodeContext *ctx)
697 {
698     int ch;
699     int nchans;
700
701     nchans = ctx->nfchans;
702     if(ctx->output_mode & AC3_OUTPUT_LFEON)
703         nchans++;
704
705     for (ch=1; ch<=nchans; ch++) {
706         if (ctx->blksw[ch]) {
707             do_imdct_256(ctx, ch);
708         } else {
709             ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
710                                           ctx->transform_coeffs[ch],
711                                           ctx->tmp_imdct);
712         }
713         ctx->dsp.vector_fmul_add_add(ctx->output[ch-1], ctx->tmp_output,
714                                      ctx->window, ctx->delay[ch-1], 0, 256, 1);
715         ctx->dsp.vector_fmul_reverse(ctx->delay[ch-1], ctx->tmp_output+256,
716                                      ctx->window, 256);
717     }
718 }
719
720 /**
721  * Downmixes the output to stereo.
722  */
723 static void ac3_downmix(float samples[AC3_MAX_CHANNELS][256], int nfchans,
724                         int output_mode, float coef[AC3_MAX_CHANNELS][2])
725 {
726     int i, j;
727     float v0, v1, s0, s1;
728
729     for(i=0; i<256; i++) {
730         v0 = v1 = s0 = s1 = 0.0f;
731         for(j=0; j<nfchans; j++) {
732             v0 += samples[j][i] * coef[j][0];
733             v1 += samples[j][i] * coef[j][1];
734             s0 += coef[j][0];
735             s1 += coef[j][1];
736         }
737         v0 /= s0;
738         v1 /= s1;
739         if(output_mode == AC3_ACMOD_MONO) {
740             samples[0][i] = (v0 + v1) * LEVEL_MINUS_3DB;
741         } else if(output_mode == AC3_ACMOD_STEREO) {
742             samples[0][i] = v0;
743             samples[1][i] = v1;
744         }
745     }
746 }
747
748 /* Parse the audio block from ac3 bitstream.
749  * This function extract the audio block from the ac3 bitstream
750  * and produces the output for the block. This function must
751  * be called for each of the six audio block in the ac3 bitstream.
752  */
753 static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
754 {
755     int nfchans = ctx->nfchans;
756     int acmod = ctx->acmod;
757     int i, bnd, seg, ch;
758     GetBitContext *gb = &ctx->gb;
759     uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
760
761     memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
762
763     for (ch = 1; ch <= nfchans; ch++) /*block switch flag */
764         ctx->blksw[ch] = get_bits1(gb);
765
766     ctx->dither_all = 1;
767     for (ch = 1; ch <= nfchans; ch++) { /* dithering flag */
768         ctx->dithflag[ch] = get_bits1(gb);
769         if(!ctx->dithflag[ch])
770             ctx->dither_all = 0;
771     }
772
773     if (get_bits1(gb)) { /* dynamic range */
774         ctx->dynrng = dynrng_tbl[get_bits(gb, 8)];
775     } else if(blk == 0) {
776         ctx->dynrng = 1.0;
777     }
778
779     if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
780         if(get_bits1(gb)) {
781             ctx->dynrng2 = dynrng_tbl[get_bits(gb, 8)];
782         } else if(blk == 0) {
783             ctx->dynrng2 = 1.0;
784         }
785     }
786
787     if (get_bits1(gb)) { /* coupling strategy */
788         memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
789         ctx->cplinu = get_bits1(gb);
790         if (ctx->cplinu) { /* coupling in use */
791             int cplbegf, cplendf;
792
793             for (ch = 1; ch <= nfchans; ch++)
794                 ctx->chincpl[ch] = get_bits1(gb);
795
796             if (acmod == AC3_ACMOD_STEREO)
797                 ctx->phsflginu = get_bits1(gb); //phase flag in use
798
799             cplbegf = get_bits(gb, 4);
800             cplendf = get_bits(gb, 4);
801
802             if (3 + cplendf - cplbegf < 0) {
803                 av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
804                 return -1;
805             }
806
807             ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
808             ctx->startmant[CPL_CH] = cplbegf * 12 + 37;
809             ctx->endmant[CPL_CH] = cplendf * 12 + 73;
810             for (bnd = 0; bnd < ctx->ncplsubnd - 1; bnd++) { /* coupling band structure */
811                 if (get_bits1(gb)) {
812                     ctx->cplbndstrc[bnd] = 1;
813                     ctx->ncplbnd--;
814                 }
815             }
816         } else {
817             for (ch = 1; ch <= nfchans; ch++)
818                 ctx->chincpl[ch] = 0;
819         }
820     }
821
822     if (ctx->cplinu) {
823         int cplcoe = 0;
824
825         for (ch = 1; ch <= nfchans; ch++) {
826             if (ctx->chincpl[ch]) {
827                 if (get_bits1(gb)) { /* coupling co-ordinates */
828                     int mstrcplco, cplcoexp, cplcomant;
829                     cplcoe = 1;
830                     mstrcplco = 3 * get_bits(gb, 2);
831                     for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
832                         cplcoexp = get_bits(gb, 4);
833                         cplcomant = get_bits(gb, 4);
834                         if (cplcoexp == 15)
835                             ctx->cplco[ch][bnd] = cplcomant / 16.0f;
836                         else
837                             ctx->cplco[ch][bnd] = (cplcomant + 16.0f) / 32.0f;
838                         ctx->cplco[ch][bnd] *= scale_factors[cplcoexp + mstrcplco];
839                     }
840                 }
841             }
842         }
843
844         if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && cplcoe) {
845             for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
846                 if (get_bits1(gb))
847                     ctx->cplco[2][bnd] = -ctx->cplco[2][bnd];
848             }
849         }
850     }
851
852     if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
853         ctx->rematstr = get_bits1(gb);
854         if (ctx->rematstr) {
855             ctx->nrematbnd = 4;
856             if(ctx->cplinu && ctx->startmant[CPL_CH] <= 61)
857                 ctx->nrematbnd -= 1 + (ctx->startmant[CPL_CH] == 37);
858             for(bnd=0; bnd<ctx->nrematbnd; bnd++)
859                 ctx->rematflg[bnd] = get_bits1(gb);
860         }
861     }
862
863     ctx->expstr[CPL_CH] = EXP_REUSE;
864     ctx->expstr[ctx->lfe_ch] = EXP_REUSE;
865     for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
866         if(ch == ctx->lfe_ch)
867             ctx->expstr[ch] = get_bits(gb, 1);
868         else
869             ctx->expstr[ch] = get_bits(gb, 2);
870         if(ctx->expstr[ch] != EXP_REUSE)
871             bit_alloc_stages[ch] = 3;
872     }
873
874     for (ch = 1; ch <= nfchans; ch++) { /* channel bandwidth code */
875         ctx->startmant[ch] = 0;
876         if (ctx->expstr[ch] != EXP_REUSE) {
877             int prev = ctx->endmant[ch];
878             if (ctx->chincpl[ch])
879                 ctx->endmant[ch] = ctx->startmant[CPL_CH];
880             else {
881                 int chbwcod = get_bits(gb, 6);
882                 if (chbwcod > 60) {
883                     av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
884                     return -1;
885                 }
886                 ctx->endmant[ch] = chbwcod * 3 + 73;
887             }
888             if(blk > 0 && ctx->endmant[ch] != prev)
889                 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
890         }
891     }
892     ctx->startmant[ctx->lfe_ch] = 0;
893     ctx->endmant[ctx->lfe_ch] = 7;
894
895     for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
896         if (ctx->expstr[ch] != EXP_REUSE) {
897             int grpsize, ngrps;
898             grpsize = 3 << (ctx->expstr[ch] - 1);
899             if(ch == CPL_CH)
900                 ngrps = (ctx->endmant[ch] - ctx->startmant[ch]) / grpsize;
901             else if(ch == ctx->lfe_ch)
902                 ngrps = 2;
903             else
904                 ngrps = (ctx->endmant[ch] + grpsize - 4) / grpsize;
905             ctx->dexps[ch][0] = get_bits(gb, 4) << !ch;
906             decode_exponents(gb, ctx->expstr[ch], ngrps, ctx->dexps[ch][0],
907                              &ctx->dexps[ch][ctx->startmant[ch]+!!ch]);
908             if(ch != CPL_CH && ch != ctx->lfe_ch)
909                 skip_bits(gb, 2); /* skip gainrng */
910         }
911     }
912
913     if (get_bits1(gb)) { /* bit allocation information */
914         ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
915         ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
916         ctx->bit_alloc_params.sgain  = ff_sgaintab[get_bits(gb, 2)];
917         ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
918         ctx->bit_alloc_params.floor  = ff_floortab[get_bits(gb, 3)];
919         for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
920             bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
921         }
922     }
923
924     if (get_bits1(gb)) { /* snroffset */
925         int csnr;
926         csnr = (get_bits(gb, 6) - 15) << 4;
927         for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) { /* snr offset and fast gain */
928             ctx->snroffst[ch] = (csnr + get_bits(gb, 4)) << 2;
929             ctx->fgain[ch] = ff_fgaintab[get_bits(gb, 3)];
930         }
931         memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
932     }
933
934     if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
935         ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
936         ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
937         bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
938     }
939
940     if (get_bits1(gb)) { /* delta bit allocation information */
941         for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
942             ctx->deltbae[ch] = get_bits(gb, 2);
943             if (ctx->deltbae[ch] == DBA_RESERVED) {
944                 av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
945                 return -1;
946             }
947             bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
948         }
949
950         for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
951             if (ctx->deltbae[ch] == DBA_NEW) {/*channel delta offset, len and bit allocation */
952                 ctx->deltnseg[ch] = get_bits(gb, 3);
953                 for (seg = 0; seg <= ctx->deltnseg[ch]; seg++) {
954                     ctx->deltoffst[ch][seg] = get_bits(gb, 5);
955                     ctx->deltlen[ch][seg] = get_bits(gb, 4);
956                     ctx->deltba[ch][seg] = get_bits(gb, 3);
957                 }
958             }
959         }
960     } else if(blk == 0) {
961         for(ch=0; ch<=ctx->nchans; ch++) {
962             ctx->deltbae[ch] = DBA_NONE;
963         }
964     }
965
966     for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
967         if(bit_alloc_stages[ch] > 2) {
968             /* Exponent mapping into PSD and PSD integration */
969             ff_ac3_bit_alloc_calc_psd(ctx->dexps[ch],
970                                       ctx->startmant[ch], ctx->endmant[ch],
971                                       ctx->psd[ch], ctx->bndpsd[ch]);
972         }
973         if(bit_alloc_stages[ch] > 1) {
974             /* Compute excitation function, Compute masking curve, and
975                Apply delta bit allocation */
976             ff_ac3_bit_alloc_calc_mask(&ctx->bit_alloc_params, ctx->bndpsd[ch],
977                                        ctx->startmant[ch], ctx->endmant[ch],
978                                        ctx->fgain[ch], (ch == ctx->lfe_ch),
979                                        ctx->deltbae[ch], ctx->deltnseg[ch],
980                                        ctx->deltoffst[ch], ctx->deltlen[ch],
981                                        ctx->deltba[ch], ctx->mask[ch]);
982         }
983         if(bit_alloc_stages[ch] > 0) {
984             /* Compute bit allocation */
985             ff_ac3_bit_alloc_calc_bap(ctx->mask[ch], ctx->psd[ch],
986                                       ctx->startmant[ch], ctx->endmant[ch],
987                                       ctx->snroffst[ch],
988                                       ctx->bit_alloc_params.floor,
989                                       ctx->bap[ch]);
990         }
991     }
992
993     if (get_bits1(gb)) { /* unused dummy data */
994         int skipl = get_bits(gb, 9);
995         while(skipl--)
996             skip_bits(gb, 8);
997     }
998     /* unpack the transform coefficients
999      * * this also uncouples channels if coupling is in use.
1000      */
1001     if (get_transform_coeffs(ctx)) {
1002         av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
1003         return -1;
1004     }
1005
1006     /* recover coefficients if rematrixing is in use */
1007     if(ctx->acmod == AC3_ACMOD_STEREO)
1008         do_rematrixing(ctx);
1009
1010     /* apply scaling to coefficients (headroom, dynrng) */
1011     for(ch=1; ch<=ctx->nchans; ch++) {
1012         float gain = 2.0f * ctx->mul_bias;
1013         if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
1014             gain *= ctx->dynrng2;
1015         } else {
1016             gain *= ctx->dynrng;
1017         }
1018         for(i=0; i<ctx->endmant[ch]; i++) {
1019             ctx->transform_coeffs[ch][i] *= gain;
1020         }
1021     }
1022
1023     do_imdct(ctx);
1024
1025     /* downmix output if needed */
1026     if(ctx->nchans != ctx->out_channels && !((ctx->output_mode & AC3_OUTPUT_LFEON) &&
1027             ctx->nfchans == ctx->out_channels)) {
1028         ac3_downmix(ctx->output, ctx->nfchans, ctx->output_mode,
1029                     ctx->downmix_coeffs);
1030     }
1031
1032     /* convert float to 16-bit integer */
1033     for(ch=0; ch<ctx->out_channels; ch++) {
1034         for(i=0; i<256; i++) {
1035             ctx->output[ch][i] += ctx->add_bias;
1036         }
1037         ctx->dsp.float_to_int16(ctx->int_output[ch], ctx->output[ch], 256);
1038     }
1039
1040     return 0;
1041 }
1042
1043 /* Decode ac3 frame.
1044  *
1045  * @param avctx Pointer to AVCodecContext
1046  * @param data Pointer to pcm smaples
1047  * @param data_size Set to number of pcm samples produced by decoding
1048  * @param buf Data to be decoded
1049  * @param buf_size Size of the buffer
1050  */
1051 static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1052 {
1053     AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1054     int16_t *out_samples = (int16_t *)data;
1055     int i, blk, ch;
1056
1057     //Initialize the GetBitContext with the start of valid AC3 Frame.
1058     init_get_bits(&ctx->gb, buf, buf_size * 8);
1059
1060     //Parse the syncinfo.
1061     if (ac3_parse_header(ctx)) {
1062         av_log(avctx, AV_LOG_ERROR, "\n");
1063         *data_size = 0;
1064         return buf_size;
1065     }
1066
1067     avctx->sample_rate = ctx->sampling_rate;
1068     avctx->bit_rate = ctx->bit_rate;
1069
1070     /* channel config */
1071     ctx->out_channels = ctx->nchans;
1072     if (avctx->channels == 0) {
1073         avctx->channels = ctx->out_channels;
1074     } else if(ctx->out_channels < avctx->channels) {
1075         av_log(avctx, AV_LOG_ERROR, "Cannot upmix AC3 from %d to %d channels.\n",
1076                ctx->out_channels, avctx->channels);
1077         return -1;
1078     }
1079     if(avctx->channels == 2) {
1080         ctx->output_mode = AC3_ACMOD_STEREO;
1081     } else if(avctx->channels == 1) {
1082         ctx->output_mode = AC3_ACMOD_MONO;
1083     } else if(avctx->channels != ctx->out_channels) {
1084         av_log(avctx, AV_LOG_ERROR, "Cannot downmix AC3 from %d to %d channels.\n",
1085                ctx->out_channels, avctx->channels);
1086         return -1;
1087     }
1088     ctx->out_channels = avctx->channels;
1089
1090     //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);
1091
1092     //Parse the Audio Blocks.
1093     for (blk = 0; blk < NB_BLOCKS; blk++) {
1094         if (ac3_parse_audio_block(ctx, blk)) {
1095             av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1096             *data_size = 0;
1097             return ctx->frame_size;
1098         }
1099         for (i = 0; i < 256; i++)
1100             for (ch = 0; ch < ctx->out_channels; ch++)
1101                 *(out_samples++) = ctx->int_output[ch][i];
1102     }
1103     *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
1104     return ctx->frame_size;
1105 }
1106
1107 /* Uninitialize ac3 decoder.
1108  */
1109 static int ac3_decode_end(AVCodecContext *avctx)
1110 {
1111     AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1112     ff_mdct_end(&ctx->imdct_512);
1113     ff_mdct_end(&ctx->imdct_256);
1114
1115     return 0;
1116 }
1117
1118 AVCodec ac3_decoder = {
1119     .name = "ac3",
1120     .type = CODEC_TYPE_AUDIO,
1121     .id = CODEC_ID_AC3,
1122     .priv_data_size = sizeof (AC3DecodeContext),
1123     .init = ac3_decode_init,
1124     .close = ac3_decode_end,
1125     .decode = ac3_decode_frame,
1126 };
1127