]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3dec.c
0571b007dc724b50f3d2ab646bc2d88413daf7dc
[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_PLUS_3DB          1.4142135623730951
80 #define LEVEL_PLUS_6DB          2.0000000000000000
81 #define LEVEL_ZERO              0.0000000000000000
82
83 static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
84     LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
85
86 static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
87
88 #define AC3_OUTPUT_LFEON  8
89
90 typedef struct {
91     int acmod;
92     int cmixlev;
93     int surmixlev;
94     int dsurmod;
95
96     int blksw[AC3_MAX_CHANNELS];
97     int dithflag[AC3_MAX_CHANNELS];
98     int dither_all;
99     int cplinu;
100     int chincpl[AC3_MAX_CHANNELS];
101     int phsflginu;
102     int cplcoe;
103     uint32_t cplbndstrc;
104     int rematstr;
105     int nrematbnd;
106     int rematflg[AC3_MAX_CHANNELS];
107     int cplexpstr;
108     int lfeexpstr;
109     int chexpstr[5];
110     int cplsnroffst;
111     int cplfgain;
112     int snroffst[5];
113     int fgain[5];
114     int lfesnroffst;
115     int lfefgain;
116     int cpldeltbae;
117     int deltbae[5];
118     int cpldeltnseg;
119     uint8_t  cpldeltoffst[8];
120     uint8_t  cpldeltlen[8];
121     uint8_t  cpldeltba[8];
122     int deltnseg[5];
123     uint8_t  deltoffst[5][8];
124     uint8_t  deltlen[5][8];
125     uint8_t  deltba[5][8];
126
127     /* Derived Attributes. */
128     int      sampling_rate;
129     int      bit_rate;
130     int      frame_size;
131
132     int      nchans;            //number of total channels
133     int      nfchans;           //number of full-bandwidth channels
134     int      lfeon;             //lfe channel in use
135     int      output_mode;       ///< output channel configuration
136     int      out_channels;      ///< number of output channels
137
138     float    dynrng;            //dynamic range gain
139     float    dynrng2;           //dynamic range gain for 1+1 mode
140     float    cplco[5][18];      //coupling coordinates
141     int      ncplbnd;           //number of coupling bands
142     int      ncplsubnd;         //number of coupling sub bands
143     int      cplstrtmant;       //coupling start mantissa
144     int      cplendmant;        //coupling end mantissa
145     int      endmant[5];        //channel end mantissas
146     AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
147
148     int8_t   dcplexps[256];     //decoded coupling exponents
149     int8_t   dexps[5][256];     //decoded fbw channel exponents
150     int8_t   dlfeexps[256];     //decoded lfe channel exponents
151     uint8_t  cplbap[256];       //coupling bit allocation pointers
152     uint8_t  bap[5][256];       //fbw channel bit allocation pointers
153     uint8_t  lfebap[256];       //lfe channel bit allocation pointers
154
155     float transform_coeffs_cpl[256];
156     DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]);  //transform coefficients
157
158     /* For IMDCT. */
159     MDCTContext imdct_512;  //for 512 sample imdct transform
160     MDCTContext imdct_256;  //for 256 sample imdct transform
161     DSPContext  dsp;        //for optimization
162
163     DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS][256]);   //output after imdct transform and windowing
164     DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS][256]);    //delay - added to the next block
165     DECLARE_ALIGNED_16(float, tmp_imdct[256]);                  //temporary storage for imdct transform
166     DECLARE_ALIGNED_16(float, tmp_output[512]);                 //temporary storage for output before windowing
167     DECLARE_ALIGNED_16(float, window[256]);                     //window coefficients
168
169     /* Miscellaneous. */
170     GetBitContext gb;
171     AVRandomState dith_state;   //for dither generation
172 } AC3DecodeContext;
173
174 /*********** BEGIN INIT HELPER FUNCTIONS ***********/
175 /**
176  * Generate a Kaiser-Bessel Derived Window.
177  */
178 static void ac3_window_init(float *window)
179 {
180    int i, j;
181    double sum = 0.0, bessel, tmp;
182    double local_window[256];
183    double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
184
185    for (i = 0; i < 256; i++) {
186        tmp = i * (256 - i) * alpha2;
187        bessel = 1.0;
188        for (j = 100; j > 0; j--) /* defaul to 100 iterations */
189            bessel = bessel * tmp / (j * j) + 1;
190        sum += bessel;
191        local_window[i] = sum;
192    }
193
194    sum++;
195    for (i = 0; i < 256; i++)
196        window[i] = sqrt(local_window[i] / sum);
197 }
198
199 static inline float
200 symmetric_dequant(int code, int levels)
201 {
202     return (code - (levels >> 1)) * (2.0f / levels);
203 }
204
205 /*
206  * Initialize tables at runtime.
207  */
208 static void ac3_tables_init(void)
209 {
210     int i;
211
212     /* generate grouped mantissa tables
213        reference: Section 7.3.5 Ungrouping of Mantissas */
214     for(i=0; i<32; i++) {
215         /* bap=1 mantissas */
216         b1_mantissas[i][0] = symmetric_dequant( i / 9     , 3);
217         b1_mantissas[i][1] = symmetric_dequant((i % 9) / 3, 3);
218         b1_mantissas[i][2] = symmetric_dequant((i % 9) % 3, 3);
219     }
220     for(i=0; i<128; i++) {
221         /* bap=2 mantissas */
222         b2_mantissas[i][0] = symmetric_dequant( i / 25     , 5);
223         b2_mantissas[i][1] = symmetric_dequant((i % 25) / 5, 5);
224         b2_mantissas[i][2] = symmetric_dequant((i % 25) % 5, 5);
225
226         /* bap=4 mantissas */
227         b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
228         b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
229     }
230     /* generate ungrouped mantissa tables
231        reference: Tables 7.21 and 7.23 */
232     for(i=0; i<7; i++) {
233         /* bap=3 mantissas */
234         b3_mantissas[i] = symmetric_dequant(i, 7);
235     }
236     for(i=0; i<15; i++) {
237         /* bap=5 mantissas */
238         b5_mantissas[i] = symmetric_dequant(i, 15);
239     }
240
241     /* generate dynamic range table
242        reference: Section 7.7.1 Dynamic Range Control */
243     for(i=0; i<256; i++) {
244         int v = (i >> 5) - ((i >> 7) << 3) - 5;
245         dynrng_tbl[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
246     }
247
248     //generate scale factors
249     for (i = 0; i < 25; i++)
250         scale_factors[i] = pow(2.0, -i);
251
252     /* generate exponent tables
253        reference: Section 7.1.3 Exponent Decoding */
254     for(i=0; i<128; i++) {
255         exp_ungroup_tbl[i][0] =  i / 25;
256         exp_ungroup_tbl[i][1] = (i % 25) / 5;
257         exp_ungroup_tbl[i][2] = (i % 25) % 5;
258     }
259 }
260
261
262 static int ac3_decode_init(AVCodecContext *avctx)
263 {
264     AC3DecodeContext *ctx = avctx->priv_data;
265
266     ac3_common_init();
267     ac3_tables_init();
268     ff_mdct_init(&ctx->imdct_256, 8, 1);
269     ff_mdct_init(&ctx->imdct_512, 9, 1);
270     ac3_window_init(ctx->window);
271     dsputil_init(&ctx->dsp, avctx);
272     av_init_random(0, &ctx->dith_state);
273
274     return 0;
275 }
276 /*********** END INIT FUNCTIONS ***********/
277
278 /**
279  * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
280  * GetBitContext within AC3DecodeContext must point to
281  * start of the synchronized ac3 bitstream.
282  */
283 static int ac3_parse_header(AC3DecodeContext *ctx)
284 {
285     AC3HeaderInfo hdr;
286     GetBitContext *gb = &ctx->gb;
287     int err, i;
288
289     err = ff_ac3_parse_header(gb->buffer, &hdr);
290     if(err)
291         return err;
292
293     /* get decoding parameters from header info */
294     ctx->bit_alloc_params.fscod       = hdr.fscod;
295     ctx->acmod                        = hdr.acmod;
296     ctx->cmixlev                      = hdr.cmixlev;
297     ctx->surmixlev                    = hdr.surmixlev;
298     ctx->dsurmod                      = hdr.dsurmod;
299     ctx->lfeon                        = hdr.lfeon;
300     ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
301     ctx->sampling_rate                = hdr.sample_rate;
302     ctx->bit_rate                     = hdr.bit_rate;
303     ctx->nchans                       = hdr.channels;
304     ctx->nfchans                      = ctx->nchans - ctx->lfeon;
305     ctx->frame_size                   = hdr.frame_size;
306
307     /* set default output to all source channels */
308     ctx->out_channels = ctx->nchans;
309     ctx->output_mode = ctx->acmod;
310     if(ctx->lfeon)
311         ctx->output_mode |= AC3_OUTPUT_LFEON;
312
313     /* skip over portion of header which has already been read */
314     skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
315     skip_bits(gb, 16); // skip crc1
316     skip_bits(gb, 8);  // skip fscod and frmsizecod
317     skip_bits(gb, 11); // skip bsid, bsmod, and acmod
318     if(ctx->acmod == AC3_ACMOD_STEREO) {
319         skip_bits(gb, 2); // skip dsurmod
320     } else {
321         if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
322             skip_bits(gb, 2); // skip cmixlev
323         if(ctx->acmod & 4)
324             skip_bits(gb, 2); // skip surmixlev
325     }
326     skip_bits1(gb); // skip lfeon
327
328     /* read the rest of the bsi. read twice for dual mono mode. */
329     i = !(ctx->acmod);
330     do {
331         skip_bits(gb, 5); //skip dialog normalization
332         if (get_bits1(gb))
333             skip_bits(gb, 8); //skip compression
334         if (get_bits1(gb))
335             skip_bits(gb, 8); //skip language code
336         if (get_bits1(gb))
337             skip_bits(gb, 7); //skip audio production information
338     } while (i--);
339
340     skip_bits(gb, 2); //skip copyright bit and original bitstream bit
341
342     /* FIXME: read & use the xbsi1 downmix levels */
343     if (get_bits1(gb))
344         skip_bits(gb, 14); //skip timecode1
345     if (get_bits1(gb))
346         skip_bits(gb, 14); //skip timecode2
347
348     if (get_bits1(gb)) {
349         i = get_bits(gb, 6); //additional bsi length
350         do {
351             skip_bits(gb, 8);
352         } while(i--);
353     }
354
355     return 0;
356 }
357
358 /**
359  * Decodes the grouped exponents.
360  * This function decodes the coded exponents according to exponent strategy
361  * and stores them in the decoded exponents buffer.
362  *
363  * @param[in]  gb      GetBitContext which points to start of coded exponents
364  * @param[in]  expstr  Exponent coding strategy
365  * @param[in]  ngrps   Number of grouped exponents
366  * @param[in]  absexp  Absolute exponent or DC exponent
367  * @param[out] dexps   Decoded exponents are stored in dexps
368  */
369 static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
370                              uint8_t absexp, int8_t *dexps)
371 {
372     int i, j, grp, grpsize;
373     int dexp[256];
374     int expacc, prevexp;
375
376     /* unpack groups */
377     grpsize = expstr + (expstr == EXP_D45);
378     for(grp=0,i=0; grp<ngrps; grp++) {
379         expacc = get_bits(gb, 7);
380         dexp[i++] = exp_ungroup_tbl[expacc][0];
381         dexp[i++] = exp_ungroup_tbl[expacc][1];
382         dexp[i++] = exp_ungroup_tbl[expacc][2];
383     }
384
385     /* convert to absolute exps and expand groups */
386     prevexp = absexp;
387     for(i=0; i<ngrps*3; i++) {
388         prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
389         for(j=0; j<grpsize; j++) {
390             dexps[(i*grpsize)+j] = prevexp;
391         }
392     }
393 }
394
395 /**
396  * Generates transform coefficients for each coupled channel in the coupling
397  * range using the coupling coefficients and coupling coordinates.
398  * reference: Section 7.4.3 Coupling Coordinate Format
399  */
400 static void uncouple_channels(AC3DecodeContext *ctx)
401 {
402     int i, j, ch, bnd, subbnd;
403
404     subbnd = -1;
405     i = ctx->cplstrtmant;
406     for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
407         do {
408             subbnd++;
409             for(j=0; j<12; j++) {
410                 for(ch=1; ch<=ctx->nfchans; ch++) {
411                     if(ctx->chincpl[ch-1])
412                         ctx->transform_coeffs[ch][i] = ctx->transform_coeffs_cpl[i] * ctx->cplco[ch-1][bnd] * 8.0f;
413                 }
414                 i++;
415             }
416         } while((ctx->cplbndstrc >> subbnd) & 1);
417     }
418 }
419
420 typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
421     float b1_mant[3];
422     float b2_mant[3];
423     float b4_mant[2];
424     int b1ptr;
425     int b2ptr;
426     int b4ptr;
427 } mant_groups;
428
429 /* Get the transform coefficients for particular channel */
430 static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
431 {
432     GetBitContext *gb = &ctx->gb;
433     int i, gcode, tbap, start, end;
434     uint8_t *exps;
435     uint8_t *bap;
436     float *coeffs;
437
438     if (ch_index >= 0) { /* fbw channels */
439         exps = ctx->dexps[ch_index];
440         bap = ctx->bap[ch_index];
441         coeffs = ctx->transform_coeffs[ch_index + 1];
442         start = 0;
443         end = ctx->endmant[ch_index];
444     } else if (ch_index == -1) {
445         exps = ctx->dlfeexps;
446         bap = ctx->lfebap;
447         coeffs = ctx->transform_coeffs[0];
448         start = 0;
449         end = 7;
450     } else {
451         exps = ctx->dcplexps;
452         bap = ctx->cplbap;
453         coeffs = ctx->transform_coeffs_cpl;
454         start = ctx->cplstrtmant;
455         end = ctx->cplendmant;
456     }
457
458
459     for (i = start; i < end; i++) {
460         tbap = bap[i];
461         switch (tbap) {
462             case 0:
463                 coeffs[i] = ((av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB) / 32768.0f;
464                 break;
465
466             case 1:
467                 if(m->b1ptr > 2) {
468                     gcode = get_bits(gb, 5);
469                     m->b1_mant[0] = b1_mantissas[gcode][0];
470                     m->b1_mant[1] = b1_mantissas[gcode][1];
471                     m->b1_mant[2] = b1_mantissas[gcode][2];
472                     m->b1ptr = 0;
473                 }
474                 coeffs[i] = m->b1_mant[m->b1ptr++];
475                 break;
476
477             case 2:
478                 if(m->b2ptr > 2) {
479                     gcode = get_bits(gb, 7);
480                     m->b2_mant[0] = b2_mantissas[gcode][0];
481                     m->b2_mant[1] = b2_mantissas[gcode][1];
482                     m->b2_mant[2] = b2_mantissas[gcode][2];
483                     m->b2ptr = 0;
484                 }
485                 coeffs[i] = m->b2_mant[m->b2ptr++];
486                 break;
487
488             case 3:
489                 coeffs[i] = b3_mantissas[get_bits(gb, 3)];
490                 break;
491
492             case 4:
493                 if(m->b4ptr > 1) {
494                     gcode = get_bits(gb, 7);
495                     m->b4_mant[0] = b4_mantissas[gcode][0];
496                     m->b4_mant[1] = b4_mantissas[gcode][1];
497                     m->b4ptr = 0;
498                 }
499                 coeffs[i] = m->b4_mant[m->b4ptr++];
500                 break;
501
502             case 5:
503                 coeffs[i] = b5_mantissas[get_bits(gb, 4)];
504                 break;
505
506             default:
507                 coeffs[i] = get_sbits(gb, qntztab[tbap]) * scale_factors[qntztab[tbap]-1];
508                 break;
509         }
510         coeffs[i] *= scale_factors[exps[i]];
511     }
512
513     return 0;
514 }
515
516 /**
517  * Removes random dithering from coefficients with zero-bit mantissas
518  * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
519  */
520 static void remove_dithering(AC3DecodeContext *ctx) {
521     int ch, i;
522     int end=0;
523     float *coeffs;
524     uint8_t *bap;
525
526     for(ch=1; ch<=ctx->nfchans; ch++) {
527         if(!ctx->dithflag[ch-1]) {
528             coeffs = ctx->transform_coeffs[ch];
529             bap = ctx->bap[ch-1];
530             if(ctx->chincpl[ch-1])
531                 end = ctx->cplstrtmant;
532             else
533                 end = ctx->endmant[ch-1];
534             for(i=0; i<end; i++) {
535                 if(bap[i] == 0)
536                     coeffs[i] = 0.0f;
537             }
538             if(ctx->chincpl[ch-1]) {
539                 bap = ctx->cplbap;
540                 for(; i<ctx->cplendmant; i++) {
541                     if(bap[i] == 0)
542                         coeffs[i] = 0.0f;
543                 }
544             }
545         }
546     }
547 }
548
549 /* Get the transform coefficients.
550  * This function extracts the tranform coefficients form the ac3 bitstream.
551  * This function is called after bit allocation is performed.
552  */
553 static int get_transform_coeffs(AC3DecodeContext * ctx)
554 {
555     int i, end;
556     int got_cplchan = 0;
557     mant_groups m;
558
559     m.b1ptr = m.b2ptr = m.b4ptr = 3;
560
561     for (i = 0; i < ctx->nfchans; i++) {
562         /* transform coefficients for individual channel */
563         if (get_transform_coeffs_ch(ctx, i, &m))
564             return -1;
565         /* tranform coefficients for coupling channels */
566         if (ctx->chincpl[i])  {
567             if (!got_cplchan) {
568                 if (get_transform_coeffs_ch(ctx, -2, &m)) {
569                     av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
570                     return -1;
571                 }
572                 uncouple_channels(ctx);
573                 got_cplchan = 1;
574             }
575             end = ctx->cplendmant;
576         } else
577             end = ctx->endmant[i];
578         do
579             ctx->transform_coeffs[i + 1][end] = 0;
580         while(++end < 256);
581     }
582     if (ctx->lfeon) {
583         if (get_transform_coeffs_ch(ctx, -1, &m))
584                 return -1;
585         for (i = 7; i < 256; i++) {
586             ctx->transform_coeffs[0][i] = 0;
587         }
588     }
589
590     /* if any channel doesn't use dithering, zero appropriate coefficients */
591     if(!ctx->dither_all)
592         remove_dithering(ctx);
593
594     return 0;
595 }
596
597 /**
598  * Performs stereo rematrixing.
599  * reference: Section 7.5.4 Rematrixing : Decoding Technique
600  */
601 static void do_rematrixing(AC3DecodeContext *ctx)
602 {
603     int bnd, i;
604     int end, bndend;
605     float tmp0, tmp1;
606
607     end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
608
609     for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
610         if(ctx->rematflg[bnd]) {
611             bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
612             for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
613                 tmp0 = ctx->transform_coeffs[1][i];
614                 tmp1 = ctx->transform_coeffs[2][i];
615                 ctx->transform_coeffs[1][i] = tmp0 + tmp1;
616                 ctx->transform_coeffs[2][i] = tmp0 - tmp1;
617             }
618         }
619     }
620 }
621
622 /* This function performs the imdct on 256 sample transform
623  * coefficients.
624  */
625 static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
626 {
627     int i, k;
628     DECLARE_ALIGNED_16(float, x[128]);
629     FFTComplex z[2][64];
630     float *o_ptr = ctx->tmp_output;
631
632     for(i=0; i<2; i++) {
633         /* de-interleave coefficients */
634         for(k=0; k<128; k++) {
635             x[k] = ctx->transform_coeffs[chindex][2*k+i];
636         }
637
638         /* run standard IMDCT */
639         ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
640
641         /* reverse the post-rotation & reordering from standard IMDCT */
642         for(k=0; k<32; k++) {
643             z[i][32+k].re = -o_ptr[128+2*k];
644             z[i][32+k].im = -o_ptr[2*k];
645             z[i][31-k].re =  o_ptr[2*k+1];
646             z[i][31-k].im =  o_ptr[128+2*k+1];
647         }
648     }
649
650     /* apply AC-3 post-rotation & reordering */
651     for(k=0; k<64; k++) {
652         o_ptr[    2*k  ] = -z[0][   k].im;
653         o_ptr[    2*k+1] =  z[0][63-k].re;
654         o_ptr[128+2*k  ] = -z[0][   k].re;
655         o_ptr[128+2*k+1] =  z[0][63-k].im;
656         o_ptr[256+2*k  ] = -z[1][   k].re;
657         o_ptr[256+2*k+1] =  z[1][63-k].im;
658         o_ptr[384+2*k  ] =  z[1][   k].im;
659         o_ptr[384+2*k+1] = -z[1][63-k].re;
660     }
661 }
662
663 /* IMDCT Transform. */
664 static inline void do_imdct(AC3DecodeContext *ctx)
665 {
666     int ch;
667
668     if (ctx->output_mode & AC3_OUTPUT_LFEON) {
669         ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
670                                       ctx->transform_coeffs[0], ctx->tmp_imdct);
671         ctx->dsp.vector_fmul_add_add(ctx->output[0], ctx->tmp_output,
672                                      ctx->window, ctx->delay[0], 384, 256, 1);
673         ctx->dsp.vector_fmul_reverse(ctx->delay[0], ctx->tmp_output+256,
674                                      ctx->window, 256);
675     }
676     for (ch=1; ch<=ctx->nfchans; ch++) {
677         if (ctx->blksw[ch-1])
678             do_imdct_256(ctx, ch);
679         else
680             ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
681                                           ctx->transform_coeffs[ch],
682                                           ctx->tmp_imdct);
683
684         ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
685                                      ctx->window, ctx->delay[ch], 384, 256, 1);
686         ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
687                                      ctx->window, 256);
688     }
689 }
690
691 /* Parse the audio block from ac3 bitstream.
692  * This function extract the audio block from the ac3 bitstream
693  * and produces the output for the block. This function must
694  * be called for each of the six audio block in the ac3 bitstream.
695  */
696 static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
697 {
698     int nfchans = ctx->nfchans;
699     int acmod = ctx->acmod;
700     int i, bnd, seg, grpsize, ch;
701     GetBitContext *gb = &ctx->gb;
702     int bit_alloc_flags = 0;
703     int8_t *dexps;
704     int mstrcplco, cplcoexp, cplcomant;
705     int chbwcod, ngrps, cplabsexp, skipl;
706
707     for (i = 0; i < nfchans; i++) /*block switch flag */
708         ctx->blksw[i] = get_bits1(gb);
709
710     ctx->dither_all = 1;
711     for (i = 0; i < nfchans; i++) { /* dithering flag */
712         ctx->dithflag[i] = get_bits1(gb);
713         if(!ctx->dithflag[i])
714             ctx->dither_all = 0;
715     }
716
717     if (get_bits1(gb)) { /* dynamic range */
718         ctx->dynrng = dynrng_tbl[get_bits(gb, 8)];
719     } else if(blk == 0) {
720         ctx->dynrng = 1.0;
721     }
722
723     if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
724         if(get_bits1(gb)) {
725             ctx->dynrng2 = dynrng_tbl[get_bits(gb, 8)];
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                             ctx->cplco[i][bnd] = cplcomant / 16.0f;
778                         else
779                             ctx->cplco[i][bnd] = (cplcomant + 16.0f) / 32.0f;
780                         ctx->cplco[i][bnd] *= 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