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