]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3dec.c
10l to me. I accidentally removed a word.
[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  *
7  * For exponent decoding the code is inspired by the code in liba52 by
8  * Michel Lespinasse and Aaron Holtzman.
9  * http://liba52.sourceforge.net
10  *
11  * The Mersenne Twister is based on code written by Makoto Matsumoto and
12  * Takuji Nishimura.
13  *
14  * This file is part of FFmpeg.
15  *
16  * FFmpeg is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU General Public
18  * License as published by the Free Software Foundation; either
19  * version 2 of the License, or (at your option) any later version.
20  *
21  * FFmpeg is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public
27  * License along with FFmpeg; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29  */
30
31 #include <stdio.h>
32 #include <stddef.h>
33 #include <math.h>
34 #include <string.h>
35
36 #define ALT_BITSTREAM_READER
37
38 #include "avcodec.h"
39 #include "ac3tab.h"
40 #include "bitstream.h"
41 #include "dsputil.h"
42
43 static const int nfchans_tbl[8] = { 2, 1, 2, 3, 3, 4, 4, 5 };
44
45 /* table for exponent to scale_factor mapping
46  * scale_factor[i] = 2 ^ -(i + 15)
47  */
48 static float scale_factors[25];
49
50 static int16_t psdtab[25];
51
52 static int8_t exp_1[128];
53 static int8_t exp_2[128];
54 static int8_t exp_3[128];
55
56 static int16_t l3_quantizers_1[32];
57 static int16_t l3_quantizers_2[32];
58 static int16_t l3_quantizers_3[32];
59
60 static int16_t l5_quantizers_1[128];
61 static int16_t l5_quantizers_2[128];
62 static int16_t l5_quantizers_3[128];
63
64 static int16_t l7_quantizers[7];
65
66 static int16_t l11_quantizers_1[128];
67 static int16_t l11_quantizers_2[128];
68
69 static int16_t l15_quantizers[15];
70
71 static const uint8_t qntztab[16] = { 0, 5, 7, 3, 7, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16 };
72
73 /* Adjustmens in dB gain */
74 #define LEVEL_MINUS_3DB         0.7071067811865476
75 #define LEVEL_MINUS_4POINT5DB   0.5946035575013605
76 #define LEVEL_MINUS_6DB         0.5000000000000000
77 #define LEVEL_PLUS_3DB          1.4142135623730951
78 #define LEVEL_PLUS_6DB          2.0000000000000000
79 #define LEVEL_ZERO              0.0000000000000000
80
81 static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
82     LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
83
84 static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
85
86 #define N 512   /* constant for IMDCT Block size */
87
88 #define MAX_CHANNELS    6
89 #define BLOCK_SIZE    256
90 #define AUDIO_BLOCKS    6
91
92 /* Exponent strategies. */
93 #define AC3_EXPSTR_D15      0x01
94 #define AC3_EXPSTR_D25      0x02
95 #define AC3_EXPSTR_D45      0x03
96 #define AC3_EXPSTR_REUSE    0x00
97
98 /* Bit allocation strategies. */
99 #define AC3_DBASTR_NEW      0x01
100 #define AC3_DBASTR_NONE     0x02
101 #define AC3_DBASTR_RESERVED 0x03
102 #define AC3_DBASTR_REUSE    0x00
103
104 /* Output and input configurations. */
105 #define AC3_OUTPUT_UNMODIFIED   0x01
106 #define AC3_OUTPUT_MONO         0x02
107 #define AC3_OUTPUT_STEREO       0x04
108 #define AC3_OUTPUT_DOLBY        0x08
109 #define AC3_OUTPUT_LFEON        0x10
110
111 #define AC3_INPUT_DUALMONO      0x00
112 #define AC3_INPUT_MONO          0x01
113 #define AC3_INPUT_STEREO        0x02
114 #define AC3_INPUT_3F            0x03
115 #define AC3_INPUT_2F_1R         0x04
116 #define AC3_INPUT_3F_1R         0x05
117 #define AC3_INPUT_2F_2R         0x06
118 #define AC3_INPUT_3F_2R         0x07
119
120 /* Mersenne Twister */
121 #define NMT 624
122 #define MMT 397
123 #define MATRIX_A    0x9908b0df
124 #define UPPER_MASK  0x80000000
125 #define LOWER_MASK  0x7fffffff
126
127
128 typedef struct {
129     uint32_t mt[NMT];
130     int      mti;
131 } dither_state;
132 /* Mersenne Twister */
133
134 typedef struct {
135     uint16_t crc1;
136     uint8_t  fscod;
137
138     uint8_t  acmod;
139     uint8_t  cmixlev;
140     uint8_t  surmixlev;
141     uint8_t  dsurmod;
142
143     uint8_t  blksw;
144     uint8_t  dithflag;
145     uint8_t  cplinu;
146     uint8_t  chincpl;
147     uint8_t  phsflginu;
148     uint8_t  cplbegf;
149     uint8_t  cplendf;
150     uint8_t  cplcoe;
151     uint32_t cplbndstrc;
152     uint8_t  rematstr;
153     uint8_t  rematflg;
154     uint8_t  cplexpstr;
155     uint8_t  lfeexpstr;
156     uint8_t  chexpstr[5];
157     uint8_t  sdcycod;
158     uint8_t  fdcycod;
159     uint8_t  sgaincod;
160     uint8_t  dbpbcod;
161     uint8_t  floorcod;
162     uint8_t  csnroffst;
163     uint8_t  cplfsnroffst;
164     uint8_t  cplfgaincod;
165     uint8_t  fsnroffst[5];
166     uint8_t  fgaincod[5];
167     uint8_t  lfefsnroffst;
168     uint8_t  lfefgaincod;
169     uint8_t  cplfleak;
170     uint8_t  cplsleak;
171     uint8_t  cpldeltbae;
172     uint8_t  deltbae[5];
173     uint8_t  cpldeltnseg;
174     uint8_t  cpldeltoffst[8];
175     uint8_t  cpldeltlen[8];
176     uint8_t  cpldeltba[8];
177     uint8_t  deltnseg[5];
178     uint8_t  deltoffst[5][8];
179     uint8_t  deltlen[5][8];
180     uint8_t  deltba[5][8];
181
182     /* Derived Attributes. */
183     int      sampling_rate;
184     int      bit_rate;
185     int      frame_size;
186
187     int      nfchans;           //number of channels
188     int      lfeon;             //lfe channel in use
189
190     float    dynrng;            //dynamic range gain
191     float    dynrng2;           //dynamic range gain for 1+1 mode
192     float    chcoeffs[6];       //normalized channel coefficients
193     float    cplco[5][18];      //coupling coordinates
194     int      ncplbnd;           //number of coupling bands
195     int      ncplsubnd;         //number of coupling sub bands
196     int      cplstrtmant;       //coupling start mantissa
197     int      cplendmant;        //coupling end mantissa
198     int      endmant[5];        //channel end mantissas
199
200     uint8_t  dcplexps[256];     //decoded coupling exponents
201     uint8_t  dexps[5][256];     //decoded fbw channel exponents
202     uint8_t  dlfeexps[256];     //decoded lfe channel exponents
203     uint8_t  cplbap[256];       //coupling bit allocation pointers
204     uint8_t  bap[5][256];       //fbw channel bit allocation pointers
205     uint8_t  lfebap[256];       //lfe channel bit allocation pointers
206
207     int      blkoutput;         //output configuration for block
208
209     DECLARE_ALIGNED_16(float, transform_coeffs[MAX_CHANNELS][BLOCK_SIZE]);  //transform coefficients
210
211     /* For IMDCT. */
212     MDCTContext imdct_512;  //for 512 sample imdct transform
213     MDCTContext imdct_256;  //for 256 sample imdct transform
214     DSPContext  dsp;        //for optimization
215
216     DECLARE_ALIGNED_16(float, output[MAX_CHANNELS][BLOCK_SIZE]);    //output after imdct transform and windowing
217     DECLARE_ALIGNED_16(float, delay[MAX_CHANNELS][BLOCK_SIZE]);     //delay - added to the next block
218     DECLARE_ALIGNED_16(float, tmp_imdct[BLOCK_SIZE]);               //temporary storage for imdct transform
219     DECLARE_ALIGNED_16(float, tmp_output[BLOCK_SIZE * 2]);          //temporary storage for output before windowing
220     DECLARE_ALIGNED_16(float, window[BLOCK_SIZE]);                  //window coefficients
221
222     /* Miscellaneous. */
223     GetBitContext gb;
224     dither_state  dith_state;   //for dither generation
225 } AC3DecodeContext;
226
227
228 /* BEGIN Mersenne Twister Code. */
229 static void dither_seed(dither_state *state, uint32_t seed)
230 {
231     static const uint32_t mag01[2] = { 0x00, MATRIX_A };
232     uint32_t y;
233     int kk;
234
235     if (seed == 0)
236         seed = 0x7ba05e;    //default seed to my birthday!
237
238     state->mt[0] = seed;
239     for (state->mti = 1; state->mti < NMT; state->mti++)
240         state->mt[state->mti] = ((69069 * state->mt[state->mti - 1]) + 1);
241
242     for (kk = 0; kk < NMT - MMT; kk++) {
243         y = (state->mt[kk] & UPPER_MASK) | (state->mt[kk + 1] & LOWER_MASK);
244         state->mt[kk] = state->mt[kk + MMT] ^ (y >> 1) ^ mag01[y & 0x01];
245     }
246     for (;kk < NMT - 1; kk++) {
247         y = (state->mt[kk] & UPPER_MASK) | (state->mt[kk + 1] & LOWER_MASK);
248         state->mt[kk] = state->mt[kk + (MMT - NMT)] ^ (y >> 1) ^ mag01[y & 0x01];
249     }
250     y = (state->mt[NMT - 1] & UPPER_MASK) | (state->mt[0] & LOWER_MASK);
251     state->mt[NMT - 1] = state->mt[MMT - 1] ^ (y >> 1) ^ mag01[y & 0x01];
252
253     state->mti = 0;
254 }
255
256 static int16_t dither_int16(dither_state *state)
257 {
258     uint32_t y;
259
260     if (state->mti >= NMT)
261         state->mti = 0;
262
263     y = state->mt[state->mti++];
264     y ^= (y >> 11);
265     y ^= ((y << 7) & 0x9d2c5680);
266     y ^= ((y << 15) & 0xefc60000);
267     y ^= (y >> 18);
268
269     return ((y << 16) >> 16);
270 }
271 /* END Mersenne Twister */
272
273 /*********** BEGIN INIT HELPER FUNCTIONS ***********/
274 /**
275  * Generate a Kaiser-Bessel Derived Window.
276  */
277 static void ac3_window_init(float *window)
278 {
279    int i, j;
280    double sum = 0.0, bessel, tmp;
281    double local_window[256];
282    double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
283
284    for (i = 0; i < 256; i++) {
285        tmp = i * (256 - i) * alpha2;
286        bessel = 1.0;
287        for (j = 100; j > 0; j--) /* defaul to 100 iterations */
288            bessel = bessel * tmp / (j * j) + 1;
289        sum += bessel;
290        local_window[i] = sum;
291    }
292
293    sum++;
294    for (i = 0; i < 256; i++)
295        window[i] = sqrt(local_window[i] / sum);
296 }
297
298 /*
299  * Generate quantizer tables.
300  */
301 static void generate_quantizers_table(int16_t quantizers[], int level, int length)
302 {
303     int i;
304
305     for (i = 0; i < length; i++)
306         quantizers[i] = ((2 * i - level + 1) << 15) / level;
307 }
308
309 static void generate_quantizers_table_1(int16_t quantizers[], int level, int length1, int length2, int size)
310 {
311     int i, j;
312     int16_t v;
313
314     for (i = 0; i < length1; i++) {
315         v = ((2 * i - level + 1) << 15) / level;
316         for (j = 0; j < length2; j++)
317             quantizers[i * length2 + j] = v;
318     }
319
320     for (i = length1 * length2; i < size; i++)
321         quantizers[i] = 0;
322 }
323
324 static void generate_quantizers_table_2(int16_t quantizers[], int level, int length1, int length2, int size)
325 {
326     int i, j;
327     int16_t v;
328
329     for (i = 0; i < length1; i++) {
330         v = ((2 * (i % level) - level + 1) << 15) / level;
331         for (j = 0; j < length2; j++)
332             quantizers[i * length2 + j] = v;
333     }
334
335     for (i = length1 * length2; i < size; i++)
336         quantizers[i] = 0;
337
338 }
339
340 static void generate_quantizers_table_3(int16_t quantizers[], int level, int length1, int length2, int size)
341 {
342     int i, j;
343
344     for (i = 0; i < length1; i++)
345         for (j = 0; j < length2; j++)
346             quantizers[i * length2 + j] = ((2 * (j % level) - level + 1) << 15) / level;
347
348     for (i = length1 * length2; i < size; i++)
349         quantizers[i] = 0;
350 }
351
352 /*
353  * Initialize tables at runtime.
354  */
355 static void ac3_tables_init(void)
356 {
357     int i, j, k, l, v;
358     /* compute bndtab and masktab from bandsz */
359     k = 0;
360     l = 0;
361     for(i=0;i<50;i++) {
362         bndtab[i] = l;
363         v = bndsz[i];
364         for(j=0;j<v;j++) masktab[k++]=i;
365         l += v;
366     }
367     masktab[253] = masktab[254] = masktab[255] = 0;
368     bndtab[50] = 0;
369
370     /* PSD Table For Mapping Exponents To PSD. */
371     for (i = 0; i < 25; i++)
372         psdtab[i] = 3072 - (i << 7);
373
374     /* Exponent Decoding Tables */
375     for (i = 0; i < 5; i++) {
376         v = i - 2;
377         for (j = 0; j < 25; j++)
378             exp_1[i * 25 + j] = v;
379     }
380
381     for (i = 0; i < 25; i++) {
382         v = (i % 5) - 2;
383         for (j = 0; j < 5; j++)
384             exp_2[i * 5 + j] = v;
385     }
386
387     for (i = 0; i < 25; i++) {
388         v = -2;
389         for (j = 0; j < 5; j++)
390             exp_3[i * 5 + j] = v++;
391     }
392
393     for (i = 125; i < 128; i++)
394         exp_1[i] = exp_2[i] = exp_3[i] = 25;
395     /* End Exponent Decoding Tables */
396
397     /* Quantizer ungrouping tables. */
398     // for level-3 quantizers
399     generate_quantizers_table_1(l3_quantizers_1, 3, 3, 9, 32);
400     generate_quantizers_table_2(l3_quantizers_2, 3, 9, 3, 32);
401     generate_quantizers_table_3(l3_quantizers_3, 3, 9, 3, 32);
402
403     //for level-5 quantizers
404     generate_quantizers_table_1(l5_quantizers_1, 5, 5, 25, 128);
405     generate_quantizers_table_2(l5_quantizers_2, 5, 25, 5, 128);
406     generate_quantizers_table_3(l5_quantizers_3, 5, 25, 5, 128);
407
408     //for level-7 quantizers
409     generate_quantizers_table(l7_quantizers, 7, 7);
410
411     //for level-4 quantizers
412     generate_quantizers_table_2(l11_quantizers_1, 11, 11, 11, 128);
413     generate_quantizers_table_3(l11_quantizers_2, 11, 11, 11, 128);
414
415     //for level-15 quantizers
416     generate_quantizers_table(l15_quantizers, 15, 15);
417     /* End Quantizer ungrouping tables. */
418
419     //generate scale factors
420     for (i = 0; i < 25; i++)
421         scale_factors[i] = pow(2.0, -(i + 15));
422 }
423
424
425 static int ac3_decode_init(AVCodecContext *avctx)
426 {
427     AC3DecodeContext *ctx = avctx->priv_data;
428
429     ac3_tables_init();
430     ff_mdct_init(&ctx->imdct_256, 8, 1);
431     ff_mdct_init(&ctx->imdct_512, 9, 1);
432     ac3_window_init(ctx->window);
433     dsputil_init(&ctx->dsp, avctx);
434     dither_seed(&ctx->dith_state, 0);
435
436     return 0;
437 }
438 /*********** END INIT FUNCTIONS ***********/
439
440 /* Synchronize to ac3 bitstream.
441  * This function searches for the syncword '0xb77'.
442  *
443  * @param buf Pointer to "probable" ac3 bitstream buffer
444  * @param buf_size Size of buffer
445  * @return Returns the position where syncword is found, -1 if no syncword is found
446  */
447 static int ac3_synchronize(uint8_t *buf, int buf_size)
448 {
449     int i;
450
451     for (i = 0; i < buf_size - 1; i++)
452         if (buf[i] == 0x0b && buf[i + 1] == 0x77)
453             return i;
454
455     return -1;
456 }
457
458 /* Parse the 'sync_info' from the ac3 bitstream.
459  * This function extracts the sync_info from ac3 bitstream.
460  * GetBitContext within AC3DecodeContext must point to
461  * start of the synchronized ac3 bitstream.
462  *
463  * @param ctx  AC3DecodeContext
464  * @return Returns framesize, returns 0 if fscod, frmsizecod or bsid is not valid
465  */
466 static int ac3_parse_sync_info(AC3DecodeContext *ctx)
467 {
468     GetBitContext *gb = &ctx->gb;
469     int frmsizecod, bsid;
470
471     skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
472     ctx->crc1 = get_bits(gb, 16);
473     ctx->fscod = get_bits(gb, 2);
474     if (ctx->fscod == 0x03)
475         return 0;
476     frmsizecod = get_bits(gb, 6);
477     if (frmsizecod >= 38)
478         return 0;
479     ctx->sampling_rate = ac3_freqs[ctx->fscod];
480     ctx->bit_rate = ac3_bitratetab[frmsizecod >> 1];
481
482     /* we include it here in order to determine validity of ac3 frame */
483     bsid = get_bits(gb, 5);
484     if (bsid > 0x08)
485         return 0;
486     skip_bits(gb, 3); //skip the bsmod, bsi->bsmod = get_bits(gb, 3);
487
488     switch (ctx->fscod) {
489         case 0x00:
490             ctx->frame_size = 4 * ctx->bit_rate;
491             return ctx->frame_size;
492         case 0x01:
493             ctx->frame_size = 2 * (320 * ctx->bit_rate / 147 + (frmsizecod & 1));
494             return ctx->frame_size;
495         case 0x02:
496             ctx->frame_size =  6 * ctx->bit_rate;
497             return ctx->frame_size;
498     }
499
500     /* never reached */
501     return 0;
502 }
503
504 /* Parse bsi from ac3 bitstream.
505  * This function extracts the bitstream information (bsi) from ac3 bitstream.
506  *
507  * @param ctx AC3DecodeContext after processed by ac3_parse_sync_info
508  */
509 static void ac3_parse_bsi(AC3DecodeContext *ctx)
510 {
511     GetBitContext *gb = &ctx->gb;
512     int i;
513
514     ctx->cmixlev = 0;
515     ctx->surmixlev = 0;
516     ctx->dsurmod = 0;
517     ctx->nfchans = 0;
518     ctx->cpldeltbae = AC3_DBASTR_NONE;
519     ctx->cpldeltnseg = 0;
520     for (i = 0; i < 5; i++) {
521         ctx->deltbae[i] = AC3_DBASTR_NONE;
522         ctx->deltnseg[i] = 0;
523     }
524     ctx->dynrng = 1.0;
525     ctx->dynrng2 = 1.0;
526
527     ctx->acmod = get_bits(gb, 3);
528     ctx->nfchans = nfchans_tbl[ctx->acmod];
529
530     if (ctx->acmod & 0x01 && ctx->acmod != 0x01)
531         ctx->cmixlev = get_bits(gb, 2);
532     if (ctx->acmod & 0x04)
533         ctx->surmixlev = get_bits(gb, 2);
534     if (ctx->acmod == 0x02)
535         ctx->dsurmod = get_bits(gb, 2);
536
537     ctx->lfeon = get_bits1(gb);
538
539     i = !(ctx->acmod);
540     do {
541         skip_bits(gb, 5); //skip dialog normalization
542         if (get_bits1(gb))
543             skip_bits(gb, 8); //skip compression
544         if (get_bits1(gb))
545             skip_bits(gb, 8); //skip language code
546         if (get_bits1(gb))
547             skip_bits(gb, 7); //skip audio production information
548     } while (i--);
549
550     skip_bits(gb, 2); //skip copyright bit and original bitstream bit
551
552     if (get_bits1(gb))
553         skip_bits(gb, 14); //skip timecode1
554     if (get_bits1(gb))
555         skip_bits(gb, 14); //skip timecode2
556
557     if (get_bits1(gb)) {
558         i = get_bits(gb, 6); //additional bsi length
559         do {
560             skip_bits(gb, 8);
561         } while(i--);
562     }
563 }
564
565 /* Decodes the grouped exponents.
566  * This function decodes the coded exponents according to exponent strategy
567  * and stores them in the decoded exponents buffer.
568  *
569  * @param gb GetBitContext which points to start of coded exponents
570  * @param expstr Exponent coding strategy
571  * @param ngrps Number of grouped exponetns
572  * @param absexp Absolute exponent
573  * @param dexps Decoded exponents are stored in dexps
574  * @return Returns 0 if exponents are decoded successfully, -1 if error occurs
575  */
576 static int decode_exponents(GetBitContext *gb, int expstr, int ngrps, uint8_t absexp, uint8_t *dexps)
577 {
578     int exps;
579
580     while (ngrps--) {
581         exps = get_bits(gb, 7);
582
583         absexp += exp_1[exps];
584         if (absexp > 24) {
585             av_log(NULL, AV_LOG_ERROR, "Absolute Exponent > 24, ngrp = %d\n", ngrps);
586             return -ngrps;
587         }
588         switch (expstr) {
589             case AC3_EXPSTR_D45:
590                 *(dexps++) = absexp;
591                 *(dexps++) = absexp;
592             case AC3_EXPSTR_D25:
593                 *(dexps++) = absexp;
594             case AC3_EXPSTR_D15:
595                 *(dexps++) = absexp;
596         }
597
598         absexp += exp_2[exps];
599         if (absexp > 24) {
600             av_log(NULL, AV_LOG_ERROR, "Absolute Exponent > 24, ngrp = %d\n", ngrps);
601             return -ngrps;
602         }
603         switch (expstr) {
604             case AC3_EXPSTR_D45:
605                 *(dexps++) = absexp;
606                 *(dexps++) = absexp;
607             case AC3_EXPSTR_D25:
608                 *(dexps++) = absexp;
609             case AC3_EXPSTR_D15:
610                 *(dexps++) = absexp;
611         }
612
613         absexp += exp_3[exps];
614         if (absexp > 24) {
615             av_log(NULL, AV_LOG_ERROR, "Absolute Exponent > 24, ngrp = %d\n", ngrps);
616             return -ngrps;
617         }
618         switch (expstr) {
619             case AC3_EXPSTR_D45:
620                 *(dexps++) = absexp;
621                 *(dexps++) = absexp;
622             case AC3_EXPSTR_D25:
623                 *(dexps++) = absexp;
624             case AC3_EXPSTR_D15:
625                 *(dexps++) = absexp;
626         }
627     }
628
629     return 0;
630 }
631
632 /*********** HELPER FUNCTIONS FOR BIT ALLOCATION ***********/
633 static inline int logadd(int a, int b)
634 {
635     int c = a - b;
636     int address;
637
638     address = FFMIN((ABS(c) >> 1), 255);
639
640     if (c >= 0)
641         return (a + latab[address]);
642     else
643         return (b + latab[address]);
644 }
645
646 static inline int calc_lowcomp(int a, int b0, int b1, int bin)
647 {
648     if (bin < 7) {
649         if ((b0 + 256) == b1)
650             a = 384;
651         else if (b0 > b1)
652             a = FFMAX(0, (a - 64));
653     }
654     else if (bin < 20) {
655         if ((b0 + 256) == b1)
656             a = 320;
657         else if (b0 > b1)
658             a = FFMAX(0, (a - 64));
659     }
660     else
661         a = FFMAX(0, (a - 128));
662
663     return a;
664 }
665 /*********** END HELPER FUNCTIONS FOR BIT ALLOCATION ***********/
666
667 /* Performs bit allocation.
668  * This function performs bit allocation for the requested chanenl.
669  */
670 static void do_bit_allocation(AC3DecodeContext *ctx, int chnl)
671 {
672     int16_t psd[256], bndpsd[50], excite[50], mask[50], delta;
673     int sdecay, fdecay, sgain, dbknee, floor;
674     int lowcomp = 0, fgain = 0, snroffset = 0, fastleak = 0, slowleak = 0, do_delta = 0;
675     int start = 0, end = 0, bin = 0, i = 0, j = 0, k = 0, lastbin = 0, bndstrt = 0;
676     int bndend = 0, begin = 0, deltnseg = 0, band = 0, seg = 0, address = 0;
677     int fscod = ctx->fscod;
678     uint8_t *deltoffst = 0, *deltlen = 0, *deltba = 0;
679     uint8_t *exps = 0, *bap = 0;
680
681     /* initialization */
682     sdecay = sdecaytab[ctx->sdcycod];
683     fdecay = fdecaytab[ctx->fdcycod];
684     sgain = sgaintab[ctx->sgaincod];
685     dbknee = dbkneetab[ctx->dbpbcod];
686     floor = floortab[ctx->floorcod];
687
688     if (chnl == 5) {
689         start = ctx->cplstrtmant;
690         end = ctx->cplendmant;
691         fgain = fgaintab[ctx->cplfgaincod];
692         snroffset = (((ctx->csnroffst - 15) << 4) + ctx->cplfsnroffst) << 2;
693         fastleak = (ctx->cplfleak << 8) + 768;
694         slowleak = (ctx->cplsleak << 8) + 768;
695         exps = ctx->dcplexps;
696         bap = ctx->cplbap;
697         if (ctx->cpldeltbae == AC3_DBASTR_NEW || ctx->deltbae == AC3_DBASTR_REUSE) {
698             do_delta = 1;
699             deltnseg = ctx->cpldeltnseg;
700             deltoffst = ctx->cpldeltoffst;
701             deltlen = ctx->cpldeltlen;
702             deltba = ctx->cpldeltba;
703         }
704     }
705     else if (chnl == 6) {
706         start = 0;
707         end = 7;
708         lowcomp = 0;
709         fastleak = 0;
710         slowleak = 0;
711         fgain = fgaintab[ctx->lfefgaincod];
712         snroffset = (((ctx->csnroffst - 15) << 4) + ctx->lfefsnroffst) << 2;
713         exps = ctx->dlfeexps;
714         bap = ctx->lfebap;
715     }
716     else {
717         start = 0;
718         end = ctx->endmant[chnl];
719         lowcomp = 0;
720         fastleak = 0;
721         slowleak = 0;
722         fgain = fgaintab[ctx->fgaincod[chnl]];
723         snroffset = (((ctx->csnroffst - 15) << 4) + ctx->fsnroffst[chnl]) << 2;
724         exps = ctx->dexps[chnl];
725         bap = ctx->bap[chnl];
726         if (ctx->deltbae[chnl] == AC3_DBASTR_NEW || ctx->deltbae[chnl] == AC3_DBASTR_REUSE) {
727             do_delta = 1;
728             deltnseg = ctx->deltnseg[chnl];
729             deltoffst = ctx->deltoffst[chnl];
730             deltlen = ctx->deltlen[chnl];
731             deltba = ctx->deltba[chnl];
732         }
733     }
734
735     for (bin = start; bin < end; bin++) /* exponent mapping into psd */
736         psd[bin] = psdtab[exps[bin]];
737
738     /* psd integration */
739     j = start;
740     k = masktab[start];
741     do {
742         lastbin = FFMIN((bndtab[k] + bndsz[k]), end);
743         bndpsd[k] = psd[j];
744         j++;
745         for (i = j; i < lastbin; i++) {
746             bndpsd[k] = logadd(bndpsd[k], psd[j]);
747             j++;
748         }
749         k++;
750     } while (end > lastbin);
751
752     /* compute the excite function */
753     bndstrt = masktab[start];
754     bndend = masktab[end - 1] + 1;
755     if (bndstrt == 0) {
756         lowcomp = calc_lowcomp(lowcomp, bndpsd[0], bndpsd[1], 0);
757         excite[0] = bndpsd[0] - fgain - lowcomp;
758         lowcomp = calc_lowcomp(lowcomp, bndpsd[1], bndpsd[2], 1);
759         excite[1] = bndpsd[1] - fgain - lowcomp;
760         begin = 7;
761         for (bin = 2; bin < 7; bin++) {
762             if ((bndend != 7) || (bin != 6))
763                 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);
764             fastleak = bndpsd[bin] - fgain;
765             slowleak = bndpsd[bin] - sgain;
766             excite[bin] = fastleak - lowcomp;
767             if ((bndend != 7) || (bin != 6))
768                 if (bndpsd[bin] <= bndpsd[bin + 1]) {
769                     begin = bin + 1;
770                     break;
771                 }
772         }
773         for (bin = begin; bin < FFMIN(bndend, 22); bin++) {
774             if ((bndend != 7) || (bin != 6))
775                 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);
776             fastleak -= fdecay;
777             fastleak = FFMAX(fastleak, (bndpsd[bin] - fgain));
778             slowleak -= sdecay;
779             slowleak = FFMAX(slowleak, (bndpsd[bin] - sgain));
780             excite[bin] = FFMAX((fastleak - lowcomp), slowleak);
781         }
782         begin = 22;
783     }
784     else {
785         begin = bndstrt;
786     }
787     for (bin = begin; bin < bndend; bin++) {
788         fastleak -= fdecay;
789         fastleak = FFMAX(fastleak, (bndpsd[bin] - fgain));
790         slowleak -= sdecay;
791         slowleak = FFMAX(slowleak, (bndpsd[bin] - sgain));
792         excite[bin] = FFMAX(fastleak, slowleak);
793     }
794
795     /* compute the masking curve */
796     for (bin = bndstrt; bin < bndend; bin++) {
797         if (bndpsd[bin] < dbknee)
798             excite[bin] += ((dbknee - bndpsd[bin]) >> 2);
799         mask[bin] = FFMAX(excite[bin], hth[bin][fscod]);
800     }
801
802     /* apply the delta bit allocation */
803     if (do_delta) {
804         band = 0;
805         for (seg = 0; seg < deltnseg + 1; seg++) {
806             band += deltoffst[seg];
807             if (deltba[seg] >= 4)
808                 delta = (deltba[seg] - 3) << 7;
809             else
810                 delta = (deltba[seg] - 4) << 7;
811             for (k = 0; k < deltlen[seg]; k++) {
812                 mask[band] += delta;
813                 band++;
814             }
815         }
816     }
817
818     /*compute the bit allocation */
819     i = start;
820     j = masktab[start];
821     do {
822         lastbin = FFMIN((bndtab[j] + bndsz[j]), end);
823         mask[j] -= snroffset;
824         mask[j] -= floor;
825         if (mask[j] < 0)
826             mask[j] = 0;
827         mask[j] &= 0x1fe0;
828         mask[j] += floor;
829         for (k = i; k < lastbin; k++) {
830             address = (psd[i] - mask[j]) >> 5;
831             address = FFMIN(63, (FFMAX(0, address)));
832             bap[i] = baptab[address];
833             i++;
834         }
835         j++;
836     } while (end > lastbin);
837 }
838
839 /* Check if snroffsets are zero. */
840 static int is_snr_offsets_zero(AC3DecodeContext *ctx)
841 {
842     int i;
843
844     if ((ctx->csnroffst) || (ctx->cplinu && ctx->cplfsnroffst) ||
845             (ctx->lfeon && ctx->lfefsnroffst))
846         return 0;
847
848     for (i = 0; i < ctx->nfchans; i++)
849         if (ctx->fsnroffst[i])
850             return 0;
851
852     return 1;
853 }
854
855 typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
856     int16_t l3_quantizers[3];
857     int16_t l5_quantizers[3];
858     int16_t l11_quantizers[2];
859     int l3ptr;
860     int l5ptr;
861     int l11ptr;
862 } mant_groups;
863
864 #define TRANSFORM_COEFF(tc, m, e, f) (tc) = (m) * (f)[(e)]
865
866 /* Get the transform coefficients for coupling channel and uncouple channels.
867  * The coupling transform coefficients starts at the the cplstrtmant, which is
868  * equal to endmant[ch] for fbw channels. Hence we can uncouple channels before
869  * getting transform coefficients for the channel.
870  */
871 static int get_transform_coeffs_cpling(AC3DecodeContext *ctx, mant_groups *m)
872 {
873     GetBitContext *gb = &ctx->gb;
874     int ch, start, end, cplbndstrc, bnd, gcode, tbap;
875     float cplcos[5], cplcoeff;
876     uint8_t *exps = ctx->dcplexps;
877     uint8_t *bap = ctx->cplbap;
878
879     cplbndstrc = ctx->cplbndstrc;
880     start = ctx->cplstrtmant;
881     bnd = 0;
882
883     while (start < ctx->cplendmant) {
884         end = start + 12;
885         while (cplbndstrc & 1) {
886             end += 12;
887             cplbndstrc >>= 1;
888         }
889         cplbndstrc >>= 1;
890         for (ch = 0; ch < ctx->nfchans; ch++)
891             cplcos[ch] = ctx->chcoeffs[ch] * ctx->cplco[ch][bnd];
892         bnd++;
893
894         while (start < end) {
895             tbap = bap[start];
896             switch(tbap) {
897                 case 0:
898                     for (ch = 0; ch < ctx->nfchans; ch++)
899                         if (((ctx->chincpl) >> ch) & 1) {
900                             if ((ctx->dithflag >> ch) & 1) {
901                                 TRANSFORM_COEFF(cplcoeff, dither_int16(&ctx->dith_state), exps[start], scale_factors);
902                                 ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch] * LEVEL_MINUS_3DB;
903                             } else
904                                 ctx->transform_coeffs[ch + 1][start] = 0;
905                         }
906                     start++;
907                     continue;
908                 case 1:
909                     if (m->l3ptr > 2) {
910                         gcode = get_bits(gb, 5);
911                         m->l3_quantizers[0] = l3_quantizers_1[gcode];
912                         m->l3_quantizers[1] = l3_quantizers_2[gcode];
913                         m->l3_quantizers[2] = l3_quantizers_3[gcode];
914                         m->l3ptr = 0;
915                     }
916                     TRANSFORM_COEFF(cplcoeff, m->l3_quantizers[m->l3ptr++], exps[start], scale_factors);
917                     break;
918
919                 case 2:
920                     if (m->l5ptr > 2) {
921                         gcode = get_bits(gb, 7);
922                         m->l5_quantizers[0] = l5_quantizers_1[gcode];
923                         m->l5_quantizers[1] = l5_quantizers_2[gcode];
924                         m->l5_quantizers[2] = l5_quantizers_3[gcode];
925                         m->l5ptr = 0;
926                     }
927                     TRANSFORM_COEFF(cplcoeff, m->l5_quantizers[m->l5ptr++], exps[start], scale_factors);
928                     break;
929
930                 case 3:
931                     TRANSFORM_COEFF(cplcoeff, l7_quantizers[get_bits(gb, 3)], exps[start], scale_factors);
932                     break;
933
934                 case 4:
935                     if (m->l11ptr > 1) {
936                         gcode = get_bits(gb, 7);
937                         m->l11_quantizers[0] = l11_quantizers_1[gcode];
938                         m->l11_quantizers[1] = l11_quantizers_2[gcode];
939                         m->l11ptr = 0;
940                     }
941                     TRANSFORM_COEFF(cplcoeff, m->l11_quantizers[m->l11ptr++], exps[start], scale_factors);
942                     break;
943
944                 case 5:
945                     TRANSFORM_COEFF(cplcoeff, l15_quantizers[get_bits(gb, 4)], exps[start], scale_factors);
946                     break;
947
948                 default:
949                     TRANSFORM_COEFF(cplcoeff, get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap]),
950                             exps[start], scale_factors);
951             }
952             for (ch = 0; ch < ctx->nfchans; ch++)
953                 if ((ctx->chincpl >> ch) & 1)
954                     ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch];
955             start++;
956         }
957     }
958
959     return 0;
960 }
961
962 /* Get the transform coefficients for particular channel */
963 static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
964 {
965     GetBitContext *gb = &ctx->gb;
966     int i, gcode, tbap, dithflag, end;
967     uint8_t *exps;
968     uint8_t *bap;
969     float *coeffs;
970     float factors[25];
971
972     for (i = 0; i < 25; i++)
973         factors[i] = scale_factors[i] * ctx->chcoeffs[ch_index];
974
975     if (ch_index != -1) { /* fbw channels */
976         dithflag = (ctx->dithflag >> ch_index) & 1;
977         exps = ctx->dexps[ch_index];
978         bap = ctx->bap[ch_index];
979         coeffs = ctx->transform_coeffs[ch_index + 1];
980         end = ctx->endmant[ch_index];
981     } else if (ch_index == -1) {
982         dithflag = 0;
983         exps = ctx->dlfeexps;
984         bap = ctx->lfebap;
985         coeffs = ctx->transform_coeffs[0];
986         end = 7;
987     }
988
989
990     for (i = 0; i < end; i++) {
991         tbap = bap[i];
992         switch (tbap) {
993             case 0:
994                 if (!dithflag) {
995                     coeffs[i] = 0;
996                     continue;
997                 }
998                 else {
999                     TRANSFORM_COEFF(coeffs[i], dither_int16(&ctx->dith_state), exps[i], factors);
1000                     coeffs[i] *= LEVEL_MINUS_3DB;
1001                     continue;
1002                 }
1003
1004             case 1:
1005                 if (m->l3ptr > 2) {
1006                     gcode = get_bits(gb, 5);
1007                     m->l3_quantizers[0] = l3_quantizers_1[gcode];
1008                     m->l3_quantizers[1] = l3_quantizers_2[gcode];
1009                     m->l3_quantizers[2] = l3_quantizers_3[gcode];
1010                     m->l3ptr = 0;
1011                 }
1012                 TRANSFORM_COEFF(coeffs[i], m->l3_quantizers[m->l3ptr++], exps[i], factors);
1013                 continue;
1014
1015             case 2:
1016                 if (m->l5ptr > 2) {
1017                     gcode = get_bits(gb, 7);
1018                     m->l5_quantizers[0] = l5_quantizers_1[gcode];
1019                     m->l5_quantizers[1] = l5_quantizers_2[gcode];
1020                     m->l5_quantizers[2] = l5_quantizers_3[gcode];
1021                     m->l5ptr = 0;
1022                 }
1023                 TRANSFORM_COEFF(coeffs[i], m->l5_quantizers[m->l5ptr++], exps[i], factors);
1024                 continue;
1025
1026             case 3:
1027                 TRANSFORM_COEFF(coeffs[i], l7_quantizers[get_bits(gb, 3)], exps[i], factors);
1028                 continue;
1029
1030             case 4:
1031                 if (m->l11ptr > 1) {
1032                     gcode = get_bits(gb, 7);
1033                     m->l11_quantizers[0] = l11_quantizers_1[gcode];
1034                     m->l11_quantizers[1] = l11_quantizers_2[gcode];
1035                     m->l11ptr = 0;
1036                 }
1037                 TRANSFORM_COEFF(coeffs[i], m->l11_quantizers[m->l11ptr++], exps[i], factors);
1038                 continue;
1039
1040             case 5:
1041                 TRANSFORM_COEFF(coeffs[i], l15_quantizers[get_bits(gb, 4)], exps[i], factors);
1042                 continue;
1043
1044             default:
1045                 TRANSFORM_COEFF(coeffs[i], get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap]), exps[i], factors);
1046                 continue;
1047         }
1048     }
1049
1050     return 0;
1051 }
1052
1053 /* Get the transform coefficients.
1054  * This function extracts the tranform coefficients form the ac3 bitstream.
1055  * This function is called after bit allocation is performed.
1056  */
1057 static int get_transform_coeffs(AC3DecodeContext * ctx)
1058 {
1059     int i, end;
1060     int got_cplchan = 0;
1061     mant_groups m;
1062
1063     m.l3ptr = m.l5ptr = m.l11ptr = 3;
1064
1065     for (i = 0; i < ctx->nfchans; i++) {
1066         /* transform coefficients for individual channel */
1067         if (get_transform_coeffs_ch(ctx, i, &m))
1068             return -1;
1069         /* tranform coefficients for coupling channels */
1070         if ((ctx->chincpl >> i) & 1)  {
1071             if (!got_cplchan) {
1072                 if (get_transform_coeffs_cpling(ctx, &m)) {
1073                     av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
1074                     return -1;
1075                 }
1076                 got_cplchan = 1;
1077             }
1078             end = ctx->cplendmant;
1079         } else
1080             end = ctx->endmant[i];
1081         do
1082             ctx->transform_coeffs[i + 1][end] = 0;
1083         while(++end < 256);
1084     }
1085     if (ctx->lfeon) {
1086         if (get_transform_coeffs_ch(ctx, -1, &m))
1087                 return -1;
1088         for (i = 7; i < 256; i++) {
1089             ctx->transform_coeffs[0][i] = 0;
1090         }
1091     }
1092
1093     return 0;
1094 }
1095
1096 /* Rematrixing routines. */
1097 static void do_rematrixing1(AC3DecodeContext *ctx, int start, int end)
1098 {
1099     float tmp0, tmp1;
1100
1101     while (start < end) {
1102         tmp0 = ctx->transform_coeffs[1][start];
1103         tmp1 = ctx->transform_coeffs[2][start];
1104         ctx->transform_coeffs[1][start] = tmp0 + tmp1;
1105         ctx->transform_coeffs[2][start] = tmp0 - tmp1;
1106         start++;
1107     }
1108 }
1109
1110 static void do_rematrixing(AC3DecodeContext *ctx)
1111 {
1112     int bnd1 = 13, bnd2 = 25, bnd3 = 37, bnd4 = 61;
1113     int end, bndend;
1114
1115     end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
1116
1117     if (ctx->rematflg & 1)
1118         do_rematrixing1(ctx, bnd1, bnd2);
1119
1120     if (ctx->rematflg & 2)
1121         do_rematrixing1(ctx, bnd2, bnd3);
1122
1123     bndend = bnd4;
1124     if (bndend > end) {
1125         bndend = end;
1126         if (ctx->rematflg & 4)
1127             do_rematrixing1(ctx, bnd3, bndend);
1128     } else {
1129         if (ctx->rematflg & 4)
1130             do_rematrixing1(ctx, bnd3, bnd4);
1131         if (ctx->rematflg & 8)
1132             do_rematrixing1(ctx, bnd4, end);
1133     }
1134 }
1135
1136 /* This function sets the normalized channel coefficients.
1137  * Transform coefficients are multipllied by the channel
1138  * coefficients to get normalized transform coefficients.
1139  */
1140 static void get_downmix_coeffs(AC3DecodeContext *ctx)
1141 {
1142     int from = ctx->acmod;
1143     int to = ctx->blkoutput;
1144     float clev = clevs[ctx->cmixlev];
1145     float slev = slevs[ctx->surmixlev];
1146     float nf = 1.0; //normalization factor for downmix coeffs
1147     int i;
1148
1149     if (!ctx->acmod) {
1150         ctx->chcoeffs[0] = 2 * ctx->dynrng;
1151         ctx->chcoeffs[1] = 2 * ctx->dynrng2;
1152     } else {
1153         for (i = 0; i < ctx->nfchans; i++)
1154             ctx->chcoeffs[i] = 2 * ctx->dynrng;
1155     }
1156
1157     if (to == AC3_OUTPUT_UNMODIFIED)
1158         return;
1159
1160     switch (from) {
1161         case AC3_INPUT_DUALMONO:
1162             switch (to) {
1163                 case AC3_OUTPUT_MONO:
1164                 case AC3_OUTPUT_STEREO: /* We Assume that sum of both mono channels is requested */
1165                     nf = 0.5;
1166                     ctx->chcoeffs[0] *= nf;
1167                     ctx->chcoeffs[1] *= nf;
1168                     break;
1169             }
1170             break;
1171         case AC3_INPUT_MONO:
1172             switch (to) {
1173                 case AC3_OUTPUT_STEREO:
1174                     nf = LEVEL_MINUS_3DB;
1175                     ctx->chcoeffs[0] *= nf;
1176                     break;
1177             }
1178             break;
1179         case AC3_INPUT_STEREO:
1180             switch (to) {
1181                 case AC3_OUTPUT_MONO:
1182                     nf = LEVEL_MINUS_3DB;
1183                     ctx->chcoeffs[0] *= nf;
1184                     ctx->chcoeffs[1] *= nf;
1185                     break;
1186             }
1187             break;
1188         case AC3_INPUT_3F:
1189             switch (to) {
1190                 case AC3_OUTPUT_MONO:
1191                     nf = LEVEL_MINUS_3DB / (1.0 + clev);
1192                     ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
1193                     ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
1194                     ctx->chcoeffs[1] *= ((nf * clev * LEVEL_MINUS_3DB) / 2.0);
1195                     break;
1196                 case AC3_OUTPUT_STEREO:
1197                     nf = 1.0 / (1.0 + clev);
1198                     ctx->chcoeffs[0] *= nf;
1199                     ctx->chcoeffs[2] *= nf;
1200                     ctx->chcoeffs[1] *= (nf * clev);
1201                     break;
1202             }
1203             break;
1204         case AC3_INPUT_2F_1R:
1205             switch (to) {
1206                 case AC3_OUTPUT_MONO:
1207                     nf = 2.0 * LEVEL_MINUS_3DB / (2.0 + slev);
1208                     ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
1209                     ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
1210                     ctx->chcoeffs[2] *= (nf * slev * LEVEL_MINUS_3DB);
1211                     break;
1212                 case AC3_OUTPUT_STEREO:
1213                     nf = 1.0 / (1.0 + (slev * LEVEL_MINUS_3DB));
1214                     ctx->chcoeffs[0] *= nf;
1215                     ctx->chcoeffs[1] *= nf;
1216                     ctx->chcoeffs[2] *= (nf * slev * LEVEL_MINUS_3DB);
1217                     break;
1218                 case AC3_OUTPUT_DOLBY:
1219                     nf = 1.0 / (1.0 + LEVEL_MINUS_3DB);
1220                     ctx->chcoeffs[0] *= nf;
1221                     ctx->chcoeffs[1] *= nf;
1222                     ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
1223                     break;
1224             }
1225             break;
1226         case AC3_INPUT_3F_1R:
1227             switch (to) {
1228                 case AC3_OUTPUT_MONO:
1229                     nf = LEVEL_MINUS_3DB / (1.0 + clev + (slev / 2.0));
1230                     ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
1231                     ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
1232                     ctx->chcoeffs[1] *= (nf * clev * LEVEL_PLUS_3DB);
1233                     ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
1234                     break;
1235                 case AC3_OUTPUT_STEREO:
1236                     nf = 1.0 / (1.0 + clev + (slev * LEVEL_MINUS_3DB));
1237                     ctx->chcoeffs[0] *= nf;
1238                     ctx->chcoeffs[2] *= nf;
1239                     ctx->chcoeffs[1] *= (nf * clev);
1240                     ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
1241                     break;
1242                 case AC3_OUTPUT_DOLBY:
1243                     nf = 1.0 / (1.0 + (2.0 * LEVEL_MINUS_3DB));
1244                     ctx->chcoeffs[0] *= nf;
1245                     ctx->chcoeffs[1] *= nf;
1246                     ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
1247                     ctx->chcoeffs[3] *= (nf * LEVEL_MINUS_3DB);
1248                     break;
1249             }
1250             break;
1251         case AC3_INPUT_2F_2R:
1252             switch (to) {
1253                 case AC3_OUTPUT_MONO:
1254                     nf = LEVEL_MINUS_3DB / (1.0 + slev);
1255                     ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
1256                     ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
1257                     ctx->chcoeffs[2] *= (nf * slev * LEVEL_MINUS_3DB);
1258                     ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
1259                     break;
1260                 case AC3_OUTPUT_STEREO:
1261                     nf = 1.0 / (1.0 + slev);
1262                     ctx->chcoeffs[0] *= nf;
1263                     ctx->chcoeffs[1] *= nf;
1264                     ctx->chcoeffs[2] *= (nf * slev);
1265                     ctx->chcoeffs[3] *= (nf * slev);
1266                     break;
1267                 case AC3_OUTPUT_DOLBY:
1268                     nf = 1.0 / (1.0 + (2.0 * LEVEL_MINUS_3DB));
1269                     ctx->chcoeffs[0] *= nf;
1270                     ctx->chcoeffs[1] *= nf;
1271                     ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
1272                     ctx->chcoeffs[3] *= (nf * LEVEL_MINUS_3DB);
1273                     break;
1274             }
1275             break;
1276         case AC3_INPUT_3F_2R:
1277             switch (to) {
1278                 case AC3_OUTPUT_MONO:
1279                     nf = LEVEL_MINUS_3DB / (1.0 + clev + slev);
1280                     ctx->chcoeffs[0] *= (nf * LEVEL_MINUS_3DB);
1281                     ctx->chcoeffs[2] *= (nf * LEVEL_MINUS_3DB);
1282                     ctx->chcoeffs[1] *= (nf * clev * LEVEL_PLUS_3DB);
1283                     ctx->chcoeffs[3] *= (nf * slev * LEVEL_MINUS_3DB);
1284                     ctx->chcoeffs[4] *= (nf * slev * LEVEL_MINUS_3DB);
1285                     break;
1286                 case AC3_OUTPUT_STEREO:
1287                     nf = 1.0 / (1.0 + clev + slev);
1288                     ctx->chcoeffs[0] *= nf;
1289                     ctx->chcoeffs[2] *= nf;
1290                     ctx->chcoeffs[1] *= (nf * clev);
1291                     ctx->chcoeffs[3] *= (nf * slev);
1292                     ctx->chcoeffs[4] *= (nf * slev);
1293                     break;
1294                 case AC3_OUTPUT_DOLBY:
1295                     nf = 1.0 / (1.0 + (3.0 * LEVEL_MINUS_3DB));
1296                     ctx->chcoeffs[0] *= nf;
1297                     ctx->chcoeffs[1] *= nf;
1298                     ctx->chcoeffs[1] *= (nf * LEVEL_MINUS_3DB);
1299                     ctx->chcoeffs[3] *= (nf * LEVEL_MINUS_3DB);
1300                     ctx->chcoeffs[4] *= (nf * LEVEL_MINUS_3DB);
1301                     break;
1302             }
1303             break;
1304     }
1305 }
1306
1307 /*********** BEGIN DOWNMIX FUNCTIONS ***********/
1308 static inline void mix_dualmono_to_mono(AC3DecodeContext *ctx)
1309 {
1310     int i;
1311     float (*output)[BLOCK_SIZE] = ctx->output;
1312
1313     for (i = 0; i < 256; i++)
1314         output[1][i] += output[2][i];
1315     memset(output[2], 0, sizeof(output[2]));
1316 }
1317
1318 static inline void mix_dualmono_to_stereo(AC3DecodeContext *ctx)
1319 {
1320     int i;
1321     float tmp;
1322     float (*output)[BLOCK_SIZE] = ctx->output;
1323
1324     for (i = 0; i < 256; i++) {
1325         tmp = output[1][i] + output[2][i];
1326         output[1][i] = output[2][i] = tmp;
1327     }
1328 }
1329
1330 static inline void upmix_mono_to_stereo(AC3DecodeContext *ctx)
1331 {
1332     int i;
1333     float (*output)[BLOCK_SIZE] = ctx->output;
1334
1335     for (i = 0; i < 256; i++)
1336         output[2][i] = output[1][i];
1337 }
1338
1339 static inline void mix_stereo_to_mono(AC3DecodeContext *ctx)
1340 {
1341     int i;
1342     float (*output)[BLOCK_SIZE] = ctx->output;
1343
1344     for (i = 0; i < 256; i++)
1345         output[1][i] += output[2][i];
1346     memset(output[2], 0, sizeof(output[2]));
1347 }
1348
1349 static inline void mix_3f_to_mono(AC3DecodeContext *ctx)
1350 {
1351     int i;
1352     float (*output)[BLOCK_SIZE] = ctx->output;
1353
1354     for (i = 0; i < 256; i++)
1355         output[1][i] += (output[2][i] + output[3][i]);
1356     memset(output[2], 0, sizeof(output[2]));
1357     memset(output[3], 0, sizeof(output[3]));
1358 }
1359
1360 static inline void mix_3f_to_stereo(AC3DecodeContext *ctx)
1361 {
1362     int i;
1363     float (*output)[BLOCK_SIZE] = ctx->output;
1364
1365     for (i = 0; i < 256; i++) {
1366         output[1][i] += output[2][i];
1367         output[2][i] += output[3][i];
1368     }
1369     memset(output[3], 0, sizeof(output[3]));
1370 }
1371
1372 static inline void mix_2f_1r_to_mono(AC3DecodeContext *ctx)
1373 {
1374     int i;
1375     float (*output)[BLOCK_SIZE] = ctx->output;
1376
1377     for (i = 0; i < 256; i++)
1378         output[1][i] += (output[2][i] + output[3][i]);
1379     memset(output[2], 0, sizeof(output[2]));
1380     memset(output[3], 0, sizeof(output[3]));
1381
1382 }
1383
1384 static inline void mix_2f_1r_to_stereo(AC3DecodeContext *ctx)
1385 {
1386     int i;
1387     float (*output)[BLOCK_SIZE] = ctx->output;
1388
1389     for (i = 0; i < 256; i++) {
1390         output[1][i] += output[2][i];
1391         output[2][i] += output[3][i];
1392     }
1393     memset(output[3], 0, sizeof(output[3]));
1394 }
1395
1396 static inline void mix_2f_1r_to_dolby(AC3DecodeContext *ctx)
1397 {
1398     int i;
1399     float (*output)[BLOCK_SIZE] = ctx->output;
1400
1401     for (i = 0; i < 256; i++) {
1402         output[1][i] -= output[3][i];
1403         output[2][i] += output[3][i];
1404     }
1405     memset(output[3], 0, sizeof(output[3]));
1406 }
1407
1408 static inline void mix_3f_1r_to_mono(AC3DecodeContext *ctx)
1409 {
1410     int i;
1411     float (*output)[BLOCK_SIZE] = ctx->output;
1412
1413     for (i = 0; i < 256; i++)
1414         output[1][i] = (output[2][i] + output[3][i] + output[4][i]);
1415     memset(output[2], 0, sizeof(output[2]));
1416     memset(output[3], 0, sizeof(output[3]));
1417     memset(output[4], 0, sizeof(output[4]));
1418 }
1419
1420 static inline void mix_3f_1r_to_stereo(AC3DecodeContext *ctx)
1421 {
1422     int i;
1423     float (*output)[BLOCK_SIZE] = ctx->output;
1424
1425     for (i = 0; i < 256; i++) {
1426         output[1][i] += (output[2][i] + output[4][i]);
1427         output[2][i] += (output[3][i] + output[4][i]);
1428     }
1429     memset(output[3], 0, sizeof(output[3]));
1430     memset(output[4], 0, sizeof(output[4]));
1431 }
1432
1433 static inline void mix_3f_1r_to_dolby(AC3DecodeContext *ctx)
1434 {
1435     int i;
1436     float (*output)[BLOCK_SIZE] = ctx->output;
1437
1438     for (i = 0; i < 256; i++) {
1439         output[1][i] += (output[2][i] - output[4][i]);
1440         output[2][i] += (output[3][i] + output[4][i]);
1441     }
1442     memset(output[3], 0, sizeof(output[3]));
1443     memset(output[4], 0, sizeof(output[4]));
1444 }
1445
1446 static inline void mix_2f_2r_to_mono(AC3DecodeContext *ctx)
1447 {
1448     int i;
1449     float (*output)[BLOCK_SIZE] = ctx->output;
1450
1451     for (i = 0; i < 256; i++)
1452         output[1][i] = (output[2][i] + output[3][i] + output[4][i]);
1453     memset(output[2], 0, sizeof(output[2]));
1454     memset(output[3], 0, sizeof(output[3]));
1455     memset(output[4], 0, sizeof(output[4]));
1456 }
1457
1458 static inline void mix_2f_2r_to_stereo(AC3DecodeContext *ctx)
1459 {
1460     int i;
1461     float (*output)[BLOCK_SIZE] = ctx->output;
1462
1463     for (i = 0; i < 256; i++) {
1464         output[1][i] += output[3][i];
1465         output[2][i] += output[4][i];
1466     }
1467     memset(output[3], 0, sizeof(output[3]));
1468     memset(output[4], 0, sizeof(output[4]));
1469 }
1470
1471 static inline void mix_2f_2r_to_dolby(AC3DecodeContext *ctx)
1472 {
1473     int i;
1474     float (*output)[BLOCK_SIZE] = ctx->output;
1475
1476     for (i = 0; i < 256; i++) {
1477         output[1][i] -= output[3][i];
1478         output[2][i] += output[4][i];
1479     }
1480     memset(output[3], 0, sizeof(output[3]));
1481     memset(output[4], 0, sizeof(output[4]));
1482 }
1483
1484 static inline void mix_3f_2r_to_mono(AC3DecodeContext *ctx)
1485 {
1486     int i;
1487     float (*output)[BLOCK_SIZE] = ctx->output;
1488
1489     for (i = 0; i < 256; i++)
1490         output[1][i] += (output[2][i] + output[3][i] + output[4][i] + output[5][i]);
1491     memset(output[2], 0, sizeof(output[2]));
1492     memset(output[3], 0, sizeof(output[3]));
1493     memset(output[4], 0, sizeof(output[4]));
1494     memset(output[5], 0, sizeof(output[5]));
1495 }
1496
1497 static inline void mix_3f_2r_to_stereo(AC3DecodeContext *ctx)
1498 {
1499     int i;
1500     float (*output)[BLOCK_SIZE] = ctx->output;
1501
1502     for (i = 0; i < 256; i++) {
1503         output[1][i] += (output[2][i] + output[4][i]);
1504         output[2][i] += (output[3][i] + output[5][i]);
1505     }
1506     memset(output[3], 0, sizeof(output[3]));
1507     memset(output[4], 0, sizeof(output[4]));
1508     memset(output[5], 0, sizeof(output[5]));
1509 }
1510
1511 static inline void mix_3f_2r_to_dolby(AC3DecodeContext *ctx)
1512 {
1513     int i;
1514     float (*output)[BLOCK_SIZE] = ctx->output;
1515
1516     for (i = 0; i < 256; i++) {
1517         output[1][i] += (output[2][i] - output[4][i] - output[5][i]);
1518         output[2][i] += (output[3][i] + output[4][i] + output[5][i]);
1519     }
1520     memset(output[3], 0, sizeof(output[3]));
1521     memset(output[4], 0, sizeof(output[4]));
1522     memset(output[5], 0, sizeof(output[5]));
1523 }
1524 /*********** END DOWNMIX FUNCTIONS ***********/
1525
1526 /* Downmix the output.
1527  * This function downmixes the output when the number of input
1528  * channels is not equal to the number of output channels requested.
1529  */
1530 static void do_downmix(AC3DecodeContext *ctx)
1531 {
1532     int from = ctx->acmod;
1533     int to = ctx->blkoutput;
1534
1535     if (to == AC3_OUTPUT_UNMODIFIED)
1536         return;
1537
1538     switch (from) {
1539         case AC3_INPUT_DUALMONO:
1540             switch (to) {
1541                 case AC3_OUTPUT_MONO:
1542                     mix_dualmono_to_mono(ctx);
1543                     break;
1544                 case AC3_OUTPUT_STEREO: /* We assume that sum of both mono channels is requested */
1545                     mix_dualmono_to_stereo(ctx);
1546                     break;
1547             }
1548             break;
1549         case AC3_INPUT_MONO:
1550             switch (to) {
1551                 case AC3_OUTPUT_STEREO:
1552                     upmix_mono_to_stereo(ctx);
1553                     break;
1554             }
1555             break;
1556         case AC3_INPUT_STEREO:
1557             switch (to) {
1558                 case AC3_OUTPUT_MONO:
1559                     mix_stereo_to_mono(ctx);
1560                     break;
1561             }
1562             break;
1563         case AC3_INPUT_3F:
1564             switch (to) {
1565                 case AC3_OUTPUT_MONO:
1566                     mix_3f_to_mono(ctx);
1567                     break;
1568                 case AC3_OUTPUT_STEREO:
1569                     mix_3f_to_stereo(ctx);
1570                     break;
1571             }
1572             break;
1573         case AC3_INPUT_2F_1R:
1574             switch (to) {
1575                 case AC3_OUTPUT_MONO:
1576                     mix_2f_1r_to_mono(ctx);
1577                     break;
1578                 case AC3_OUTPUT_STEREO:
1579                     mix_2f_1r_to_stereo(ctx);
1580                     break;
1581                 case AC3_OUTPUT_DOLBY:
1582                     mix_2f_1r_to_dolby(ctx);
1583                     break;
1584             }
1585             break;
1586         case AC3_INPUT_3F_1R:
1587             switch (to) {
1588                 case AC3_OUTPUT_MONO:
1589                     mix_3f_1r_to_mono(ctx);
1590                     break;
1591                 case AC3_OUTPUT_STEREO:
1592                     mix_3f_1r_to_stereo(ctx);
1593                     break;
1594                 case AC3_OUTPUT_DOLBY:
1595                     mix_3f_1r_to_dolby(ctx);
1596                     break;
1597             }
1598             break;
1599         case AC3_INPUT_2F_2R:
1600             switch (to) {
1601                 case AC3_OUTPUT_MONO:
1602                     mix_2f_2r_to_mono(ctx);
1603                     break;
1604                 case AC3_OUTPUT_STEREO:
1605                     mix_2f_2r_to_stereo(ctx);
1606                     break;
1607                 case AC3_OUTPUT_DOLBY:
1608                     mix_2f_2r_to_dolby(ctx);
1609                     break;
1610             }
1611             break;
1612         case AC3_INPUT_3F_2R:
1613             switch (to) {
1614                 case AC3_OUTPUT_MONO:
1615                     mix_3f_2r_to_mono(ctx);
1616                     break;
1617                 case AC3_OUTPUT_STEREO:
1618                     mix_3f_2r_to_stereo(ctx);
1619                     break;
1620                 case AC3_OUTPUT_DOLBY:
1621                     mix_3f_2r_to_dolby(ctx);
1622                     break;
1623             }
1624             break;
1625     }
1626 }
1627
1628 static void dump_floats(const char *name, int prec, const float *tab, int n)
1629 {
1630     int i;
1631
1632     av_log(NULL, AV_LOG_INFO, "%s[%d]:\n", name, n);
1633     for(i=0;i<n;i++) {
1634         if ((i & 7) == 0)
1635             av_log(NULL, AV_LOG_INFO, "%4d: ", i);
1636         av_log(NULL, AV_LOG_INFO, " %8.*f", prec, tab[i]);
1637         if ((i & 7) == 7)
1638             av_log(NULL, AV_LOG_INFO, "\n");
1639     }
1640     if ((i & 7) != 0)
1641         av_log(NULL, AV_LOG_INFO, "\n");
1642 }
1643
1644 /* This function performs the imdct on 256 sample transform
1645  * coefficients.
1646  */
1647 static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
1648 {
1649     int k;
1650     float x1[128], x2[128];
1651     float *o_ptr, *d_ptr, *w;
1652     FFTComplex *ptr1, *ptr2;
1653
1654     for (k = 0; k < N / 4; k++) {
1655         x1[k] = ctx->transform_coeffs[chindex][2 * k];
1656         x2[k] = ctx->transform_coeffs[chindex][2 * k + 1];
1657     }
1658
1659     ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, ctx->tmp_output, x1, ctx->tmp_imdct);
1660     ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, ctx->tmp_output + 256, x2, ctx->tmp_imdct);
1661
1662     o_ptr = ctx->output[chindex];
1663     d_ptr = ctx->delay[chindex];
1664     ptr1 = (FFTComplex *)ctx->tmp_output;
1665     ptr2 = (FFTComplex *)ctx->tmp_output + 256;
1666     w = ctx->window;
1667
1668     for (k = 0; k < N / 8; k++)
1669     {
1670         o_ptr[2 * k] = -ptr1[k].im * w[2 * k] + d_ptr[2 * k] + 384.0;
1671         o_ptr[2 * k + 1] = ptr1[N / 8 - k - 1].re * w[2 * k + 1] + 384.0;
1672         o_ptr[N / 4 + 2 * k] = -ptr1[k].re * w[N / 4 + 2 * k] + d_ptr[N / 4 + 2 * k] + 384.0;
1673         o_ptr[N / 4 + 2 * k + 1] = ptr1[N / 8 - k - 1].im * w[N / 4 + 2 * k + 1] + d_ptr[N / 4 + 2 * k + 1] + 384.0;
1674         d_ptr[2 * k] = ptr2[k].re * w[k / 2 - 2 * k - 1];
1675         d_ptr[2 * k + 1] = -ptr2[N / 8 - k - 1].im * w[N / 2 - 2 * k - 2];
1676         d_ptr[N / 4 + 2 * k] = ptr2[k].im * w[N / 4 - 2 * k - 1];
1677         d_ptr[N / 4 + 2 * k + 1] = -ptr2[N / 8 - k - 1].re * w[N / 4 - 2 * k - 2];
1678     }
1679 }
1680
1681 /* This function performs the imdct on 512 sample transform
1682  * coefficients.
1683  */
1684 static void do_imdct_512(AC3DecodeContext *ctx, int chindex)
1685 {
1686     float *ptr;
1687
1688     ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
1689                                   ctx->transform_coeffs[chindex], ctx->tmp_imdct);
1690     ptr = ctx->output[chindex];
1691     ctx->dsp.vector_fmul_add_add(ptr, ctx->tmp_output, ctx->window, ctx->delay[chindex], 384, BLOCK_SIZE, 1);
1692     ptr = ctx->delay[chindex];
1693     ctx->dsp.vector_fmul_reverse(ptr, ctx->tmp_output + 256, ctx->window, BLOCK_SIZE);
1694 }
1695
1696 /* IMDCT Transform. */
1697 static inline void do_imdct(AC3DecodeContext *ctx)
1698 {
1699     int i;
1700
1701     if (ctx->blkoutput & AC3_OUTPUT_LFEON) {
1702         do_imdct_512(ctx, 0);
1703     }
1704     for (i = 0; i < ctx->nfchans; i++) {
1705         if ((ctx->blksw >> i) & 1)
1706             do_imdct_256(ctx, i + 1);
1707         else
1708             do_imdct_512(ctx, i + 1);
1709     }
1710 }
1711
1712 /* Parse the audio block from ac3 bitstream.
1713  * This function extract the audio block from the ac3 bitstream
1714  * and produces the output for the block. This function must
1715  * be called for each of the six audio block in the ac3 bitstream.
1716  */
1717 static int ac3_parse_audio_block(AC3DecodeContext * ctx)
1718 {
1719     int nfchans = ctx->nfchans;
1720     int acmod = ctx->acmod;
1721     int i, bnd, rbnd, seg, grpsize;
1722     GetBitContext *gb = &ctx->gb;
1723     int bit_alloc_flags = 0;
1724     uint8_t *dexps;
1725     int mstrcplco, cplcoexp, cplcomant;
1726     int dynrng, chbwcod, ngrps, cplabsexp, skipl;
1727
1728     ctx->blksw = 0;
1729     for (i = 0; i < nfchans; i++) /*block switch flag */
1730         ctx->blksw |= get_bits1(gb) << i;
1731
1732     ctx->dithflag = 0;
1733     for (i = 0; i < nfchans; i++) /* dithering flag */
1734         ctx->dithflag |= get_bits1(gb) << i;
1735
1736     if (get_bits1(gb)) { /* dynamic range */
1737         dynrng = get_sbits(gb, 8);
1738         ctx->dynrng = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
1739     }
1740
1741     if (acmod == 0x00 && get_bits1(gb)) { /* dynamic range 1+1 mode */
1742         dynrng = get_sbits(gb, 8);
1743         ctx->dynrng2 = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
1744     }
1745
1746     get_downmix_coeffs(ctx);
1747
1748     if (get_bits1(gb)) { /* coupling strategy */
1749         ctx->cplinu = get_bits1(gb);
1750         ctx->cplbndstrc = 0;
1751         ctx->chincpl = 0;
1752         if (ctx->cplinu) { /* coupling in use */
1753             for (i = 0; i < nfchans; i++)
1754                 ctx->chincpl |= get_bits1(gb) << i;
1755
1756             if (acmod == 0x02)
1757                 ctx->phsflginu = get_bits1(gb); //phase flag in use
1758
1759             ctx->cplbegf = get_bits(gb, 4);
1760             ctx->cplendf = get_bits(gb, 4);
1761
1762             if (3 + ctx->cplendf - ctx->cplbegf < 0) {
1763                 av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", ctx->cplendf, ctx->cplbegf);
1764                 return -1;
1765             }
1766
1767             ctx->ncplbnd = ctx->ncplsubnd = 3 + ctx->cplendf - ctx->cplbegf;
1768             ctx->cplstrtmant = ctx->cplbegf * 12 + 37;
1769             ctx->cplendmant = ctx->cplendf * 12 + 73;
1770             for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
1771                 if (get_bits1(gb)) {
1772                     ctx->cplbndstrc |= 1 << i;
1773                     ctx->ncplbnd--;
1774                 }
1775         }
1776     }
1777
1778     if (ctx->cplinu) {
1779         ctx->cplcoe = 0;
1780
1781         for (i = 0; i < nfchans; i++)
1782             if ((ctx->chincpl) >> i & 1)
1783                 if (get_bits1(gb)) { /* coupling co-ordinates */
1784                     ctx->cplcoe |= 1 << i;
1785                     mstrcplco = 3 * get_bits(gb, 2);
1786                     for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
1787                         cplcoexp = get_bits(gb, 4);
1788                         cplcomant = get_bits(gb, 4);
1789                         if (cplcoexp == 15)
1790                             cplcomant <<= 14;
1791                         else
1792                             cplcomant = (cplcomant | 0x10) << 13;
1793                         ctx->cplco[i][bnd] = cplcomant * scale_factors[cplcoexp + mstrcplco];
1794                     }
1795                 }
1796
1797         if (acmod == 0x02 && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
1798             for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
1799                 if (get_bits1(gb))
1800                     ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
1801     }
1802
1803     if (acmod == 0x02) {/* rematrixing */
1804         ctx->rematstr = get_bits1(gb);
1805         if (ctx->rematstr) {
1806             ctx->rematflg = 0;
1807
1808             if (!(ctx->cplinu) || ctx->cplbegf > 2)
1809                 for (rbnd = 0; rbnd < 4; rbnd++)
1810                     ctx->rematflg |= get_bits1(gb) << rbnd;
1811             if (ctx->cplbegf > 0 && ctx->cplbegf <= 2 && ctx->cplinu)
1812                 for (rbnd = 0; rbnd < 3; rbnd++)
1813                     ctx->rematflg |= get_bits1(gb) << rbnd;
1814             if (ctx->cplbegf == 0 && ctx->cplinu)
1815                 for (rbnd = 0; rbnd < 2; rbnd++)
1816                     ctx->rematflg |= get_bits1(gb) << rbnd;
1817         }
1818     }
1819
1820     ctx->cplexpstr = AC3_EXPSTR_REUSE;
1821     ctx->lfeexpstr = AC3_EXPSTR_REUSE;
1822     if (ctx->cplinu) /* coupling exponent strategy */
1823         ctx->cplexpstr = get_bits(gb, 2);
1824     for (i = 0; i < nfchans; i++)  /* channel exponent strategy */
1825         ctx->chexpstr[i] = get_bits(gb, 2);
1826     if (ctx->lfeon)  /* lfe exponent strategy */
1827         ctx->lfeexpstr = get_bits1(gb);
1828
1829     for (i = 0; i < nfchans; i++) /* channel bandwidth code */
1830         if (ctx->chexpstr[i] != AC3_EXPSTR_REUSE) {
1831             if ((ctx->chincpl >> i) & 1)
1832                 ctx->endmant[i] = ctx->cplstrtmant;
1833             else {
1834                 chbwcod = get_bits(gb, 6);
1835                 if (chbwcod > 60) {
1836                     av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
1837                     return -1;
1838                 }
1839                 ctx->endmant[i] = chbwcod * 3 + 73;
1840             }
1841         }
1842
1843     if (ctx->cplexpstr != AC3_EXPSTR_REUSE) {/* coupling exponents */
1844         bit_alloc_flags = 64;
1845         cplabsexp = get_bits(gb, 4) << 1;
1846         ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
1847         if (decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant)) {
1848             av_log(NULL, AV_LOG_ERROR, "error decoding coupling exponents\n");
1849             return -1;
1850         }
1851     }
1852
1853     for (i = 0; i < nfchans; i++) /* fbw channel exponents */
1854         if (ctx->chexpstr[i] != AC3_EXPSTR_REUSE) {
1855             bit_alloc_flags |= 1 << i;
1856             grpsize = 3 << (ctx->chexpstr[i] - 1);
1857             ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
1858             dexps = ctx->dexps[i];
1859             dexps[0] = get_bits(gb, 4);
1860             if (decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1)) {
1861                 av_log(NULL, AV_LOG_ERROR, "error decoding channel %d exponents\n", i);
1862                 return -1;
1863             }
1864             skip_bits(gb, 2); /* skip gainrng */
1865         }
1866
1867     if (ctx->lfeexpstr != AC3_EXPSTR_REUSE) { /* lfe exponents */
1868         bit_alloc_flags |= 32;
1869         ctx->dlfeexps[0] = get_bits(gb, 4);
1870         if (decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1)) {
1871             av_log(NULL, AV_LOG_ERROR, "error decoding lfe exponents\n");
1872             return -1;
1873         }
1874     }
1875
1876     if (get_bits1(gb)) { /* bit allocation information */
1877         bit_alloc_flags = 127;
1878         ctx->sdcycod = get_bits(gb, 2);
1879         ctx->fdcycod = get_bits(gb, 2);
1880         ctx->sgaincod = get_bits(gb, 2);
1881         ctx->dbpbcod = get_bits(gb, 2);
1882         ctx->floorcod = get_bits(gb, 3);
1883     }
1884
1885     if (get_bits1(gb)) { /* snroffset */
1886         bit_alloc_flags = 127;
1887         ctx->csnroffst = get_bits(gb, 6);
1888         if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
1889             ctx->cplfsnroffst = get_bits(gb, 4);
1890             ctx->cplfgaincod = get_bits(gb, 3);
1891         }
1892         for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
1893             ctx->fsnroffst[i] = get_bits(gb, 4);
1894             ctx->fgaincod[i] = get_bits(gb, 3);
1895         }
1896         if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
1897             ctx->lfefsnroffst = get_bits(gb, 4);
1898             ctx->lfefgaincod = get_bits(gb, 3);
1899         }
1900     }
1901
1902     if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
1903         bit_alloc_flags |= 64;
1904         ctx->cplfleak = get_bits(gb, 3);
1905         ctx->cplsleak = get_bits(gb, 3);
1906     }
1907
1908     if (get_bits1(gb)) { /* delta bit allocation information */
1909         bit_alloc_flags = 127;
1910
1911         if (ctx->cplinu) {
1912             ctx->cpldeltbae = get_bits(gb, 2);
1913             if (ctx->cpldeltbae == AC3_DBASTR_RESERVED) {
1914                 av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
1915                 return -1;
1916             }
1917         }
1918
1919         for (i = 0; i < nfchans; i++) {
1920             ctx->deltbae[i] = get_bits(gb, 2);
1921             if (ctx->deltbae[i] == AC3_DBASTR_RESERVED) {
1922                 av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
1923                 return -1;
1924             }
1925         }
1926
1927         if (ctx->cplinu)
1928             if (ctx->cpldeltbae == AC3_DBASTR_NEW) { /*coupling delta offset, len and bit allocation */
1929                 ctx->cpldeltnseg = get_bits(gb, 3);
1930                 for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
1931                     ctx->cpldeltoffst[seg] = get_bits(gb, 5);
1932                     ctx->cpldeltlen[seg] = get_bits(gb, 4);
1933                     ctx->cpldeltba[seg] = get_bits(gb, 3);
1934                 }
1935             }
1936
1937         for (i = 0; i < nfchans; i++)
1938             if (ctx->deltbae[i] == AC3_DBASTR_NEW) {/*channel delta offset, len and bit allocation */
1939                 ctx->deltnseg[i] = get_bits(gb, 3);
1940                 for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
1941                     ctx->deltoffst[i][seg] = get_bits(gb, 5);
1942                     ctx->deltlen[i][seg] = get_bits(gb, 4);
1943                     ctx->deltba[i][seg] = get_bits(gb, 3);
1944                 }
1945             }
1946     }
1947
1948     if (bit_alloc_flags) {
1949         if (is_snr_offsets_zero(ctx)) {
1950             memset(ctx->cplbap, 0, sizeof (ctx->cplbap));
1951             memset(ctx->lfebap, 0, sizeof (ctx->lfebap));
1952             for (i = 0; i < nfchans; i++)
1953                 memset(ctx->bap[i], 0, sizeof(ctx->bap[i]));
1954         } else {
1955             if (ctx->chincpl && (bit_alloc_flags & 64))
1956                 do_bit_allocation(ctx, 5);
1957             for (i = 0; i < nfchans; i++)
1958                 if ((bit_alloc_flags >> i) & 1)
1959                     do_bit_allocation(ctx, i);
1960             if (ctx->lfeon && (bit_alloc_flags & 32))
1961                 do_bit_allocation(ctx, 6);
1962         }
1963     }
1964
1965     if (get_bits1(gb)) { /* unused dummy data */
1966         skipl = get_bits(gb, 9);
1967         while(skipl--)
1968             skip_bits(gb, 8);
1969     }
1970     /* unpack the transform coefficients
1971      * * this also uncouples channels if coupling is in use.
1972      */
1973     if (get_transform_coeffs(ctx)) {
1974         av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
1975         return -1;
1976     }
1977     /*for (i = 0; i < nfchans; i++)
1978         dump_floats("channel transform coefficients", 10, ctx->transform_coeffs[i + 1], BLOCK_SIZE);*/
1979
1980     /* recover coefficients if rematrixing is in use */
1981     if (ctx->rematflg)
1982         do_rematrixing(ctx);
1983
1984     do_downmix(ctx);
1985
1986     do_imdct(ctx);
1987     /*for(i = 0; i < nfchans; i++)
1988         dump_floats("channel output", 10, ctx->output[i + 1], BLOCK_SIZE);*/
1989
1990     return 0;
1991 }
1992
1993 static inline int16_t convert(int32_t i)
1994 {
1995     if (i > 0x43c07fff)
1996         return 32767;
1997     else if (i <= 0x43bf8000)
1998         return -32768;
1999     else
2000         return (i - 0x43c00000);
2001 }
2002
2003 static int frame_count = 0;
2004
2005 /* Decode ac3 frame.
2006  *
2007  * @param avctx Pointer to AVCodecContext
2008  * @param data Pointer to pcm smaples
2009  * @param data_size Set to number of pcm samples produced by decoding
2010  * @param buf Data to be decoded
2011  * @param buf_size Size of the buffer
2012  */
2013 static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
2014 {
2015     AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
2016     int frame_start;
2017     int16_t *out_samples = (int16_t *)data;
2018     int i, j, k, start;
2019     int32_t *int_ptr[6];
2020
2021     for (i = 0; i < 6; i++)
2022         int_ptr[i] = (int32_t *)(&ctx->output[i]);
2023
2024     //av_log(NULL, AV_LOG_INFO, "decoding frame %d buf_size = %d\n", frame_count++, buf_size);
2025
2026     //Synchronize the frame.
2027     frame_start = ac3_synchronize(buf, buf_size);
2028     if (frame_start == -1) {
2029         av_log(avctx, AV_LOG_ERROR, "frame is not synchronized\n");
2030         *data_size = 0;
2031         return buf_size;
2032     }
2033
2034     //Initialize the GetBitContext with the start of valid AC3 Frame.
2035     init_get_bits(&(ctx->gb), buf + frame_start, (buf_size - frame_start) * 8);
2036
2037     //Parse the syncinfo.
2038     //If 'fscod' or 'bsid' is not valid the decoder shall mute as per the standard.
2039     if (!ac3_parse_sync_info(ctx)) {
2040         av_log(avctx, AV_LOG_ERROR, "\n");
2041         *data_size = 0;
2042         return buf_size;
2043     }
2044
2045     //Parse the BSI.
2046     //If 'bsid' is not valid decoder shall not decode the audio as per the standard.
2047     ac3_parse_bsi(ctx);
2048
2049     avctx->sample_rate = ctx->sampling_rate;
2050     avctx->bit_rate = ctx->bit_rate;
2051
2052     if (avctx->channels == 0) {
2053         ctx->blkoutput |= AC3_OUTPUT_UNMODIFIED;
2054         if (ctx->lfeon)
2055             ctx->blkoutput |= AC3_OUTPUT_LFEON;
2056         avctx->channels = ctx->nfchans + ctx->lfeon;
2057     }
2058     else if (avctx->channels == 1)
2059         ctx->blkoutput |= AC3_OUTPUT_MONO;
2060     else if (avctx->channels == 2) {
2061         if (ctx->dsurmod == 0x02)
2062             ctx->blkoutput |= AC3_OUTPUT_DOLBY;
2063         else
2064             ctx->blkoutput |= AC3_OUTPUT_STEREO;
2065     }
2066     else {
2067         if (avctx->channels < (ctx->nfchans + ctx->lfeon))
2068             av_log(avctx, AV_LOG_INFO, "ac3_decoder: AC3 Source Channels Are Less Then Specified %d: Output to %d Channels\n",avctx->channels, ctx->nfchans + ctx->lfeon);
2069         ctx->blkoutput |= AC3_OUTPUT_UNMODIFIED;
2070         if (ctx->lfeon)
2071             ctx->blkoutput |= AC3_OUTPUT_LFEON;
2072         avctx->channels = ctx->nfchans + ctx->lfeon;
2073     }
2074
2075     //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);
2076
2077     //Parse the Audio Blocks.
2078     for (i = 0; i < AUDIO_BLOCKS; i++) {
2079         if (ac3_parse_audio_block(ctx)) {
2080             av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
2081             *data_size = 0;
2082             return ctx->frame_size;
2083         }
2084         start = (ctx->blkoutput & AC3_OUTPUT_LFEON) ? 0 : 1;
2085         for (k = 0; k < BLOCK_SIZE; k++)
2086             for (j = start; j <= avctx->channels; j++)
2087                 *(out_samples++) = convert(int_ptr[j][k]);
2088     }
2089     *data_size = AUDIO_BLOCKS * BLOCK_SIZE * avctx->channels * sizeof (int16_t);
2090     return ctx->frame_size;
2091 }
2092
2093 /* Uninitialize ac3 decoder.
2094  */
2095 static int ac3_decode_end(AVCodecContext *avctx)
2096 {
2097     AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
2098     ff_mdct_end(&ctx->imdct_512);
2099     ff_mdct_end(&ctx->imdct_256);
2100
2101     return 0;
2102 }
2103
2104 AVCodec lgpl_ac3_decoder = {
2105     .name = "ac3",
2106     .type = CODEC_TYPE_AUDIO,
2107     .id = CODEC_ID_AC3,
2108     .priv_data_size = sizeof (AC3DecodeContext),
2109     .init = ac3_decode_init,
2110     .close = ac3_decode_end,
2111     .decode = ac3_decode_frame,
2112 };
2113