cosmetics: rename common ac3 variables
[libav.git] / libavcodec / ac3dec.c
CommitLineData
0ec2cc35
JR
1/*
2 * AC-3 Audio Decoder
032732d4
JR
3 * This code is developed as part of Google Summer of Code 2006 Program.
4 *
0ec2cc35 5 * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com).
36266421 6 * Copyright (c) 2007 Justin Ruggles
032732d4 7 *
36266421 8 * Portions of this code are derived from liba52
032732d4 9 * http://liba52.sourceforge.net
36266421
JR
10 * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
11 * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
032732d4 12 *
0ec2cc35 13 * This file is part of FFmpeg.
2aa2c5c4 14 *
0ec2cc35 15 * FFmpeg is free software; you can redistribute it and/or
9d109601 16 * modify it under the terms of the GNU General Public
2aa2c5c4
JR
17 * License as published by the Free Software Foundation; either
18 * version 2 of the License, or (at your option) any later version.
19 *
0ec2cc35 20 * FFmpeg is distributed in the hope that it will be useful,
2aa2c5c4
JR
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
283614b5 23 * General Public License for more details.
2aa2c5c4 24 *
283614b5 25 * You should have received a copy of the GNU General Public
0ec2cc35 26 * License along with FFmpeg; if not, write to the Free Software
2aa2c5c4
JR
27 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 */
29
30#include <stdio.h>
31#include <stddef.h>
32#include <math.h>
2aa2c5c4
JR
33#include <string.h>
34
e6bca37c 35#include "avcodec.h"
9fc1ab72 36#include "ac3_parser.h"
2aa2c5c4
JR
37#include "bitstream.h"
38#include "dsputil.h"
cb503702 39#include "random.h"
98a27a8a 40
8b60bbbf
JR
41/**
42 * Table of bin locations for rematrixing bands
43 * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
44 */
bfcf690c 45static const uint8_t rematrix_band_tab[5] = { 13, 25, 37, 61, 253 };
8b60bbbf 46
5066f515
JR
47/**
48 * table for exponent to scale_factor mapping
49 * scale_factors[i] = 2 ^ -i
967d397a
JR
50 */
51static float scale_factors[25];
52
4415076f 53/** table for grouping exponents */
bfcf690c 54static uint8_t exp_ungroup_tab[128][3];
967d397a 55
967d397a 56
5aefe3eb
JR
57/** tables for ungrouping mantissas */
58static float b1_mantissas[32][3];
59static float b2_mantissas[128][3];
60static float b3_mantissas[8];
61static float b4_mantissas[128][2];
62static float b5_mantissas[16];
967d397a 63
5aefe3eb
JR
64/**
65 * Quantization table: levels for symmetric. bits for asymmetric.
66 * reference: Table 7.18 Mapping of bap to Quantizer
67 */
68static const uint8_t qntztab[16] = {
69 0, 3, 5, 7, 11, 15,
70 5, 6, 7, 8, 9, 10, 11, 12, 14, 16
71};
967d397a 72
3357ff33 73/** dynamic range table. converts codes to scale factors. */
bfcf690c 74static float dynrng_tab[256];
3357ff33 75
56cc85a0 76/** dialog normalization table */
bfcf690c 77static float dialnorm_tab[32];
01f35453 78
5066f515 79/** Adjustments in dB gain */
967d397a
JR
80#define LEVEL_MINUS_3DB 0.7071067811865476
81#define LEVEL_MINUS_4POINT5DB 0.5946035575013605
82#define LEVEL_MINUS_6DB 0.5000000000000000
3bbb0bf8 83#define LEVEL_MINUS_9DB 0.3535533905932738
967d397a 84#define LEVEL_ZERO 0.0000000000000000
3bbb0bf8
JR
85#define LEVEL_ONE 1.0000000000000000
86
87static const float gain_levels[6] = {
88 LEVEL_ZERO,
89 LEVEL_ONE,
90 LEVEL_MINUS_3DB,
91 LEVEL_MINUS_4POINT5DB,
92 LEVEL_MINUS_6DB,
93 LEVEL_MINUS_9DB
94};
967d397a 95
3bbb0bf8
JR
96/**
97 * Table for center mix levels
98 * reference: Section 5.4.2.4 cmixlev
99 */
e59cc205 100static const uint8_t center_levels[4] = { 2, 3, 4, 3 };
967d397a 101
3bbb0bf8
JR
102/**
103 * Table for surround mix levels
104 * reference: Section 5.4.2.5 surmixlev
105 */
e59cc205 106static const uint8_t surround_levels[4] = { 2, 4, 0, 4 };
3bbb0bf8
JR
107
108/**
109 * Table for default stereo downmixing coefficients
110 * reference: Section 7.8.2 Downmixing Into Two Channels
111 */
112static const uint8_t ac3_default_coeffs[8][5][2] = {
113 { { 1, 0 }, { 0, 1 }, },
114 { { 2, 2 }, },
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 }, },
121};
967d397a 122
7b4076a7
JR
123/* override ac3.h to include coupling channel */
124#undef AC3_MAX_CHANNELS
125#define AC3_MAX_CHANNELS 7
126#define CPL_CH 0
127
7bfd22f2 128#define AC3_OUTPUT_LFEON 8
1b293437 129
98a27a8a 130typedef struct {
e59cc205
JR
131 int channel_mode; ///< channel mode (acmod)
132 int dolby_surround_mode; ///< dolby surround mode
5066f515
JR
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
5ce21342
JR
144 int snr_offset[AC3_MAX_CHANNELS]; ///< signal-to-noise ratio offsets
145 int fast_gain[AC3_MAX_CHANNELS]; ///< fast gain values (signal-to-mask ratio)
146 int dba_mode[AC3_MAX_CHANNELS]; ///< delta bit allocation mode
147 int dba_nsegs[AC3_MAX_CHANNELS]; ///< number of delta segments
148 uint8_t dba_offsets[AC3_MAX_CHANNELS][8]; ///< delta segment offsets
149 uint8_t dba_lengths[AC3_MAX_CHANNELS][8]; ///< delta segment lengths
150 uint8_t dba_values[AC3_MAX_CHANNELS][8]; ///< delta values for each segment
5066f515
JR
151
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
155
156 int nchans; ///< number of total channels
157 int nfchans; ///< number of full-bandwidth channels
e59cc205 158 int lfe_on; ///< lfe channel in use
222ae64c
JR
159 int lfe_ch; ///< index of LFE channel
160 int output_mode; ///< output channel configuration
161 int out_channels; ///< number of output channels
c7cfc48f 162
222ae64c 163 float downmix_coeffs[AC3_MAX_CHANNELS][2]; ///< stereo downmix coefficients
56cc85a0 164 float dialnorm[2]; ///< dialog normalization
222ae64c 165 float dynrng[2]; ///< dynamic range
5066f515 166 float cplco[AC3_MAX_CHANNELS][18]; ///< coupling coordinates
222ae64c
JR
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
623b7943 171 AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
c7cfc48f 172
222ae64c
JR
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
5ce21342 176 int16_t band_psd[AC3_MAX_CHANNELS][50]; ///< interpolated exponents
222ae64c 177 int16_t mask[AC3_MAX_CHANNELS][50]; ///< masking curve values
c7cfc48f 178
5066f515 179 DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]); ///< transform coefficients
98a27a8a
JR
180
181 /* For IMDCT. */
5066f515
JR
182 MDCTContext imdct_512; ///< for 512 sample IMDCT
183 MDCTContext imdct_256; ///< for 256 sample IMDCT
184 DSPContext dsp; ///< for optimization
222ae64c
JR
185 float add_bias; ///< offset for float_to_int16 conversion
186 float mul_bias; ///< scaling for float_to_int16 conversion
c7cfc48f 187
5066f515 188 DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS-1][256]); ///< output after imdct transform and windowing
4e092320 189 DECLARE_ALIGNED_16(short, int_output[AC3_MAX_CHANNELS-1][256]); ///< final 16-bit integer output
5066f515
JR
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
98a27a8a
JR
194
195 /* Miscellaneous. */
5066f515
JR
196 GetBitContext gb; ///< bitstream reader
197 AVRandomState dith_state; ///< for dither generation
222ae64c 198 AVCodecContext *avctx; ///< parent context
98a27a8a
JR
199} AC3DecodeContext;
200
2fbbd087 201/**
2fbbd087 202 * Generate a Kaiser-Bessel Derived Window.
2fbbd087 203 */
860fe8c9 204static void ac3_window_init(float *window)
2fbbd087 205{
6dc5d71f
JR
206 int i, j;
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);
210
211 for (i = 0; i < 256; i++) {
212 tmp = i * (256 - i) * alpha2;
213 bessel = 1.0;
5066f515 214 for (j = 100; j > 0; j--) /* default to 100 iterations */
6dc5d71f
JR
215 bessel = bessel * tmp / (j * j) + 1;
216 sum += bessel;
217 local_window[i] = sum;
218 }
219
220 sum++;
221 for (i = 0; i < 256; i++)
222 window[i] = sqrt(local_window[i] / sum);
2fbbd087
JR
223}
224
5066f515
JR
225/**
226 * Symmetrical Dequantization
227 * reference: Section 7.3.3 Expansion of Mantissas for Symmetrical Quantization
228 * Tables 7.19 to 7.23
229 */
5aefe3eb
JR
230static inline float
231symmetric_dequant(int code, int levels)
98a27a8a 232{
5aefe3eb 233 return (code - (levels >> 1)) * (2.0f / levels);
98a27a8a
JR
234}
235
c7cfc48f
JR
236/*
237 * Initialize tables at runtime.
238 */
98a27a8a 239static void ac3_tables_init(void)
00585845 240{
4415076f 241 int i;
98a27a8a 242
5aefe3eb
JR
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);
250 }
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);
256
257 /* bap=4 mantissas */
258 b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
259 b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
260 }
261 /* generate ungrouped mantissa tables
262 reference: Tables 7.21 and 7.23 */
263 for(i=0; i<7; i++) {
264 /* bap=3 mantissas */
265 b3_mantissas[i] = symmetric_dequant(i, 7);
266 }
267 for(i=0; i<15; i++) {
268 /* bap=5 mantissas */
269 b5_mantissas[i] = symmetric_dequant(i, 15);
270 }
c7cfc48f 271
3357ff33
JR
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;
bfcf690c 276 dynrng_tab[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
3357ff33
JR
277 }
278
56cc85a0 279 /* generate dialog normalization table
01f35453
JR
280 references: Section 5.4.2.8 dialnorm
281 Section 7.6 Dialogue Normalization */
282 for(i=1; i<32; i++) {
bfcf690c 283 dialnorm_tab[i] = expf((i-31) * M_LN10 / 20.0f);
01f35453 284 }
bfcf690c 285 dialnorm_tab[0] = dialnorm_tab[31];
01f35453 286
5066f515
JR
287 /* generate scale factors for exponents and asymmetrical dequantization
288 reference: Section 7.3.2 Expansion of Mantissas for Asymmetric Quantization */
c7cfc48f 289 for (i = 0; i < 25; i++)
5aefe3eb 290 scale_factors[i] = pow(2.0, -i);
4415076f
JR
291
292 /* generate exponent tables
293 reference: Section 7.1.3 Exponent Decoding */
294 for(i=0; i<128; i++) {
bfcf690c
JR
295 exp_ungroup_tab[i][0] = i / 25;
296 exp_ungroup_tab[i][1] = (i % 25) / 5;
297 exp_ungroup_tab[i][2] = (i % 25) % 5;
4415076f 298 }
00585845
JR
299}
300
1b293437 301
5066f515
JR
302/**
303 * AVCodec initialization
304 */
1b293437
JR
305static int ac3_decode_init(AVCodecContext *avctx)
306{
307 AC3DecodeContext *ctx = avctx->priv_data;
82758fd6 308 ctx->avctx = avctx;
1b293437 309
cc2a8443 310 ac3_common_init();
98a27a8a 311 ac3_tables_init();
45b0ed13
JR
312 ff_mdct_init(&ctx->imdct_256, 8, 1);
313 ff_mdct_init(&ctx->imdct_512, 9, 1);
6dc5d71f 314 ac3_window_init(ctx->window);
1d0a6f52 315 dsputil_init(&ctx->dsp, avctx);
cb503702 316 av_init_random(0, &ctx->dith_state);
2aa2c5c4 317
5066f515 318 /* set bias values for float to int16 conversion */
4e092320
JR
319 if(ctx->dsp.float_to_int16 == ff_float_to_int16_c) {
320 ctx->add_bias = 385.0f;
321 ctx->mul_bias = 1.0f;
322 } else {
323 ctx->add_bias = 0.0f;
324 ctx->mul_bias = 32767.0f;
325 }
326
1b293437 327 return 0;
2aa2c5c4
JR
328}
329
9fc1ab72 330/**
5066f515 331 * Parse the 'sync info' and 'bit stream info' from the AC-3 bitstream.
c7cfc48f
JR
332 * GetBitContext within AC3DecodeContext must point to
333 * start of the synchronized ac3 bitstream.
c7cfc48f 334 */
9fc1ab72 335static int ac3_parse_header(AC3DecodeContext *ctx)
2aa2c5c4 336{
9fc1ab72 337 AC3HeaderInfo hdr;
1b293437 338 GetBitContext *gb = &ctx->gb;
e59cc205 339 float center_mix_level, surround_mix_level;
9fc1ab72
JR
340 int err, i;
341
342 err = ff_ac3_parse_header(gb->buffer, &hdr);
343 if(err)
344 return err;
345
346 /* get decoding parameters from header info */
5ce21342 347 ctx->bit_alloc_params.sr_code = hdr.sr_code;
e59cc205
JR
348 ctx->channel_mode = hdr.channel_mode;
349 center_mix_level = gain_levels[center_levels[hdr.center_mix_level]];
350 surround_mix_level = gain_levels[surround_levels[hdr.surround_mix_level]];
351 ctx->dolby_surround_mode = hdr.dolby_surround_mode;
352 ctx->lfe_on = hdr.lfe_on;
5ce21342 353 ctx->bit_alloc_params.sr_shift = hdr.sr_shift;
9fc1ab72
JR
354 ctx->sampling_rate = hdr.sample_rate;
355 ctx->bit_rate = hdr.bit_rate;
356 ctx->nchans = hdr.channels;
e59cc205 357 ctx->nfchans = ctx->nchans - ctx->lfe_on;
7b4076a7 358 ctx->lfe_ch = ctx->nfchans + 1;
9fc1ab72 359 ctx->frame_size = hdr.frame_size;
7bfd22f2
JR
360
361 /* set default output to all source channels */
362 ctx->out_channels = ctx->nchans;
e59cc205
JR
363 ctx->output_mode = ctx->channel_mode;
364 if(ctx->lfe_on)
7bfd22f2 365 ctx->output_mode |= AC3_OUTPUT_LFEON;
9fc1ab72
JR
366
367 /* skip over portion of header which has already been read */
5066f515 368 skip_bits(gb, 16); // skip the sync_word
9fc1ab72
JR
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
e59cc205 372 if(ctx->channel_mode == AC3_CHMODE_STEREO) {
9fc1ab72
JR
373 skip_bits(gb, 2); // skip dsurmod
374 } else {
e59cc205 375 if((ctx->channel_mode & 1) && ctx->channel_mode != AC3_CHMODE_MONO)
9fc1ab72 376 skip_bits(gb, 2); // skip cmixlev
e59cc205 377 if(ctx->channel_mode & 4)
9fc1ab72 378 skip_bits(gb, 2); // skip surmixlev
00585845 379 }
9fc1ab72 380 skip_bits1(gb); // skip lfeon
98a27a8a 381
9fc1ab72 382 /* read the rest of the bsi. read twice for dual mono mode. */
e59cc205 383 i = !(ctx->channel_mode);
98a27a8a 384 do {
56cc85a0 385 ctx->dialnorm[i] = dialnorm_tab[get_bits(gb, 5)]; // dialog normalization
98a27a8a
JR
386 if (get_bits1(gb))
387 skip_bits(gb, 8); //skip compression
388 if (get_bits1(gb))
389 skip_bits(gb, 8); //skip language code
390 if (get_bits1(gb))
391 skip_bits(gb, 7); //skip audio production information
392 } while (i--);
393
394 skip_bits(gb, 2); //skip copyright bit and original bitstream bit
395
5066f515
JR
396 /* skip the timecodes (or extra bitstream information for Alternate Syntax)
397 TODO: read & use the xbsi1 downmix levels */
00585845 398 if (get_bits1(gb))
5066f515 399 skip_bits(gb, 14); //skip timecode1 / xbsi1
00585845 400 if (get_bits1(gb))
5066f515 401 skip_bits(gb, 14); //skip timecode2 / xbsi2
98a27a8a 402
5066f515 403 /* skip additional bitstream info */
00585845 404 if (get_bits1(gb)) {
5066f515 405 i = get_bits(gb, 6);
486637af 406 do {
00585845 407 skip_bits(gb, 8);
98a27a8a 408 } while(i--);
1b293437 409 }
9fc1ab72 410
3bbb0bf8
JR
411 /* set stereo downmixing coefficients
412 reference: Section 7.8.2 Downmixing Into Two Channels */
413 for(i=0; i<ctx->nfchans; i++) {
e59cc205
JR
414 ctx->downmix_coeffs[i][0] = gain_levels[ac3_default_coeffs[ctx->channel_mode][i][0]];
415 ctx->downmix_coeffs[i][1] = gain_levels[ac3_default_coeffs[ctx->channel_mode][i][1]];
3bbb0bf8 416 }
e59cc205
JR
417 if(ctx->channel_mode > 1 && ctx->channel_mode & 1) {
418 ctx->downmix_coeffs[1][0] = ctx->downmix_coeffs[1][1] = center_mix_level;
3bbb0bf8 419 }
e59cc205
JR
420 if(ctx->channel_mode == AC3_CHMODE_2F1R || ctx->channel_mode == AC3_CHMODE_3F1R) {
421 int nf = ctx->channel_mode - 2;
422 ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf][1] = surround_mix_level * LEVEL_MINUS_3DB;
3bbb0bf8 423 }
e59cc205
JR
424 if(ctx->channel_mode == AC3_CHMODE_2F2R || ctx->channel_mode == AC3_CHMODE_3F2R) {
425 int nf = ctx->channel_mode - 4;
426 ctx->downmix_coeffs[nf][0] = ctx->downmix_coeffs[nf+1][1] = surround_mix_level;
3bbb0bf8
JR
427 }
428
9fc1ab72 429 return 0;
2aa2c5c4
JR
430}
431
3bb004fc 432/**
5066f515
JR
433 * Decode the grouped exponents according to exponent strategy.
434 * reference: Section 7.1.3 Exponent Decoding
2aa2c5c4 435 */
4415076f 436static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
bc8edb7e 437 uint8_t absexp, int8_t *dexps)
2aa2c5c4 438{
4415076f
JR
439 int i, j, grp, grpsize;
440 int dexp[256];
441 int expacc, prevexp;
442
443 /* unpack groups */
444 grpsize = expstr + (expstr == EXP_D45);
445 for(grp=0,i=0; grp<ngrps; grp++) {
446 expacc = get_bits(gb, 7);
bfcf690c
JR
447 dexp[i++] = exp_ungroup_tab[expacc][0];
448 dexp[i++] = exp_ungroup_tab[expacc][1];
449 dexp[i++] = exp_ungroup_tab[expacc][2];
4415076f 450 }
2aa2c5c4 451
4415076f
JR
452 /* convert to absolute exps and expand groups */
453 prevexp = absexp;
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;
1b293437 458 }
2aa2c5c4 459 }
2aa2c5c4
JR
460}
461
d7dc7ad0 462/**
5066f515 463 * Generate transform coefficients for each coupled channel in the coupling
d7dc7ad0
JR
464 * range using the coupling coefficients and coupling coordinates.
465 * reference: Section 7.4.3 Coupling Coordinate Format
466 */
467static void uncouple_channels(AC3DecodeContext *ctx)
468{
469 int i, j, ch, bnd, subbnd;
470
471 subbnd = -1;
7b4076a7 472 i = ctx->startmant[CPL_CH];
d7dc7ad0
JR
473 for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
474 do {
475 subbnd++;
476 for(j=0; j<12; j++) {
477 for(ch=1; ch<=ctx->nfchans; ch++) {
7b4076a7
JR
478 if(ctx->chincpl[ch])
479 ctx->transform_coeffs[ch][i] = ctx->transform_coeffs[CPL_CH][i] * ctx->cplco[ch][bnd] * 8.0f;
d7dc7ad0
JR
480 }
481 i++;
482 }
6d96d626 483 } while(ctx->cplbndstrc[subbnd]);
d7dc7ad0
JR
484 }
485}
486
5066f515
JR
487/**
488 * Grouped mantissas for 3-level 5-level and 11-level quantization
489 */
490typedef struct {
5aefe3eb
JR
491 float b1_mant[3];
492 float b2_mant[3];
493 float b4_mant[2];
494 int b1ptr;
495 int b2ptr;
496 int b4ptr;
486637af
JR
497} mant_groups;
498
5066f515
JR
499/**
500 * Get the transform coefficients for a particular channel
501 * reference: Section 7.3 Quantization and Decoding of Mantissas
502 */
2fbbd087 503static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
1b293437 504{
2fbbd087 505 GetBitContext *gb = &ctx->gb;
60f07fad 506 int i, gcode, tbap, start, end;
2fbbd087
JR
507 uint8_t *exps;
508 uint8_t *bap;
509 float *coeffs;
2fbbd087 510
775369e0
JR
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];
1b293437 516
285bf28c 517 for (i = start; i < end; i++) {
98a27a8a
JR
518 tbap = bap[i];
519 switch (tbap) {
1b293437 520 case 0:
d5b7144e 521 coeffs[i] = ((av_random(&ctx->dith_state) & 0xFFFF) / 65535.0f) - 0.5f;
d63f6fea 522 break;
1b293437
JR
523
524 case 1:
5aefe3eb 525 if(m->b1ptr > 2) {
00585845 526 gcode = get_bits(gb, 5);
5aefe3eb
JR
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];
530 m->b1ptr = 0;
1b293437 531 }
5aefe3eb 532 coeffs[i] = m->b1_mant[m->b1ptr++];
d63f6fea 533 break;
1b293437
JR
534
535 case 2:
5aefe3eb 536 if(m->b2ptr > 2) {
00585845 537 gcode = get_bits(gb, 7);
5aefe3eb
JR
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];
541 m->b2ptr = 0;
1b293437 542 }
5aefe3eb 543 coeffs[i] = m->b2_mant[m->b2ptr++];
d63f6fea 544 break;
1b293437
JR
545
546 case 3:
5aefe3eb 547 coeffs[i] = b3_mantissas[get_bits(gb, 3)];
d63f6fea 548 break;
1b293437
JR
549
550 case 4:
5aefe3eb 551 if(m->b4ptr > 1) {
00585845 552 gcode = get_bits(gb, 7);
5aefe3eb
JR
553 m->b4_mant[0] = b4_mantissas[gcode][0];
554 m->b4_mant[1] = b4_mantissas[gcode][1];
555 m->b4ptr = 0;
1b293437 556 }
5aefe3eb 557 coeffs[i] = m->b4_mant[m->b4ptr++];
d63f6fea 558 break;
1b293437
JR
559
560 case 5:
5aefe3eb 561 coeffs[i] = b5_mantissas[get_bits(gb, 4)];
d63f6fea 562 break;
1b293437
JR
563
564 default:
5066f515 565 /* asymmetric dequantization */
5aefe3eb 566 coeffs[i] = get_sbits(gb, qntztab[tbap]) * scale_factors[qntztab[tbap]-1];
d63f6fea 567 break;
1b293437 568 }
d63f6fea 569 coeffs[i] *= scale_factors[exps[i]];
1b293437
JR
570 }
571
1b293437
JR
572 return 0;
573}
574
60f07fad 575/**
5066f515 576 * Remove random dithering from coefficients with zero-bit mantissas
60f07fad
JR
577 * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
578 */
579static void remove_dithering(AC3DecodeContext *ctx) {
580 int ch, i;
581 int end=0;
582 float *coeffs;
583 uint8_t *bap;
584
585 for(ch=1; ch<=ctx->nfchans; ch++) {
7b4076a7 586 if(!ctx->dithflag[ch]) {
60f07fad 587 coeffs = ctx->transform_coeffs[ch];
7b4076a7
JR
588 bap = ctx->bap[ch];
589 if(ctx->chincpl[ch])
590 end = ctx->startmant[CPL_CH];
60f07fad 591 else
7b4076a7 592 end = ctx->endmant[ch];
60f07fad
JR
593 for(i=0; i<end; i++) {
594 if(bap[i] == 0)
595 coeffs[i] = 0.0f;
596 }
7b4076a7
JR
597 if(ctx->chincpl[ch]) {
598 bap = ctx->bap[CPL_CH];
599 for(; i<ctx->endmant[CPL_CH]; i++) {
60f07fad
JR
600 if(bap[i] == 0)
601 coeffs[i] = 0.0f;
602 }
603 }
604 }
605 }
606}
607
5066f515
JR
608/**
609 * Get the transform coefficients.
c7cfc48f 610 */
1b293437
JR
611static int get_transform_coeffs(AC3DecodeContext * ctx)
612{
7b4076a7 613 int ch, end;
1b293437 614 int got_cplchan = 0;
486637af
JR
615 mant_groups m;
616
5aefe3eb 617 m.b1ptr = m.b2ptr = m.b4ptr = 3;
1b293437 618
7b4076a7 619 for (ch = 1; ch <= ctx->nchans; ch++) {
5066f515 620 /* transform coefficients for full-bandwidth channel */
75b9b036 621 if (get_transform_coeffs_ch(ctx, ch, &m))
1b293437 622 return -1;
5066f515
JR
623 /* tranform coefficients for coupling channel come right after the
624 coefficients for the first coupled channel*/
75b9b036 625 if (ctx->chincpl[ch]) {
486637af 626 if (!got_cplchan) {
7b4076a7 627 if (get_transform_coeffs_ch(ctx, CPL_CH, &m)) {
82758fd6 628 av_log(ctx->avctx, AV_LOG_ERROR, "error in decoupling channels\n");
486637af 629 return -1;
98a27a8a 630 }
d7dc7ad0 631 uncouple_channels(ctx);
486637af
JR
632 got_cplchan = 1;
633 }
7b4076a7 634 end = ctx->endmant[CPL_CH];
eaf84d97 635 } else {
75b9b036 636 end = ctx->endmant[ch];
eaf84d97 637 }
486637af 638 do
7b4076a7 639 ctx->transform_coeffs[ch][end] = 0;
486637af
JR
640 while(++end < 256);
641 }
1b293437 642
60f07fad
JR
643 /* if any channel doesn't use dithering, zero appropriate coefficients */
644 if(!ctx->dither_all)
645 remove_dithering(ctx);
646
1b293437 647 return 0;
2aa2c5c4
JR
648}
649
8b60bbbf 650/**
5066f515 651 * Stereo rematrixing.
8b60bbbf
JR
652 * reference: Section 7.5.4 Rematrixing : Decoding Technique
653 */
1b293437
JR
654static void do_rematrixing(AC3DecodeContext *ctx)
655{
8b60bbbf 656 int bnd, i;
2fbbd087 657 int end, bndend;
8b60bbbf 658 float tmp0, tmp1;
2fbbd087 659
7b4076a7 660 end = FFMIN(ctx->endmant[1], ctx->endmant[2]);
1b293437 661
8b60bbbf
JR
662 for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
663 if(ctx->rematflg[bnd]) {
bfcf690c
JR
664 bndend = FFMIN(end, rematrix_band_tab[bnd+1]);
665 for(i=rematrix_band_tab[bnd]; i<bndend; i++) {
8b60bbbf
JR
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;
670 }
671 }
1b293437
JR
672 }
673}
2aa2c5c4 674
5066f515
JR
675/**
676 * Perform the 256-point IMDCT
c7cfc48f 677 */
45b0ed13 678static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
486637af 679{
0de73a46 680 int i, k;
dfd57c36 681 DECLARE_ALIGNED_16(float, x[128]);
0de73a46
JR
682 FFTComplex z[2][64];
683 float *o_ptr = ctx->tmp_output;
684
685 for(i=0; i<2; i++) {
686 /* de-interleave coefficients */
687 for(k=0; k<128; k++) {
688 x[k] = ctx->transform_coeffs[chindex][2*k+i];
689 }
98a27a8a 690
0de73a46
JR
691 /* run standard IMDCT */
692 ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
693
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];
700 }
1ea76064 701 }
486637af 702
0de73a46
JR
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;
713 }
98a27a8a 714}
486637af 715
5066f515
JR
716/**
717 * Inverse MDCT Transform.
718 * Convert frequency domain coefficients to time-domain audio samples.
719 * reference: Section 7.9.4 Transformation Equations
720 */
486637af
JR
721static inline void do_imdct(AC3DecodeContext *ctx)
722{
0de73a46 723 int ch;
7b4076a7 724 int nchans;
486637af 725
5066f515 726 /* Don't perform the IMDCT on the LFE channel unless it's used in the output */
7b4076a7
JR
727 nchans = ctx->nfchans;
728 if(ctx->output_mode & AC3_OUTPUT_LFEON)
729 nchans++;
730
731 for (ch=1; ch<=nchans; ch++) {
732 if (ctx->blksw[ch]) {
0de73a46 733 do_imdct_256(ctx, ch);
eaf84d97 734 } else {
0de73a46
JR
735 ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
736 ctx->transform_coeffs[ch],
737 ctx->tmp_imdct);
eaf84d97 738 }
5066f515
JR
739 /* For the first half of the block, apply the window, add the delay
740 from the previous block, and send to output */
7b4076a7 741 ctx->dsp.vector_fmul_add_add(ctx->output[ch-1], ctx->tmp_output,
3bbb0bf8 742 ctx->window, ctx->delay[ch-1], 0, 256, 1);
5066f515
JR
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 */
7b4076a7 745 ctx->dsp.vector_fmul_reverse(ctx->delay[ch-1], ctx->tmp_output+256,
0de73a46 746 ctx->window, 256);
486637af
JR
747 }
748}
749
3bbb0bf8 750/**
5066f515 751 * Downmix the output to mono or stereo.
3bbb0bf8
JR
752 */
753static void ac3_downmix(float samples[AC3_MAX_CHANNELS][256], int nfchans,
754 int output_mode, float coef[AC3_MAX_CHANNELS][2])
755{
756 int i, j;
757 float v0, v1, s0, s1;
758
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];
764 s0 += coef[j][0];
765 s1 += coef[j][1];
766 }
767 v0 /= s0;
768 v1 /= s1;
e59cc205 769 if(output_mode == AC3_CHMODE_MONO) {
3bbb0bf8 770 samples[0][i] = (v0 + v1) * LEVEL_MINUS_3DB;
e59cc205 771 } else if(output_mode == AC3_CHMODE_STEREO) {
3bbb0bf8
JR
772 samples[0][i] = v0;
773 samples[1][i] = v1;
774 }
775 }
776}
777
5066f515
JR
778/**
779 * Parse an audio block from AC-3 bitstream.
c7cfc48f 780 */
9fc1ab72 781static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
2aa2c5c4 782{
98a27a8a 783 int nfchans = ctx->nfchans;
e59cc205 784 int channel_mode = ctx->channel_mode;
0bff58a5 785 int i, bnd, seg, ch;
1b293437 786 GetBitContext *gb = &ctx->gb;
7b4076a7 787 uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
1b293437 788
7b4076a7
JR
789 memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
790
5066f515
JR
791 /* block switch flags */
792 for (ch = 1; ch <= nfchans; ch++)
75b9b036 793 ctx->blksw[ch] = get_bits1(gb);
98a27a8a 794
5066f515 795 /* dithering flags */
60f07fad 796 ctx->dither_all = 1;
5066f515 797 for (ch = 1; ch <= nfchans; ch++) {
75b9b036
JR
798 ctx->dithflag[ch] = get_bits1(gb);
799 if(!ctx->dithflag[ch])
60f07fad
JR
800 ctx->dither_all = 0;
801 }
98a27a8a 802
77416325 803 /* dynamic range */
e59cc205 804 i = !(ctx->channel_mode);
77416325 805 do {
9fc1ab72 806 if(get_bits1(gb)) {
bfcf690c 807 ctx->dynrng[i] = dynrng_tab[get_bits(gb, 8)];
9fc1ab72 808 } else if(blk == 0) {
77416325 809 ctx->dynrng[i] = 1.0f;
9fc1ab72 810 }
77416325 811 } while(i--);
98a27a8a 812
5066f515
JR
813 /* coupling strategy */
814 if (get_bits1(gb)) {
7b4076a7 815 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
98a27a8a 816 ctx->cplinu = get_bits1(gb);
5066f515
JR
817 if (ctx->cplinu) {
818 /* coupling in use */
b6acc57f
JR
819 int cplbegf, cplendf;
820
5066f515 821 /* determine which channels are coupled */
7b4076a7 822 for (ch = 1; ch <= nfchans; ch++)
75b9b036 823 ctx->chincpl[ch] = get_bits1(gb);
98a27a8a 824
5066f515 825 /* phase flags in use */
e59cc205 826 if (channel_mode == AC3_CHMODE_STEREO)
5066f515 827 ctx->phsflginu = get_bits1(gb);
98a27a8a 828
5066f515 829 /* coupling frequency range and band structure */
b6acc57f
JR
830 cplbegf = get_bits(gb, 4);
831 cplendf = get_bits(gb, 4);
b6acc57f 832 if (3 + cplendf - cplbegf < 0) {
82758fd6 833 av_log(ctx->avctx, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
00585845 834 return -1;
98a27a8a 835 }
b6acc57f 836 ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
7b4076a7
JR
837 ctx->startmant[CPL_CH] = cplbegf * 12 + 37;
838 ctx->endmant[CPL_CH] = cplendf * 12 + 73;
5066f515 839 for (bnd = 0; bnd < ctx->ncplsubnd - 1; bnd++) {
00585845 840 if (get_bits1(gb)) {
75b9b036 841 ctx->cplbndstrc[bnd] = 1;
98a27a8a 842 ctx->ncplbnd--;
1b293437 843 }
eaf84d97 844 }
878c40a1 845 } else {
5066f515 846 /* coupling not in use */
7b4076a7 847 for (ch = 1; ch <= nfchans; ch++)
75b9b036 848 ctx->chincpl[ch] = 0;
1b293437
JR
849 }
850 }
98a27a8a 851
5066f515 852 /* coupling coordinates */
98a27a8a 853 if (ctx->cplinu) {
fc59010b 854 int cplcoe = 0;
98a27a8a 855
7b4076a7 856 for (ch = 1; ch <= nfchans; ch++) {
75b9b036 857 if (ctx->chincpl[ch]) {
5066f515 858 if (get_bits1(gb)) {
8e2eb3b6 859 int mstrcplco, cplcoexp, cplcomant;
fc59010b 860 cplcoe = 1;
486637af 861 mstrcplco = 3 * get_bits(gb, 2);
98a27a8a 862 for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
486637af
JR
863 cplcoexp = get_bits(gb, 4);
864 cplcomant = get_bits(gb, 4);
865 if (cplcoexp == 15)
75b9b036 866 ctx->cplco[ch][bnd] = cplcomant / 16.0f;
486637af 867 else
75b9b036
JR
868 ctx->cplco[ch][bnd] = (cplcomant + 16.0f) / 32.0f;
869 ctx->cplco[ch][bnd] *= scale_factors[cplcoexp + mstrcplco];
486637af 870 }
486637af 871 }
eaf84d97
JR
872 }
873 }
5066f515 874 /* phase flags */
e59cc205 875 if (channel_mode == AC3_CHMODE_STEREO && ctx->phsflginu && cplcoe) {
eaf84d97 876 for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
98a27a8a 877 if (get_bits1(gb))
7b4076a7 878 ctx->cplco[2][bnd] = -ctx->cplco[2][bnd];
eaf84d97
JR
879 }
880 }
2aa2c5c4 881 }
98a27a8a 882
5066f515 883 /* stereo rematrixing strategy and band structure */
e59cc205 884 if (channel_mode == AC3_CHMODE_STEREO) {
98a27a8a
JR
885 ctx->rematstr = get_bits1(gb);
886 if (ctx->rematstr) {
8b60bbbf 887 ctx->nrematbnd = 4;
7b4076a7
JR
888 if(ctx->cplinu && ctx->startmant[CPL_CH] <= 61)
889 ctx->nrematbnd -= 1 + (ctx->startmant[CPL_CH] == 37);
8b60bbbf
JR
890 for(bnd=0; bnd<ctx->nrematbnd; bnd++)
891 ctx->rematflg[bnd] = get_bits1(gb);
1b293437 892 }
98a27a8a
JR
893 }
894
5066f515 895 /* exponent strategies for each channel */
7b4076a7
JR
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);
901 else
902 ctx->expstr[ch] = get_bits(gb, 2);
903 if(ctx->expstr[ch] != EXP_REUSE)
904 bit_alloc_stages[ch] = 3;
905 }
906
5066f515
JR
907 /* channel bandwidth */
908 for (ch = 1; ch <= nfchans; ch++) {
7b4076a7
JR
909 ctx->startmant[ch] = 0;
910 if (ctx->expstr[ch] != EXP_REUSE) {
911 int prev = ctx->endmant[ch];
75b9b036 912 if (ctx->chincpl[ch])
7b4076a7 913 ctx->endmant[ch] = ctx->startmant[CPL_CH];
00585845 914 else {
8e2eb3b6 915 int chbwcod = get_bits(gb, 6);
98a27a8a 916 if (chbwcod > 60) {
82758fd6 917 av_log(ctx->avctx, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
00585845
JR
918 return -1;
919 }
75b9b036 920 ctx->endmant[ch] = chbwcod * 3 + 73;
1b293437 921 }
7b4076a7
JR
922 if(blk > 0 && ctx->endmant[ch] != prev)
923 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
00585845 924 }
eaf84d97 925 }
7b4076a7
JR
926 ctx->startmant[ctx->lfe_ch] = 0;
927 ctx->endmant[ctx->lfe_ch] = 7;
928
5066f515 929 /* decode exponents for each channel */
7b4076a7
JR
930 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) {
931 if (ctx->expstr[ch] != EXP_REUSE) {
932 int grpsize, ngrps;
933 grpsize = 3 << (ctx->expstr[ch] - 1);
934 if(ch == CPL_CH)
935 ngrps = (ctx->endmant[ch] - ctx->startmant[ch]) / grpsize;
936 else if(ch == ctx->lfe_ch)
937 ngrps = 2;
938 else
775369e0 939 ngrps = (ctx->endmant[ch] + grpsize - 4) / grpsize;
7b4076a7
JR
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)
775369e0 944 skip_bits(gb, 2); /* skip gainrng */
1b293437 945 }
eaf84d97 946 }
98a27a8a 947
5066f515
JR
948 /* bit allocation information */
949 if (get_bits1(gb)) {
5ce21342
JR
950 ctx->bit_alloc_params.slow_decay = ff_ac3_slow_decay_tab[get_bits(gb, 2)] >> ctx->bit_alloc_params.sr_shift;
951 ctx->bit_alloc_params.fast_decay = ff_ac3_fast_decay_tab[get_bits(gb, 2)] >> ctx->bit_alloc_params.sr_shift;
952 ctx->bit_alloc_params.slow_gain = ff_ac3_slow_gain_tab[get_bits(gb, 2)];
953 ctx->bit_alloc_params.db_per_bit = ff_ac3_db_per_bit_tab[get_bits(gb, 2)];
66ecf18e 954 ctx->bit_alloc_params.floor = ff_ac3_floor_tab[get_bits(gb, 3)];
7b4076a7
JR
955 for(ch=!ctx->cplinu; ch<=ctx->nchans; ch++) {
956 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
957 }
1b293437 958 }
98a27a8a 959
5066f515
JR
960 /* signal-to-noise ratio offsets and fast gains (signal-to-mask ratios) */
961 if (get_bits1(gb)) {
4611b64e 962 int csnr;
4611b64e 963 csnr = (get_bits(gb, 6) - 15) << 4;
7b4076a7 964 for (ch = !ctx->cplinu; ch <= ctx->nchans; ch++) { /* snr offset and fast gain */
5ce21342
JR
965 ctx->snr_offset[ch] = (csnr + get_bits(gb, 4)) << 2;
966 ctx->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gb, 3)];
1b293437 967 }
7b4076a7 968 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
1b293437 969 }
98a27a8a 970
5066f515
JR
971 /* coupling leak information */
972 if (ctx->cplinu && get_bits1(gb)) {
5ce21342
JR
973 ctx->bit_alloc_params.cpl_fast_leak = get_bits(gb, 3);
974 ctx->bit_alloc_params.cpl_slow_leak = get_bits(gb, 3);
7b4076a7 975 bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
98a27a8a
JR
976 }
977
5066f515
JR
978 /* delta bit allocation information */
979 if (get_bits1(gb)) {
980 /* delta bit allocation exists (strategy) */
7b4076a7 981 for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
5ce21342
JR
982 ctx->dba_mode[ch] = get_bits(gb, 2);
983 if (ctx->dba_mode[ch] == DBA_RESERVED) {
82758fd6 984 av_log(ctx->avctx, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
1b293437
JR
985 return -1;
986 }
7b4076a7 987 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1b293437 988 }
5066f515 989 /* channel delta offset, len and bit allocation */
7b4076a7 990 for (ch = !ctx->cplinu; ch <= nfchans; ch++) {
5ce21342
JR
991 if (ctx->dba_mode[ch] == DBA_NEW) {
992 ctx->dba_nsegs[ch] = get_bits(gb, 3);
993 for (seg = 0; seg <= ctx->dba_nsegs[ch]; seg++) {
994 ctx->dba_offsets[ch][seg] = get_bits(gb, 5);
995 ctx->dba_lengths[ch][seg] = get_bits(gb, 4);
996 ctx->dba_values[ch][seg] = get_bits(gb, 3);
1b293437
JR
997 }
998 }
eaf84d97 999 }
9fc1ab72 1000 } else if(blk == 0) {
7b4076a7 1001 for(ch=0; ch<=ctx->nchans; ch++) {
5ce21342 1002 ctx->dba_mode[ch] = DBA_NONE;
9fc1ab72 1003 }
1b293437 1004 }
00585845 1005
5066f515 1006 /* Bit allocation */
7b4076a7
JR
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],
5ce21342 1012 ctx->psd[ch], ctx->band_psd[ch]);
eaf84d97 1013 }
7b4076a7
JR
1014 if(bit_alloc_stages[ch] > 1) {
1015 /* Compute excitation function, Compute masking curve, and
1016 Apply delta bit allocation */
5ce21342 1017 ff_ac3_bit_alloc_calc_mask(&ctx->bit_alloc_params, ctx->band_psd[ch],
7b4076a7 1018 ctx->startmant[ch], ctx->endmant[ch],
5ce21342
JR
1019 ctx->fast_gain[ch], (ch == ctx->lfe_ch),
1020 ctx->dba_mode[ch], ctx->dba_nsegs[ch],
1021 ctx->dba_offsets[ch], ctx->dba_lengths[ch],
1022 ctx->dba_values[ch], ctx->mask[ch]);
eaf84d97 1023 }
7b4076a7
JR
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],
5ce21342 1028 ctx->snr_offset[ch],
7b4076a7
JR
1029 ctx->bit_alloc_params.floor,
1030 ctx->bap[ch]);
eaf84d97 1031 }
2fbbd087 1032 }
98a27a8a 1033
5066f515
JR
1034 /* unused dummy data */
1035 if (get_bits1(gb)) {
8e2eb3b6 1036 int skipl = get_bits(gb, 9);
98a27a8a 1037 while(skipl--)
00585845 1038 skip_bits(gb, 8);
1b293437 1039 }
f5cefb21 1040
1b293437 1041 /* unpack the transform coefficients
5066f515 1042 this also uncouples channels if coupling is in use. */
1b293437 1043 if (get_transform_coeffs(ctx)) {
82758fd6 1044 av_log(ctx->avctx, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
1b293437
JR
1045 return -1;
1046 }
486637af 1047
1b293437 1048 /* recover coefficients if rematrixing is in use */
e59cc205 1049 if(ctx->channel_mode == AC3_CHMODE_STEREO)
1b293437
JR
1050 do_rematrixing(ctx);
1051
01f35453 1052 /* apply scaling to coefficients (headroom, dialnorm, dynrng) */
7b4076a7 1053 for(ch=1; ch<=ctx->nchans; ch++) {
4e092320 1054 float gain = 2.0f * ctx->mul_bias;
e59cc205 1055 if(ctx->channel_mode == AC3_CHMODE_DUALMONO) {
77416325 1056 gain *= ctx->dialnorm[ch-1] * ctx->dynrng[ch-1];
7bfd22f2 1057 } else {
77416325 1058 gain *= ctx->dialnorm[0] * ctx->dynrng[0];
7bfd22f2 1059 }
7b4076a7 1060 for(i=0; i<ctx->endmant[ch]; i++) {
7bfd22f2
JR
1061 ctx->transform_coeffs[ch][i] *= gain;
1062 }
1063 }
d7bcc4ad 1064
486637af 1065 do_imdct(ctx);
486637af 1066
3bbb0bf8
JR
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);
1072 }
1073
4e092320
JR
1074 /* convert float to 16-bit integer */
1075 for(ch=0; ch<ctx->out_channels; ch++) {
3bbb0bf8
JR
1076 for(i=0; i<256; i++) {
1077 ctx->output[ch][i] += ctx->add_bias;
1078 }
4e092320
JR
1079 ctx->dsp.float_to_int16(ctx->int_output[ch], ctx->output[ch], 256);
1080 }
1b293437 1081
4e092320 1082 return 0;
486637af
JR
1083}
1084
5066f515
JR
1085/**
1086 * Decode a single AC-3 frame.
c7cfc48f 1087 */
00585845 1088static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
1b293437 1089{
00585845 1090 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
00585845 1091 int16_t *out_samples = (int16_t *)data;
3df88093 1092 int i, blk, ch, err;
d7bcc4ad 1093
5066f515 1094 /* initialize the GetBitContext with the start of valid AC-3 Frame */
9ef60390 1095 init_get_bits(&ctx->gb, buf, buf_size * 8);
00585845 1096
5066f515 1097 /* parse the syncinfo */
3df88093
JR
1098 err = ac3_parse_header(ctx);
1099 if(err) {
1100 switch(err) {
1101 case AC3_PARSE_ERROR_SYNC:
1102 av_log(avctx, AV_LOG_ERROR, "frame sync error\n");
1103 break;
1104 case AC3_PARSE_ERROR_BSID:
1105 av_log(avctx, AV_LOG_ERROR, "invalid bitstream id\n");
1106 break;
1107 case AC3_PARSE_ERROR_SAMPLE_RATE:
1108 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1109 break;
1110 case AC3_PARSE_ERROR_FRAME_SIZE:
1111 av_log(avctx, AV_LOG_ERROR, "invalid frame size\n");
1112 break;
1113 default:
1114 av_log(avctx, AV_LOG_ERROR, "invalid header\n");
1115 break;
1116 }
1117 return -1;
1b293437 1118 }
2aa2c5c4 1119
98a27a8a
JR
1120 avctx->sample_rate = ctx->sampling_rate;
1121 avctx->bit_rate = ctx->bit_rate;
45b0ed13 1122
a135bea5
JR
1123 /* check that reported frame size fits in input buffer */
1124 if(ctx->frame_size > buf_size) {
1125 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1126 return -1;
1127 }
1128
7bfd22f2 1129 /* channel config */
3bbb0bf8 1130 ctx->out_channels = ctx->nchans;
1b293437 1131 if (avctx->channels == 0) {
7bfd22f2 1132 avctx->channels = ctx->out_channels;
3bbb0bf8
JR
1133 } else if(ctx->out_channels < avctx->channels) {
1134 av_log(avctx, AV_LOG_ERROR, "Cannot upmix AC3 from %d to %d channels.\n",
1135 ctx->out_channels, avctx->channels);
1136 return -1;
45b0ed13 1137 }
3bbb0bf8 1138 if(avctx->channels == 2) {
e59cc205 1139 ctx->output_mode = AC3_CHMODE_STEREO;
3bbb0bf8 1140 } else if(avctx->channels == 1) {
e59cc205 1141 ctx->output_mode = AC3_CHMODE_MONO;
3bbb0bf8
JR
1142 } else if(avctx->channels != ctx->out_channels) {
1143 av_log(avctx, AV_LOG_ERROR, "Cannot downmix AC3 from %d to %d channels.\n",
1144 ctx->out_channels, avctx->channels);
7bfd22f2 1145 return -1;
1b293437 1146 }
3bbb0bf8 1147 ctx->out_channels = avctx->channels;
1b293437 1148
5066f515 1149 /* parse the audio blocks */
75b9b036
JR
1150 for (blk = 0; blk < NB_BLOCKS; blk++) {
1151 if (ac3_parse_audio_block(ctx, blk)) {
1b293437
JR
1152 av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1153 *data_size = 0;
98a27a8a 1154 return ctx->frame_size;
1b293437 1155 }
75b9b036 1156 for (i = 0; i < 256; i++)
7b4076a7 1157 for (ch = 0; ch < ctx->out_channels; ch++)
4e092320 1158 *(out_samples++) = ctx->int_output[ch][i];
1b293437 1159 }
8fbb368d 1160 *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
98a27a8a 1161 return ctx->frame_size;
2aa2c5c4 1162}
1b293437 1163
5066f515
JR
1164/**
1165 * Uninitialize the AC-3 decoder.
c7cfc48f
JR
1166 */
1167static int ac3_decode_end(AVCodecContext *avctx)
1b293437 1168{
c7cfc48f
JR
1169 AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
1170 ff_mdct_end(&ctx->imdct_512);
1171 ff_mdct_end(&ctx->imdct_256);
1172
1b293437
JR
1173 return 0;
1174}
1175
fa67992d 1176AVCodec ac3_decoder = {
e6bca37c
JR
1177 .name = "ac3",
1178 .type = CODEC_TYPE_AUDIO,
1179 .id = CODEC_ID_AC3,
1180 .priv_data_size = sizeof (AC3DecodeContext),
1181 .init = ac3_decode_init,
1182 .close = ac3_decode_end,
1183 .decode = ac3_decode_frame,
1b293437 1184};