only calculate number of exponent groups when exponents are not reused.
[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
245976da
DB
35#include "libavutil/crc.h"
36#include "libavutil/random.h"
e6bca37c 37#include "avcodec.h"
9fc1ab72 38#include "ac3_parser.h"
2aa2c5c4
JR
39#include "bitstream.h"
40#include "dsputil.h"
98a27a8a 41
c33a1967
JR
42/** Maximum possible frame size when the specification limit is ignored */
43#define AC3_MAX_FRAME_SIZE 21695
44
8b60bbbf
JR
45/**
46 * Table of bin locations for rematrixing bands
47 * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
48 */
bfcf690c 49static const uint8_t rematrix_band_tab[5] = { 13, 25, 37, 61, 253 };
8b60bbbf 50
4415076f 51/** table for grouping exponents */
bfcf690c 52static uint8_t exp_ungroup_tab[128][3];
967d397a 53
967d397a 54
5aefe3eb 55/** tables for ungrouping mantissas */
a4de6dd2
JR
56static int b1_mantissas[32][3];
57static int b2_mantissas[128][3];
58static int b3_mantissas[8];
59static int b4_mantissas[128][2];
60static int b5_mantissas[16];
967d397a 61
5aefe3eb
JR
62/**
63 * Quantization table: levels for symmetric. bits for asymmetric.
64 * reference: Table 7.18 Mapping of bap to Quantizer
65 */
e2270b4e 66static const uint8_t quantization_tab[16] = {
5aefe3eb
JR
67 0, 3, 5, 7, 11, 15,
68 5, 6, 7, 8, 9, 10, 11, 12, 14, 16
69};
967d397a 70
3357ff33 71/** dynamic range table. converts codes to scale factors. */
e2270b4e 72static float dynamic_range_tab[256];
3357ff33 73
5066f515 74/** Adjustments in dB gain */
967d397a
JR
75#define LEVEL_MINUS_3DB 0.7071067811865476
76#define LEVEL_MINUS_4POINT5DB 0.5946035575013605
77#define LEVEL_MINUS_6DB 0.5000000000000000
3bbb0bf8 78#define LEVEL_MINUS_9DB 0.3535533905932738
967d397a 79#define LEVEL_ZERO 0.0000000000000000
3bbb0bf8
JR
80#define LEVEL_ONE 1.0000000000000000
81
82static const float gain_levels[6] = {
83 LEVEL_ZERO,
84 LEVEL_ONE,
85 LEVEL_MINUS_3DB,
86 LEVEL_MINUS_4POINT5DB,
87 LEVEL_MINUS_6DB,
88 LEVEL_MINUS_9DB
89};
967d397a 90
3bbb0bf8 91/**
3bbb0bf8
JR
92 * Table for default stereo downmixing coefficients
93 * reference: Section 7.8.2 Downmixing Into Two Channels
94 */
95static const uint8_t ac3_default_coeffs[8][5][2] = {
96 { { 1, 0 }, { 0, 1 }, },
97 { { 2, 2 }, },
98 { { 1, 0 }, { 0, 1 }, },
99 { { 1, 0 }, { 3, 3 }, { 0, 1 }, },
100 { { 1, 0 }, { 0, 1 }, { 4, 4 }, },
101 { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 5, 5 }, },
102 { { 1, 0 }, { 0, 1 }, { 4, 0 }, { 0, 4 }, },
103 { { 1, 0 }, { 3, 3 }, { 0, 1 }, { 4, 0 }, { 0, 4 }, },
104};
967d397a 105
7b4076a7
JR
106/* override ac3.h to include coupling channel */
107#undef AC3_MAX_CHANNELS
108#define AC3_MAX_CHANNELS 7
109#define CPL_CH 0
110
7bfd22f2 111#define AC3_OUTPUT_LFEON 8
1b293437 112
98a27a8a 113typedef struct {
e59cc205 114 int channel_mode; ///< channel mode (acmod)
e2270b4e
JR
115 int block_switch[AC3_MAX_CHANNELS]; ///< block switch flags
116 int dither_flag[AC3_MAX_CHANNELS]; ///< dither flags
5066f515 117 int dither_all; ///< true if all channels are dithered
e2270b4e
JR
118 int cpl_in_use; ///< coupling in use
119 int channel_in_cpl[AC3_MAX_CHANNELS]; ///< channel in coupling
120 int phase_flags_in_use; ///< phase flags in use
b02fbf75 121 int phase_flags[18]; ///< phase flags
e2270b4e 122 int cpl_band_struct[18]; ///< coupling band structure
e2270b4e
JR
123 int num_rematrixing_bands; ///< number of rematrixing bands
124 int rematrixing_flags[4]; ///< rematrixing flags
125 int exp_strategy[AC3_MAX_CHANNELS]; ///< exponent strategies
5ce21342
JR
126 int snr_offset[AC3_MAX_CHANNELS]; ///< signal-to-noise ratio offsets
127 int fast_gain[AC3_MAX_CHANNELS]; ///< fast gain values (signal-to-mask ratio)
128 int dba_mode[AC3_MAX_CHANNELS]; ///< delta bit allocation mode
129 int dba_nsegs[AC3_MAX_CHANNELS]; ///< number of delta segments
130 uint8_t dba_offsets[AC3_MAX_CHANNELS][8]; ///< delta segment offsets
131 uint8_t dba_lengths[AC3_MAX_CHANNELS][8]; ///< delta segment lengths
132 uint8_t dba_values[AC3_MAX_CHANNELS][8]; ///< delta values for each segment
5066f515 133
866181e5 134 int sample_rate; ///< sample frequency, in Hz
5066f515
JR
135 int bit_rate; ///< stream bit rate, in bits-per-second
136 int frame_size; ///< current frame size, in bytes
137
e2270b4e
JR
138 int channels; ///< number of total channels
139 int fbw_channels; ///< number of full-bandwidth channels
e59cc205 140 int lfe_on; ///< lfe channel in use
222ae64c
JR
141 int lfe_ch; ///< index of LFE channel
142 int output_mode; ///< output channel configuration
143 int out_channels; ///< number of output channels
c7cfc48f 144
f0b3a7ba
JR
145 int center_mix_level; ///< Center mix level index
146 int surround_mix_level; ///< Surround mix level index
222ae64c 147 float downmix_coeffs[AC3_MAX_CHANNELS][2]; ///< stereo downmix coefficients
d8870f12 148 float downmix_coeff_adjust[2]; ///< adjustment needed for each output channel when downmixing
e2270b4e 149 float dynamic_range[2]; ///< dynamic range
a4de6dd2 150 int cpl_coords[AC3_MAX_CHANNELS][18]; ///< coupling coordinates
e2270b4e
JR
151 int num_cpl_bands; ///< number of coupling bands
152 int num_cpl_subbands; ///< number of coupling sub bands
153 int start_freq[AC3_MAX_CHANNELS]; ///< start frequency bin
154 int end_freq[AC3_MAX_CHANNELS]; ///< end frequency bin
623b7943 155 AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
c7cfc48f 156
b85a15fe 157 int num_exp_groups[AC3_MAX_CHANNELS]; ///< Number of exponent groups
222ae64c
JR
158 int8_t dexps[AC3_MAX_CHANNELS][256]; ///< decoded exponents
159 uint8_t bap[AC3_MAX_CHANNELS][256]; ///< bit allocation pointers
160 int16_t psd[AC3_MAX_CHANNELS][256]; ///< scaled exponents
5ce21342 161 int16_t band_psd[AC3_MAX_CHANNELS][50]; ///< interpolated exponents
222ae64c 162 int16_t mask[AC3_MAX_CHANNELS][50]; ///< masking curve values
c7cfc48f 163
a4de6dd2 164 int fixed_coeffs[AC3_MAX_CHANNELS][256]; ///> fixed-point transform coefficients
5066f515 165 DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]); ///< transform coefficients
38dae9c3 166 int downmixed; ///< indicates if coeffs are currently downmixed
98a27a8a
JR
167
168 /* For IMDCT. */
5066f515
JR
169 MDCTContext imdct_512; ///< for 512 sample IMDCT
170 MDCTContext imdct_256; ///< for 256 sample IMDCT
171 DSPContext dsp; ///< for optimization
222ae64c
JR
172 float add_bias; ///< offset for float_to_int16 conversion
173 float mul_bias; ///< scaling for float_to_int16 conversion
c7cfc48f 174
38dae9c3 175 DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS][256]); ///< output after imdct transform and windowing
4e092320 176 DECLARE_ALIGNED_16(short, int_output[AC3_MAX_CHANNELS-1][256]); ///< final 16-bit integer output
38dae9c3 177 DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS][256]); ///< delay - added to the next block
5066f515
JR
178 DECLARE_ALIGNED_16(float, tmp_imdct[256]); ///< temporary storage for imdct transform
179 DECLARE_ALIGNED_16(float, tmp_output[512]); ///< temporary storage for output before windowing
180 DECLARE_ALIGNED_16(float, window[256]); ///< window coefficients
98a27a8a
JR
181
182 /* Miscellaneous. */
23c8cb89 183 GetBitContext gbc; ///< bitstream reader
5066f515 184 AVRandomState dith_state; ///< for dither generation
222ae64c 185 AVCodecContext *avctx; ///< parent context
509fdb0b 186 uint8_t *input_buffer; ///< temp buffer to prevent overread
98a27a8a
JR
187} AC3DecodeContext;
188
2fbbd087 189/**
5066f515
JR
190 * Symmetrical Dequantization
191 * reference: Section 7.3.3 Expansion of Mantissas for Symmetrical Quantization
192 * Tables 7.19 to 7.23
193 */
a4de6dd2 194static inline int
5aefe3eb 195symmetric_dequant(int code, int levels)
98a27a8a 196{
a4de6dd2 197 return ((code - (levels >> 1)) << 24) / levels;
98a27a8a
JR
198}
199
c7cfc48f
JR
200/*
201 * Initialize tables at runtime.
202 */
98a6fff9 203static av_cold void ac3_tables_init(void)
00585845 204{
4415076f 205 int i;
98a27a8a 206
5aefe3eb
JR
207 /* generate grouped mantissa tables
208 reference: Section 7.3.5 Ungrouping of Mantissas */
209 for(i=0; i<32; i++) {
210 /* bap=1 mantissas */
211 b1_mantissas[i][0] = symmetric_dequant( i / 9 , 3);
212 b1_mantissas[i][1] = symmetric_dequant((i % 9) / 3, 3);
213 b1_mantissas[i][2] = symmetric_dequant((i % 9) % 3, 3);
214 }
215 for(i=0; i<128; i++) {
216 /* bap=2 mantissas */
217 b2_mantissas[i][0] = symmetric_dequant( i / 25 , 5);
218 b2_mantissas[i][1] = symmetric_dequant((i % 25) / 5, 5);
219 b2_mantissas[i][2] = symmetric_dequant((i % 25) % 5, 5);
220
221 /* bap=4 mantissas */
222 b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
223 b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
224 }
225 /* generate ungrouped mantissa tables
226 reference: Tables 7.21 and 7.23 */
227 for(i=0; i<7; i++) {
228 /* bap=3 mantissas */
229 b3_mantissas[i] = symmetric_dequant(i, 7);
230 }
231 for(i=0; i<15; i++) {
232 /* bap=5 mantissas */
233 b5_mantissas[i] = symmetric_dequant(i, 15);
234 }
c7cfc48f 235
3357ff33
JR
236 /* generate dynamic range table
237 reference: Section 7.7.1 Dynamic Range Control */
238 for(i=0; i<256; i++) {
239 int v = (i >> 5) - ((i >> 7) << 3) - 5;
e2270b4e 240 dynamic_range_tab[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
3357ff33
JR
241 }
242
4415076f
JR
243 /* generate exponent tables
244 reference: Section 7.1.3 Exponent Decoding */
245 for(i=0; i<128; i++) {
bfcf690c
JR
246 exp_ungroup_tab[i][0] = i / 25;
247 exp_ungroup_tab[i][1] = (i % 25) / 5;
248 exp_ungroup_tab[i][2] = (i % 25) % 5;
4415076f 249 }
00585845
JR
250}
251
1b293437 252
5066f515
JR
253/**
254 * AVCodec initialization
255 */
98a6fff9 256static av_cold int ac3_decode_init(AVCodecContext *avctx)
1b293437 257{
d802d7ca
JR
258 AC3DecodeContext *s = avctx->priv_data;
259 s->avctx = avctx;
1b293437 260
cc2a8443 261 ac3_common_init();
98a27a8a 262 ac3_tables_init();
d802d7ca
JR
263 ff_mdct_init(&s->imdct_256, 8, 1);
264 ff_mdct_init(&s->imdct_512, 9, 1);
3ed546fe 265 ff_kbd_window_init(s->window, 5.0, 256);
d802d7ca
JR
266 dsputil_init(&s->dsp, avctx);
267 av_init_random(0, &s->dith_state);
2aa2c5c4 268
5066f515 269 /* set bias values for float to int16 conversion */
d802d7ca
JR
270 if(s->dsp.float_to_int16 == ff_float_to_int16_c) {
271 s->add_bias = 385.0f;
272 s->mul_bias = 1.0f;
4e092320 273 } else {
d802d7ca
JR
274 s->add_bias = 0.0f;
275 s->mul_bias = 32767.0f;
4e092320
JR
276 }
277
95283c17
JR
278 /* allow downmixing to stereo or mono */
279 if (avctx->channels > 0 && avctx->request_channels > 0 &&
280 avctx->request_channels < avctx->channels &&
281 avctx->request_channels <= 2) {
282 avctx->channels = avctx->request_channels;
283 }
38dae9c3 284 s->downmixed = 1;
95283c17 285
509fdb0b
JR
286 /* allocate context input buffer */
287 if (avctx->error_resilience >= FF_ER_CAREFUL) {
288 s->input_buffer = av_mallocz(AC3_MAX_FRAME_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
289 if (!s->input_buffer)
290 return AVERROR_NOMEM;
291 }
292
1b293437 293 return 0;
2aa2c5c4
JR
294}
295
9fc1ab72 296/**
5066f515 297 * Parse the 'sync info' and 'bit stream info' from the AC-3 bitstream.
c7cfc48f
JR
298 * GetBitContext within AC3DecodeContext must point to
299 * start of the synchronized ac3 bitstream.
c7cfc48f 300 */
d802d7ca 301static int ac3_parse_header(AC3DecodeContext *s)
2aa2c5c4 302{
9fc1ab72 303 AC3HeaderInfo hdr;
d802d7ca 304 GetBitContext *gbc = &s->gbc;
9fc1ab72
JR
305 int err, i;
306
55736cfb 307 err = ff_ac3_parse_header(gbc, &hdr);
9fc1ab72
JR
308 if(err)
309 return err;
310
646800f7
JR
311 if(hdr.bitstream_id > 10)
312 return AC3_PARSE_ERROR_BSID;
313
9fc1ab72 314 /* get decoding parameters from header info */
d802d7ca
JR
315 s->bit_alloc_params.sr_code = hdr.sr_code;
316 s->channel_mode = hdr.channel_mode;
1b70d88b 317 s->lfe_on = hdr.lfe_on;
d802d7ca 318 s->bit_alloc_params.sr_shift = hdr.sr_shift;
866181e5 319 s->sample_rate = hdr.sample_rate;
d802d7ca
JR
320 s->bit_rate = hdr.bit_rate;
321 s->channels = hdr.channels;
322 s->fbw_channels = s->channels - s->lfe_on;
323 s->lfe_ch = s->fbw_channels + 1;
324 s->frame_size = hdr.frame_size;
55736cfb
BW
325 s->center_mix_level = hdr.center_mix_level;
326 s->surround_mix_level = hdr.surround_mix_level;
7bfd22f2 327
9fc1ab72 328 /* read the rest of the bsi. read twice for dual mono mode. */
d802d7ca 329 i = !(s->channel_mode);
98a27a8a 330 do {
23c8cb89
JR
331 skip_bits(gbc, 5); // skip dialog normalization
332 if (get_bits1(gbc))
333 skip_bits(gbc, 8); //skip compression
334 if (get_bits1(gbc))
335 skip_bits(gbc, 8); //skip language code
336 if (get_bits1(gbc))
337 skip_bits(gbc, 7); //skip audio production information
98a27a8a
JR
338 } while (i--);
339
23c8cb89 340 skip_bits(gbc, 2); //skip copyright bit and original bitstream bit
98a27a8a 341
5066f515
JR
342 /* skip the timecodes (or extra bitstream information for Alternate Syntax)
343 TODO: read & use the xbsi1 downmix levels */
23c8cb89
JR
344 if (get_bits1(gbc))
345 skip_bits(gbc, 14); //skip timecode1 / xbsi1
346 if (get_bits1(gbc))
347 skip_bits(gbc, 14); //skip timecode2 / xbsi2
98a27a8a 348
5066f515 349 /* skip additional bitstream info */
23c8cb89
JR
350 if (get_bits1(gbc)) {
351 i = get_bits(gbc, 6);
486637af 352 do {
23c8cb89 353 skip_bits(gbc, 8);
98a27a8a 354 } while(i--);
1b293437 355 }
9fc1ab72 356
f0b3a7ba
JR
357 return 0;
358}
359
360/**
361 * Set stereo downmixing coefficients based on frame header info.
362 * reference: Section 7.8.2 Downmixing Into Two Channels
363 */
364static void set_downmix_coeffs(AC3DecodeContext *s)
365{
366 int i;
367 float cmix = gain_levels[s->center_mix_level];
368 float smix = gain_levels[s->surround_mix_level];
369
d802d7ca
JR
370 for(i=0; i<s->fbw_channels; i++) {
371 s->downmix_coeffs[i][0] = gain_levels[ac3_default_coeffs[s->channel_mode][i][0]];
372 s->downmix_coeffs[i][1] = gain_levels[ac3_default_coeffs[s->channel_mode][i][1]];
3bbb0bf8 373 }
d802d7ca 374 if(s->channel_mode > 1 && s->channel_mode & 1) {
f0b3a7ba 375 s->downmix_coeffs[1][0] = s->downmix_coeffs[1][1] = cmix;
3bbb0bf8 376 }
d802d7ca
JR
377 if(s->channel_mode == AC3_CHMODE_2F1R || s->channel_mode == AC3_CHMODE_3F1R) {
378 int nf = s->channel_mode - 2;
f0b3a7ba 379 s->downmix_coeffs[nf][0] = s->downmix_coeffs[nf][1] = smix * LEVEL_MINUS_3DB;
3bbb0bf8 380 }
d802d7ca
JR
381 if(s->channel_mode == AC3_CHMODE_2F2R || s->channel_mode == AC3_CHMODE_3F2R) {
382 int nf = s->channel_mode - 4;
f0b3a7ba 383 s->downmix_coeffs[nf][0] = s->downmix_coeffs[nf+1][1] = smix;
3bbb0bf8 384 }
9d10e6e6 385
d8870f12
JR
386 /* calculate adjustment needed for each channel to avoid clipping */
387 s->downmix_coeff_adjust[0] = s->downmix_coeff_adjust[1] = 0.0f;
9d10e6e6 388 for(i=0; i<s->fbw_channels; i++) {
d8870f12
JR
389 s->downmix_coeff_adjust[0] += s->downmix_coeffs[i][0];
390 s->downmix_coeff_adjust[1] += s->downmix_coeffs[i][1];
9d10e6e6 391 }
d8870f12
JR
392 s->downmix_coeff_adjust[0] = 1.0f / s->downmix_coeff_adjust[0];
393 s->downmix_coeff_adjust[1] = 1.0f / s->downmix_coeff_adjust[1];
2aa2c5c4
JR
394}
395
3bb004fc 396/**
5066f515
JR
397 * Decode the grouped exponents according to exponent strategy.
398 * reference: Section 7.1.3 Exponent Decoding
2aa2c5c4 399 */
23c8cb89 400static void decode_exponents(GetBitContext *gbc, int exp_strategy, int ngrps,
bc8edb7e 401 uint8_t absexp, int8_t *dexps)
2aa2c5c4 402{
e2270b4e 403 int i, j, grp, group_size;
4415076f
JR
404 int dexp[256];
405 int expacc, prevexp;
406
407 /* unpack groups */
e2270b4e 408 group_size = exp_strategy + (exp_strategy == EXP_D45);
4415076f 409 for(grp=0,i=0; grp<ngrps; grp++) {
23c8cb89 410 expacc = get_bits(gbc, 7);
bfcf690c
JR
411 dexp[i++] = exp_ungroup_tab[expacc][0];
412 dexp[i++] = exp_ungroup_tab[expacc][1];
413 dexp[i++] = exp_ungroup_tab[expacc][2];
4415076f 414 }
2aa2c5c4 415
4415076f
JR
416 /* convert to absolute exps and expand groups */
417 prevexp = absexp;
418 for(i=0; i<ngrps*3; i++) {
419 prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
e2270b4e
JR
420 for(j=0; j<group_size; j++) {
421 dexps[(i*group_size)+j] = prevexp;
1b293437 422 }
2aa2c5c4 423 }
2aa2c5c4
JR
424}
425
d7dc7ad0 426/**
5066f515 427 * Generate transform coefficients for each coupled channel in the coupling
d7dc7ad0
JR
428 * range using the coupling coefficients and coupling coordinates.
429 * reference: Section 7.4.3 Coupling Coordinate Format
430 */
d802d7ca 431static void uncouple_channels(AC3DecodeContext *s)
d7dc7ad0
JR
432{
433 int i, j, ch, bnd, subbnd;
434
435 subbnd = -1;
d802d7ca
JR
436 i = s->start_freq[CPL_CH];
437 for(bnd=0; bnd<s->num_cpl_bands; bnd++) {
d7dc7ad0
JR
438 do {
439 subbnd++;
440 for(j=0; j<12; j++) {
d802d7ca 441 for(ch=1; ch<=s->fbw_channels; ch++) {
b02fbf75 442 if(s->channel_in_cpl[ch]) {
a4de6dd2 443 s->fixed_coeffs[ch][i] = ((int64_t)s->fixed_coeffs[CPL_CH][i] * (int64_t)s->cpl_coords[ch][bnd]) >> 23;
b02fbf75 444 if (ch == 2 && s->phase_flags[bnd])
a4de6dd2 445 s->fixed_coeffs[ch][i] = -s->fixed_coeffs[ch][i];
b02fbf75 446 }
d7dc7ad0
JR
447 }
448 i++;
449 }
d802d7ca 450 } while(s->cpl_band_struct[subbnd]);
d7dc7ad0
JR
451 }
452}
453
5066f515
JR
454/**
455 * Grouped mantissas for 3-level 5-level and 11-level quantization
456 */
457typedef struct {
a4de6dd2
JR
458 int b1_mant[3];
459 int b2_mant[3];
460 int b4_mant[2];
5aefe3eb
JR
461 int b1ptr;
462 int b2ptr;
463 int b4ptr;
486637af
JR
464} mant_groups;
465
5066f515
JR
466/**
467 * Get the transform coefficients for a particular channel
468 * reference: Section 7.3 Quantization and Decoding of Mantissas
469 */
ff5d419e 470static void get_transform_coeffs_ch(AC3DecodeContext *s, int ch_index, mant_groups *m)
1b293437 471{
d802d7ca 472 GetBitContext *gbc = &s->gbc;
60f07fad 473 int i, gcode, tbap, start, end;
2fbbd087
JR
474 uint8_t *exps;
475 uint8_t *bap;
a4de6dd2 476 int *coeffs;
2fbbd087 477
d802d7ca
JR
478 exps = s->dexps[ch_index];
479 bap = s->bap[ch_index];
a4de6dd2 480 coeffs = s->fixed_coeffs[ch_index];
d802d7ca
JR
481 start = s->start_freq[ch_index];
482 end = s->end_freq[ch_index];
1b293437 483
285bf28c 484 for (i = start; i < end; i++) {
98a27a8a
JR
485 tbap = bap[i];
486 switch (tbap) {
1b293437 487 case 0:
a4de6dd2 488 coeffs[i] = (av_random(&s->dith_state) & 0x7FFFFF) - 4194304;
d63f6fea 489 break;
1b293437
JR
490
491 case 1:
5aefe3eb 492 if(m->b1ptr > 2) {
23c8cb89 493 gcode = get_bits(gbc, 5);
5aefe3eb
JR
494 m->b1_mant[0] = b1_mantissas[gcode][0];
495 m->b1_mant[1] = b1_mantissas[gcode][1];
496 m->b1_mant[2] = b1_mantissas[gcode][2];
497 m->b1ptr = 0;
1b293437 498 }
5aefe3eb 499 coeffs[i] = m->b1_mant[m->b1ptr++];
d63f6fea 500 break;
1b293437
JR
501
502 case 2:
5aefe3eb 503 if(m->b2ptr > 2) {
23c8cb89 504 gcode = get_bits(gbc, 7);
5aefe3eb
JR
505 m->b2_mant[0] = b2_mantissas[gcode][0];
506 m->b2_mant[1] = b2_mantissas[gcode][1];
507 m->b2_mant[2] = b2_mantissas[gcode][2];
508 m->b2ptr = 0;
1b293437 509 }
5aefe3eb 510 coeffs[i] = m->b2_mant[m->b2ptr++];
d63f6fea 511 break;
1b293437
JR
512
513 case 3:
23c8cb89 514 coeffs[i] = b3_mantissas[get_bits(gbc, 3)];
d63f6fea 515 break;
1b293437
JR
516
517 case 4:
5aefe3eb 518 if(m->b4ptr > 1) {
23c8cb89 519 gcode = get_bits(gbc, 7);
5aefe3eb
JR
520 m->b4_mant[0] = b4_mantissas[gcode][0];
521 m->b4_mant[1] = b4_mantissas[gcode][1];
522 m->b4ptr = 0;
1b293437 523 }
5aefe3eb 524 coeffs[i] = m->b4_mant[m->b4ptr++];
d63f6fea 525 break;
1b293437
JR
526
527 case 5:
23c8cb89 528 coeffs[i] = b5_mantissas[get_bits(gbc, 4)];
d63f6fea 529 break;
1b293437 530
a4de6dd2 531 default: {
5066f515 532 /* asymmetric dequantization */
a4de6dd2
JR
533 int qlevel = quantization_tab[tbap];
534 coeffs[i] = get_sbits(gbc, qlevel) << (24 - qlevel);
d63f6fea 535 break;
a4de6dd2 536 }
1b293437 537 }
a4de6dd2 538 coeffs[i] >>= exps[i];
1b293437 539 }
1b293437
JR
540}
541
60f07fad 542/**
5066f515 543 * Remove random dithering from coefficients with zero-bit mantissas
60f07fad
JR
544 * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
545 */
d802d7ca 546static void remove_dithering(AC3DecodeContext *s) {
60f07fad
JR
547 int ch, i;
548 int end=0;
a4de6dd2 549 int *coeffs;
60f07fad
JR
550 uint8_t *bap;
551
d802d7ca
JR
552 for(ch=1; ch<=s->fbw_channels; ch++) {
553 if(!s->dither_flag[ch]) {
a4de6dd2 554 coeffs = s->fixed_coeffs[ch];
d802d7ca
JR
555 bap = s->bap[ch];
556 if(s->channel_in_cpl[ch])
557 end = s->start_freq[CPL_CH];
60f07fad 558 else
d802d7ca 559 end = s->end_freq[ch];
60f07fad 560 for(i=0; i<end; i++) {
12eaa3b7 561 if(!bap[i])
a4de6dd2 562 coeffs[i] = 0;
60f07fad 563 }
d802d7ca
JR
564 if(s->channel_in_cpl[ch]) {
565 bap = s->bap[CPL_CH];
566 for(; i<s->end_freq[CPL_CH]; i++) {
12eaa3b7 567 if(!bap[i])
a4de6dd2 568 coeffs[i] = 0;
60f07fad
JR
569 }
570 }
571 }
572 }
573}
574
5066f515
JR
575/**
576 * Get the transform coefficients.
c7cfc48f 577 */
ff5d419e 578static void get_transform_coeffs(AC3DecodeContext *s)
1b293437 579{
7b4076a7 580 int ch, end;
1b293437 581 int got_cplchan = 0;
486637af
JR
582 mant_groups m;
583
5aefe3eb 584 m.b1ptr = m.b2ptr = m.b4ptr = 3;
1b293437 585
d802d7ca 586 for (ch = 1; ch <= s->channels; ch++) {
5066f515 587 /* transform coefficients for full-bandwidth channel */
ff5d419e 588 get_transform_coeffs_ch(s, ch, &m);
5066f515
JR
589 /* tranform coefficients for coupling channel come right after the
590 coefficients for the first coupled channel*/
d802d7ca 591 if (s->channel_in_cpl[ch]) {
486637af 592 if (!got_cplchan) {
ff5d419e 593 get_transform_coeffs_ch(s, CPL_CH, &m);
d802d7ca 594 uncouple_channels(s);
486637af
JR
595 got_cplchan = 1;
596 }
d802d7ca 597 end = s->end_freq[CPL_CH];
eaf84d97 598 } else {
d802d7ca 599 end = s->end_freq[ch];
eaf84d97 600 }
486637af 601 do
bd98e9e2 602 s->fixed_coeffs[ch][end] = 0;
486637af
JR
603 while(++end < 256);
604 }
1b293437 605
60f07fad 606 /* if any channel doesn't use dithering, zero appropriate coefficients */
d802d7ca
JR
607 if(!s->dither_all)
608 remove_dithering(s);
2aa2c5c4
JR
609}
610
8b60bbbf 611/**
5066f515 612 * Stereo rematrixing.
8b60bbbf
JR
613 * reference: Section 7.5.4 Rematrixing : Decoding Technique
614 */
d802d7ca 615static void do_rematrixing(AC3DecodeContext *s)
1b293437 616{
8b60bbbf 617 int bnd, i;
2fbbd087 618 int end, bndend;
a4de6dd2 619 int tmp0, tmp1;
2fbbd087 620
d802d7ca 621 end = FFMIN(s->end_freq[1], s->end_freq[2]);
1b293437 622
d802d7ca
JR
623 for(bnd=0; bnd<s->num_rematrixing_bands; bnd++) {
624 if(s->rematrixing_flags[bnd]) {
bfcf690c
JR
625 bndend = FFMIN(end, rematrix_band_tab[bnd+1]);
626 for(i=rematrix_band_tab[bnd]; i<bndend; i++) {
a4de6dd2
JR
627 tmp0 = s->fixed_coeffs[1][i];
628 tmp1 = s->fixed_coeffs[2][i];
629 s->fixed_coeffs[1][i] = tmp0 + tmp1;
630 s->fixed_coeffs[2][i] = tmp0 - tmp1;
8b60bbbf
JR
631 }
632 }
1b293437
JR
633 }
634}
2aa2c5c4 635
5066f515
JR
636/**
637 * Perform the 256-point IMDCT
c7cfc48f 638 */
d802d7ca 639static void do_imdct_256(AC3DecodeContext *s, int chindex)
486637af 640{
0de73a46 641 int i, k;
dfd57c36 642 DECLARE_ALIGNED_16(float, x[128]);
0de73a46 643 FFTComplex z[2][64];
d802d7ca 644 float *o_ptr = s->tmp_output;
0de73a46
JR
645
646 for(i=0; i<2; i++) {
647 /* de-interleave coefficients */
648 for(k=0; k<128; k++) {
d802d7ca 649 x[k] = s->transform_coeffs[chindex][2*k+i];
0de73a46 650 }
98a27a8a 651
0de73a46 652 /* run standard IMDCT */
d802d7ca 653 s->imdct_256.fft.imdct_calc(&s->imdct_256, o_ptr, x, s->tmp_imdct);
0de73a46
JR
654
655 /* reverse the post-rotation & reordering from standard IMDCT */
656 for(k=0; k<32; k++) {
657 z[i][32+k].re = -o_ptr[128+2*k];
658 z[i][32+k].im = -o_ptr[2*k];
659 z[i][31-k].re = o_ptr[2*k+1];
660 z[i][31-k].im = o_ptr[128+2*k+1];
661 }
1ea76064 662 }
486637af 663
0de73a46
JR
664 /* apply AC-3 post-rotation & reordering */
665 for(k=0; k<64; k++) {
666 o_ptr[ 2*k ] = -z[0][ k].im;
667 o_ptr[ 2*k+1] = z[0][63-k].re;
668 o_ptr[128+2*k ] = -z[0][ k].re;
669 o_ptr[128+2*k+1] = z[0][63-k].im;
670 o_ptr[256+2*k ] = -z[1][ k].re;
671 o_ptr[256+2*k+1] = z[1][63-k].im;
672 o_ptr[384+2*k ] = z[1][ k].im;
673 o_ptr[384+2*k+1] = -z[1][63-k].re;
674 }
98a27a8a 675}
486637af 676
5066f515
JR
677/**
678 * Inverse MDCT Transform.
679 * Convert frequency domain coefficients to time-domain audio samples.
680 * reference: Section 7.9.4 Transformation Equations
681 */
38dae9c3 682static inline void do_imdct(AC3DecodeContext *s, int channels)
486637af 683{
0de73a46 684 int ch;
7b4076a7 685
e2270b4e 686 for (ch=1; ch<=channels; ch++) {
d802d7ca
JR
687 if (s->block_switch[ch]) {
688 do_imdct_256(s, ch);
eaf84d97 689 } else {
d802d7ca 690 s->imdct_512.fft.imdct_calc(&s->imdct_512, s->tmp_output,
1b70d88b 691 s->transform_coeffs[ch], s->tmp_imdct);
eaf84d97 692 }
5066f515
JR
693 /* For the first half of the block, apply the window, add the delay
694 from the previous block, and send to output */
d802d7ca
JR
695 s->dsp.vector_fmul_add_add(s->output[ch-1], s->tmp_output,
696 s->window, s->delay[ch-1], 0, 256, 1);
5066f515
JR
697 /* For the second half of the block, apply the window and store the
698 samples to delay, to be combined with the next block */
d802d7ca 699 s->dsp.vector_fmul_reverse(s->delay[ch-1], s->tmp_output+256,
1b70d88b 700 s->window, 256);
486637af
JR
701 }
702}
703
3bbb0bf8 704/**
5066f515 705 * Downmix the output to mono or stereo.
3bbb0bf8 706 */
38dae9c3
JR
707static void ac3_downmix(AC3DecodeContext *s,
708 float samples[AC3_MAX_CHANNELS][256], int ch_offset)
3bbb0bf8
JR
709{
710 int i, j;
9d10e6e6 711 float v0, v1;
3bbb0bf8
JR
712
713 for(i=0; i<256; i++) {
9d10e6e6 714 v0 = v1 = 0.0f;
b35c67e5 715 for(j=0; j<s->fbw_channels; j++) {
38dae9c3
JR
716 v0 += samples[j+ch_offset][i] * s->downmix_coeffs[j][0];
717 v1 += samples[j+ch_offset][i] * s->downmix_coeffs[j][1];
3bbb0bf8 718 }
d8870f12
JR
719 v0 *= s->downmix_coeff_adjust[0];
720 v1 *= s->downmix_coeff_adjust[1];
b35c67e5 721 if(s->output_mode == AC3_CHMODE_MONO) {
38dae9c3 722 samples[ch_offset][i] = (v0 + v1) * LEVEL_MINUS_3DB;
b35c67e5 723 } else if(s->output_mode == AC3_CHMODE_STEREO) {
38dae9c3
JR
724 samples[ ch_offset][i] = v0;
725 samples[1+ch_offset][i] = v1;
3bbb0bf8
JR
726 }
727 }
728}
729
5066f515 730/**
38dae9c3
JR
731 * Upmix delay samples from stereo to original channel layout.
732 */
733static void ac3_upmix_delay(AC3DecodeContext *s)
734{
735 int channel_data_size = sizeof(s->delay[0]);
736 switch(s->channel_mode) {
737 case AC3_CHMODE_DUALMONO:
738 case AC3_CHMODE_STEREO:
739 /* upmix mono to stereo */
740 memcpy(s->delay[1], s->delay[0], channel_data_size);
741 break;
742 case AC3_CHMODE_2F2R:
743 memset(s->delay[3], 0, channel_data_size);
744 case AC3_CHMODE_2F1R:
745 memset(s->delay[2], 0, channel_data_size);
746 break;
747 case AC3_CHMODE_3F2R:
748 memset(s->delay[4], 0, channel_data_size);
749 case AC3_CHMODE_3F1R:
750 memset(s->delay[3], 0, channel_data_size);
751 case AC3_CHMODE_3F:
752 memcpy(s->delay[2], s->delay[1], channel_data_size);
753 memset(s->delay[1], 0, channel_data_size);
754 break;
755 }
756}
757
758/**
5066f515 759 * Parse an audio block from AC-3 bitstream.
c7cfc48f 760 */
d802d7ca 761static int ac3_parse_audio_block(AC3DecodeContext *s, int blk)
2aa2c5c4 762{
d802d7ca
JR
763 int fbw_channels = s->fbw_channels;
764 int channel_mode = s->channel_mode;
0bff58a5 765 int i, bnd, seg, ch;
38dae9c3
JR
766 int different_transforms;
767 int downmix_output;
d802d7ca 768 GetBitContext *gbc = &s->gbc;
7b4076a7 769 uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
1b293437 770
7b4076a7
JR
771 memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
772
5066f515 773 /* block switch flags */
38dae9c3
JR
774 different_transforms = 0;
775 for (ch = 1; ch <= fbw_channels; ch++) {
d802d7ca 776 s->block_switch[ch] = get_bits1(gbc);
38dae9c3
JR
777 if(ch > 1 && s->block_switch[ch] != s->block_switch[1])
778 different_transforms = 1;
779 }
98a27a8a 780
5066f515 781 /* dithering flags */
d802d7ca 782 s->dither_all = 1;
e2270b4e 783 for (ch = 1; ch <= fbw_channels; ch++) {
d802d7ca
JR
784 s->dither_flag[ch] = get_bits1(gbc);
785 if(!s->dither_flag[ch])
786 s->dither_all = 0;
60f07fad 787 }
98a27a8a 788
77416325 789 /* dynamic range */
d802d7ca 790 i = !(s->channel_mode);
77416325 791 do {
23c8cb89 792 if(get_bits1(gbc)) {
d802d7ca 793 s->dynamic_range[i] = ((dynamic_range_tab[get_bits(gbc, 8)]-1.0) *
1b70d88b 794 s->avctx->drc_scale)+1.0;
9fc1ab72 795 } else if(blk == 0) {
d802d7ca 796 s->dynamic_range[i] = 1.0f;
9fc1ab72 797 }
77416325 798 } while(i--);
98a27a8a 799
5066f515 800 /* coupling strategy */
23c8cb89 801 if (get_bits1(gbc)) {
7b4076a7 802 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
d802d7ca
JR
803 s->cpl_in_use = get_bits1(gbc);
804 if (s->cpl_in_use) {
5066f515 805 /* coupling in use */
e2270b4e 806 int cpl_begin_freq, cpl_end_freq;
b6acc57f 807
3af91313
JR
808 if (channel_mode < AC3_CHMODE_STEREO) {
809 av_log(s->avctx, AV_LOG_ERROR, "coupling not allowed in mono or dual-mono\n");
810 return -1;
811 }
812
5066f515 813 /* determine which channels are coupled */
e2270b4e 814 for (ch = 1; ch <= fbw_channels; ch++)
d802d7ca 815 s->channel_in_cpl[ch] = get_bits1(gbc);
98a27a8a 816
5066f515 817 /* phase flags in use */
e59cc205 818 if (channel_mode == AC3_CHMODE_STEREO)
d802d7ca 819 s->phase_flags_in_use = get_bits1(gbc);
98a27a8a 820
5066f515 821 /* coupling frequency range and band structure */
23c8cb89
JR
822 cpl_begin_freq = get_bits(gbc, 4);
823 cpl_end_freq = get_bits(gbc, 4);
e2270b4e 824 if (3 + cpl_end_freq - cpl_begin_freq < 0) {
d802d7ca 825 av_log(s->avctx, AV_LOG_ERROR, "3+cplendf = %d < cplbegf = %d\n", 3+cpl_end_freq, cpl_begin_freq);
00585845 826 return -1;
98a27a8a 827 }
d802d7ca
JR
828 s->num_cpl_bands = s->num_cpl_subbands = 3 + cpl_end_freq - cpl_begin_freq;
829 s->start_freq[CPL_CH] = cpl_begin_freq * 12 + 37;
830 s->end_freq[CPL_CH] = cpl_end_freq * 12 + 73;
831 for (bnd = 0; bnd < s->num_cpl_subbands - 1; bnd++) {
23c8cb89 832 if (get_bits1(gbc)) {
d802d7ca
JR
833 s->cpl_band_struct[bnd] = 1;
834 s->num_cpl_bands--;
1b293437 835 }
eaf84d97 836 }
4bc829bb 837 s->cpl_band_struct[s->num_cpl_subbands-1] = 0;
878c40a1 838 } else {
5066f515 839 /* coupling not in use */
e2270b4e 840 for (ch = 1; ch <= fbw_channels; ch++)
d802d7ca 841 s->channel_in_cpl[ch] = 0;
1b293437 842 }
82a591d8
JR
843 } else if (!blk) {
844 av_log(s->avctx, AV_LOG_ERROR, "new coupling strategy must be present in block 0\n");
845 return -1;
1b293437 846 }
98a27a8a 847
5066f515 848 /* coupling coordinates */
d802d7ca 849 if (s->cpl_in_use) {
e2270b4e 850 int cpl_coords_exist = 0;
98a27a8a 851
e2270b4e 852 for (ch = 1; ch <= fbw_channels; ch++) {
d802d7ca 853 if (s->channel_in_cpl[ch]) {
23c8cb89 854 if (get_bits1(gbc)) {
e2270b4e
JR
855 int master_cpl_coord, cpl_coord_exp, cpl_coord_mant;
856 cpl_coords_exist = 1;
23c8cb89 857 master_cpl_coord = 3 * get_bits(gbc, 2);
d802d7ca 858 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
23c8cb89
JR
859 cpl_coord_exp = get_bits(gbc, 4);
860 cpl_coord_mant = get_bits(gbc, 4);
e2270b4e 861 if (cpl_coord_exp == 15)
a4de6dd2 862 s->cpl_coords[ch][bnd] = cpl_coord_mant << 22;
486637af 863 else
a4de6dd2
JR
864 s->cpl_coords[ch][bnd] = (cpl_coord_mant + 16) << 21;
865 s->cpl_coords[ch][bnd] >>= (cpl_coord_exp + master_cpl_coord);
486637af 866 }
82a591d8
JR
867 } else if (!blk) {
868 av_log(s->avctx, AV_LOG_ERROR, "new coupling coordinates must be present in block 0\n");
869 return -1;
486637af 870 }
eaf84d97
JR
871 }
872 }
5066f515 873 /* phase flags */
b02fbf75 874 if (channel_mode == AC3_CHMODE_STEREO && cpl_coords_exist) {
d802d7ca 875 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
b02fbf75 876 s->phase_flags[bnd] = s->phase_flags_in_use? get_bits1(gbc) : 0;
eaf84d97
JR
877 }
878 }
2aa2c5c4 879 }
98a27a8a 880
5066f515 881 /* stereo rematrixing strategy and band structure */
e59cc205 882 if (channel_mode == AC3_CHMODE_STEREO) {
82a6c481 883 if (get_bits1(gbc)) {
d802d7ca
JR
884 s->num_rematrixing_bands = 4;
885 if(s->cpl_in_use && s->start_freq[CPL_CH] <= 61)
886 s->num_rematrixing_bands -= 1 + (s->start_freq[CPL_CH] == 37);
887 for(bnd=0; bnd<s->num_rematrixing_bands; bnd++)
888 s->rematrixing_flags[bnd] = get_bits1(gbc);
82a591d8
JR
889 } else if (!blk) {
890 av_log(s->avctx, AV_LOG_ERROR, "new rematrixing strategy must be present in block 0\n");
891 return -1;
1b293437 892 }
98a27a8a
JR
893 }
894
5066f515 895 /* exponent strategies for each channel */
d802d7ca
JR
896 s->exp_strategy[CPL_CH] = EXP_REUSE;
897 s->exp_strategy[s->lfe_ch] = EXP_REUSE;
898 for (ch = !s->cpl_in_use; ch <= s->channels; ch++) {
899 if(ch == s->lfe_ch)
900 s->exp_strategy[ch] = get_bits(gbc, 1);
7b4076a7 901 else
d802d7ca
JR
902 s->exp_strategy[ch] = get_bits(gbc, 2);
903 if(s->exp_strategy[ch] != EXP_REUSE)
7b4076a7
JR
904 bit_alloc_stages[ch] = 3;
905 }
906
5066f515 907 /* channel bandwidth */
e2270b4e 908 for (ch = 1; ch <= fbw_channels; ch++) {
d802d7ca
JR
909 s->start_freq[ch] = 0;
910 if (s->exp_strategy[ch] != EXP_REUSE) {
b85a15fe 911 int group_size;
d802d7ca
JR
912 int prev = s->end_freq[ch];
913 if (s->channel_in_cpl[ch])
914 s->end_freq[ch] = s->start_freq[CPL_CH];
00585845 915 else {
23c8cb89 916 int bandwidth_code = get_bits(gbc, 6);
e2270b4e 917 if (bandwidth_code > 60) {
d802d7ca 918 av_log(s->avctx, AV_LOG_ERROR, "bandwidth code = %d > 60", bandwidth_code);
00585845
JR
919 return -1;
920 }
d802d7ca 921 s->end_freq[ch] = bandwidth_code * 3 + 73;
1b293437 922 }
b85a15fe
JR
923 group_size = 3 << (s->exp_strategy[ch] - 1);
924 s->num_exp_groups[ch] = (s->end_freq[ch]+group_size-4) / group_size;
d802d7ca 925 if(blk > 0 && s->end_freq[ch] != prev)
7b4076a7 926 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
00585845 927 }
eaf84d97 928 }
d802d7ca
JR
929 s->start_freq[s->lfe_ch] = 0;
930 s->end_freq[s->lfe_ch] = 7;
b85a15fe
JR
931 s->num_exp_groups[s->lfe_ch] = 2;
932 if (s->cpl_in_use && s->exp_strategy[CPL_CH] != EXP_REUSE) {
933 s->num_exp_groups[CPL_CH] = (s->end_freq[CPL_CH] - s->start_freq[CPL_CH]) /
934 (3 << (s->exp_strategy[CPL_CH] - 1));
935 }
7b4076a7 936
5066f515 937 /* decode exponents for each channel */
d802d7ca
JR
938 for (ch = !s->cpl_in_use; ch <= s->channels; ch++) {
939 if (s->exp_strategy[ch] != EXP_REUSE) {
d802d7ca 940 s->dexps[ch][0] = get_bits(gbc, 4) << !ch;
b85a15fe
JR
941 decode_exponents(gbc, s->exp_strategy[ch],
942 s->num_exp_groups[ch], s->dexps[ch][0],
d802d7ca
JR
943 &s->dexps[ch][s->start_freq[ch]+!!ch]);
944 if(ch != CPL_CH && ch != s->lfe_ch)
23c8cb89 945 skip_bits(gbc, 2); /* skip gainrng */
1b293437 946 }
eaf84d97 947 }
98a27a8a 948
5066f515 949 /* bit allocation information */
23c8cb89 950 if (get_bits1(gbc)) {
d802d7ca
JR
951 s->bit_alloc_params.slow_decay = ff_ac3_slow_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
952 s->bit_alloc_params.fast_decay = ff_ac3_fast_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
953 s->bit_alloc_params.slow_gain = ff_ac3_slow_gain_tab[get_bits(gbc, 2)];
954 s->bit_alloc_params.db_per_bit = ff_ac3_db_per_bit_tab[get_bits(gbc, 2)];
955 s->bit_alloc_params.floor = ff_ac3_floor_tab[get_bits(gbc, 3)];
aa148649 956 for(ch=!s->cpl_in_use; ch<=s->channels; ch++)
7b4076a7 957 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
82a591d8
JR
958 } else if (!blk) {
959 av_log(s->avctx, AV_LOG_ERROR, "new bit allocation info must be present in block 0\n");
960 return -1;
1b293437 961 }
98a27a8a 962
5066f515 963 /* signal-to-noise ratio offsets and fast gains (signal-to-mask ratios) */
23c8cb89 964 if (get_bits1(gbc)) {
4611b64e 965 int csnr;
23c8cb89 966 csnr = (get_bits(gbc, 6) - 15) << 4;
d802d7ca
JR
967 for (ch = !s->cpl_in_use; ch <= s->channels; ch++) { /* snr offset and fast gain */
968 s->snr_offset[ch] = (csnr + get_bits(gbc, 4)) << 2;
969 s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];
1b293437 970 }
7b4076a7 971 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
82a591d8
JR
972 } else if (!blk) {
973 av_log(s->avctx, AV_LOG_ERROR, "new snr offsets must be present in block 0\n");
974 return -1;
1b293437 975 }
98a27a8a 976
5066f515 977 /* coupling leak information */
43ad93a4
JR
978 if (s->cpl_in_use) {
979 if (get_bits1(gbc)) {
93a2c8c1
JR
980 s->bit_alloc_params.cpl_fast_leak = get_bits(gbc, 3);
981 s->bit_alloc_params.cpl_slow_leak = get_bits(gbc, 3);
982 bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
983 } else if (!blk) {
984 av_log(s->avctx, AV_LOG_ERROR, "new coupling leak info must be present in block 0\n");
985 return -1;
986 }
43ad93a4 987 }
98a27a8a 988
5066f515 989 /* delta bit allocation information */
23c8cb89 990 if (get_bits1(gbc)) {
5066f515 991 /* delta bit allocation exists (strategy) */
d802d7ca
JR
992 for (ch = !s->cpl_in_use; ch <= fbw_channels; ch++) {
993 s->dba_mode[ch] = get_bits(gbc, 2);
994 if (s->dba_mode[ch] == DBA_RESERVED) {
995 av_log(s->avctx, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
1b293437
JR
996 return -1;
997 }
7b4076a7 998 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1b293437 999 }
5066f515 1000 /* channel delta offset, len and bit allocation */
d802d7ca
JR
1001 for (ch = !s->cpl_in_use; ch <= fbw_channels; ch++) {
1002 if (s->dba_mode[ch] == DBA_NEW) {
1003 s->dba_nsegs[ch] = get_bits(gbc, 3);
1004 for (seg = 0; seg <= s->dba_nsegs[ch]; seg++) {
1005 s->dba_offsets[ch][seg] = get_bits(gbc, 5);
1006 s->dba_lengths[ch][seg] = get_bits(gbc, 4);
1007 s->dba_values[ch][seg] = get_bits(gbc, 3);
1b293437 1008 }
e25973a1
JR
1009 /* run last 2 bit allocation stages if new dba values */
1010 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1b293437 1011 }
eaf84d97 1012 }
9fc1ab72 1013 } else if(blk == 0) {
d802d7ca
JR
1014 for(ch=0; ch<=s->channels; ch++) {
1015 s->dba_mode[ch] = DBA_NONE;
9fc1ab72 1016 }
1b293437 1017 }
00585845 1018
5066f515 1019 /* Bit allocation */
d802d7ca 1020 for(ch=!s->cpl_in_use; ch<=s->channels; ch++) {
7b4076a7
JR
1021 if(bit_alloc_stages[ch] > 2) {
1022 /* Exponent mapping into PSD and PSD integration */
d802d7ca
JR
1023 ff_ac3_bit_alloc_calc_psd(s->dexps[ch],
1024 s->start_freq[ch], s->end_freq[ch],
1025 s->psd[ch], s->band_psd[ch]);
eaf84d97 1026 }
7b4076a7
JR
1027 if(bit_alloc_stages[ch] > 1) {
1028 /* Compute excitation function, Compute masking curve, and
1029 Apply delta bit allocation */
d802d7ca
JR
1030 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc_params, s->band_psd[ch],
1031 s->start_freq[ch], s->end_freq[ch],
1032 s->fast_gain[ch], (ch == s->lfe_ch),
1033 s->dba_mode[ch], s->dba_nsegs[ch],
1034 s->dba_offsets[ch], s->dba_lengths[ch],
1035 s->dba_values[ch], s->mask[ch]);
eaf84d97 1036 }
7b4076a7
JR
1037 if(bit_alloc_stages[ch] > 0) {
1038 /* Compute bit allocation */
d802d7ca
JR
1039 ff_ac3_bit_alloc_calc_bap(s->mask[ch], s->psd[ch],
1040 s->start_freq[ch], s->end_freq[ch],
1041 s->snr_offset[ch],
1042 s->bit_alloc_params.floor,
1043 s->bap[ch]);
eaf84d97 1044 }
2fbbd087 1045 }
98a27a8a 1046
5066f515 1047 /* unused dummy data */
23c8cb89
JR
1048 if (get_bits1(gbc)) {
1049 int skipl = get_bits(gbc, 9);
98a27a8a 1050 while(skipl--)
23c8cb89 1051 skip_bits(gbc, 8);
1b293437 1052 }
f5cefb21 1053
1b293437 1054 /* unpack the transform coefficients
5066f515 1055 this also uncouples channels if coupling is in use. */
ff5d419e 1056 get_transform_coeffs(s);
486637af 1057
1b293437 1058 /* recover coefficients if rematrixing is in use */
d802d7ca
JR
1059 if(s->channel_mode == AC3_CHMODE_STEREO)
1060 do_rematrixing(s);
1b293437 1061
03726b70 1062 /* apply scaling to coefficients (headroom, dynrng) */
d802d7ca 1063 for(ch=1; ch<=s->channels; ch++) {
a4de6dd2 1064 float gain = s->mul_bias / 4194304.0f;
d802d7ca
JR
1065 if(s->channel_mode == AC3_CHMODE_DUALMONO) {
1066 gain *= s->dynamic_range[ch-1];
7bfd22f2 1067 } else {
d802d7ca 1068 gain *= s->dynamic_range[0];
7bfd22f2 1069 }
a4de6dd2
JR
1070 for(i=0; i<256; i++) {
1071 s->transform_coeffs[ch][i] = s->fixed_coeffs[ch][i] * gain;
7bfd22f2
JR
1072 }
1073 }
d7bcc4ad 1074
38dae9c3
JR
1075 /* downmix and MDCT. order depends on whether block switching is used for
1076 any channel in this block. this is because coefficients for the long
1077 and short transforms cannot be mixed. */
1078 downmix_output = s->channels != s->out_channels &&
1079 !((s->output_mode & AC3_OUTPUT_LFEON) &&
1080 s->fbw_channels == s->out_channels);
1081 if(different_transforms) {
1082 /* the delay samples have already been downmixed, so we upmix the delay
1083 samples in order to reconstruct all channels before downmixing. */
1084 if(s->downmixed) {
1085 s->downmixed = 0;
1086 ac3_upmix_delay(s);
1087 }
1088
1089 do_imdct(s, s->channels);
1090
1091 if(downmix_output) {
1092 ac3_downmix(s, s->output, 0);
1093 }
1094 } else {
1095 if(downmix_output) {
1096 ac3_downmix(s, s->transform_coeffs, 1);
1097 }
1098
1099 if(!s->downmixed) {
1100 s->downmixed = 1;
1101 ac3_downmix(s, s->delay, 0);
1102 }
486637af 1103
38dae9c3 1104 do_imdct(s, s->out_channels);
3bbb0bf8
JR
1105 }
1106
4e092320 1107 /* convert float to 16-bit integer */
d802d7ca 1108 for(ch=0; ch<s->out_channels; ch++) {
3bbb0bf8 1109 for(i=0; i<256; i++) {
d802d7ca 1110 s->output[ch][i] += s->add_bias;
3bbb0bf8 1111 }
d802d7ca 1112 s->dsp.float_to_int16(s->int_output[ch], s->output[ch], 256);
4e092320 1113 }
1b293437 1114
4e092320 1115 return 0;
486637af
JR
1116}
1117
5066f515
JR
1118/**
1119 * Decode a single AC-3 frame.
c7cfc48f 1120 */
98f6dfa6
JR
1121static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size,
1122 const uint8_t *buf, int buf_size)
1b293437 1123{
0345fade 1124 AC3DecodeContext *s = avctx->priv_data;
00585845 1125 int16_t *out_samples = (int16_t *)data;
3df88093 1126 int i, blk, ch, err;
d7bcc4ad 1127
5066f515 1128 /* initialize the GetBitContext with the start of valid AC-3 Frame */
509fdb0b 1129 if (s->input_buffer) {
c33a1967
JR
1130 /* copy input buffer to decoder context to avoid reading past the end
1131 of the buffer, which can be caused by a damaged input stream. */
1132 memcpy(s->input_buffer, buf, FFMIN(buf_size, AC3_MAX_FRAME_SIZE));
1133 init_get_bits(&s->gbc, s->input_buffer, buf_size * 8);
1134 } else {
984ff38a 1135 init_get_bits(&s->gbc, buf, buf_size * 8);
c33a1967 1136 }
00585845 1137
5066f515 1138 /* parse the syncinfo */
c78c6d6c 1139 *data_size = 0;
d802d7ca 1140 err = ac3_parse_header(s);
c78c6d6c
JR
1141
1142 /* check that reported frame size fits in input buffer */
1143 if(s->frame_size > buf_size) {
1144 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1145 err = AC3_PARSE_ERROR_FRAME_SIZE;
1146 }
1147
1148 /* check for crc mismatch */
1149 if(err != AC3_PARSE_ERROR_FRAME_SIZE && avctx->error_resilience >= FF_ER_CAREFUL) {
1150 if(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, &buf[2], s->frame_size-2)) {
1151 av_log(avctx, AV_LOG_ERROR, "frame CRC mismatch\n");
fbe52e41 1152 err = AC3_PARSE_ERROR_CRC;
c78c6d6c
JR
1153 }
1154 }
1155
1156 /* parse the syncinfo */
fbe52e41 1157 if(err && err != AC3_PARSE_ERROR_CRC) {
3df88093
JR
1158 switch(err) {
1159 case AC3_PARSE_ERROR_SYNC:
c78c6d6c
JR
1160 av_log(avctx, AV_LOG_ERROR, "frame sync error\n");
1161 break;
3df88093
JR
1162 case AC3_PARSE_ERROR_BSID:
1163 av_log(avctx, AV_LOG_ERROR, "invalid bitstream id\n");
1164 break;
1165 case AC3_PARSE_ERROR_SAMPLE_RATE:
1166 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1167 break;
1168 case AC3_PARSE_ERROR_FRAME_SIZE:
1169 av_log(avctx, AV_LOG_ERROR, "invalid frame size\n");
1170 break;
79b25a27
BW
1171 case AC3_PARSE_ERROR_FRAME_TYPE:
1172 av_log(avctx, AV_LOG_ERROR, "invalid frame type\n");
4e6eeaf0 1173 break;
3df88093
JR
1174 default:
1175 av_log(avctx, AV_LOG_ERROR, "invalid header\n");
1176 break;
1177 }
1b293437 1178 }
2aa2c5c4 1179
eccba2bc
JR
1180 /* if frame is ok, set audio parameters */
1181 if (!err) {
3336110a
JR
1182 avctx->sample_rate = s->sample_rate;
1183 avctx->bit_rate = s->bit_rate;
1184
1185 /* channel config */
1186 s->out_channels = s->channels;
eccba2bc
JR
1187 s->output_mode = s->channel_mode;
1188 if(s->lfe_on)
1189 s->output_mode |= AC3_OUTPUT_LFEON;
3336110a
JR
1190 if (avctx->request_channels > 0 && avctx->request_channels <= 2 &&
1191 avctx->request_channels < s->channels) {
1192 s->out_channels = avctx->request_channels;
1193 s->output_mode = avctx->request_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO;
1194 }
1195 avctx->channels = s->out_channels;
1b293437 1196
3336110a
JR
1197 /* set downmixing coefficients if needed */
1198 if(s->channels != s->out_channels && !((s->output_mode & AC3_OUTPUT_LFEON) &&
1199 s->fbw_channels == s->out_channels)) {
1200 set_downmix_coeffs(s);
1201 }
eccba2bc
JR
1202 } else if (!s->out_channels) {
1203 s->out_channels = avctx->channels;
1204 if(s->out_channels < s->channels)
1205 s->output_mode = s->out_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO;
ecfe94b2 1206 }
f0b3a7ba 1207
5066f515 1208 /* parse the audio blocks */
75b9b036 1209 for (blk = 0; blk < NB_BLOCKS; blk++) {
ecfe94b2 1210 if (!err && ac3_parse_audio_block(s, blk)) {
1b293437 1211 av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
1b293437 1212 }
75b9b036 1213 for (i = 0; i < 256; i++)
d802d7ca
JR
1214 for (ch = 0; ch < s->out_channels; ch++)
1215 *(out_samples++) = s->int_output[ch][i];
1b293437 1216 }
8fbb368d 1217 *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
d802d7ca 1218 return s->frame_size;
2aa2c5c4 1219}
1b293437 1220
5066f515
JR
1221/**
1222 * Uninitialize the AC-3 decoder.
c7cfc48f 1223 */
98a6fff9 1224static av_cold int ac3_decode_end(AVCodecContext *avctx)
1b293437 1225{
0345fade 1226 AC3DecodeContext *s = avctx->priv_data;
d802d7ca
JR
1227 ff_mdct_end(&s->imdct_512);
1228 ff_mdct_end(&s->imdct_256);
c7cfc48f 1229
509fdb0b
JR
1230 av_freep(&s->input_buffer);
1231
1b293437
JR
1232 return 0;
1233}
1234
fa67992d 1235AVCodec ac3_decoder = {
e6bca37c
JR
1236 .name = "ac3",
1237 .type = CODEC_TYPE_AUDIO,
1238 .id = CODEC_ID_AC3,
1239 .priv_data_size = sizeof (AC3DecodeContext),
1240 .init = ac3_decode_init,
1241 .close = ac3_decode_end,
1242 .decode = ac3_decode_frame,
162d4fc9 1243 .long_name = "ATSC A/52 / AC-3",
1b293437 1244};