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