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 };
48 * table for exponent to scale_factor mapping
49 * scale_factors[i] = 2 ^ -i
51 static float scale_factors[25];
53 /** table for grouping exponents */
54 static uint8_t exp_ungroup_tbl[128][3];
57 /** tables for ungrouping mantissas */
58 static float b1_mantissas[32][3];
59 static float b2_mantissas[128][3];
60 static float b3_mantissas[8];
61 static float b4_mantissas[128][2];
62 static float b5_mantissas[16];
65 * Quantization table: levels for symmetric. bits for asymmetric.
66 * reference: Table 7.18 Mapping of bap to Quantizer
68 static const uint8_t qntztab[16] = {
70 5, 6, 7, 8, 9, 10, 11, 12, 14, 16
73 /** dynamic range table. converts codes to scale factors. */
74 static float dynrng_tbl[256];
76 /** dialogue normalization table */
77 static float dialnorm_tbl[32];
79 /** Adjustments in dB gain */
80 #define LEVEL_MINUS_3DB 0.7071067811865476
81 #define LEVEL_MINUS_4POINT5DB 0.5946035575013605
82 #define LEVEL_MINUS_6DB 0.5000000000000000
83 #define LEVEL_MINUS_9DB 0.3535533905932738
84 #define LEVEL_ZERO 0.0000000000000000
85 #define LEVEL_ONE 1.0000000000000000
87 static const float gain_levels[6] = {
91 LEVEL_MINUS_4POINT5DB,
97 * Table for center mix levels
98 * reference: Section 5.4.2.4 cmixlev
100 static const uint8_t clevs[4] = { 2, 3, 4, 3 };
103 * Table for surround mix levels
104 * reference: Section 5.4.2.5 surmixlev
106 static const uint8_t slevs[4] = { 2, 4, 0, 4 };
109 * Table for default stereo downmixing coefficients
110 * reference: Section 7.8.2 Downmixing Into Two Channels
112 static const uint8_t ac3_default_coeffs[8][5][2] = {
113 { { 1, 0 }, { 0, 1 }, },
115 { { 1, 0 }, { 0, 1 }, },
116 { { 1, 0 }, { 3, 3 }, { 0, 1 }, },
117 { { 1, 0 }, { 0, 1 }, { 4, 4 }, },
118 { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 5, 5 }, },
119 { { 1, 0 }, { 0, 1 }, { 4, 0 }, { 0, 4 }, },
120 { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 4, 0 }, { 0, 4 }, },
123 /* override ac3.h to include coupling channel */
124 #undef AC3_MAX_CHANNELS
125 #define AC3_MAX_CHANNELS 7
128 #define AC3_OUTPUT_LFEON 8
131 int acmod; ///< audio coding mode
132 int dsurmod; ///< dolby surround mode
133 int blksw[AC3_MAX_CHANNELS]; ///< block switch flags
134 int dithflag[AC3_MAX_CHANNELS]; ///< dither flags
135 int dither_all; ///< true if all channels are dithered
136 int cplinu; ///< coupling in use
137 int chincpl[AC3_MAX_CHANNELS]; ///< channel in coupling
138 int phsflginu; ///< phase flags in use
139 int cplbndstrc[18]; ///< coupling band structure
140 int rematstr; ///< rematrixing strategy
141 int nrematbnd; ///< number of rematrixing bands
142 int rematflg[4]; ///< rematrixing flags
143 int expstr[AC3_MAX_CHANNELS]; ///< exponent strategies
144 int snroffst[AC3_MAX_CHANNELS]; ///< signal-to-noise ratio offsets
145 int fgain[AC3_MAX_CHANNELS]; ///< fast gain values (signal-to-mask ratio)
146 int deltbae[AC3_MAX_CHANNELS]; ///< delta bit allocation exists
147 int deltnseg[AC3_MAX_CHANNELS]; ///< number of delta segments
148 uint8_t deltoffst[AC3_MAX_CHANNELS][8]; ///< delta segment offsets
149 uint8_t deltlen[AC3_MAX_CHANNELS][8]; ///< delta segment lengths
150 uint8_t deltba[AC3_MAX_CHANNELS][8]; ///< delta values for each segment
152 int sampling_rate; ///< sample frequency, in Hz
153 int bit_rate; ///< stream bit rate, in bits-per-second
154 int frame_size; ///< current frame size, in bytes
156 int nchans; ///< number of total channels
157 int nfchans; ///< number of full-bandwidth channels
158 int lfeon; ///< lfe channel in use
159 int lfe_ch; ///< index of LFE channel
160 int output_mode; ///< output channel configuration
161 int out_channels; ///< number of output channels
163 float downmix_coeffs[AC3_MAX_CHANNELS][2]; ///< stereo downmix coefficients
164 float dialnorm[2]; ///< dialogue normalization
165 float dynrng[2]; ///< dynamic range
166 float cplco[AC3_MAX_CHANNELS][18]; ///< coupling coordinates
167 int ncplbnd; ///< number of coupling bands
168 int ncplsubnd; ///< number of coupling sub bands
169 int startmant[AC3_MAX_CHANNELS]; ///< start frequency bin
170 int endmant[AC3_MAX_CHANNELS]; ///< end frequency bin
171 AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
173 int8_t dexps[AC3_MAX_CHANNELS][256]; ///< decoded exponents
174 uint8_t bap[AC3_MAX_CHANNELS][256]; ///< bit allocation pointers
175 int16_t psd[AC3_MAX_CHANNELS][256]; ///< scaled exponents
176 int16_t bndpsd[AC3_MAX_CHANNELS][50]; ///< interpolated exponents
177 int16_t mask[AC3_MAX_CHANNELS][50]; ///< masking curve values
179 DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]); ///< transform coefficients
182 MDCTContext imdct_512; ///< for 512 sample IMDCT
183 MDCTContext imdct_256; ///< for 256 sample IMDCT
184 DSPContext dsp; ///< for optimization
185 float add_bias; ///< offset for float_to_int16 conversion
186 float mul_bias; ///< scaling for float_to_int16 conversion
188 DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS-1][256]); ///< output after imdct transform and windowing
189 DECLARE_ALIGNED_16(short, int_output[AC3_MAX_CHANNELS-1][256]); ///< final 16-bit integer output
190 DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS-1][256]); ///< delay - added to the next block
191 DECLARE_ALIGNED_16(float, tmp_imdct[256]); ///< temporary storage for imdct transform
192 DECLARE_ALIGNED_16(float, tmp_output[512]); ///< temporary storage for output before windowing
193 DECLARE_ALIGNED_16(float, window[256]); ///< window coefficients
196 GetBitContext gb; ///< bitstream reader
197 AVRandomState dith_state; ///< for dither generation
198 AVCodecContext *avctx; ///< parent context
202 * Generate a Kaiser-Bessel Derived Window.
204 static void ac3_window_init(float *window)
207 double sum = 0.0, bessel, tmp;
208 double local_window[256];
209 double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
211 for (i = 0; i < 256; i++) {
212 tmp = i * (256 - i) * alpha2;
214 for (j = 100; j > 0; j--) /* default to 100 iterations */
215 bessel = bessel * tmp / (j * j) + 1;
217 local_window[i] = sum;
221 for (i = 0; i < 256; i++)
222 window[i] = sqrt(local_window[i] / sum);
226 * Symmetrical Dequantization
227 * reference: Section 7.3.3 Expansion of Mantissas for Symmetrical Quantization
228 * Tables 7.19 to 7.23
231 symmetric_dequant(int code, int levels)
233 return (code - (levels >> 1)) * (2.0f / levels);
237 * Initialize tables at runtime.
239 static void ac3_tables_init(void)
243 /* generate grouped mantissa tables
244 reference: Section 7.3.5 Ungrouping of Mantissas */
245 for(i=0; i<32; i++) {
246 /* bap=1 mantissas */
247 b1_mantissas[i][0] = symmetric_dequant( i / 9 , 3);
248 b1_mantissas[i][1] = symmetric_dequant((i % 9) / 3, 3);
249 b1_mantissas[i][2] = symmetric_dequant((i % 9) % 3, 3);
251 for(i=0; i<128; i++) {
252 /* bap=2 mantissas */
253 b2_mantissas[i][0] = symmetric_dequant( i / 25 , 5);
254 b2_mantissas[i][1] = symmetric_dequant((i % 25) / 5, 5);
255 b2_mantissas[i][2] = symmetric_dequant((i % 25) % 5, 5);
257 /* bap=4 mantissas */
258 b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
259 b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
261 /* generate ungrouped mantissa tables
262 reference: Tables 7.21 and 7.23 */
264 /* bap=3 mantissas */
265 b3_mantissas[i] = symmetric_dequant(i, 7);
267 for(i=0; i<15; i++) {
268 /* bap=5 mantissas */
269 b5_mantissas[i] = symmetric_dequant(i, 15);
272 /* generate dynamic range table
273 reference: Section 7.7.1 Dynamic Range Control */
274 for(i=0; i<256; i++) {
275 int v = (i >> 5) - ((i >> 7) << 3) - 5;
276 dynrng_tbl[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
279 /* generate dialogue normalization table
280 references: Section 5.4.2.8 dialnorm
281 Section 7.6 Dialogue Normalization */
282 for(i=1; i<32; i++) {
283 dialnorm_tbl[i] = expf((i-31) * M_LN10 / 20.0f);
285 dialnorm_tbl[0] = dialnorm_tbl[31];
287 /* generate scale factors for exponents and asymmetrical dequantization
288 reference: Section 7.3.2 Expansion of Mantissas for Asymmetric Quantization */
289 for (i = 0; i < 25; i++)
290 scale_factors[i] = pow(2.0, -i);
292 /* generate exponent tables
293 reference: Section 7.1.3 Exponent Decoding */
294 for(i=0; i<128; i++) {
295 exp_ungroup_tbl[i][0] = i / 25;
296 exp_ungroup_tbl[i][1] = (i % 25) / 5;
297 exp_ungroup_tbl[i][2] = (i % 25) % 5;
303 * AVCodec initialization
305 static int ac3_decode_init(AVCodecContext *avctx)
307 AC3DecodeContext *ctx = avctx->priv_data;
312 ff_mdct_init(&ctx->imdct_256, 8, 1);
313 ff_mdct_init(&ctx->imdct_512, 9, 1);
314 ac3_window_init(ctx->window);
315 dsputil_init(&ctx->dsp, avctx);
316 av_init_random(0, &ctx->dith_state);
318 /* set bias values for float to int16 conversion */
319 if(ctx->dsp.float_to_int16 == ff_float_to_int16_c) {
320 ctx->add_bias = 385.0f;
321 ctx->mul_bias = 1.0f;
323 ctx->add_bias = 0.0f;
324 ctx->mul_bias = 32767.0f;
331 * Parse the 'sync info' and 'bit stream info' from the AC-3 bitstream.
332 * GetBitContext within AC3DecodeContext must point to
333 * start of the synchronized ac3 bitstream.
335 static int ac3_parse_header(AC3DecodeContext *ctx)
338 GetBitContext *gb = &ctx->gb;
339 float cmixlev, surmixlev;
342 err = ff_ac3_parse_header(gb->buffer, &hdr);
346 /* get decoding parameters from header info */
347 ctx->bit_alloc_params.fscod = hdr.fscod;
348 ctx->acmod = hdr.acmod;
349 cmixlev = gain_levels[clevs[hdr.cmixlev]];
350 surmixlev = gain_levels[slevs[hdr.surmixlev]];
351 ctx->dsurmod = hdr.dsurmod;
352 ctx->lfeon = hdr.lfeon;
353 ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
354 ctx->sampling_rate = hdr.sample_rate;
355 ctx->bit_rate = hdr.bit_rate;
356 ctx->nchans = hdr.channels;
357 ctx->nfchans = ctx->nchans - ctx->lfeon;
358 ctx->lfe_ch = ctx->nfchans + 1;
359 ctx->frame_size = hdr.frame_size;
361 /* set default output to all source channels */
362 ctx->out_channels = ctx->nchans;
363 ctx->output_mode = ctx->acmod;
365 ctx->output_mode |= AC3_OUTPUT_LFEON;
367 /* skip over portion of header which has already been read */
368 skip_bits(gb, 16); // skip the sync_word
369 skip_bits(gb, 16); // skip crc1
370 skip_bits(gb, 8); // skip fscod and frmsizecod
371 skip_bits(gb, 11); // skip bsid, bsmod, and acmod
372 if(ctx->acmod == AC3_ACMOD_STEREO) {
373 skip_bits(gb, 2); // skip dsurmod
375 if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
376 skip_bits(gb, 2); // skip cmixlev
378 skip_bits(gb, 2); // skip surmixlev
380 skip_bits1(gb); // skip lfeon
382 /* read the rest of the bsi. read twice for dual mono mode. */
385 ctx->dialnorm[i] = dialnorm_tbl[get_bits(gb, 5)]; // dialogue normalization
387 skip_bits(gb, 8); //skip compression
389 skip_bits(gb, 8); //skip language code
391 skip_bits(gb, 7); //skip audio production information
394 skip_bits(gb, 2); //skip copyright bit and original bitstream bit
396 /* skip the timecodes (or extra bitstream information for Alternate Syntax)
397 TODO: read & use the xbsi1 downmix levels */
399 skip_bits(gb, 14); //skip timecode1 / xbsi1
401 skip_bits(gb, 14); //skip timecode2 / xbsi2
403 /* skip additional bitstream info */
411 /* set stereo downmixing coefficients
412 reference: Section 7.8.2 Downmixing Into Two Channels */
413 for(i=0; i<ctx->nfchans; i++) {
414 ctx->downmix_coeffs[i][0] = gain_levels[ac3_default_coeffs[ctx->acmod][i][0]];
415 ctx->downmix_coeffs[i][1] = gain_levels[ac3_default_coeffs[ctx->acmod][i][1]];
417 if(ctx->acmod > 1 && ctx->acmod & 1) {
418 ctx->downmix_coeffs[1][0] = ctx->downmix_coeffs[1][1] = cmixlev;
420 if(ctx->acmod == AC3_ACMOD_2F1R || ctx->acmod == AC3_ACMOD_3F1R) {
421 int nf = ctx->acmod - 2;
422 ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf][1] = surmixlev * LEVEL_MINUS_3DB;
424 if(ctx->acmod == AC3_ACMOD_2F2R || ctx->acmod == AC3_ACMOD_3F2R) {
425 int nf = ctx->acmod - 4;
426 ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf+1][1] = surmixlev;
433 * Decode the grouped exponents according to exponent strategy.
434 * reference: Section 7.1.3 Exponent Decoding
436 static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
437 uint8_t absexp, int8_t *dexps)
439 int i, j, grp, grpsize;
444 grpsize = expstr + (expstr == EXP_D45);
445 for(grp=0,i=0; grp<ngrps; grp++) {
446 expacc = get_bits(gb, 7);
447 dexp[i++] = exp_ungroup_tbl[expacc][0];
448 dexp[i++] = exp_ungroup_tbl[expacc][1];
449 dexp[i++] = exp_ungroup_tbl[expacc][2];
452 /* convert to absolute exps and expand groups */
454 for(i=0; i<ngrps*3; i++) {
455 prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
456 for(j=0; j<grpsize; j++) {
457 dexps[(i*grpsize)+j] = prevexp;
463 * Generate transform coefficients for each coupled channel in the coupling
464 * range using the coupling coefficients and coupling coordinates.
465 * reference: Section 7.4.3 Coupling Coordinate Format
467 static void uncouple_channels(AC3DecodeContext *ctx)
469 int i, j, ch, bnd, subbnd;
472 i = ctx->startmant[CPL_CH];
473 for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
476 for(j=0; j<12; j++) {
477 for(ch=1; ch<=ctx->nfchans; ch++) {
479 ctx->transform_coeffs[ch][i] = ctx->transform_coeffs[CPL_CH][i] * ctx->cplco[ch][bnd] * 8.0f;
483 } while(ctx->cplbndstrc[subbnd]);
488 * Grouped mantissas for 3-level 5-level and 11-level quantization
500 * Get the transform coefficients for a particular channel
501 * reference: Section 7.3 Quantization and Decoding of Mantissas
503 static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
505 GetBitContext *gb = &ctx->gb;
506 int i, gcode, tbap, start, end;
511 exps = ctx->dexps[ch_index];
512 bap = ctx->bap[ch_index];
513 coeffs = ctx->transform_coeffs[ch_index];
514 start = ctx->startmant[ch_index];
515 end = ctx->endmant[ch_index];
517 for (i = start; i < end; i++) {
521 coeffs[i] = ((av_random(&ctx->dith_state) & 0xFFFF) * LEVEL_MINUS_3DB) / 32768.0f;
526 gcode = get_bits(gb, 5);
527 m->b1_mant[0] = b1_mantissas[gcode][0];
528 m->b1_mant[1] = b1_mantissas[gcode][1];
529 m->b1_mant[2] = b1_mantissas[gcode][2];
532 coeffs[i] = m->b1_mant[m->b1ptr++];
537 gcode = get_bits(gb, 7);
538 m->b2_mant[0] = b2_mantissas[gcode][0];
539 m->b2_mant[1] = b2_mantissas[gcode][1];
540 m->b2_mant[2] = b2_mantissas[gcode][2];
543 coeffs[i] = m->b2_mant[m->b2ptr++];
547 coeffs[i] = b3_mantissas[get_bits(gb, 3)];
552 gcode = get_bits(gb, 7);
553 m->b4_mant[0] = b4_mantissas[gcode][0];
554 m->b4_mant[1] = b4_mantissas[gcode][1];
557 coeffs[i] = m->b4_mant[m->b4ptr++];
561 coeffs[i] = b5_mantissas[get_bits(gb, 4)];
565 /* asymmetric dequantization */
566 coeffs[i] = get_sbits(gb, qntztab[tbap]) * scale_factors[qntztab[tbap]-1];
569 coeffs[i] *= scale_factors[exps[i]];
576 * Remove random dithering from coefficients with zero-bit mantissas
577 * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
579 static void remove_dithering(AC3DecodeContext *ctx) {
585 for(ch=1; ch<=ctx->nfchans; ch++) {
586 if(!ctx->dithflag[ch]) {
587 coeffs = ctx->transform_coeffs[ch];
590 end = ctx->startmant[CPL_CH];
592 end = ctx->endmant[ch];
593 for(i=0; i<end; i++) {
597 if(ctx->chincpl[ch]) {
598 bap = ctx->bap[CPL_CH];
599 for(; i<ctx->endmant[CPL_CH]; i++) {
609 * Get the transform coefficients.
611 static int get_transform_coeffs(AC3DecodeContext * ctx)
617 m.b1ptr = m.b2ptr = m.b4ptr = 3;
619 for (ch = 1; ch <= ctx->nchans; ch++) {
620 /* transform coefficients for full-bandwidth channel */
621 if (get_transform_coeffs_ch(ctx, ch, &m))
623 /* tranform coefficients for coupling channel come right after the
624 coefficients for the first coupled channel*/
625 if (ctx->chincpl[ch]) {
627 if (get_transform_coeffs_ch(ctx, CPL_CH, &m)) {
628 av_log(ctx->avctx, AV_LOG_ERROR, "error in decoupling channels\n");
631 uncouple_channels(ctx);
634 end = ctx->endmant[CPL_CH];
636 end = ctx->endmant[ch];
639 ctx->transform_coeffs[ch][end] = 0;
643 /* if any channel doesn't use dithering, zero appropriate coefficients */
645 remove_dithering(ctx);
651 * Stereo rematrixing.
652 * reference: Section 7.5.4 Rematrixing : Decoding Technique
654 static void do_rematrixing(AC3DecodeContext *ctx)
660 end = FFMIN(ctx->endmant[1], ctx->endmant[2]);
662 for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
663 if(ctx->rematflg[bnd]) {
664 bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
665 for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
666 tmp0 = ctx->transform_coeffs[1][i];
667 tmp1 = ctx->transform_coeffs[2][i];
668 ctx->transform_coeffs[1][i] = tmp0 + tmp1;
669 ctx->transform_coeffs[2][i] = tmp0 - tmp1;
676 * Perform the 256-point IMDCT
678 static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
681 DECLARE_ALIGNED_16(float, x[128]);
683 float *o_ptr = ctx->tmp_output;
686 /* de-interleave coefficients */
687 for(k=0; k<128; k++) {
688 x[k] = ctx->transform_coeffs[chindex][2*k+i];
691 /* run standard IMDCT */
692 ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
694 /* reverse the post-rotation & reordering from standard IMDCT */
695 for(k=0; k<32; k++) {
696 z[i][32+k].re = -o_ptr[128+2*k];
697 z[i][32+k].im = -o_ptr[2*k];
698 z[i][31-k].re = o_ptr[2*k+1];
699 z[i][31-k].im = o_ptr[128+2*k+1];
703 /* apply AC-3 post-rotation & reordering */
704 for(k=0; k<64; k++) {
705 o_ptr[ 2*k ] = -z[0][ k].im;
706 o_ptr[ 2*k+1] = z[0][63-k].re;
707 o_ptr[128+2*k ] = -z[0][ k].re;
708 o_ptr[128+2*k+1] = z[0][63-k].im;
709 o_ptr[256+2*k ] = -z[1][ k].re;
710 o_ptr[256+2*k+1] = z[1][63-k].im;
711 o_ptr[384+2*k ] = z[1][ k].im;
712 o_ptr[384+2*k+1] = -z[1][63-k].re;
717 * Inverse MDCT Transform.
718 * Convert frequency domain coefficients to time-domain audio samples.
719 * reference: Section 7.9.4 Transformation Equations
721 static inline void do_imdct(AC3DecodeContext *ctx)
726 /* Don't perform the IMDCT on the LFE channel unless it's used in the output */
727 nchans = ctx->nfchans;
728 if(ctx->output_mode & AC3_OUTPUT_LFEON)
731 for (ch=1; ch<=nchans; ch++) {
732 if (ctx->blksw[ch]) {
733 do_imdct_256(ctx, ch);
735 ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
736 ctx->transform_coeffs[ch],
739 /* For the first half of the block, apply the window, add the delay
740 from the previous block, and send to output */
741 ctx->dsp.vector_fmul_add_add(ctx->output[ch-1], ctx->tmp_output,
742 ctx->window, ctx->delay[ch-1], 0, 256, 1);
743 /* For the second half of the block, apply the window and store the
744 samples to delay, to be combined with the next block */
745 ctx->dsp.vector_fmul_reverse(ctx->delay[ch-1], ctx->tmp_output+256,
751 * Downmix the output to mono or stereo.
753 static void ac3_downmix(float samples[AC3_MAX_CHANNELS][256], int nfchans,
754 int output_mode, float coef[AC3_MAX_CHANNELS][2])
757 float v0, v1, s0, s1;
759 for(i=0; i<256; i++) {
760 v0 = v1 = s0 = s1 = 0.0f;
761 for(j=0; j<nfchans; j++) {
762 v0 += samples[j][i] * coef[j][0];
763 v1 += samples[j][i] * coef[j][1];
769 if(output_mode == AC3_ACMOD_MONO) {
770 samples[0][i] = (v0 + v1) * LEVEL_MINUS_3DB;
771 } else if(output_mode == AC3_ACMOD_STEREO) {
779 * Parse an audio block from AC-3 bitstream.
781 static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
783 int nfchans = ctx->nfchans;
784 int acmod = ctx->acmod;
786 GetBitContext *gb = &ctx->gb;
787 uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
789 memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
791 /* block switch flags */
792 for (ch = 1; ch <= nfchans; ch++)
793 ctx->blksw[ch] = get_bits1(gb);
795 /* dithering flags */
797 for (ch = 1; ch <= nfchans; ch++) {
798 ctx->dithflag[ch] = get_bits1(gb);
799 if(!ctx->dithflag[ch])
807 ctx->dynrng[i] = dynrng_tbl[get_bits(gb, 8)];
808 } else if(blk == 0) {
809 ctx->dynrng[i] = 1.0f;
813 /* coupling strategy */
815 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
816 ctx->cplinu = get_bits1(gb);
818 /* coupling in use */
819 int cplbegf, cplendf;
821 /* determine which channels are coupled */
822 for (ch = 1; ch <= nfchans; ch++)
823 ctx->chincpl[ch] = get_bits1(gb);
825 /* phase flags in use */
826 if (acmod == AC3_ACMOD_STEREO)
827 ctx->phsflginu = get_bits1(gb);
829 /* coupling frequency range and band structure */
830 cplbegf = get_bits(gb, 4);
831 cplendf = get_bits(gb, 4);
832 if (3 + cplendf - cplbegf < 0) {
833 av_log(ctx->avctx, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
836 ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
837 ctx->startmant[CPL_CH] = cplbegf * 12 + 37;
838 ctx->endmant[CPL_CH] = cplendf * 12 + 73;
839 for (bnd = 0; bnd < ctx->ncplsubnd - 1; bnd++) {
841 ctx->cplbndstrc[bnd] = 1;
846 /* coupling not in use */
847 for (ch = 1; ch <= nfchans; ch++)
848 ctx->chincpl[ch] = 0;
852 /* coupling coordinates */
856 for (ch = 1; ch <= nfchans; ch++) {
857 if (ctx->chincpl[ch]) {
859 int mstrcplco, cplcoexp, cplcomant;
861 mstrcplco = 3 * get_bits(gb, 2);
862 for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
863 cplcoexp = get_bits(gb, 4);
864 cplcomant = get_bits(gb, 4);
866 ctx->cplco[ch][bnd] = cplcomant / 16.0f;
868 ctx->cplco[ch][bnd] = (cplcomant + 16.0f) / 32.0f;
869 ctx->cplco[ch][bnd] *= scale_factors[cplcoexp + mstrcplco];
875 if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && cplcoe) {
876 for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
878 ctx->cplco[2][bnd] = -ctx->cplco[2][bnd];
883 /* stereo rematrixing strategy and band structure */
884 if (acmod == AC3_ACMOD_STEREO) {
885 ctx->rematstr = get_bits1(gb);
888 if(ctx->cplinu && ctx->startmant[CPL_CH] <= 61)
889 ctx->nrematbnd -= 1 + (ctx->startmant[CPL_CH] == 37);
890 for(bnd=0; bnd<ctx->nrematbnd; bnd++)
891 ctx->rematflg[bnd] = get_bits1(gb);
895 /* exponent strategies for each channel */
896 ctx->expstr[CPL_CH] = EXP_REUSE;
897 ctx->expstr[ctx->lfe_ch] = EXP_REUSE;
898 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
899 if(ch == ctx->lfe_ch)
900 ctx->expstr[ch] = get_bits(gb, 1);
902 ctx->expstr[ch] = get_bits(gb, 2);
903 if(ctx->expstr[ch] != EXP_REUSE)
904 bit_alloc_stages[ch] = 3;
907 /* channel bandwidth */
908 for (ch = 1; ch <= nfchans; ch++) {
909 ctx->startmant[ch] = 0;
910 if (ctx->expstr[ch] != EXP_REUSE) {
911 int prev = ctx->endmant[ch];
912 if (ctx->chincpl[ch])
913 ctx->endmant[ch] = ctx->startmant[CPL_CH];
915 int chbwcod = get_bits(gb, 6);
917 av_log(ctx->avctx, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
920 ctx->endmant[ch] = chbwcod * 3 + 73;
922 if(blk > 0 && ctx->endmant[ch] != prev)
923 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
926 ctx->startmant[ctx->lfe_ch] = 0;
927 ctx->endmant[ctx->lfe_ch] = 7;
929 /* decode exponents for each channel */
930 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
931 if (ctx->expstr[ch] != EXP_REUSE) {
933 grpsize = 3 << (ctx->expstr[ch] - 1);
935 ngrps = (ctx->endmant[ch] - ctx->startmant[ch]) / grpsize;
936 else if(ch == ctx->lfe_ch)
939 ngrps = (ctx->endmant[ch] + grpsize - 4) / grpsize;
940 ctx->dexps[ch][0] = get_bits(gb, 4) << !ch;
941 decode_exponents(gb, ctx->expstr[ch], ngrps, ctx->dexps[ch][0],
942 &ctx->dexps[ch][ctx->startmant[ch]+!!ch]);
943 if(ch != CPL_CH && ch != ctx->lfe_ch)
944 skip_bits(gb, 2); /* skip gainrng */
948 /* bit allocation information */
950 ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
951 ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
952 ctx->bit_alloc_params.sgain = ff_sgaintab[get_bits(gb, 2)];
953 ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
954 ctx->bit_alloc_params.floor = ff_floortab[get_bits(gb, 3)];
955 for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
956 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
960 /* signal-to-noise ratio offsets and fast gains (signal-to-mask ratios) */
963 csnr = (get_bits(gb, 6) - 15) << 4;
964 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) { /* snr offset and fast gain */
965 ctx->snroffst[ch] = (csnr + get_bits(gb, 4)) << 2;
966 ctx->fgain[ch] = ff_fgaintab[get_bits(gb, 3)];
968 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
971 /* coupling leak information */
972 if (ctx->cplinu && get_bits1(gb)) {
973 ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
974 ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
975 bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
978 /* delta bit allocation information */
980 /* delta bit allocation exists (strategy) */
981 for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
982 ctx->deltbae[ch] = get_bits(gb, 2);
983 if (ctx->deltbae[ch] == DBA_RESERVED) {
984 av_log(ctx->avctx, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
987 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
989 /* channel delta offset, len and bit allocation */
990 for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
991 if (ctx->deltbae[ch] == DBA_NEW) {
992 ctx->deltnseg[ch] = get_bits(gb, 3);
993 for (seg = 0; seg <= ctx->deltnseg[ch]; seg++) {
994 ctx->deltoffst[ch][seg] = get_bits(gb, 5);
995 ctx->deltlen[ch][seg] = get_bits(gb, 4);
996 ctx->deltba[ch][seg] = get_bits(gb, 3);
1000 } else if(blk == 0) {
1001 for(ch=0; ch<=ctx->nchans; ch++) {
1002 ctx->deltbae[ch] = DBA_NONE;
1006 /* Bit allocation */
1007 for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
1008 if(bit_alloc_stages[ch] > 2) {
1009 /* Exponent mapping into PSD and PSD integration */
1010 ff_ac3_bit_alloc_calc_psd(ctx->dexps[ch],
1011 ctx->startmant[ch], ctx->endmant[ch],
1012 ctx->psd[ch], ctx->bndpsd[ch]);
1014 if(bit_alloc_stages[ch] > 1) {
1015 /* Compute excitation function, Compute masking curve, and
1016 Apply delta bit allocation */
1017 ff_ac3_bit_alloc_calc_mask(&ctx->bit_alloc_params, ctx->bndpsd[ch],
1018 ctx->startmant[ch], ctx->endmant[ch],
1019 ctx->fgain[ch], (ch == ctx->lfe_ch),
1020 ctx->deltbae[ch], ctx->deltnseg[ch],
1021 ctx->deltoffst[ch], ctx->deltlen[ch],
1022 ctx->deltba[ch], ctx->mask[ch]);
1024 if(bit_alloc_stages[ch] > 0) {
1025 /* Compute bit allocation */
1026 ff_ac3_bit_alloc_calc_bap(ctx->mask[ch], ctx->psd[ch],
1027 ctx->startmant[ch], ctx->endmant[ch],
1029 ctx->bit_alloc_params.floor,
1034 /* unused dummy data */
1035 if (get_bits1(gb)) {
1036 int skipl = get_bits(gb, 9);
1041 /* unpack the transform coefficients
1042 this also uncouples channels if coupling is in use. */
1043 if (get_transform_coeffs(ctx)) {
1044 av_log(ctx->avctx, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
1048 /* recover coefficients if rematrixing is in use */
1049 if(ctx->acmod == AC3_ACMOD_STEREO)
1050 do_rematrixing(ctx);
1052 /* apply scaling to coefficients (headroom, dialnorm, dynrng) */
1053 for(ch=1; ch<=ctx->nchans; ch++) {
1054 float gain = 2.0f * ctx->mul_bias;
1055 if(ctx->acmod == AC3_ACMOD_DUALMONO) {
1056 gain *= ctx->dialnorm[ch-1] * ctx->dynrng[ch-1];
1058 gain *= ctx->dialnorm[0] * ctx->dynrng[0];
1060 for(i=0; i<ctx->endmant[ch]; i++) {
1061 ctx->transform_coeffs[ch][i] *= gain;
1067 /* downmix output if needed */
1068 if(ctx->nchans != ctx->out_channels && !((ctx->output_mode & AC3_OUTPUT_LFEON) &&
1069 ctx->nfchans == ctx->out_channels)) {
1070 ac3_downmix(ctx->output, ctx->nfchans, ctx->output_mode,
1071 ctx->downmix_coeffs);
1074 /* convert float to 16-bit integer */
1075 for(ch=0; ch<ctx->out_channels; ch++) {
1076 for(i=0; i<256; i++) {
1077 ctx->output[ch][i] += ctx->add_bias;
1079 ctx->dsp.float_to_int16(ctx->int_output[ch], ctx->output[ch], 256);
1086 * Decode a single AC-3 frame.
1088 static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1090 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1091 int16_t *out_samples = (int16_t *)data;
1094 /* initialize the GetBitContext with the start of valid AC-3 Frame */
1095 init_get_bits(&ctx->gb, buf, buf_size * 8);
1097 /* parse the syncinfo */
1098 if (ac3_parse_header(ctx)) {
1099 av_log(avctx, AV_LOG_ERROR, "\n");
1104 avctx->sample_rate = ctx->sampling_rate;
1105 avctx->bit_rate = ctx->bit_rate;
1107 /* channel config */
1108 ctx->out_channels = ctx->nchans;
1109 if (avctx->channels == 0) {
1110 avctx->channels = ctx->out_channels;
1111 } else if(ctx->out_channels < avctx->channels) {
1112 av_log(avctx, AV_LOG_ERROR, "Cannot upmix AC3 from %d to %d channels.\n",
1113 ctx->out_channels, avctx->channels);
1116 if(avctx->channels == 2) {
1117 ctx->output_mode = AC3_ACMOD_STEREO;
1118 } else if(avctx->channels == 1) {
1119 ctx->output_mode = AC3_ACMOD_MONO;
1120 } else if(avctx->channels != ctx->out_channels) {
1121 av_log(avctx, AV_LOG_ERROR, "Cannot downmix AC3 from %d to %d channels.\n",
1122 ctx->out_channels, avctx->channels);
1125 ctx->out_channels = avctx->channels;
1127 /* parse the audio blocks */
1128 for (blk = 0; blk < NB_BLOCKS; blk++) {
1129 if (ac3_parse_audio_block(ctx, blk)) {
1130 av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1132 return ctx->frame_size;
1134 for (i = 0; i < 256; i++)
1135 for (ch = 0; ch < ctx->out_channels; ch++)
1136 *(out_samples++) = ctx->int_output[ch][i];
1138 *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
1139 return ctx->frame_size;
1143 * Uninitialize the AC-3 decoder.
1145 static int ac3_decode_end(AVCodecContext *avctx)
1147 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1148 ff_mdct_end(&ctx->imdct_512);
1149 ff_mdct_end(&ctx->imdct_256);
1154 AVCodec ac3_decoder = {
1156 .type = CODEC_TYPE_AUDIO,
1158 .priv_data_size = sizeof (AC3DecodeContext),
1159 .init = ac3_decode_init,
1160 .close = ac3_decode_end,
1161 .decode = ac3_decode_frame,