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"
42 * Table of bin locations for rematrixing bands
43 * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
45 static const uint8_t rematrix_band_tbl[5] = { 13, 25, 37, 61, 253 };
47 /* table for exponent to scale_factor mapping
48 * scale_factor[i] = 2 ^ -(i + 15)
50 static float scale_factors[25];
52 /** table for grouping exponents */
53 static uint8_t exp_ungroup_tbl[128][3];
56 /** tables for ungrouping mantissas */
57 static float b1_mantissas[32][3];
58 static float b2_mantissas[128][3];
59 static float b3_mantissas[8];
60 static float b4_mantissas[128][2];
61 static float b5_mantissas[16];
64 * Quantization table: levels for symmetric. bits for asymmetric.
65 * reference: Table 7.18 Mapping of bap to Quantizer
67 static const uint8_t qntztab[16] = {
69 5, 6, 7, 8, 9, 10, 11, 12, 14, 16
72 /** dynamic range table. converts codes to scale factors. */
73 static float dynrng_tbl[256];
75 /* Adjustmens in dB gain */
76 #define LEVEL_MINUS_3DB 0.7071067811865476
77 #define LEVEL_MINUS_4POINT5DB 0.5946035575013605
78 #define LEVEL_MINUS_6DB 0.5000000000000000
79 #define LEVEL_MINUS_9DB 0.3535533905932738
80 #define LEVEL_ZERO 0.0000000000000000
81 #define LEVEL_ONE 1.0000000000000000
83 static const float gain_levels[6] = {
87 LEVEL_MINUS_4POINT5DB,
93 * Table for center mix levels
94 * reference: Section 5.4.2.4 cmixlev
96 static const uint8_t clevs[4] = { 2, 3, 4, 3 };
99 * Table for surround mix levels
100 * reference: Section 5.4.2.5 surmixlev
102 static const uint8_t slevs[4] = { 2, 4, 0, 4 };
105 * Table for default stereo downmixing coefficients
106 * reference: Section 7.8.2 Downmixing Into Two Channels
108 static const uint8_t ac3_default_coeffs[8][5][2] = {
109 { { 1, 0 }, { 0, 1 }, },
111 { { 1, 0 }, { 0, 1 }, },
112 { { 1, 0 }, { 3, 3 }, { 0, 1 }, },
113 { { 1, 0 }, { 0, 1 }, { 4, 4 }, },
114 { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 5, 5 }, },
115 { { 1, 0 }, { 0, 1 }, { 4, 0 }, { 0, 4 }, },
116 { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 4, 0 }, { 0, 4 }, },
119 /* override ac3.h to include coupling channel */
120 #undef AC3_MAX_CHANNELS
121 #define AC3_MAX_CHANNELS 7
124 #define AC3_OUTPUT_LFEON 8
130 int blksw[AC3_MAX_CHANNELS];
131 int dithflag[AC3_MAX_CHANNELS];
134 int chincpl[AC3_MAX_CHANNELS];
140 int expstr[AC3_MAX_CHANNELS];
141 int snroffst[AC3_MAX_CHANNELS];
142 int fgain[AC3_MAX_CHANNELS];
143 int deltbae[AC3_MAX_CHANNELS];
144 int deltnseg[AC3_MAX_CHANNELS];
145 uint8_t deltoffst[AC3_MAX_CHANNELS][8];
146 uint8_t deltlen[AC3_MAX_CHANNELS][8];
147 uint8_t deltba[AC3_MAX_CHANNELS][8];
149 /* Derived Attributes. */
154 int nchans; //number of total channels
155 int nfchans; //number of full-bandwidth channels
156 int lfeon; //lfe channel in use
157 int lfe_ch; ///< index of LFE channel
158 int output_mode; ///< output channel configuration
159 int out_channels; ///< number of output channels
161 float downmix_coeffs[AC3_MAX_CHANNELS][2]; ///< stereo downmix coefficients
162 float dynrng; //dynamic range gain
163 float dynrng2; //dynamic range gain for 1+1 mode
164 float cplco[AC3_MAX_CHANNELS][18]; //coupling coordinates
165 int ncplbnd; //number of coupling bands
166 int ncplsubnd; //number of coupling sub bands
167 int startmant[AC3_MAX_CHANNELS]; ///< start frequency bin
168 int endmant[AC3_MAX_CHANNELS]; //channel end mantissas
169 AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
171 int8_t dexps[AC3_MAX_CHANNELS][256]; ///< decoded exponents
172 uint8_t bap[AC3_MAX_CHANNELS][256]; ///< bit allocation pointers
173 int16_t psd[AC3_MAX_CHANNELS][256]; ///< scaled exponents
174 int16_t bndpsd[AC3_MAX_CHANNELS][50]; ///< interpolated exponents
175 int16_t mask[AC3_MAX_CHANNELS][50]; ///< masking curve values
177 DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]); //transform coefficients
180 MDCTContext imdct_512; //for 512 sample imdct transform
181 MDCTContext imdct_256; //for 256 sample imdct transform
182 DSPContext dsp; //for optimization
183 float add_bias; ///< offset for float_to_int16 conversion
184 float mul_bias; ///< scaling for float_to_int16 conversion
186 DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS-1][256]); //output after imdct transform and windowing
187 DECLARE_ALIGNED_16(short, int_output[AC3_MAX_CHANNELS-1][256]); ///< final 16-bit integer output
188 DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS-1][256]); //delay - added to the next block
189 DECLARE_ALIGNED_16(float, tmp_imdct[256]); //temporary storage for imdct transform
190 DECLARE_ALIGNED_16(float, tmp_output[512]); //temporary storage for output before windowing
191 DECLARE_ALIGNED_16(float, window[256]); //window coefficients
195 AVRandomState dith_state; //for dither generation
198 /*********** BEGIN INIT HELPER FUNCTIONS ***********/
200 * Generate a Kaiser-Bessel Derived Window.
202 static void ac3_window_init(float *window)
205 double sum = 0.0, bessel, tmp;
206 double local_window[256];
207 double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
209 for (i = 0; i < 256; i++) {
210 tmp = i * (256 - i) * alpha2;
212 for (j = 100; j > 0; j--) /* defaul to 100 iterations */
213 bessel = bessel * tmp / (j * j) + 1;
215 local_window[i] = sum;
219 for (i = 0; i < 256; i++)
220 window[i] = sqrt(local_window[i] / sum);
224 symmetric_dequant(int code, int levels)
226 return (code - (levels >> 1)) * (2.0f / levels);
230 * Initialize tables at runtime.
232 static void ac3_tables_init(void)
236 /* generate grouped mantissa tables
237 reference: Section 7.3.5 Ungrouping of Mantissas */
238 for(i=0; i<32; i++) {
239 /* bap=1 mantissas */
240 b1_mantissas[i][0] = symmetric_dequant( i / 9 , 3);
241 b1_mantissas[i][1] = symmetric_dequant((i % 9) / 3, 3);
242 b1_mantissas[i][2] = symmetric_dequant((i % 9) % 3, 3);
244 for(i=0; i<128; i++) {
245 /* bap=2 mantissas */
246 b2_mantissas[i][0] = symmetric_dequant( i / 25 , 5);
247 b2_mantissas[i][1] = symmetric_dequant((i % 25) / 5, 5);
248 b2_mantissas[i][2] = symmetric_dequant((i % 25) % 5, 5);
250 /* bap=4 mantissas */
251 b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
252 b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
254 /* generate ungrouped mantissa tables
255 reference: Tables 7.21 and 7.23 */
257 /* bap=3 mantissas */
258 b3_mantissas[i] = symmetric_dequant(i, 7);
260 for(i=0; i<15; i++) {
261 /* bap=5 mantissas */
262 b5_mantissas[i] = symmetric_dequant(i, 15);
265 /* generate dynamic range table
266 reference: Section 7.7.1 Dynamic Range Control */
267 for(i=0; i<256; i++) {
268 int v = (i >> 5) - ((i >> 7) << 3) - 5;
269 dynrng_tbl[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
272 //generate scale factors
273 for (i = 0; i < 25; i++)
274 scale_factors[i] = pow(2.0, -i);
276 /* generate exponent tables
277 reference: Section 7.1.3 Exponent Decoding */
278 for(i=0; i<128; i++) {
279 exp_ungroup_tbl[i][0] = i / 25;
280 exp_ungroup_tbl[i][1] = (i % 25) / 5;
281 exp_ungroup_tbl[i][2] = (i % 25) % 5;
286 static int ac3_decode_init(AVCodecContext *avctx)
288 AC3DecodeContext *ctx = avctx->priv_data;
292 ff_mdct_init(&ctx->imdct_256, 8, 1);
293 ff_mdct_init(&ctx->imdct_512, 9, 1);
294 ac3_window_init(ctx->window);
295 dsputil_init(&ctx->dsp, avctx);
296 av_init_random(0, &ctx->dith_state);
298 if(ctx->dsp.float_to_int16 == ff_float_to_int16_c) {
299 ctx->add_bias = 385.0f;
300 ctx->mul_bias = 1.0f;
302 ctx->add_bias = 0.0f;
303 ctx->mul_bias = 32767.0f;
308 /*********** END INIT FUNCTIONS ***********/
311 * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
312 * GetBitContext within AC3DecodeContext must point to
313 * start of the synchronized ac3 bitstream.
315 static int ac3_parse_header(AC3DecodeContext *ctx)
318 GetBitContext *gb = &ctx->gb;
319 float cmixlev, surmixlev;
322 err = ff_ac3_parse_header(gb->buffer, &hdr);
326 /* get decoding parameters from header info */
327 ctx->bit_alloc_params.fscod = hdr.fscod;
328 ctx->acmod = hdr.acmod;
329 cmixlev = gain_levels[clevs[hdr.cmixlev]];
330 surmixlev = gain_levels[slevs[hdr.surmixlev]];
331 ctx->dsurmod = hdr.dsurmod;
332 ctx->lfeon = hdr.lfeon;
333 ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
334 ctx->sampling_rate = hdr.sample_rate;
335 ctx->bit_rate = hdr.bit_rate;
336 ctx->nchans = hdr.channels;
337 ctx->nfchans = ctx->nchans - ctx->lfeon;
338 ctx->lfe_ch = ctx->nfchans + 1;
339 ctx->frame_size = hdr.frame_size;
341 /* set default output to all source channels */
342 ctx->out_channels = ctx->nchans;
343 ctx->output_mode = ctx->acmod;
345 ctx->output_mode |= AC3_OUTPUT_LFEON;
347 /* skip over portion of header which has already been read */
348 skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
349 skip_bits(gb, 16); // skip crc1
350 skip_bits(gb, 8); // skip fscod and frmsizecod
351 skip_bits(gb, 11); // skip bsid, bsmod, and acmod
352 if(ctx->acmod == AC3_ACMOD_STEREO) {
353 skip_bits(gb, 2); // skip dsurmod
355 if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
356 skip_bits(gb, 2); // skip cmixlev
358 skip_bits(gb, 2); // skip surmixlev
360 skip_bits1(gb); // skip lfeon
362 /* read the rest of the bsi. read twice for dual mono mode. */
365 skip_bits(gb, 5); //skip dialog normalization
367 skip_bits(gb, 8); //skip compression
369 skip_bits(gb, 8); //skip language code
371 skip_bits(gb, 7); //skip audio production information
374 skip_bits(gb, 2); //skip copyright bit and original bitstream bit
376 /* FIXME: read & use the xbsi1 downmix levels */
378 skip_bits(gb, 14); //skip timecode1
380 skip_bits(gb, 14); //skip timecode2
383 i = get_bits(gb, 6); //additional bsi length
389 /* set stereo downmixing coefficients
390 reference: Section 7.8.2 Downmixing Into Two Channels */
391 for(i=0; i<ctx->nfchans; i++) {
392 ctx->downmix_coeffs[i][0] = gain_levels[ac3_default_coeffs[ctx->acmod][i][0]];
393 ctx->downmix_coeffs[i][1] = gain_levels[ac3_default_coeffs[ctx->acmod][i][1]];
395 if(ctx->acmod > 1 && ctx->acmod & 1) {
396 ctx->downmix_coeffs[1][0] = ctx->downmix_coeffs[1][1] = cmixlev;
398 if(ctx->acmod == AC3_ACMOD_2F1R || ctx->acmod == AC3_ACMOD_3F1R) {
399 int nf = ctx->acmod - 2;
400 ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf][1] = surmixlev * LEVEL_MINUS_3DB;
402 if(ctx->acmod == AC3_ACMOD_2F2R || ctx->acmod == AC3_ACMOD_3F2R) {
403 int nf = ctx->acmod - 4;
404 ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf+1][1] = surmixlev;
411 * Decodes the grouped exponents.
412 * This function decodes the coded exponents according to exponent strategy
413 * and stores them in the decoded exponents buffer.
415 * @param[in] gb GetBitContext which points to start of coded exponents
416 * @param[in] expstr Exponent coding strategy
417 * @param[in] ngrps Number of grouped exponents
418 * @param[in] absexp Absolute exponent or DC exponent
419 * @param[out] dexps Decoded exponents are stored in dexps
421 static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
422 uint8_t absexp, int8_t *dexps)
424 int i, j, grp, grpsize;
429 grpsize = expstr + (expstr == EXP_D45);
430 for(grp=0,i=0; grp<ngrps; grp++) {
431 expacc = get_bits(gb, 7);
432 dexp[i++] = exp_ungroup_tbl[expacc][0];
433 dexp[i++] = exp_ungroup_tbl[expacc][1];
434 dexp[i++] = exp_ungroup_tbl[expacc][2];
437 /* convert to absolute exps and expand groups */
439 for(i=0; i<ngrps*3; i++) {
440 prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
441 for(j=0; j<grpsize; j++) {
442 dexps[(i*grpsize)+j] = prevexp;
448 * Generates transform coefficients for each coupled channel in the coupling
449 * range using the coupling coefficients and coupling coordinates.
450 * reference: Section 7.4.3 Coupling Coordinate Format
452 static void uncouple_channels(AC3DecodeContext *ctx)
454 int i, j, ch, bnd, subbnd;
457 i = ctx->startmant[CPL_CH];
458 for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
461 for(j=0; j<12; j++) {
462 for(ch=1; ch<=ctx->nfchans; ch++) {
464 ctx->transform_coeffs[ch][i] = ctx->transform_coeffs[CPL_CH][i] * ctx->cplco[ch][bnd] * 8.0f;
468 } while(ctx->cplbndstrc[subbnd]);
472 typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
481 /* Get the transform coefficients for particular channel */
482 static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
484 GetBitContext *gb = &ctx->gb;
485 int i, gcode, tbap, start, end;
490 exps = ctx->dexps[ch_index];
491 bap = ctx->bap[ch_index];
492 coeffs = ctx->transform_coeffs[ch_index];
493 start = ctx->startmant[ch_index];
494 end = ctx->endmant[ch_index];
497 for (i = start; i < end; i++) {
501 coeffs[i] = ((av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB) / 32768.0f;
506 gcode = get_bits(gb, 5);
507 m->b1_mant[0] = b1_mantissas[gcode][0];
508 m->b1_mant[1] = b1_mantissas[gcode][1];
509 m->b1_mant[2] = b1_mantissas[gcode][2];
512 coeffs[i] = m->b1_mant[m->b1ptr++];
517 gcode = get_bits(gb, 7);
518 m->b2_mant[0] = b2_mantissas[gcode][0];
519 m->b2_mant[1] = b2_mantissas[gcode][1];
520 m->b2_mant[2] = b2_mantissas[gcode][2];
523 coeffs[i] = m->b2_mant[m->b2ptr++];
527 coeffs[i] = b3_mantissas[get_bits(gb, 3)];
532 gcode = get_bits(gb, 7);
533 m->b4_mant[0] = b4_mantissas[gcode][0];
534 m->b4_mant[1] = b4_mantissas[gcode][1];
537 coeffs[i] = m->b4_mant[m->b4ptr++];
541 coeffs[i] = b5_mantissas[get_bits(gb, 4)];
545 coeffs[i] = get_sbits(gb, qntztab[tbap]) * scale_factors[qntztab[tbap]-1];
548 coeffs[i] *= scale_factors[exps[i]];
555 * Removes random dithering from coefficients with zero-bit mantissas
556 * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
558 static void remove_dithering(AC3DecodeContext *ctx) {
564 for(ch=1; ch<=ctx->nfchans; ch++) {
565 if(!ctx->dithflag[ch]) {
566 coeffs = ctx->transform_coeffs[ch];
569 end = ctx->startmant[CPL_CH];
571 end = ctx->endmant[ch];
572 for(i=0; i<end; i++) {
576 if(ctx->chincpl[ch]) {
577 bap = ctx->bap[CPL_CH];
578 for(; i<ctx->endmant[CPL_CH]; i++) {
587 /* Get the transform coefficients.
588 * This function extracts the tranform coefficients form the ac3 bitstream.
589 * This function is called after bit allocation is performed.
591 static int get_transform_coeffs(AC3DecodeContext * ctx)
597 m.b1ptr = m.b2ptr = m.b4ptr = 3;
599 for (ch = 1; ch <= ctx->nchans; ch++) {
600 /* transform coefficients for individual channel */
601 if (get_transform_coeffs_ch(ctx, ch, &m))
603 /* tranform coefficients for coupling channels */
604 if (ctx->chincpl[ch]) {
606 if (get_transform_coeffs_ch(ctx, CPL_CH, &m)) {
607 av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
610 uncouple_channels(ctx);
613 end = ctx->endmant[CPL_CH];
615 end = ctx->endmant[ch];
618 ctx->transform_coeffs[ch][end] = 0;
622 /* if any channel doesn't use dithering, zero appropriate coefficients */
624 remove_dithering(ctx);
630 * Performs stereo rematrixing.
631 * reference: Section 7.5.4 Rematrixing : Decoding Technique
633 static void do_rematrixing(AC3DecodeContext *ctx)
639 end = FFMIN(ctx->endmant[1], ctx->endmant[2]);
641 for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
642 if(ctx->rematflg[bnd]) {
643 bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
644 for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
645 tmp0 = ctx->transform_coeffs[1][i];
646 tmp1 = ctx->transform_coeffs[2][i];
647 ctx->transform_coeffs[1][i] = tmp0 + tmp1;
648 ctx->transform_coeffs[2][i] = tmp0 - tmp1;
654 /* This function performs the imdct on 256 sample transform
657 static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
660 DECLARE_ALIGNED_16(float, x[128]);
662 float *o_ptr = ctx->tmp_output;
665 /* de-interleave coefficients */
666 for(k=0; k<128; k++) {
667 x[k] = ctx->transform_coeffs[chindex][2*k+i];
670 /* run standard IMDCT */
671 ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
673 /* reverse the post-rotation & reordering from standard IMDCT */
674 for(k=0; k<32; k++) {
675 z[i][32+k].re = -o_ptr[128+2*k];
676 z[i][32+k].im = -o_ptr[2*k];
677 z[i][31-k].re = o_ptr[2*k+1];
678 z[i][31-k].im = o_ptr[128+2*k+1];
682 /* apply AC-3 post-rotation & reordering */
683 for(k=0; k<64; k++) {
684 o_ptr[ 2*k ] = -z[0][ k].im;
685 o_ptr[ 2*k+1] = z[0][63-k].re;
686 o_ptr[128+2*k ] = -z[0][ k].re;
687 o_ptr[128+2*k+1] = z[0][63-k].im;
688 o_ptr[256+2*k ] = -z[1][ k].re;
689 o_ptr[256+2*k+1] = z[1][63-k].im;
690 o_ptr[384+2*k ] = z[1][ k].im;
691 o_ptr[384+2*k+1] = -z[1][63-k].re;
695 /* IMDCT Transform. */
696 static inline void do_imdct(AC3DecodeContext *ctx)
701 nchans = ctx->nfchans;
702 if(ctx->output_mode & AC3_OUTPUT_LFEON)
705 for (ch=1; ch<=nchans; ch++) {
706 if (ctx->blksw[ch]) {
707 do_imdct_256(ctx, ch);
709 ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
710 ctx->transform_coeffs[ch],
713 ctx->dsp.vector_fmul_add_add(ctx->output[ch-1], ctx->tmp_output,
714 ctx->window, ctx->delay[ch-1], 0, 256, 1);
715 ctx->dsp.vector_fmul_reverse(ctx->delay[ch-1], ctx->tmp_output+256,
721 * Downmixes the output to stereo.
723 static void ac3_downmix(float samples[AC3_MAX_CHANNELS][256], int nfchans,
724 int output_mode, float coef[AC3_MAX_CHANNELS][2])
727 float v0, v1, s0, s1;
729 for(i=0; i<256; i++) {
730 v0 = v1 = s0 = s1 = 0.0f;
731 for(j=0; j<nfchans; j++) {
732 v0 += samples[j][i] * coef[j][0];
733 v1 += samples[j][i] * coef[j][1];
739 if(output_mode == AC3_ACMOD_MONO) {
740 samples[0][i] = (v0 + v1) * LEVEL_MINUS_3DB;
741 } else if(output_mode == AC3_ACMOD_STEREO) {
748 /* Parse the audio block from ac3 bitstream.
749 * This function extract the audio block from the ac3 bitstream
750 * and produces the output for the block. This function must
751 * be called for each of the six audio block in the ac3 bitstream.
753 static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
755 int nfchans = ctx->nfchans;
756 int acmod = ctx->acmod;
758 GetBitContext *gb = &ctx->gb;
759 uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
761 memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
763 for (ch = 1; ch <= nfchans; ch++) /*block switch flag */
764 ctx->blksw[ch] = get_bits1(gb);
767 for (ch = 1; ch <= nfchans; ch++) { /* dithering flag */
768 ctx->dithflag[ch] = get_bits1(gb);
769 if(!ctx->dithflag[ch])
773 if (get_bits1(gb)) { /* dynamic range */
774 ctx->dynrng = dynrng_tbl[get_bits(gb, 8)];
775 } else if(blk == 0) {
779 if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
781 ctx->dynrng2 = dynrng_tbl[get_bits(gb, 8)];
782 } else if(blk == 0) {
787 if (get_bits1(gb)) { /* coupling strategy */
788 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
789 ctx->cplinu = get_bits1(gb);
790 if (ctx->cplinu) { /* coupling in use */
791 int cplbegf, cplendf;
793 for (ch = 1; ch <= nfchans; ch++)
794 ctx->chincpl[ch] = get_bits1(gb);
796 if (acmod == AC3_ACMOD_STEREO)
797 ctx->phsflginu = get_bits1(gb); //phase flag in use
799 cplbegf = get_bits(gb, 4);
800 cplendf = get_bits(gb, 4);
802 if (3 + cplendf - cplbegf < 0) {
803 av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
807 ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
808 ctx->startmant[CPL_CH] = cplbegf * 12 + 37;
809 ctx->endmant[CPL_CH] = cplendf * 12 + 73;
810 for (bnd = 0; bnd < ctx->ncplsubnd - 1; bnd++) { /* coupling band structure */
812 ctx->cplbndstrc[bnd] = 1;
817 for (ch = 1; ch <= nfchans; ch++)
818 ctx->chincpl[ch] = 0;
825 for (ch = 1; ch <= nfchans; ch++) {
826 if (ctx->chincpl[ch]) {
827 if (get_bits1(gb)) { /* coupling co-ordinates */
828 int mstrcplco, cplcoexp, cplcomant;
830 mstrcplco = 3 * get_bits(gb, 2);
831 for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
832 cplcoexp = get_bits(gb, 4);
833 cplcomant = get_bits(gb, 4);
835 ctx->cplco[ch][bnd] = cplcomant / 16.0f;
837 ctx->cplco[ch][bnd] = (cplcomant + 16.0f) / 32.0f;
838 ctx->cplco[ch][bnd] *= scale_factors[cplcoexp + mstrcplco];
844 if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && cplcoe) {
845 for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
847 ctx->cplco[2][bnd] = -ctx->cplco[2][bnd];
852 if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
853 ctx->rematstr = get_bits1(gb);
856 if(ctx->cplinu && ctx->startmant[CPL_CH] <= 61)
857 ctx->nrematbnd -= 1 + (ctx->startmant[CPL_CH] == 37);
858 for(bnd=0; bnd<ctx->nrematbnd; bnd++)
859 ctx->rematflg[bnd] = get_bits1(gb);
863 ctx->expstr[CPL_CH] = EXP_REUSE;
864 ctx->expstr[ctx->lfe_ch] = EXP_REUSE;
865 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
866 if(ch == ctx->lfe_ch)
867 ctx->expstr[ch] = get_bits(gb, 1);
869 ctx->expstr[ch] = get_bits(gb, 2);
870 if(ctx->expstr[ch] != EXP_REUSE)
871 bit_alloc_stages[ch] = 3;
874 for (ch = 1; ch <= nfchans; ch++) { /* channel bandwidth code */
875 ctx->startmant[ch] = 0;
876 if (ctx->expstr[ch] != EXP_REUSE) {
877 int prev = ctx->endmant[ch];
878 if (ctx->chincpl[ch])
879 ctx->endmant[ch] = ctx->startmant[CPL_CH];
881 int chbwcod = get_bits(gb, 6);
883 av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
886 ctx->endmant[ch] = chbwcod * 3 + 73;
888 if(blk > 0 && ctx->endmant[ch] != prev)
889 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
892 ctx->startmant[ctx->lfe_ch] = 0;
893 ctx->endmant[ctx->lfe_ch] = 7;
895 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
896 if (ctx->expstr[ch] != EXP_REUSE) {
898 grpsize = 3 << (ctx->expstr[ch] - 1);
900 ngrps = (ctx->endmant[ch] - ctx->startmant[ch]) / grpsize;
901 else if(ch == ctx->lfe_ch)
904 ngrps = (ctx->endmant[ch] + grpsize - 4) / grpsize;
905 ctx->dexps[ch][0] = get_bits(gb, 4) << !ch;
906 decode_exponents(gb, ctx->expstr[ch], ngrps, ctx->dexps[ch][0],
907 &ctx->dexps[ch][ctx->startmant[ch]+!!ch]);
908 if(ch != CPL_CH && ch != ctx->lfe_ch)
909 skip_bits(gb, 2); /* skip gainrng */
913 if (get_bits1(gb)) { /* bit allocation information */
914 ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
915 ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
916 ctx->bit_alloc_params.sgain = ff_sgaintab[get_bits(gb, 2)];
917 ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
918 ctx->bit_alloc_params.floor = ff_floortab[get_bits(gb, 3)];
919 for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
920 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
924 if (get_bits1(gb)) { /* snroffset */
926 csnr = (get_bits(gb, 6) - 15) << 4;
927 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) { /* snr offset and fast gain */
928 ctx->snroffst[ch] = (csnr + get_bits(gb, 4)) << 2;
929 ctx->fgain[ch] = ff_fgaintab[get_bits(gb, 3)];
931 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
934 if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
935 ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
936 ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
937 bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
940 if (get_bits1(gb)) { /* delta bit allocation information */
941 for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
942 ctx->deltbae[ch] = get_bits(gb, 2);
943 if (ctx->deltbae[ch] == DBA_RESERVED) {
944 av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
947 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
950 for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
951 if (ctx->deltbae[ch] == DBA_NEW) {/*channel delta offset, len and bit allocation */
952 ctx->deltnseg[ch] = get_bits(gb, 3);
953 for (seg = 0; seg <= ctx->deltnseg[ch]; seg++) {
954 ctx->deltoffst[ch][seg] = get_bits(gb, 5);
955 ctx->deltlen[ch][seg] = get_bits(gb, 4);
956 ctx->deltba[ch][seg] = get_bits(gb, 3);
960 } else if(blk == 0) {
961 for(ch=0; ch<=ctx->nchans; ch++) {
962 ctx->deltbae[ch] = DBA_NONE;
966 for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
967 if(bit_alloc_stages[ch] > 2) {
968 /* Exponent mapping into PSD and PSD integration */
969 ff_ac3_bit_alloc_calc_psd(ctx->dexps[ch],
970 ctx->startmant[ch], ctx->endmant[ch],
971 ctx->psd[ch], ctx->bndpsd[ch]);
973 if(bit_alloc_stages[ch] > 1) {
974 /* Compute excitation function, Compute masking curve, and
975 Apply delta bit allocation */
976 ff_ac3_bit_alloc_calc_mask(&ctx->bit_alloc_params, ctx->bndpsd[ch],
977 ctx->startmant[ch], ctx->endmant[ch],
978 ctx->fgain[ch], (ch == ctx->lfe_ch),
979 ctx->deltbae[ch], ctx->deltnseg[ch],
980 ctx->deltoffst[ch], ctx->deltlen[ch],
981 ctx->deltba[ch], ctx->mask[ch]);
983 if(bit_alloc_stages[ch] > 0) {
984 /* Compute bit allocation */
985 ff_ac3_bit_alloc_calc_bap(ctx->mask[ch], ctx->psd[ch],
986 ctx->startmant[ch], ctx->endmant[ch],
988 ctx->bit_alloc_params.floor,
993 if (get_bits1(gb)) { /* unused dummy data */
994 int skipl = get_bits(gb, 9);
998 /* unpack the transform coefficients
999 * * this also uncouples channels if coupling is in use.
1001 if (get_transform_coeffs(ctx)) {
1002 av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
1006 /* recover coefficients if rematrixing is in use */
1007 if(ctx->acmod == AC3_ACMOD_STEREO)
1008 do_rematrixing(ctx);
1010 /* apply scaling to coefficients (headroom, dynrng) */
1011 for(ch=1; ch<=ctx->nchans; ch++) {
1012 float gain = 2.0f * ctx->mul_bias;
1013 if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
1014 gain *= ctx->dynrng2;
1016 gain *= ctx->dynrng;
1018 for(i=0; i<ctx->endmant[ch]; i++) {
1019 ctx->transform_coeffs[ch][i] *= gain;
1025 /* downmix output if needed */
1026 if(ctx->nchans != ctx->out_channels && !((ctx->output_mode & AC3_OUTPUT_LFEON) &&
1027 ctx->nfchans == ctx->out_channels)) {
1028 ac3_downmix(ctx->output, ctx->nfchans, ctx->output_mode,
1029 ctx->downmix_coeffs);
1032 /* convert float to 16-bit integer */
1033 for(ch=0; ch<ctx->out_channels; ch++) {
1034 for(i=0; i<256; i++) {
1035 ctx->output[ch][i] += ctx->add_bias;
1037 ctx->dsp.float_to_int16(ctx->int_output[ch], ctx->output[ch], 256);
1043 /* Decode ac3 frame.
1045 * @param avctx Pointer to AVCodecContext
1046 * @param data Pointer to pcm smaples
1047 * @param data_size Set to number of pcm samples produced by decoding
1048 * @param buf Data to be decoded
1049 * @param buf_size Size of the buffer
1051 static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1053 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1054 int16_t *out_samples = (int16_t *)data;
1057 //Initialize the GetBitContext with the start of valid AC3 Frame.
1058 init_get_bits(&ctx->gb, buf, buf_size * 8);
1060 //Parse the syncinfo.
1061 if (ac3_parse_header(ctx)) {
1062 av_log(avctx, AV_LOG_ERROR, "\n");
1067 avctx->sample_rate = ctx->sampling_rate;
1068 avctx->bit_rate = ctx->bit_rate;
1070 /* channel config */
1071 ctx->out_channels = ctx->nchans;
1072 if (avctx->channels == 0) {
1073 avctx->channels = ctx->out_channels;
1074 } else if(ctx->out_channels < avctx->channels) {
1075 av_log(avctx, AV_LOG_ERROR, "Cannot upmix AC3 from %d to %d channels.\n",
1076 ctx->out_channels, avctx->channels);
1079 if(avctx->channels == 2) {
1080 ctx->output_mode = AC3_ACMOD_STEREO;
1081 } else if(avctx->channels == 1) {
1082 ctx->output_mode = AC3_ACMOD_MONO;
1083 } else if(avctx->channels != ctx->out_channels) {
1084 av_log(avctx, AV_LOG_ERROR, "Cannot downmix AC3 from %d to %d channels.\n",
1085 ctx->out_channels, avctx->channels);
1088 ctx->out_channels = avctx->channels;
1090 //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);
1092 //Parse the Audio Blocks.
1093 for (blk = 0; blk < NB_BLOCKS; blk++) {
1094 if (ac3_parse_audio_block(ctx, blk)) {
1095 av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1097 return ctx->frame_size;
1099 for (i = 0; i < 256; i++)
1100 for (ch = 0; ch < ctx->out_channels; ch++)
1101 *(out_samples++) = ctx->int_output[ch][i];
1103 *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
1104 return ctx->frame_size;
1107 /* Uninitialize ac3 decoder.
1109 static int ac3_decode_end(AVCodecContext *avctx)
1111 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1112 ff_mdct_end(&ctx->imdct_512);
1113 ff_mdct_end(&ctx->imdct_256);
1118 AVCodec ac3_decoder = {
1120 .type = CODEC_TYPE_AUDIO,
1122 .priv_data_size = sizeof (AC3DecodeContext),
1123 .init = ac3_decode_init,
1124 .close = ac3_decode_end,
1125 .decode = ac3_decode_frame,