3 * This code is developed as part of Google Summer of Code 2006 Program.
5 * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com).
6 * Copyright (c) 2007 Justin Ruggles
8 * Portions of this code are derived from liba52
9 * http://liba52.sourceforge.net
10 * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
11 * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
13 * This file is part of FFmpeg.
15 * FFmpeg is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU General Public
17 * License as published by the Free Software Foundation; either
18 * version 2 of the License, or (at your option) any later version.
20 * FFmpeg is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * General Public License for more details.
25 * You should have received a copy of the GNU General Public
26 * License along with FFmpeg; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
36 #include "ac3_parser.h"
37 #include "bitstream.h"
41 /* table for exponent to scale_factor mapping
42 * scale_factor[i] = 2 ^ -(i + 15)
44 static float scale_factors[25];
46 /** table for grouping exponents */
47 static uint8_t exp_ungroup_tbl[128][3];
49 static int16_t l3_quantizers_1[32];
50 static int16_t l3_quantizers_2[32];
51 static int16_t l3_quantizers_3[32];
53 static int16_t l5_quantizers_1[128];
54 static int16_t l5_quantizers_2[128];
55 static int16_t l5_quantizers_3[128];
57 static int16_t l7_quantizers[7];
59 static int16_t l11_quantizers_1[128];
60 static int16_t l11_quantizers_2[128];
62 static int16_t l15_quantizers[15];
64 static const uint8_t qntztab[16] = { 0, 5, 7, 3, 7, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16 };
66 /* Adjustmens in dB gain */
67 #define LEVEL_MINUS_3DB 0.7071067811865476
68 #define LEVEL_MINUS_4POINT5DB 0.5946035575013605
69 #define LEVEL_MINUS_6DB 0.5000000000000000
70 #define LEVEL_PLUS_3DB 1.4142135623730951
71 #define LEVEL_PLUS_6DB 2.0000000000000000
72 #define LEVEL_ZERO 0.0000000000000000
74 static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
75 LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
77 static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
79 #define BLOCK_SIZE 256
81 #define AC3_OUTPUT_LFEON 8
89 int blksw[AC3_MAX_CHANNELS];
90 int dithflag[AC3_MAX_CHANNELS];
92 int chincpl[AC3_MAX_CHANNELS];
99 int rematflg[AC3_MAX_CHANNELS];
112 uint8_t cpldeltoffst[8];
113 uint8_t cpldeltlen[8];
114 uint8_t cpldeltba[8];
116 uint8_t deltoffst[5][8];
117 uint8_t deltlen[5][8];
118 uint8_t deltba[5][8];
120 /* Derived Attributes. */
125 int nchans; //number of total channels
126 int nfchans; //number of full-bandwidth channels
127 int lfeon; //lfe channel in use
128 int output_mode; ///< output channel configuration
129 int out_channels; ///< number of output channels
131 float dynrng; //dynamic range gain
132 float dynrng2; //dynamic range gain for 1+1 mode
133 float cplco[5][18]; //coupling coordinates
134 int ncplbnd; //number of coupling bands
135 int ncplsubnd; //number of coupling sub bands
136 int cplstrtmant; //coupling start mantissa
137 int cplendmant; //coupling end mantissa
138 int endmant[5]; //channel end mantissas
139 AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
141 int8_t dcplexps[256]; //decoded coupling exponents
142 int8_t dexps[5][256]; //decoded fbw channel exponents
143 int8_t dlfeexps[256]; //decoded lfe channel exponents
144 uint8_t cplbap[256]; //coupling bit allocation pointers
145 uint8_t bap[5][256]; //fbw channel bit allocation pointers
146 uint8_t lfebap[256]; //lfe channel bit allocation pointers
148 DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][BLOCK_SIZE]); //transform coefficients
151 MDCTContext imdct_512; //for 512 sample imdct transform
152 MDCTContext imdct_256; //for 256 sample imdct transform
153 DSPContext dsp; //for optimization
155 DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS][BLOCK_SIZE]); //output after imdct transform and windowing
156 DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS][BLOCK_SIZE]); //delay - added to the next block
157 DECLARE_ALIGNED_16(float, tmp_imdct[BLOCK_SIZE]); //temporary storage for imdct transform
158 DECLARE_ALIGNED_16(float, tmp_output[BLOCK_SIZE * 2]); //temporary storage for output before windowing
159 DECLARE_ALIGNED_16(float, window[BLOCK_SIZE]); //window coefficients
163 AVRandomState dith_state; //for dither generation
166 /*********** BEGIN INIT HELPER FUNCTIONS ***********/
168 * Generate a Kaiser-Bessel Derived Window.
170 static void ac3_window_init(float *window)
173 double sum = 0.0, bessel, tmp;
174 double local_window[256];
175 double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
177 for (i = 0; i < 256; i++) {
178 tmp = i * (256 - i) * alpha2;
180 for (j = 100; j > 0; j--) /* defaul to 100 iterations */
181 bessel = bessel * tmp / (j * j) + 1;
183 local_window[i] = sum;
187 for (i = 0; i < 256; i++)
188 window[i] = sqrt(local_window[i] / sum);
192 * Generate quantizer tables.
194 static void generate_quantizers_table(int16_t quantizers[], int level, int length)
198 for (i = 0; i < length; i++)
199 quantizers[i] = ((2 * i - level + 1) << 15) / level;
202 static void generate_quantizers_table_1(int16_t quantizers[], int level, int length1, int length2, int size)
207 for (i = 0; i < length1; i++) {
208 v = ((2 * i - level + 1) << 15) / level;
209 for (j = 0; j < length2; j++)
210 quantizers[i * length2 + j] = v;
213 for (i = length1 * length2; i < size; i++)
217 static void generate_quantizers_table_2(int16_t quantizers[], int level, int length1, int length2, int size)
222 for (i = 0; i < length1; i++) {
223 v = ((2 * (i % level) - level + 1) << 15) / level;
224 for (j = 0; j < length2; j++)
225 quantizers[i * length2 + j] = v;
228 for (i = length1 * length2; i < size; i++)
233 static void generate_quantizers_table_3(int16_t quantizers[], int level, int length1, int length2, int size)
237 for (i = 0; i < length1; i++)
238 for (j = 0; j < length2; j++)
239 quantizers[i * length2 + j] = ((2 * (j % level) - level + 1) << 15) / level;
241 for (i = length1 * length2; i < size; i++)
246 * Initialize tables at runtime.
248 static void ac3_tables_init(void)
252 /* Quantizer ungrouping tables. */
253 // for level-3 quantizers
254 generate_quantizers_table_1(l3_quantizers_1, 3, 3, 9, 32);
255 generate_quantizers_table_2(l3_quantizers_2, 3, 9, 3, 32);
256 generate_quantizers_table_3(l3_quantizers_3, 3, 9, 3, 32);
258 //for level-5 quantizers
259 generate_quantizers_table_1(l5_quantizers_1, 5, 5, 25, 128);
260 generate_quantizers_table_2(l5_quantizers_2, 5, 25, 5, 128);
261 generate_quantizers_table_3(l5_quantizers_3, 5, 25, 5, 128);
263 //for level-7 quantizers
264 generate_quantizers_table(l7_quantizers, 7, 7);
266 //for level-4 quantizers
267 generate_quantizers_table_2(l11_quantizers_1, 11, 11, 11, 128);
268 generate_quantizers_table_3(l11_quantizers_2, 11, 11, 11, 128);
270 //for level-15 quantizers
271 generate_quantizers_table(l15_quantizers, 15, 15);
272 /* End Quantizer ungrouping tables. */
274 //generate scale factors
275 for (i = 0; i < 25; i++)
276 scale_factors[i] = pow(2.0, -(i + 15));
278 /* generate exponent tables
279 reference: Section 7.1.3 Exponent Decoding */
280 for(i=0; i<128; i++) {
281 exp_ungroup_tbl[i][0] = i / 25;
282 exp_ungroup_tbl[i][1] = (i % 25) / 5;
283 exp_ungroup_tbl[i][2] = (i % 25) % 5;
288 static int ac3_decode_init(AVCodecContext *avctx)
290 AC3DecodeContext *ctx = avctx->priv_data;
294 ff_mdct_init(&ctx->imdct_256, 8, 1);
295 ff_mdct_init(&ctx->imdct_512, 9, 1);
296 ac3_window_init(ctx->window);
297 dsputil_init(&ctx->dsp, avctx);
298 av_init_random(0, &ctx->dith_state);
302 /*********** END INIT FUNCTIONS ***********/
305 * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
306 * GetBitContext within AC3DecodeContext must point to
307 * start of the synchronized ac3 bitstream.
309 static int ac3_parse_header(AC3DecodeContext *ctx)
312 GetBitContext *gb = &ctx->gb;
315 err = ff_ac3_parse_header(gb->buffer, &hdr);
319 /* get decoding parameters from header info */
320 ctx->bit_alloc_params.fscod = hdr.fscod;
321 ctx->acmod = hdr.acmod;
322 ctx->cmixlev = hdr.cmixlev;
323 ctx->surmixlev = hdr.surmixlev;
324 ctx->dsurmod = hdr.dsurmod;
325 ctx->lfeon = hdr.lfeon;
326 ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
327 ctx->sampling_rate = hdr.sample_rate;
328 ctx->bit_rate = hdr.bit_rate;
329 ctx->nchans = hdr.channels;
330 ctx->nfchans = ctx->nchans - ctx->lfeon;
331 ctx->frame_size = hdr.frame_size;
333 /* set default output to all source channels */
334 ctx->out_channels = ctx->nchans;
335 ctx->output_mode = ctx->acmod;
337 ctx->output_mode |= AC3_OUTPUT_LFEON;
339 /* skip over portion of header which has already been read */
340 skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
341 skip_bits(gb, 16); // skip crc1
342 skip_bits(gb, 8); // skip fscod and frmsizecod
343 skip_bits(gb, 11); // skip bsid, bsmod, and acmod
344 if(ctx->acmod == AC3_ACMOD_STEREO) {
345 skip_bits(gb, 2); // skip dsurmod
347 if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
348 skip_bits(gb, 2); // skip cmixlev
350 skip_bits(gb, 2); // skip surmixlev
352 skip_bits1(gb); // skip lfeon
354 /* read the rest of the bsi. read twice for dual mono mode. */
357 skip_bits(gb, 5); //skip dialog normalization
359 skip_bits(gb, 8); //skip compression
361 skip_bits(gb, 8); //skip language code
363 skip_bits(gb, 7); //skip audio production information
366 skip_bits(gb, 2); //skip copyright bit and original bitstream bit
368 /* FIXME: read & use the xbsi1 downmix levels */
370 skip_bits(gb, 14); //skip timecode1
372 skip_bits(gb, 14); //skip timecode2
375 i = get_bits(gb, 6); //additional bsi length
385 * Decodes the grouped exponents.
386 * This function decodes the coded exponents according to exponent strategy
387 * and stores them in the decoded exponents buffer.
389 * @param[in] gb GetBitContext which points to start of coded exponents
390 * @param[in] expstr Exponent coding strategy
391 * @param[in] ngrps Number of grouped exponents
392 * @param[in] absexp Absolute exponent or DC exponent
393 * @param[out] dexps Decoded exponents are stored in dexps
395 static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
396 uint8_t absexp, int8_t *dexps)
398 int i, j, grp, grpsize;
403 grpsize = expstr + (expstr == EXP_D45);
404 for(grp=0,i=0; grp<ngrps; grp++) {
405 expacc = get_bits(gb, 7);
406 dexp[i++] = exp_ungroup_tbl[expacc][0];
407 dexp[i++] = exp_ungroup_tbl[expacc][1];
408 dexp[i++] = exp_ungroup_tbl[expacc][2];
411 /* convert to absolute exps and expand groups */
413 for(i=0; i<ngrps*3; i++) {
414 prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
415 for(j=0; j<grpsize; j++) {
416 dexps[(i*grpsize)+j] = prevexp;
421 typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
422 int16_t l3_quantizers[3];
423 int16_t l5_quantizers[3];
424 int16_t l11_quantizers[2];
430 /* Get the transform coefficients for coupling channel and uncouple channels.
431 * The coupling transform coefficients starts at the the cplstrtmant, which is
432 * equal to endmant[ch] for fbw channels. Hence we can uncouple channels before
433 * getting transform coefficients for the channel.
435 static int get_transform_coeffs_cpling(AC3DecodeContext *ctx, mant_groups *m)
437 GetBitContext *gb = &ctx->gb;
438 int ch, start, end, cplbndstrc, bnd, gcode, tbap;
439 float cplcos[5], cplcoeff;
440 uint8_t *exps = ctx->dcplexps;
441 uint8_t *bap = ctx->cplbap;
443 cplbndstrc = ctx->cplbndstrc;
444 start = ctx->cplstrtmant;
447 while (start < ctx->cplendmant) {
449 while (cplbndstrc & 1) {
454 for (ch = 0; ch < ctx->nfchans; ch++)
455 cplcos[ch] = ctx->cplco[ch][bnd];
458 while (start < end) {
462 for (ch = 0; ch < ctx->nfchans; ch++)
463 if (ctx->chincpl[ch]) {
464 if (ctx->dithflag[ch]) {
465 cplcoeff = (av_random(&ctx->dith_state) & 0xFFFF) * scale_factors[exps[start]];
466 ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch] * LEVEL_MINUS_3DB;
468 ctx->transform_coeffs[ch + 1][start] = 0;
474 gcode = get_bits(gb, 5);
475 m->l3_quantizers[0] = l3_quantizers_1[gcode];
476 m->l3_quantizers[1] = l3_quantizers_2[gcode];
477 m->l3_quantizers[2] = l3_quantizers_3[gcode];
480 cplcoeff = m->l3_quantizers[m->l3ptr++] * scale_factors[exps[start]];
485 gcode = get_bits(gb, 7);
486 m->l5_quantizers[0] = l5_quantizers_1[gcode];
487 m->l5_quantizers[1] = l5_quantizers_2[gcode];
488 m->l5_quantizers[2] = l5_quantizers_3[gcode];
491 cplcoeff = m->l5_quantizers[m->l5ptr++] * scale_factors[exps[start]];
495 cplcoeff = l7_quantizers[get_bits(gb, 3)] * scale_factors[exps[start]];
500 gcode = get_bits(gb, 7);
501 m->l11_quantizers[0] = l11_quantizers_1[gcode];
502 m->l11_quantizers[1] = l11_quantizers_2[gcode];
505 cplcoeff = m->l11_quantizers[m->l11ptr++] * scale_factors[exps[start]];
509 cplcoeff = l15_quantizers[get_bits(gb, 4)] * scale_factors[exps[start]];
513 cplcoeff = (get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap])) * scale_factors[exps[start]];
515 for (ch = 0; ch < ctx->nfchans; ch++)
516 if (ctx->chincpl[ch])
517 ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch];
525 /* Get the transform coefficients for particular channel */
526 static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
528 GetBitContext *gb = &ctx->gb;
529 int i, gcode, tbap, dithflag, end;
534 if (ch_index != -1) { /* fbw channels */
535 dithflag = ctx->dithflag[ch_index];
536 exps = ctx->dexps[ch_index];
537 bap = ctx->bap[ch_index];
538 coeffs = ctx->transform_coeffs[ch_index + 1];
539 end = ctx->endmant[ch_index];
540 } else if (ch_index == -1) {
542 exps = ctx->dlfeexps;
544 coeffs = ctx->transform_coeffs[0];
549 for (i = 0; i < end; i++) {
558 coeffs[i] = (av_random(&ctx->dith_state) & 0xFFFF) * scale_factors[exps[i]];
559 coeffs[i] *= LEVEL_MINUS_3DB;
565 gcode = get_bits(gb, 5);
566 m->l3_quantizers[0] = l3_quantizers_1[gcode];
567 m->l3_quantizers[1] = l3_quantizers_2[gcode];
568 m->l3_quantizers[2] = l3_quantizers_3[gcode];
571 coeffs[i] = m->l3_quantizers[m->l3ptr++] * scale_factors[exps[i]];
576 gcode = get_bits(gb, 7);
577 m->l5_quantizers[0] = l5_quantizers_1[gcode];
578 m->l5_quantizers[1] = l5_quantizers_2[gcode];
579 m->l5_quantizers[2] = l5_quantizers_3[gcode];
582 coeffs[i] = m->l5_quantizers[m->l5ptr++] * scale_factors[exps[i]];
586 coeffs[i] = l7_quantizers[get_bits(gb, 3)] * scale_factors[exps[i]];
591 gcode = get_bits(gb, 7);
592 m->l11_quantizers[0] = l11_quantizers_1[gcode];
593 m->l11_quantizers[1] = l11_quantizers_2[gcode];
596 coeffs[i] = m->l11_quantizers[m->l11ptr++] * scale_factors[exps[i]];
600 coeffs[i] = l15_quantizers[get_bits(gb, 4)] * scale_factors[exps[i]];
604 coeffs[i] = (get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap])) * scale_factors[exps[i]];
612 /* Get the transform coefficients.
613 * This function extracts the tranform coefficients form the ac3 bitstream.
614 * This function is called after bit allocation is performed.
616 static int get_transform_coeffs(AC3DecodeContext * ctx)
622 m.l3ptr = m.l5ptr = m.l11ptr = 3;
624 for (i = 0; i < ctx->nfchans; i++) {
625 /* transform coefficients for individual channel */
626 if (get_transform_coeffs_ch(ctx, i, &m))
628 /* tranform coefficients for coupling channels */
629 if (ctx->chincpl[i]) {
631 if (get_transform_coeffs_cpling(ctx, &m)) {
632 av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
637 end = ctx->cplendmant;
639 end = ctx->endmant[i];
641 ctx->transform_coeffs[i + 1][end] = 0;
645 if (get_transform_coeffs_ch(ctx, -1, &m))
647 for (i = 7; i < 256; i++) {
648 ctx->transform_coeffs[0][i] = 0;
655 /* Rematrixing routines. */
656 static void do_rematrixing1(AC3DecodeContext *ctx, int start, int end)
660 while (start < end) {
661 tmp0 = ctx->transform_coeffs[1][start];
662 tmp1 = ctx->transform_coeffs[2][start];
663 ctx->transform_coeffs[1][start] = tmp0 + tmp1;
664 ctx->transform_coeffs[2][start] = tmp0 - tmp1;
669 static void do_rematrixing(AC3DecodeContext *ctx)
671 int bnd1 = 13, bnd2 = 25, bnd3 = 37, bnd4 = 61;
674 end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
676 if (ctx->rematflg[0])
677 do_rematrixing1(ctx, bnd1, bnd2);
679 if (ctx->rematflg[1])
680 do_rematrixing1(ctx, bnd2, bnd3);
685 if (ctx->rematflg[2])
686 do_rematrixing1(ctx, bnd3, bndend);
688 if (ctx->rematflg[2])
689 do_rematrixing1(ctx, bnd3, bnd4);
690 if (ctx->rematflg[3])
691 do_rematrixing1(ctx, bnd4, end);
695 /* This function performs the imdct on 256 sample transform
698 static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
703 float *o_ptr = ctx->tmp_output;
706 /* de-interleave coefficients */
707 for(k=0; k<128; k++) {
708 x[k] = ctx->transform_coeffs[chindex][2*k+i];
711 /* run standard IMDCT */
712 ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
714 /* reverse the post-rotation & reordering from standard IMDCT */
715 for(k=0; k<32; k++) {
716 z[i][32+k].re = -o_ptr[128+2*k];
717 z[i][32+k].im = -o_ptr[2*k];
718 z[i][31-k].re = o_ptr[2*k+1];
719 z[i][31-k].im = o_ptr[128+2*k+1];
723 /* apply AC-3 post-rotation & reordering */
724 for(k=0; k<64; k++) {
725 o_ptr[ 2*k ] = -z[0][ k].im;
726 o_ptr[ 2*k+1] = z[0][63-k].re;
727 o_ptr[128+2*k ] = -z[0][ k].re;
728 o_ptr[128+2*k+1] = z[0][63-k].im;
729 o_ptr[256+2*k ] = -z[1][ k].re;
730 o_ptr[256+2*k+1] = z[1][63-k].im;
731 o_ptr[384+2*k ] = z[1][ k].im;
732 o_ptr[384+2*k+1] = -z[1][63-k].re;
736 /* IMDCT Transform. */
737 static inline void do_imdct(AC3DecodeContext *ctx)
741 if (ctx->output_mode & AC3_OUTPUT_LFEON) {
742 ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
743 ctx->transform_coeffs[0], ctx->tmp_imdct);
744 ctx->dsp.vector_fmul_add_add(ctx->output[0], ctx->tmp_output,
745 ctx->window, ctx->delay[0], 384, 256, 1);
746 ctx->dsp.vector_fmul_reverse(ctx->delay[0], ctx->tmp_output+256,
749 for (ch=1; ch<=ctx->nfchans; ch++) {
750 if (ctx->blksw[ch-1])
751 do_imdct_256(ctx, ch);
753 ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
754 ctx->transform_coeffs[ch],
757 ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
758 ctx->window, ctx->delay[ch], 384, 256, 1);
759 ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
764 /* Parse the audio block from ac3 bitstream.
765 * This function extract the audio block from the ac3 bitstream
766 * and produces the output for the block. This function must
767 * be called for each of the six audio block in the ac3 bitstream.
769 static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
771 int nfchans = ctx->nfchans;
772 int acmod = ctx->acmod;
773 int i, bnd, rbnd, seg, grpsize, ch;
774 GetBitContext *gb = &ctx->gb;
775 int bit_alloc_flags = 0;
777 int mstrcplco, cplcoexp, cplcomant;
778 int dynrng, chbwcod, ngrps, cplabsexp, skipl;
780 for (i = 0; i < nfchans; i++) /*block switch flag */
781 ctx->blksw[i] = get_bits1(gb);
783 for (i = 0; i < nfchans; i++) /* dithering flag */
784 ctx->dithflag[i] = get_bits1(gb);
786 if (get_bits1(gb)) { /* dynamic range */
787 dynrng = get_sbits(gb, 8);
788 ctx->dynrng = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
789 } else if(blk == 0) {
793 if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
795 dynrng = get_sbits(gb, 8);
796 ctx->dynrng2 = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
797 } else if(blk == 0) {
802 if (get_bits1(gb)) { /* coupling strategy */
803 ctx->cplinu = get_bits1(gb);
805 if (ctx->cplinu) { /* coupling in use */
806 for (i = 0; i < nfchans; i++)
807 ctx->chincpl[i] = get_bits1(gb);
809 if (acmod == AC3_ACMOD_STEREO)
810 ctx->phsflginu = get_bits1(gb); //phase flag in use
812 ctx->cplbegf = get_bits(gb, 4);
813 ctx->cplendf = get_bits(gb, 4);
815 if (3 + ctx->cplendf - ctx->cplbegf < 0) {
816 av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", ctx->cplendf, ctx->cplbegf);
820 ctx->ncplbnd = ctx->ncplsubnd = 3 + ctx->cplendf - ctx->cplbegf;
821 ctx->cplstrtmant = ctx->cplbegf * 12 + 37;
822 ctx->cplendmant = ctx->cplendf * 12 + 73;
823 for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
825 ctx->cplbndstrc |= 1 << i;
829 for (i = 0; i < nfchans; i++)
837 for (i = 0; i < nfchans; i++)
839 if (get_bits1(gb)) { /* coupling co-ordinates */
840 ctx->cplcoe |= 1 << i;
841 mstrcplco = 3 * get_bits(gb, 2);
842 for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
843 cplcoexp = get_bits(gb, 4);
844 cplcomant = get_bits(gb, 4);
848 cplcomant = (cplcomant | 0x10) << 13;
849 ctx->cplco[i][bnd] = cplcomant * scale_factors[cplcoexp + mstrcplco];
853 if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
854 for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
856 ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
859 if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
860 ctx->rematstr = get_bits1(gb);
862 if (!(ctx->cplinu) || ctx->cplbegf > 2)
863 for (rbnd = 0; rbnd < 4; rbnd++)
864 ctx->rematflg[rbnd] = get_bits1(gb);
865 if (ctx->cplbegf > 0 && ctx->cplbegf <= 2 && ctx->cplinu)
866 for (rbnd = 0; rbnd < 3; rbnd++)
867 ctx->rematflg[rbnd] = get_bits1(gb);
868 if (ctx->cplbegf == 0 && ctx->cplinu)
869 for (rbnd = 0; rbnd < 2; rbnd++)
870 ctx->rematflg[rbnd] = get_bits1(gb);
874 ctx->cplexpstr = EXP_REUSE;
875 ctx->lfeexpstr = EXP_REUSE;
876 if (ctx->cplinu) /* coupling exponent strategy */
877 ctx->cplexpstr = get_bits(gb, 2);
878 for (i = 0; i < nfchans; i++) /* channel exponent strategy */
879 ctx->chexpstr[i] = get_bits(gb, 2);
880 if (ctx->lfeon) /* lfe exponent strategy */
881 ctx->lfeexpstr = get_bits1(gb);
883 for (i = 0; i < nfchans; i++) /* channel bandwidth code */
884 if (ctx->chexpstr[i] != EXP_REUSE) {
886 ctx->endmant[i] = ctx->cplstrtmant;
888 chbwcod = get_bits(gb, 6);
890 av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
893 ctx->endmant[i] = chbwcod * 3 + 73;
897 if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
898 bit_alloc_flags = 64;
899 cplabsexp = get_bits(gb, 4) << 1;
900 ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
901 decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
904 for (i = 0; i < nfchans; i++) /* fbw channel exponents */
905 if (ctx->chexpstr[i] != EXP_REUSE) {
906 bit_alloc_flags |= 1 << i;
907 grpsize = 3 << (ctx->chexpstr[i] - 1);
908 ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
909 dexps = ctx->dexps[i];
910 dexps[0] = get_bits(gb, 4);
911 decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
912 skip_bits(gb, 2); /* skip gainrng */
915 if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
916 bit_alloc_flags |= 32;
917 ctx->dlfeexps[0] = get_bits(gb, 4);
918 decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
921 if (get_bits1(gb)) { /* bit allocation information */
922 bit_alloc_flags = 127;
923 ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
924 ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
925 ctx->bit_alloc_params.sgain = ff_sgaintab[get_bits(gb, 2)];
926 ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
927 ctx->bit_alloc_params.floor = ff_floortab[get_bits(gb, 3)];
930 if (get_bits1(gb)) { /* snroffset */
932 bit_alloc_flags = 127;
933 csnr = (get_bits(gb, 6) - 15) << 4;
934 if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
935 ctx->cplsnroffst = (csnr + get_bits(gb, 4)) << 2;
936 ctx->cplfgain = ff_fgaintab[get_bits(gb, 3)];
938 for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
939 ctx->snroffst[i] = (csnr + get_bits(gb, 4)) << 2;
940 ctx->fgain[i] = ff_fgaintab[get_bits(gb, 3)];
942 if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
943 ctx->lfesnroffst = (csnr + get_bits(gb, 4)) << 2;
944 ctx->lfefgain = ff_fgaintab[get_bits(gb, 3)];
948 if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
949 bit_alloc_flags |= 64;
950 ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
951 ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
954 if (get_bits1(gb)) { /* delta bit allocation information */
955 bit_alloc_flags = 127;
958 ctx->cpldeltbae = get_bits(gb, 2);
959 if (ctx->cpldeltbae == DBA_RESERVED) {
960 av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
965 for (i = 0; i < nfchans; i++) {
966 ctx->deltbae[i] = get_bits(gb, 2);
967 if (ctx->deltbae[i] == DBA_RESERVED) {
968 av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
974 if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
975 ctx->cpldeltnseg = get_bits(gb, 3);
976 for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
977 ctx->cpldeltoffst[seg] = get_bits(gb, 5);
978 ctx->cpldeltlen[seg] = get_bits(gb, 4);
979 ctx->cpldeltba[seg] = get_bits(gb, 3);
983 for (i = 0; i < nfchans; i++)
984 if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
985 ctx->deltnseg[i] = get_bits(gb, 3);
986 for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
987 ctx->deltoffst[i][seg] = get_bits(gb, 5);
988 ctx->deltlen[i][seg] = get_bits(gb, 4);
989 ctx->deltba[i][seg] = get_bits(gb, 3);
992 } else if(blk == 0) {
994 ctx->cpldeltbae = DBA_NONE;
995 for(i=0; i<nfchans; i++) {
996 ctx->deltbae[i] = DBA_NONE;
1000 if (bit_alloc_flags) {
1001 if (ctx->cplinu && (bit_alloc_flags & 64))
1002 ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->cplbap,
1003 ctx->dcplexps, ctx->cplstrtmant,
1004 ctx->cplendmant, ctx->cplsnroffst,
1006 ctx->cpldeltbae, ctx->cpldeltnseg,
1007 ctx->cpldeltoffst, ctx->cpldeltlen,
1009 for (i = 0; i < nfchans; i++)
1010 if ((bit_alloc_flags >> i) & 1)
1011 ac3_parametric_bit_allocation(&ctx->bit_alloc_params,
1012 ctx->bap[i], ctx->dexps[i], 0,
1013 ctx->endmant[i], ctx->snroffst[i],
1014 ctx->fgain[i], 0, ctx->deltbae[i],
1015 ctx->deltnseg[i], ctx->deltoffst[i],
1016 ctx->deltlen[i], ctx->deltba[i]);
1017 if (ctx->lfeon && (bit_alloc_flags & 32))
1018 ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->lfebap,
1019 ctx->dlfeexps, 0, 7, ctx->lfesnroffst,
1021 DBA_NONE, 0, NULL, NULL, NULL);
1024 if (get_bits1(gb)) { /* unused dummy data */
1025 skipl = get_bits(gb, 9);
1029 /* unpack the transform coefficients
1030 * * this also uncouples channels if coupling is in use.
1032 if (get_transform_coeffs(ctx)) {
1033 av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
1037 /* recover coefficients if rematrixing is in use */
1038 if(ctx->acmod == AC3_ACMOD_STEREO)
1039 do_rematrixing(ctx);
1041 /* apply scaling to coefficients (headroom, dynrng) */
1043 for(i=0; i<7; i++) {
1044 ctx->transform_coeffs[0][i] *= 2.0f * ctx->dynrng;
1047 for(ch=1; ch<=ctx->nfchans; ch++) {
1049 if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
1050 gain *= ctx->dynrng2;
1052 gain *= ctx->dynrng;
1054 for(i=0; i<ctx->endmant[ch-1]; i++) {
1055 ctx->transform_coeffs[ch][i] *= gain;
1064 static inline int16_t convert(int32_t i)
1068 else if (i <= 0x43bf8000)
1071 return (i - 0x43c00000);
1074 /* Decode ac3 frame.
1076 * @param avctx Pointer to AVCodecContext
1077 * @param data Pointer to pcm smaples
1078 * @param data_size Set to number of pcm samples produced by decoding
1079 * @param buf Data to be decoded
1080 * @param buf_size Size of the buffer
1082 static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1084 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1085 int16_t *out_samples = (int16_t *)data;
1087 int32_t *int_ptr[6];
1089 for (i = 0; i < 6; i++)
1090 int_ptr[i] = (int32_t *)(&ctx->output[i]);
1092 //Initialize the GetBitContext with the start of valid AC3 Frame.
1093 init_get_bits(&ctx->gb, buf, buf_size * 8);
1095 //Parse the syncinfo.
1096 if (ac3_parse_header(ctx)) {
1097 av_log(avctx, AV_LOG_ERROR, "\n");
1102 avctx->sample_rate = ctx->sampling_rate;
1103 avctx->bit_rate = ctx->bit_rate;
1105 /* channel config */
1106 if (avctx->channels == 0) {
1107 avctx->channels = ctx->out_channels;
1109 if(avctx->channels != ctx->out_channels) {
1110 av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
1115 //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);
1117 //Parse the Audio Blocks.
1118 for (i = 0; i < NB_BLOCKS; i++) {
1119 if (ac3_parse_audio_block(ctx, i)) {
1120 av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1122 return ctx->frame_size;
1124 start = (ctx->output_mode & AC3_OUTPUT_LFEON) ? 0 : 1;
1125 for (k = 0; k < BLOCK_SIZE; k++)
1126 for (j = start; j <= ctx->nfchans; j++)
1127 *(out_samples++) = convert(int_ptr[j][k]);
1129 *data_size = NB_BLOCKS * BLOCK_SIZE * avctx->channels * sizeof (int16_t);
1130 return ctx->frame_size;
1133 /* Uninitialize ac3 decoder.
1135 static int ac3_decode_end(AVCodecContext *avctx)
1137 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1138 ff_mdct_end(&ctx->imdct_512);
1139 ff_mdct_end(&ctx->imdct_256);
1144 AVCodec ac3_decoder = {
1146 .type = CODEC_TYPE_AUDIO,
1148 .priv_data_size = sizeof (AC3DecodeContext),
1149 .init = ac3_decode_init,
1150 .close = ac3_decode_end,
1151 .decode = ac3_decode_frame,