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