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