]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3dec.c
Merge commit 'c1bcd321ea2c2ae1765a1e64f03278712221d726'
[ffmpeg] / libavcodec / ac3dec.c
1 /*
2  * AC-3 Audio Decoder
3  * This code was developed as part of Google Summer of Code 2006.
4  * E-AC-3 support was added as part of Google Summer of Code 2007.
5  *
6  * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com)
7  * Copyright (c) 2007-2008 Bartlomiej Wolowiec <bartek.wolowiec@gmail.com>
8  * Copyright (c) 2007 Justin Ruggles <justin.ruggles@gmail.com>
9  *
10  * This file is part of FFmpeg.
11  *
12  * FFmpeg is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * FFmpeg is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with FFmpeg; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26
27 #include <stdio.h>
28 #include <stddef.h>
29 #include <math.h>
30 #include <string.h>
31
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/crc.h"
34 #include "libavutil/downmix_info.h"
35 #include "libavutil/opt.h"
36 #include "bswapdsp.h"
37 #include "internal.h"
38 #include "aac_ac3_parser.h"
39 #include "ac3_parser_internal.h"
40 #include "ac3dec.h"
41 #include "ac3dec_data.h"
42 #include "kbdwin.h"
43
44 /**
45  * table for ungrouping 3 values in 7 bits.
46  * used for exponents and bap=2 mantissas
47  */
48 static uint8_t ungroup_3_in_7_bits_tab[128][3];
49
50 /** tables for ungrouping mantissas */
51 static int b1_mantissas[32][3];
52 static int b2_mantissas[128][3];
53 static int b3_mantissas[8];
54 static int b4_mantissas[128][2];
55 static int b5_mantissas[16];
56
57 /**
58  * Quantization table: levels for symmetric. bits for asymmetric.
59  * reference: Table 7.18 Mapping of bap to Quantizer
60  */
61 static const uint8_t quantization_tab[16] = {
62     0, 3, 5, 7, 11, 15,
63     5, 6, 7, 8, 9, 10, 11, 12, 14, 16
64 };
65
66 #if (!USE_FIXED)
67 /** dynamic range table. converts codes to scale factors. */
68 static float dynamic_range_tab[256];
69 float ff_ac3_heavy_dynamic_range_tab[256];
70 #endif
71
72 /** Adjustments in dB gain */
73 static const float gain_levels[9] = {
74     LEVEL_PLUS_3DB,
75     LEVEL_PLUS_1POINT5DB,
76     LEVEL_ONE,
77     LEVEL_MINUS_1POINT5DB,
78     LEVEL_MINUS_3DB,
79     LEVEL_MINUS_4POINT5DB,
80     LEVEL_MINUS_6DB,
81     LEVEL_ZERO,
82     LEVEL_MINUS_9DB
83 };
84
85 /** Adjustments in dB gain (LFE, +10 to -21 dB) */
86 static const float gain_levels_lfe[32] = {
87     3.162275, 2.818382, 2.511886, 2.238719, 1.995261, 1.778278, 1.584893,
88     1.412536, 1.258924, 1.122018, 1.000000, 0.891251, 0.794328, 0.707946,
89     0.630957, 0.562341, 0.501187, 0.446683, 0.398107, 0.354813, 0.316227,
90     0.281838, 0.251188, 0.223872, 0.199526, 0.177828, 0.158489, 0.141253,
91     0.125892, 0.112201, 0.100000, 0.089125
92 };
93
94 /**
95  * Table for default stereo downmixing coefficients
96  * reference: Section 7.8.2 Downmixing Into Two Channels
97  */
98 static const uint8_t ac3_default_coeffs[8][5][2] = {
99     { { 2, 7 }, { 7, 2 },                               },
100     { { 4, 4 },                                         },
101     { { 2, 7 }, { 7, 2 },                               },
102     { { 2, 7 }, { 5, 5 }, { 7, 2 },                     },
103     { { 2, 7 }, { 7, 2 }, { 6, 6 },                     },
104     { { 2, 7 }, { 5, 5 }, { 7, 2 }, { 8, 8 },           },
105     { { 2, 7 }, { 7, 2 }, { 6, 7 }, { 7, 6 },           },
106     { { 2, 7 }, { 5, 5 }, { 7, 2 }, { 6, 7 }, { 7, 6 }, },
107 };
108
109 static const uint64_t custom_channel_map_locations[16][2] = {
110     { 1, AV_CH_FRONT_LEFT },
111     { 1, AV_CH_FRONT_CENTER },
112     { 1, AV_CH_FRONT_RIGHT },
113     { 1, AV_CH_SIDE_LEFT },
114     { 1, AV_CH_SIDE_RIGHT },
115     { 0, AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER },
116     { 0, AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT },
117     { 0, AV_CH_BACK_CENTER },
118     { 0, AV_CH_TOP_CENTER },
119     { 0, AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT },
120     { 0, AV_CH_WIDE_LEFT | AV_CH_WIDE_RIGHT },
121     { 0, AV_CH_TOP_FRONT_LEFT | AV_CH_TOP_FRONT_RIGHT},
122     { 0, AV_CH_TOP_FRONT_CENTER },
123     { 0, AV_CH_TOP_BACK_LEFT | AV_CH_TOP_BACK_RIGHT },
124     { 0, AV_CH_LOW_FREQUENCY_2 },
125     { 1, AV_CH_LOW_FREQUENCY },
126 };
127
128 /**
129  * Symmetrical Dequantization
130  * reference: Section 7.3.3 Expansion of Mantissas for Symmetrical Quantization
131  *            Tables 7.19 to 7.23
132  */
133 static inline int
134 symmetric_dequant(int code, int levels)
135 {
136     return ((code - (levels >> 1)) * (1 << 24)) / levels;
137 }
138
139 /*
140  * Initialize tables at runtime.
141  */
142 static av_cold void ac3_tables_init(void)
143 {
144     int i;
145
146     /* generate table for ungrouping 3 values in 7 bits
147        reference: Section 7.1.3 Exponent Decoding */
148     for (i = 0; i < 128; i++) {
149         ungroup_3_in_7_bits_tab[i][0] =  i / 25;
150         ungroup_3_in_7_bits_tab[i][1] = (i % 25) / 5;
151         ungroup_3_in_7_bits_tab[i][2] = (i % 25) % 5;
152     }
153
154     /* generate grouped mantissa tables
155        reference: Section 7.3.5 Ungrouping of Mantissas */
156     for (i = 0; i < 32; i++) {
157         /* bap=1 mantissas */
158         b1_mantissas[i][0] = symmetric_dequant(ff_ac3_ungroup_3_in_5_bits_tab[i][0], 3);
159         b1_mantissas[i][1] = symmetric_dequant(ff_ac3_ungroup_3_in_5_bits_tab[i][1], 3);
160         b1_mantissas[i][2] = symmetric_dequant(ff_ac3_ungroup_3_in_5_bits_tab[i][2], 3);
161     }
162     for (i = 0; i < 128; i++) {
163         /* bap=2 mantissas */
164         b2_mantissas[i][0] = symmetric_dequant(ungroup_3_in_7_bits_tab[i][0], 5);
165         b2_mantissas[i][1] = symmetric_dequant(ungroup_3_in_7_bits_tab[i][1], 5);
166         b2_mantissas[i][2] = symmetric_dequant(ungroup_3_in_7_bits_tab[i][2], 5);
167
168         /* bap=4 mantissas */
169         b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
170         b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
171     }
172     /* generate ungrouped mantissa tables
173        reference: Tables 7.21 and 7.23 */
174     for (i = 0; i < 7; i++) {
175         /* bap=3 mantissas */
176         b3_mantissas[i] = symmetric_dequant(i, 7);
177     }
178     for (i = 0; i < 15; i++) {
179         /* bap=5 mantissas */
180         b5_mantissas[i] = symmetric_dequant(i, 15);
181     }
182
183 #if (!USE_FIXED)
184     /* generate dynamic range table
185        reference: Section 7.7.1 Dynamic Range Control */
186     for (i = 0; i < 256; i++) {
187         int v = (i >> 5) - ((i >> 7) << 3) - 5;
188         dynamic_range_tab[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
189     }
190
191     /* generate compr dynamic range table
192        reference: Section 7.7.2 Heavy Compression */
193     for (i = 0; i < 256; i++) {
194         int v = (i >> 4) - ((i >> 7) << 4) - 4;
195         ff_ac3_heavy_dynamic_range_tab[i] = powf(2.0f, v) * ((i & 0xF) | 0x10);
196     }
197 #endif
198 }
199
200 /**
201  * AVCodec initialization
202  */
203 static av_cold int ac3_decode_init(AVCodecContext *avctx)
204 {
205     AC3DecodeContext *s = avctx->priv_data;
206     int i;
207
208     s->avctx = avctx;
209
210     ac3_tables_init();
211     ff_mdct_init(&s->imdct_256, 8, 1, 1.0);
212     ff_mdct_init(&s->imdct_512, 9, 1, 1.0);
213     AC3_RENAME(ff_kbd_window_init)(s->window, 5.0, 256);
214     ff_bswapdsp_init(&s->bdsp);
215
216 #if (USE_FIXED)
217     s->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & AV_CODEC_FLAG_BITEXACT);
218 #else
219     s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
220     ff_fmt_convert_init(&s->fmt_conv, avctx);
221 #endif
222
223     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
224     av_lfg_init(&s->dith_state, 0);
225
226     if (USE_FIXED)
227         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
228     else
229         avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
230
231     /* allow downmixing to stereo or mono */
232     if (avctx->channels > 1 &&
233         avctx->request_channel_layout == AV_CH_LAYOUT_MONO)
234         avctx->channels = 1;
235     else if (avctx->channels > 2 &&
236              avctx->request_channel_layout == AV_CH_LAYOUT_STEREO)
237         avctx->channels = 2;
238     s->downmixed = 1;
239
240     for (i = 0; i < AC3_MAX_CHANNELS; i++) {
241         s->xcfptr[i] = s->transform_coeffs[i];
242         s->dlyptr[i] = s->delay[i];
243     }
244
245     return 0;
246 }
247
248 /**
249  * Parse the 'sync info' and 'bit stream info' from the AC-3 bitstream.
250  * GetBitContext within AC3DecodeContext must point to
251  * the start of the synchronized AC-3 bitstream.
252  */
253 static int ac3_parse_header(AC3DecodeContext *s)
254 {
255     GetBitContext *gbc = &s->gbc;
256     int i;
257
258     /* read the rest of the bsi. read twice for dual mono mode. */
259     i = !s->channel_mode;
260     do {
261         s->dialog_normalization[(!s->channel_mode)-i] = -get_bits(gbc, 5);
262         if (s->dialog_normalization[(!s->channel_mode)-i] == 0) {
263             s->dialog_normalization[(!s->channel_mode)-i] = -31;
264         }
265         if (s->target_level != 0) {
266             s->level_gain[(!s->channel_mode)-i] = powf(2.0f,
267                 (float)(s->target_level -
268                 s->dialog_normalization[(!s->channel_mode)-i])/6.0f);
269         }
270         if (s->compression_exists[(!s->channel_mode)-i] = get_bits1(gbc)) {
271             s->heavy_dynamic_range[(!s->channel_mode)-i] =
272                 AC3_HEAVY_RANGE(get_bits(gbc, 8));
273         }
274         if (get_bits1(gbc))
275             skip_bits(gbc, 8); //skip language code
276         if (get_bits1(gbc))
277             skip_bits(gbc, 7); //skip audio production information
278     } while (i--);
279
280     skip_bits(gbc, 2); //skip copyright bit and original bitstream bit
281
282     /* skip the timecodes or parse the Alternate Bit Stream Syntax */
283     if (s->bitstream_id != 6) {
284         if (get_bits1(gbc))
285             skip_bits(gbc, 14); //skip timecode1
286         if (get_bits1(gbc))
287             skip_bits(gbc, 14); //skip timecode2
288     } else {
289         if (get_bits1(gbc)) {
290             s->preferred_downmix       = get_bits(gbc, 2);
291             s->center_mix_level_ltrt   = get_bits(gbc, 3);
292             s->surround_mix_level_ltrt = av_clip(get_bits(gbc, 3), 3, 7);
293             s->center_mix_level        = get_bits(gbc, 3);
294             s->surround_mix_level      = av_clip(get_bits(gbc, 3), 3, 7);
295         }
296         if (get_bits1(gbc)) {
297             s->dolby_surround_ex_mode = get_bits(gbc, 2);
298             s->dolby_headphone_mode   = get_bits(gbc, 2);
299             skip_bits(gbc, 10); // skip adconvtyp (1), xbsi2 (8), encinfo (1)
300         }
301     }
302
303     /* skip additional bitstream info */
304     if (get_bits1(gbc)) {
305         i = get_bits(gbc, 6);
306         do {
307             skip_bits(gbc, 8);
308         } while (i--);
309     }
310
311     return 0;
312 }
313
314 /**
315  * Common function to parse AC-3 or E-AC-3 frame header
316  */
317 static int parse_frame_header(AC3DecodeContext *s)
318 {
319     AC3HeaderInfo hdr;
320     int err;
321
322     err = ff_ac3_parse_header(&s->gbc, &hdr);
323     if (err)
324         return err;
325
326     /* get decoding parameters from header info */
327     s->bit_alloc_params.sr_code     = hdr.sr_code;
328     s->bitstream_id                 = hdr.bitstream_id;
329     s->bitstream_mode               = hdr.bitstream_mode;
330     s->channel_mode                 = hdr.channel_mode;
331     s->lfe_on                       = hdr.lfe_on;
332     s->bit_alloc_params.sr_shift    = hdr.sr_shift;
333     s->sample_rate                  = hdr.sample_rate;
334     s->bit_rate                     = hdr.bit_rate;
335     s->channels                     = hdr.channels;
336     s->fbw_channels                 = s->channels - s->lfe_on;
337     s->lfe_ch                       = s->fbw_channels + 1;
338     s->frame_size                   = hdr.frame_size;
339     s->superframe_size             += hdr.frame_size;
340     s->preferred_downmix            = AC3_DMIXMOD_NOTINDICATED;
341     s->center_mix_level             = hdr.center_mix_level;
342     s->center_mix_level_ltrt        = 4; // -3.0dB
343     s->surround_mix_level           = hdr.surround_mix_level;
344     s->surround_mix_level_ltrt      = 4; // -3.0dB
345     s->lfe_mix_level_exists         = 0;
346     s->num_blocks                   = hdr.num_blocks;
347     s->frame_type                   = hdr.frame_type;
348     s->substreamid                  = hdr.substreamid;
349     s->dolby_surround_mode          = hdr.dolby_surround_mode;
350     s->dolby_surround_ex_mode       = AC3_DSUREXMOD_NOTINDICATED;
351     s->dolby_headphone_mode         = AC3_DHEADPHONMOD_NOTINDICATED;
352
353     if (s->lfe_on) {
354         s->start_freq[s->lfe_ch]     = 0;
355         s->end_freq[s->lfe_ch]       = 7;
356         s->num_exp_groups[s->lfe_ch] = 2;
357         s->channel_in_cpl[s->lfe_ch] = 0;
358     }
359
360     if (s->bitstream_id <= 10) {
361         s->eac3                  = 0;
362         s->snr_offset_strategy   = 2;
363         s->block_switch_syntax   = 1;
364         s->dither_flag_syntax    = 1;
365         s->bit_allocation_syntax = 1;
366         s->fast_gain_syntax      = 0;
367         s->first_cpl_leak        = 0;
368         s->dba_syntax            = 1;
369         s->skip_syntax           = 1;
370         memset(s->channel_uses_aht, 0, sizeof(s->channel_uses_aht));
371         return ac3_parse_header(s);
372     } else if (CONFIG_EAC3_DECODER) {
373         s->eac3 = 1;
374         return ff_eac3_parse_header(s);
375     } else {
376         av_log(s->avctx, AV_LOG_ERROR, "E-AC-3 support not compiled in\n");
377         return AVERROR(ENOSYS);
378     }
379 }
380
381 /**
382  * Set stereo downmixing coefficients based on frame header info.
383  * reference: Section 7.8.2 Downmixing Into Two Channels
384  */
385 static int set_downmix_coeffs(AC3DecodeContext *s)
386 {
387     int i;
388     float cmix = gain_levels[s->  center_mix_level];
389     float smix = gain_levels[s->surround_mix_level];
390     float norm0, norm1;
391     float downmix_coeffs[2][AC3_MAX_CHANNELS];
392
393     if (!s->downmix_coeffs[0]) {
394         s->downmix_coeffs[0] = av_malloc_array(2 * AC3_MAX_CHANNELS,
395                                                sizeof(**s->downmix_coeffs));
396         if (!s->downmix_coeffs[0])
397             return AVERROR(ENOMEM);
398         s->downmix_coeffs[1] = s->downmix_coeffs[0] + AC3_MAX_CHANNELS;
399     }
400
401     for (i = 0; i < s->fbw_channels; i++) {
402         downmix_coeffs[0][i] = gain_levels[ac3_default_coeffs[s->channel_mode][i][0]];
403         downmix_coeffs[1][i] = gain_levels[ac3_default_coeffs[s->channel_mode][i][1]];
404     }
405     if (s->channel_mode > 1 && s->channel_mode & 1) {
406         downmix_coeffs[0][1] = downmix_coeffs[1][1] = cmix;
407     }
408     if (s->channel_mode == AC3_CHMODE_2F1R || s->channel_mode == AC3_CHMODE_3F1R) {
409         int nf = s->channel_mode - 2;
410         downmix_coeffs[0][nf] = downmix_coeffs[1][nf] = smix * LEVEL_MINUS_3DB;
411     }
412     if (s->channel_mode == AC3_CHMODE_2F2R || s->channel_mode == AC3_CHMODE_3F2R) {
413         int nf = s->channel_mode - 4;
414         downmix_coeffs[0][nf] = downmix_coeffs[1][nf+1] = smix;
415     }
416
417     /* renormalize */
418     norm0 = norm1 = 0.0;
419     for (i = 0; i < s->fbw_channels; i++) {
420         norm0 += downmix_coeffs[0][i];
421         norm1 += downmix_coeffs[1][i];
422     }
423     norm0 = 1.0f / norm0;
424     norm1 = 1.0f / norm1;
425     for (i = 0; i < s->fbw_channels; i++) {
426         downmix_coeffs[0][i] *= norm0;
427         downmix_coeffs[1][i] *= norm1;
428     }
429
430     if (s->output_mode == AC3_CHMODE_MONO) {
431         for (i = 0; i < s->fbw_channels; i++)
432             downmix_coeffs[0][i] = (downmix_coeffs[0][i] +
433                                     downmix_coeffs[1][i]) * LEVEL_MINUS_3DB;
434     }
435     for (i = 0; i < s->fbw_channels; i++) {
436         s->downmix_coeffs[0][i] = FIXR12(downmix_coeffs[0][i]);
437         s->downmix_coeffs[1][i] = FIXR12(downmix_coeffs[1][i]);
438     }
439
440     return 0;
441 }
442
443 /**
444  * Decode the grouped exponents according to exponent strategy.
445  * reference: Section 7.1.3 Exponent Decoding
446  */
447 static int decode_exponents(AC3DecodeContext *s,
448                             GetBitContext *gbc, int exp_strategy, int ngrps,
449                             uint8_t absexp, int8_t *dexps)
450 {
451     int i, j, grp, group_size;
452     int dexp[256];
453     int expacc, prevexp;
454
455     /* unpack groups */
456     group_size = exp_strategy + (exp_strategy == EXP_D45);
457     for (grp = 0, i = 0; grp < ngrps; grp++) {
458         expacc = get_bits(gbc, 7);
459         if (expacc >= 125) {
460             av_log(s->avctx, AV_LOG_ERROR, "expacc %d is out-of-range\n", expacc);
461             return AVERROR_INVALIDDATA;
462         }
463         dexp[i++] = ungroup_3_in_7_bits_tab[expacc][0];
464         dexp[i++] = ungroup_3_in_7_bits_tab[expacc][1];
465         dexp[i++] = ungroup_3_in_7_bits_tab[expacc][2];
466     }
467
468     /* convert to absolute exps and expand groups */
469     prevexp = absexp;
470     for (i = 0, j = 0; i < ngrps * 3; i++) {
471         prevexp += dexp[i] - 2;
472         if (prevexp > 24U) {
473             av_log(s->avctx, AV_LOG_ERROR, "exponent %d is out-of-range\n", prevexp);
474             return -1;
475         }
476         switch (group_size) {
477         case 4: dexps[j++] = prevexp;
478                 dexps[j++] = prevexp;
479         case 2: dexps[j++] = prevexp;
480         case 1: dexps[j++] = prevexp;
481         }
482     }
483     return 0;
484 }
485
486 /**
487  * Generate transform coefficients for each coupled channel in the coupling
488  * range using the coupling coefficients and coupling coordinates.
489  * reference: Section 7.4.3 Coupling Coordinate Format
490  */
491 static void calc_transform_coeffs_cpl(AC3DecodeContext *s)
492 {
493     int bin, band, ch;
494
495     bin = s->start_freq[CPL_CH];
496     for (band = 0; band < s->num_cpl_bands; band++) {
497         int band_start = bin;
498         int band_end = bin + s->cpl_band_sizes[band];
499         for (ch = 1; ch <= s->fbw_channels; ch++) {
500             if (s->channel_in_cpl[ch]) {
501                 int cpl_coord = s->cpl_coords[ch][band] << 5;
502                 for (bin = band_start; bin < band_end; bin++) {
503                     s->fixed_coeffs[ch][bin] =
504                         MULH(s->fixed_coeffs[CPL_CH][bin] * (1 << 4), cpl_coord);
505                 }
506                 if (ch == 2 && s->phase_flags[band]) {
507                     for (bin = band_start; bin < band_end; bin++)
508                         s->fixed_coeffs[2][bin] = -s->fixed_coeffs[2][bin];
509                 }
510             }
511         }
512         bin = band_end;
513     }
514 }
515
516 /**
517  * Grouped mantissas for 3-level 5-level and 11-level quantization
518  */
519 typedef struct mant_groups {
520     int b1_mant[2];
521     int b2_mant[2];
522     int b4_mant;
523     int b1;
524     int b2;
525     int b4;
526 } mant_groups;
527
528 /**
529  * Decode the transform coefficients for a particular channel
530  * reference: Section 7.3 Quantization and Decoding of Mantissas
531  */
532 static void ac3_decode_transform_coeffs_ch(AC3DecodeContext *s, int ch_index, mant_groups *m)
533 {
534     int start_freq = s->start_freq[ch_index];
535     int end_freq   = s->end_freq[ch_index];
536     uint8_t *baps  = s->bap[ch_index];
537     int8_t *exps   = s->dexps[ch_index];
538     int32_t *coeffs = s->fixed_coeffs[ch_index];
539     int dither     = (ch_index == CPL_CH) || s->dither_flag[ch_index];
540     GetBitContext *gbc = &s->gbc;
541     int freq;
542
543     for (freq = start_freq; freq < end_freq; freq++) {
544         int bap = baps[freq];
545         int mantissa;
546         switch (bap) {
547         case 0:
548             /* random noise with approximate range of -0.707 to 0.707 */
549             if (dither)
550                 mantissa = (((av_lfg_get(&s->dith_state)>>8)*181)>>8) - 5931008;
551             else
552                 mantissa = 0;
553             break;
554         case 1:
555             if (m->b1) {
556                 m->b1--;
557                 mantissa = m->b1_mant[m->b1];
558             } else {
559                 int bits      = get_bits(gbc, 5);
560                 mantissa      = b1_mantissas[bits][0];
561                 m->b1_mant[1] = b1_mantissas[bits][1];
562                 m->b1_mant[0] = b1_mantissas[bits][2];
563                 m->b1         = 2;
564             }
565             break;
566         case 2:
567             if (m->b2) {
568                 m->b2--;
569                 mantissa = m->b2_mant[m->b2];
570             } else {
571                 int bits      = get_bits(gbc, 7);
572                 mantissa      = b2_mantissas[bits][0];
573                 m->b2_mant[1] = b2_mantissas[bits][1];
574                 m->b2_mant[0] = b2_mantissas[bits][2];
575                 m->b2         = 2;
576             }
577             break;
578         case 3:
579             mantissa = b3_mantissas[get_bits(gbc, 3)];
580             break;
581         case 4:
582             if (m->b4) {
583                 m->b4 = 0;
584                 mantissa = m->b4_mant;
585             } else {
586                 int bits   = get_bits(gbc, 7);
587                 mantissa   = b4_mantissas[bits][0];
588                 m->b4_mant = b4_mantissas[bits][1];
589                 m->b4      = 1;
590             }
591             break;
592         case 5:
593             mantissa = b5_mantissas[get_bits(gbc, 4)];
594             break;
595         default: /* 6 to 15 */
596             /* Shift mantissa and sign-extend it. */
597             if (bap > 15) {
598                 av_log(s->avctx, AV_LOG_ERROR, "bap %d is invalid in plain AC-3\n", bap);
599                 bap = 15;
600             }
601             mantissa = (unsigned)get_sbits(gbc, quantization_tab[bap]) << (24 - quantization_tab[bap]);
602             break;
603         }
604         coeffs[freq] = mantissa >> exps[freq];
605     }
606 }
607
608 /**
609  * Remove random dithering from coupling range coefficients with zero-bit
610  * mantissas for coupled channels which do not use dithering.
611  * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
612  */
613 static void remove_dithering(AC3DecodeContext *s) {
614     int ch, i;
615
616     for (ch = 1; ch <= s->fbw_channels; ch++) {
617         if (!s->dither_flag[ch] && s->channel_in_cpl[ch]) {
618             for (i = s->start_freq[CPL_CH]; i < s->end_freq[CPL_CH]; i++) {
619                 if (!s->bap[CPL_CH][i])
620                     s->fixed_coeffs[ch][i] = 0;
621             }
622         }
623     }
624 }
625
626 static inline void decode_transform_coeffs_ch(AC3DecodeContext *s, int blk,
627                                               int ch, mant_groups *m)
628 {
629     if (!s->channel_uses_aht[ch]) {
630         ac3_decode_transform_coeffs_ch(s, ch, m);
631     } else {
632         /* if AHT is used, mantissas for all blocks are encoded in the first
633            block of the frame. */
634         int bin;
635         if (CONFIG_EAC3_DECODER && !blk)
636             ff_eac3_decode_transform_coeffs_aht_ch(s, ch);
637         for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {
638             s->fixed_coeffs[ch][bin] = s->pre_mantissa[ch][bin][blk] >> s->dexps[ch][bin];
639         }
640     }
641 }
642
643 /**
644  * Decode the transform coefficients.
645  */
646 static inline void decode_transform_coeffs(AC3DecodeContext *s, int blk)
647 {
648     int ch, end;
649     int got_cplchan = 0;
650     mant_groups m;
651
652     m.b1 = m.b2 = m.b4 = 0;
653
654     for (ch = 1; ch <= s->channels; ch++) {
655         /* transform coefficients for full-bandwidth channel */
656         decode_transform_coeffs_ch(s, blk, ch, &m);
657         /* transform coefficients for coupling channel come right after the
658            coefficients for the first coupled channel*/
659         if (s->channel_in_cpl[ch])  {
660             if (!got_cplchan) {
661                 decode_transform_coeffs_ch(s, blk, CPL_CH, &m);
662                 calc_transform_coeffs_cpl(s);
663                 got_cplchan = 1;
664             }
665             end = s->end_freq[CPL_CH];
666         } else {
667             end = s->end_freq[ch];
668         }
669         do
670             s->fixed_coeffs[ch][end] = 0;
671         while (++end < 256);
672     }
673
674     /* zero the dithered coefficients for appropriate channels */
675     remove_dithering(s);
676 }
677
678 /**
679  * Stereo rematrixing.
680  * reference: Section 7.5.4 Rematrixing : Decoding Technique
681  */
682 static void do_rematrixing(AC3DecodeContext *s)
683 {
684     int bnd, i;
685     int end, bndend;
686
687     end = FFMIN(s->end_freq[1], s->end_freq[2]);
688
689     for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
690         if (s->rematrixing_flags[bnd]) {
691             bndend = FFMIN(end, ff_ac3_rematrix_band_tab[bnd + 1]);
692             for (i = ff_ac3_rematrix_band_tab[bnd]; i < bndend; i++) {
693                 int tmp0 = s->fixed_coeffs[1][i];
694                 s->fixed_coeffs[1][i] += s->fixed_coeffs[2][i];
695                 s->fixed_coeffs[2][i]  = tmp0 - s->fixed_coeffs[2][i];
696             }
697         }
698     }
699 }
700
701 /**
702  * Inverse MDCT Transform.
703  * Convert frequency domain coefficients to time-domain audio samples.
704  * reference: Section 7.9.4 Transformation Equations
705  */
706 static inline void do_imdct(AC3DecodeContext *s, int channels, int offset)
707 {
708     int ch;
709
710     for (ch = 1; ch <= channels; ch++) {
711         if (s->block_switch[ch]) {
712             int i;
713             FFTSample *x = s->tmp_output + 128;
714             for (i = 0; i < 128; i++)
715                 x[i] = s->transform_coeffs[ch][2 * i];
716             s->imdct_256.imdct_half(&s->imdct_256, s->tmp_output, x);
717 #if USE_FIXED
718             s->fdsp->vector_fmul_window_scaled(s->outptr[ch - 1], s->delay[ch - 1 + offset],
719                                        s->tmp_output, s->window, 128, 8);
720 #else
721             s->fdsp->vector_fmul_window(s->outptr[ch - 1], s->delay[ch - 1 + offset],
722                                        s->tmp_output, s->window, 128);
723 #endif
724             for (i = 0; i < 128; i++)
725                 x[i] = s->transform_coeffs[ch][2 * i + 1];
726             s->imdct_256.imdct_half(&s->imdct_256, s->delay[ch - 1 + offset], x);
727         } else {
728             s->imdct_512.imdct_half(&s->imdct_512, s->tmp_output, s->transform_coeffs[ch]);
729 #if USE_FIXED
730             s->fdsp->vector_fmul_window_scaled(s->outptr[ch - 1], s->delay[ch - 1 + offset],
731                                        s->tmp_output, s->window, 128, 8);
732 #else
733             s->fdsp->vector_fmul_window(s->outptr[ch - 1], s->delay[ch - 1 + offset],
734                                        s->tmp_output, s->window, 128);
735 #endif
736             memcpy(s->delay[ch - 1 + offset], s->tmp_output + 128, 128 * sizeof(FFTSample));
737         }
738     }
739 }
740
741 /**
742  * Upmix delay samples from stereo to original channel layout.
743  */
744 static void ac3_upmix_delay(AC3DecodeContext *s)
745 {
746     int channel_data_size = sizeof(s->delay[0]);
747     switch (s->channel_mode) {
748     case AC3_CHMODE_DUALMONO:
749     case AC3_CHMODE_STEREO:
750         /* upmix mono to stereo */
751         memcpy(s->delay[1], s->delay[0], channel_data_size);
752         break;
753     case AC3_CHMODE_2F2R:
754         memset(s->delay[3], 0, channel_data_size);
755     case AC3_CHMODE_2F1R:
756         memset(s->delay[2], 0, channel_data_size);
757         break;
758     case AC3_CHMODE_3F2R:
759         memset(s->delay[4], 0, channel_data_size);
760     case AC3_CHMODE_3F1R:
761         memset(s->delay[3], 0, channel_data_size);
762     case AC3_CHMODE_3F:
763         memcpy(s->delay[2], s->delay[1], channel_data_size);
764         memset(s->delay[1], 0, channel_data_size);
765         break;
766     }
767 }
768
769 /**
770  * Decode band structure for coupling, spectral extension, or enhanced coupling.
771  * The band structure defines how many subbands are in each band.  For each
772  * subband in the range, 1 means it is combined with the previous band, and 0
773  * means that it starts a new band.
774  *
775  * @param[in] gbc bit reader context
776  * @param[in] blk block number
777  * @param[in] eac3 flag to indicate E-AC-3
778  * @param[in] ecpl flag to indicate enhanced coupling
779  * @param[in] start_subband subband number for start of range
780  * @param[in] end_subband subband number for end of range
781  * @param[in] default_band_struct default band structure table
782  * @param[out] num_bands number of bands (optionally NULL)
783  * @param[out] band_sizes array containing the number of bins in each band (optionally NULL)
784  * @param[in,out] band_struct current band structure
785  */
786 static void decode_band_structure(GetBitContext *gbc, int blk, int eac3,
787                                   int ecpl, int start_subband, int end_subband,
788                                   const uint8_t *default_band_struct,
789                                   int *num_bands, uint8_t *band_sizes,
790                                   uint8_t *band_struct, int band_struct_size)
791 {
792     int subbnd, bnd, n_subbands, n_bands=0;
793     uint8_t bnd_sz[22];
794
795     n_subbands = end_subband - start_subband;
796
797     if (!blk)
798         memcpy(band_struct, default_band_struct, band_struct_size);
799
800     av_assert0(band_struct_size >= start_subband + n_subbands);
801
802     band_struct += start_subband + 1;
803
804     /* decode band structure from bitstream or use default */
805     if (!eac3 || get_bits1(gbc)) {
806         for (subbnd = 0; subbnd < n_subbands - 1; subbnd++) {
807             band_struct[subbnd] = get_bits1(gbc);
808         }
809     }
810
811     /* calculate number of bands and band sizes based on band structure.
812        note that the first 4 subbands in enhanced coupling span only 6 bins
813        instead of 12. */
814     if (num_bands || band_sizes ) {
815         n_bands = n_subbands;
816         bnd_sz[0] = ecpl ? 6 : 12;
817         for (bnd = 0, subbnd = 1; subbnd < n_subbands; subbnd++) {
818             int subbnd_size = (ecpl && subbnd < 4) ? 6 : 12;
819             if (band_struct[subbnd - 1]) {
820                 n_bands--;
821                 bnd_sz[bnd] += subbnd_size;
822             } else {
823                 bnd_sz[++bnd] = subbnd_size;
824             }
825         }
826     }
827
828     /* set optional output params */
829     if (num_bands)
830         *num_bands = n_bands;
831     if (band_sizes)
832         memcpy(band_sizes, bnd_sz, n_bands);
833 }
834
835 static inline int spx_strategy(AC3DecodeContext *s, int blk)
836 {
837     GetBitContext *bc = &s->gbc;
838     int fbw_channels = s->fbw_channels;
839     int dst_start_freq, dst_end_freq, src_start_freq,
840         start_subband, end_subband, ch;
841
842     /* determine which channels use spx */
843     if (s->channel_mode == AC3_CHMODE_MONO) {
844         s->channel_uses_spx[1] = 1;
845     } else {
846         for (ch = 1; ch <= fbw_channels; ch++)
847             s->channel_uses_spx[ch] = get_bits1(bc);
848     }
849
850     /* get the frequency bins of the spx copy region and the spx start
851        and end subbands */
852     dst_start_freq = get_bits(bc, 2);
853     start_subband  = get_bits(bc, 3) + 2;
854     if (start_subband > 7)
855         start_subband += start_subband - 7;
856     end_subband    = get_bits(bc, 3) + 5;
857 #if USE_FIXED
858     s->spx_dst_end_freq = end_freq_inv_tab[end_subband-5];
859 #endif
860     if (end_subband   > 7)
861         end_subband   += end_subband   - 7;
862     dst_start_freq = dst_start_freq * 12 + 25;
863     src_start_freq = start_subband  * 12 + 25;
864     dst_end_freq   = end_subband    * 12 + 25;
865
866     /* check validity of spx ranges */
867     if (start_subband >= end_subband) {
868         av_log(s->avctx, AV_LOG_ERROR, "invalid spectral extension "
869                "range (%d >= %d)\n", start_subband, end_subband);
870         return AVERROR_INVALIDDATA;
871     }
872     if (dst_start_freq >= src_start_freq) {
873         av_log(s->avctx, AV_LOG_ERROR, "invalid spectral extension "
874                "copy start bin (%d >= %d)\n", dst_start_freq, src_start_freq);
875         return AVERROR_INVALIDDATA;
876     }
877
878     s->spx_dst_start_freq = dst_start_freq;
879     s->spx_src_start_freq = src_start_freq;
880     if (!USE_FIXED)
881         s->spx_dst_end_freq   = dst_end_freq;
882
883     decode_band_structure(bc, blk, s->eac3, 0,
884                           start_subband, end_subband,
885                           ff_eac3_default_spx_band_struct,
886                           &s->num_spx_bands,
887                           s->spx_band_sizes,
888                           s->spx_band_struct, sizeof(s->spx_band_struct));
889     return 0;
890 }
891
892 static inline void spx_coordinates(AC3DecodeContext *s)
893 {
894     GetBitContext *bc = &s->gbc;
895     int fbw_channels = s->fbw_channels;
896     int ch, bnd;
897
898     for (ch = 1; ch <= fbw_channels; ch++) {
899         if (s->channel_uses_spx[ch]) {
900             if (s->first_spx_coords[ch] || get_bits1(bc)) {
901                 INTFLOAT spx_blend;
902                 int bin, master_spx_coord;
903
904                 s->first_spx_coords[ch] = 0;
905                 spx_blend = AC3_SPX_BLEND(get_bits(bc, 5));
906                 master_spx_coord = get_bits(bc, 2) * 3;
907
908                 bin = s->spx_src_start_freq;
909                 for (bnd = 0; bnd < s->num_spx_bands; bnd++) {
910                     int bandsize = s->spx_band_sizes[bnd];
911                     int spx_coord_exp, spx_coord_mant;
912                     INTFLOAT nratio, sblend, nblend;
913 #if USE_FIXED
914                     /* calculate blending factors */
915                     int64_t accu = ((bin << 23) + (bandsize << 22))
916                                  * (int64_t)s->spx_dst_end_freq;
917                     nratio = (int)(accu >> 32);
918                     nratio -= spx_blend << 18;
919
920                     if (nratio < 0) {
921                         nblend = 0;
922                         sblend = 0x800000;
923                     } else if (nratio > 0x7fffff) {
924                         nblend = 14529495; // sqrt(3) in FP.23
925                         sblend = 0;
926                     } else {
927                         nblend = fixed_sqrt(nratio, 23);
928                         accu = (int64_t)nblend * 1859775393;
929                         nblend = (int)((accu + (1<<29)) >> 30);
930                         sblend = fixed_sqrt(0x800000 - nratio, 23);
931                     }
932 #else
933                     float spx_coord;
934
935                     /* calculate blending factors */
936                     nratio = ((float)((bin + (bandsize >> 1))) / s->spx_dst_end_freq) - spx_blend;
937                     nratio = av_clipf(nratio, 0.0f, 1.0f);
938                     nblend = sqrtf(3.0f * nratio); // noise is scaled by sqrt(3)
939                                                    // to give unity variance
940                     sblend = sqrtf(1.0f - nratio);
941 #endif
942                     bin += bandsize;
943
944                     /* decode spx coordinates */
945                     spx_coord_exp  = get_bits(bc, 4);
946                     spx_coord_mant = get_bits(bc, 2);
947                     if (spx_coord_exp == 15) spx_coord_mant <<= 1;
948                     else                     spx_coord_mant += 4;
949                     spx_coord_mant <<= (25 - spx_coord_exp - master_spx_coord);
950
951                     /* multiply noise and signal blending factors by spx coordinate */
952 #if USE_FIXED
953                     accu = (int64_t)nblend * spx_coord_mant;
954                     s->spx_noise_blend[ch][bnd]  = (int)((accu + (1<<22)) >> 23);
955                     accu = (int64_t)sblend * spx_coord_mant;
956                     s->spx_signal_blend[ch][bnd] = (int)((accu + (1<<22)) >> 23);
957 #else
958                     spx_coord = spx_coord_mant * (1.0f / (1 << 23));
959                     s->spx_noise_blend [ch][bnd] = nblend * spx_coord;
960                     s->spx_signal_blend[ch][bnd] = sblend * spx_coord;
961 #endif
962                 }
963             }
964         } else {
965             s->first_spx_coords[ch] = 1;
966         }
967     }
968 }
969
970 static inline int coupling_strategy(AC3DecodeContext *s, int blk,
971                                     uint8_t *bit_alloc_stages)
972 {
973     GetBitContext *bc = &s->gbc;
974     int fbw_channels = s->fbw_channels;
975     int channel_mode = s->channel_mode;
976     int ch;
977
978     memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
979     if (!s->eac3)
980         s->cpl_in_use[blk] = get_bits1(bc);
981     if (s->cpl_in_use[blk]) {
982         /* coupling in use */
983         int cpl_start_subband, cpl_end_subband;
984
985         if (channel_mode < AC3_CHMODE_STEREO) {
986             av_log(s->avctx, AV_LOG_ERROR, "coupling not allowed in mono or dual-mono\n");
987             return AVERROR_INVALIDDATA;
988         }
989
990         /* check for enhanced coupling */
991         if (s->eac3 && get_bits1(bc)) {
992             /* TODO: parse enhanced coupling strategy info */
993             avpriv_request_sample(s->avctx, "Enhanced coupling");
994             return AVERROR_PATCHWELCOME;
995         }
996
997         /* determine which channels are coupled */
998         if (s->eac3 && s->channel_mode == AC3_CHMODE_STEREO) {
999             s->channel_in_cpl[1] = 1;
1000             s->channel_in_cpl[2] = 1;
1001         } else {
1002             for (ch = 1; ch <= fbw_channels; ch++)
1003                 s->channel_in_cpl[ch] = get_bits1(bc);
1004         }
1005
1006         /* phase flags in use */
1007         if (channel_mode == AC3_CHMODE_STEREO)
1008             s->phase_flags_in_use = get_bits1(bc);
1009
1010         /* coupling frequency range */
1011         cpl_start_subband = get_bits(bc, 4);
1012         cpl_end_subband = s->spx_in_use ? (s->spx_src_start_freq - 37) / 12 :
1013                                           get_bits(bc, 4) + 3;
1014         if (cpl_start_subband >= cpl_end_subband) {
1015             av_log(s->avctx, AV_LOG_ERROR, "invalid coupling range (%d >= %d)\n",
1016                    cpl_start_subband, cpl_end_subband);
1017             return AVERROR_INVALIDDATA;
1018         }
1019         s->start_freq[CPL_CH] = cpl_start_subband * 12 + 37;
1020         s->end_freq[CPL_CH]   = cpl_end_subband   * 12 + 37;
1021
1022         decode_band_structure(bc, blk, s->eac3, 0, cpl_start_subband,
1023                               cpl_end_subband,
1024                               ff_eac3_default_cpl_band_struct,
1025                               &s->num_cpl_bands, s->cpl_band_sizes,
1026                               s->cpl_band_struct, sizeof(s->cpl_band_struct));
1027     } else {
1028         /* coupling not in use */
1029         for (ch = 1; ch <= fbw_channels; ch++) {
1030             s->channel_in_cpl[ch] = 0;
1031             s->first_cpl_coords[ch] = 1;
1032         }
1033         s->first_cpl_leak = s->eac3;
1034         s->phase_flags_in_use = 0;
1035     }
1036
1037     return 0;
1038 }
1039
1040 static inline int coupling_coordinates(AC3DecodeContext *s, int blk)
1041 {
1042     GetBitContext *bc = &s->gbc;
1043     int fbw_channels = s->fbw_channels;
1044     int ch, bnd;
1045     int cpl_coords_exist = 0;
1046
1047     for (ch = 1; ch <= fbw_channels; ch++) {
1048         if (s->channel_in_cpl[ch]) {
1049             if ((s->eac3 && s->first_cpl_coords[ch]) || get_bits1(bc)) {
1050                 int master_cpl_coord, cpl_coord_exp, cpl_coord_mant;
1051                 s->first_cpl_coords[ch] = 0;
1052                 cpl_coords_exist = 1;
1053                 master_cpl_coord = 3 * get_bits(bc, 2);
1054                 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1055                     cpl_coord_exp  = get_bits(bc, 4);
1056                     cpl_coord_mant = get_bits(bc, 4);
1057                     if (cpl_coord_exp == 15)
1058                         s->cpl_coords[ch][bnd] = cpl_coord_mant << 22;
1059                     else
1060                         s->cpl_coords[ch][bnd] = (cpl_coord_mant + 16) << 21;
1061                     s->cpl_coords[ch][bnd] >>= (cpl_coord_exp + master_cpl_coord);
1062                 }
1063             } else if (!blk) {
1064                 av_log(s->avctx, AV_LOG_ERROR, "new coupling coordinates must "
1065                        "be present in block 0\n");
1066                 return AVERROR_INVALIDDATA;
1067             }
1068         } else {
1069             /* channel not in coupling */
1070             s->first_cpl_coords[ch] = 1;
1071         }
1072     }
1073     /* phase flags */
1074     if (s->channel_mode == AC3_CHMODE_STEREO && cpl_coords_exist) {
1075         for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1076             s->phase_flags[bnd] = s->phase_flags_in_use ? get_bits1(bc) : 0;
1077         }
1078     }
1079
1080     return 0;
1081 }
1082
1083 /**
1084  * Decode a single audio block from the AC-3 bitstream.
1085  */
1086 static int decode_audio_block(AC3DecodeContext *s, int blk, int offset)
1087 {
1088     int fbw_channels = s->fbw_channels;
1089     int channel_mode = s->channel_mode;
1090     int i, bnd, seg, ch, ret;
1091     int different_transforms;
1092     int downmix_output;
1093     int cpl_in_use;
1094     GetBitContext *gbc = &s->gbc;
1095     uint8_t bit_alloc_stages[AC3_MAX_CHANNELS] = { 0 };
1096
1097     /* block switch flags */
1098     different_transforms = 0;
1099     if (s->block_switch_syntax) {
1100         for (ch = 1; ch <= fbw_channels; ch++) {
1101             s->block_switch[ch] = get_bits1(gbc);
1102             if (ch > 1 && s->block_switch[ch] != s->block_switch[1])
1103                 different_transforms = 1;
1104         }
1105     }
1106
1107     /* dithering flags */
1108     if (s->dither_flag_syntax) {
1109         for (ch = 1; ch <= fbw_channels; ch++) {
1110             s->dither_flag[ch] = get_bits1(gbc);
1111         }
1112     }
1113
1114     /* dynamic range */
1115     i = !s->channel_mode;
1116     do {
1117         if (get_bits1(gbc)) {
1118             /* Allow asymmetric application of DRC when drc_scale > 1.
1119                Amplification of quiet sounds is enhanced */
1120             int range_bits = get_bits(gbc, 8);
1121             INTFLOAT range = AC3_RANGE(range_bits);
1122             if (range_bits <= 127 || s->drc_scale <= 1.0)
1123                 s->dynamic_range[i] = AC3_DYNAMIC_RANGE(range);
1124             else
1125                 s->dynamic_range[i] = range;
1126         } else if (blk == 0) {
1127             s->dynamic_range[i] = AC3_DYNAMIC_RANGE1;
1128         }
1129     } while (i--);
1130
1131     /* spectral extension strategy */
1132     if (s->eac3 && (!blk || get_bits1(gbc))) {
1133         s->spx_in_use = get_bits1(gbc);
1134         if (s->spx_in_use) {
1135             if ((ret = spx_strategy(s, blk)) < 0)
1136                 return ret;
1137         }
1138     }
1139     if (!s->eac3 || !s->spx_in_use) {
1140         s->spx_in_use = 0;
1141         for (ch = 1; ch <= fbw_channels; ch++) {
1142             s->channel_uses_spx[ch] = 0;
1143             s->first_spx_coords[ch] = 1;
1144         }
1145     }
1146
1147     /* spectral extension coordinates */
1148     if (s->spx_in_use)
1149         spx_coordinates(s);
1150
1151     /* coupling strategy */
1152     if (s->eac3 ? s->cpl_strategy_exists[blk] : get_bits1(gbc)) {
1153         if ((ret = coupling_strategy(s, blk, bit_alloc_stages)) < 0)
1154             return ret;
1155     } else if (!s->eac3) {
1156         if (!blk) {
1157             av_log(s->avctx, AV_LOG_ERROR, "new coupling strategy must "
1158                    "be present in block 0\n");
1159             return AVERROR_INVALIDDATA;
1160         } else {
1161             s->cpl_in_use[blk] = s->cpl_in_use[blk-1];
1162         }
1163     }
1164     cpl_in_use = s->cpl_in_use[blk];
1165
1166     /* coupling coordinates */
1167     if (cpl_in_use) {
1168         if ((ret = coupling_coordinates(s, blk)) < 0)
1169             return ret;
1170     }
1171
1172     /* stereo rematrixing strategy and band structure */
1173     if (channel_mode == AC3_CHMODE_STEREO) {
1174         if ((s->eac3 && !blk) || get_bits1(gbc)) {
1175             s->num_rematrixing_bands = 4;
1176             if (cpl_in_use && s->start_freq[CPL_CH] <= 61) {
1177                 s->num_rematrixing_bands -= 1 + (s->start_freq[CPL_CH] == 37);
1178             } else if (s->spx_in_use && s->spx_src_start_freq <= 61) {
1179                 s->num_rematrixing_bands--;
1180             }
1181             for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++)
1182                 s->rematrixing_flags[bnd] = get_bits1(gbc);
1183         } else if (!blk) {
1184             av_log(s->avctx, AV_LOG_WARNING, "Warning: "
1185                    "new rematrixing strategy not present in block 0\n");
1186             s->num_rematrixing_bands = 0;
1187         }
1188     }
1189
1190     /* exponent strategies for each channel */
1191     for (ch = !cpl_in_use; ch <= s->channels; ch++) {
1192         if (!s->eac3)
1193             s->exp_strategy[blk][ch] = get_bits(gbc, 2 - (ch == s->lfe_ch));
1194         if (s->exp_strategy[blk][ch] != EXP_REUSE)
1195             bit_alloc_stages[ch] = 3;
1196     }
1197
1198     /* channel bandwidth */
1199     for (ch = 1; ch <= fbw_channels; ch++) {
1200         s->start_freq[ch] = 0;
1201         if (s->exp_strategy[blk][ch] != EXP_REUSE) {
1202             int group_size;
1203             int prev = s->end_freq[ch];
1204             if (s->channel_in_cpl[ch])
1205                 s->end_freq[ch] = s->start_freq[CPL_CH];
1206             else if (s->channel_uses_spx[ch])
1207                 s->end_freq[ch] = s->spx_src_start_freq;
1208             else {
1209                 int bandwidth_code = get_bits(gbc, 6);
1210                 if (bandwidth_code > 60) {
1211                     av_log(s->avctx, AV_LOG_ERROR, "bandwidth code = %d > 60\n", bandwidth_code);
1212                     return AVERROR_INVALIDDATA;
1213                 }
1214                 s->end_freq[ch] = bandwidth_code * 3 + 73;
1215             }
1216             group_size = 3 << (s->exp_strategy[blk][ch] - 1);
1217             s->num_exp_groups[ch] = (s->end_freq[ch] + group_size-4) / group_size;
1218             if (blk > 0 && s->end_freq[ch] != prev)
1219                 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
1220         }
1221     }
1222     if (cpl_in_use && s->exp_strategy[blk][CPL_CH] != EXP_REUSE) {
1223         s->num_exp_groups[CPL_CH] = (s->end_freq[CPL_CH] - s->start_freq[CPL_CH]) /
1224                                     (3 << (s->exp_strategy[blk][CPL_CH] - 1));
1225     }
1226
1227     /* decode exponents for each channel */
1228     for (ch = !cpl_in_use; ch <= s->channels; ch++) {
1229         if (s->exp_strategy[blk][ch] != EXP_REUSE) {
1230             s->dexps[ch][0] = get_bits(gbc, 4) << !ch;
1231             if (decode_exponents(s, gbc, s->exp_strategy[blk][ch],
1232                                  s->num_exp_groups[ch], s->dexps[ch][0],
1233                                  &s->dexps[ch][s->start_freq[ch]+!!ch])) {
1234                 return AVERROR_INVALIDDATA;
1235             }
1236             if (ch != CPL_CH && ch != s->lfe_ch)
1237                 skip_bits(gbc, 2); /* skip gainrng */
1238         }
1239     }
1240
1241     /* bit allocation information */
1242     if (s->bit_allocation_syntax) {
1243         if (get_bits1(gbc)) {
1244             s->bit_alloc_params.slow_decay = ff_ac3_slow_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
1245             s->bit_alloc_params.fast_decay = ff_ac3_fast_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
1246             s->bit_alloc_params.slow_gain  = ff_ac3_slow_gain_tab[get_bits(gbc, 2)];
1247             s->bit_alloc_params.db_per_bit = ff_ac3_db_per_bit_tab[get_bits(gbc, 2)];
1248             s->bit_alloc_params.floor  = ff_ac3_floor_tab[get_bits(gbc, 3)];
1249             for (ch = !cpl_in_use; ch <= s->channels; ch++)
1250                 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1251         } else if (!blk) {
1252             av_log(s->avctx, AV_LOG_ERROR, "new bit allocation info must "
1253                    "be present in block 0\n");
1254             return AVERROR_INVALIDDATA;
1255         }
1256     }
1257
1258     /* signal-to-noise ratio offsets and fast gains (signal-to-mask ratios) */
1259     if (!s->eac3 || !blk) {
1260         if (s->snr_offset_strategy && get_bits1(gbc)) {
1261             int snr = 0;
1262             int csnr;
1263             csnr = (get_bits(gbc, 6) - 15) << 4;
1264             for (i = ch = !cpl_in_use; ch <= s->channels; ch++) {
1265                 /* snr offset */
1266                 if (ch == i || s->snr_offset_strategy == 2)
1267                     snr = (csnr + get_bits(gbc, 4)) << 2;
1268                 /* run at least last bit allocation stage if snr offset changes */
1269                 if (blk && s->snr_offset[ch] != snr) {
1270                     bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 1);
1271                 }
1272                 s->snr_offset[ch] = snr;
1273
1274                 /* fast gain (normal AC-3 only) */
1275                 if (!s->eac3) {
1276                     int prev = s->fast_gain[ch];
1277                     s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];
1278                     /* run last 2 bit allocation stages if fast gain changes */
1279                     if (blk && prev != s->fast_gain[ch])
1280                         bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1281                 }
1282             }
1283         } else if (!s->eac3 && !blk) {
1284             av_log(s->avctx, AV_LOG_ERROR, "new snr offsets must be present in block 0\n");
1285             return AVERROR_INVALIDDATA;
1286         }
1287     }
1288
1289     /* fast gain (E-AC-3 only) */
1290     if (s->fast_gain_syntax && get_bits1(gbc)) {
1291         for (ch = !cpl_in_use; ch <= s->channels; ch++) {
1292             int prev = s->fast_gain[ch];
1293             s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];
1294             /* run last 2 bit allocation stages if fast gain changes */
1295             if (blk && prev != s->fast_gain[ch])
1296                 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1297         }
1298     } else if (s->eac3 && !blk) {
1299         for (ch = !cpl_in_use; ch <= s->channels; ch++)
1300             s->fast_gain[ch] = ff_ac3_fast_gain_tab[4];
1301     }
1302
1303     /* E-AC-3 to AC-3 converter SNR offset */
1304     if (s->frame_type == EAC3_FRAME_TYPE_INDEPENDENT && get_bits1(gbc)) {
1305         skip_bits(gbc, 10); // skip converter snr offset
1306     }
1307
1308     /* coupling leak information */
1309     if (cpl_in_use) {
1310         if (s->first_cpl_leak || get_bits1(gbc)) {
1311             int fl = get_bits(gbc, 3);
1312             int sl = get_bits(gbc, 3);
1313             /* run last 2 bit allocation stages for coupling channel if
1314                coupling leak changes */
1315             if (blk && (fl != s->bit_alloc_params.cpl_fast_leak ||
1316                 sl != s->bit_alloc_params.cpl_slow_leak)) {
1317                 bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
1318             }
1319             s->bit_alloc_params.cpl_fast_leak = fl;
1320             s->bit_alloc_params.cpl_slow_leak = sl;
1321         } else if (!s->eac3 && !blk) {
1322             av_log(s->avctx, AV_LOG_ERROR, "new coupling leak info must "
1323                    "be present in block 0\n");
1324             return AVERROR_INVALIDDATA;
1325         }
1326         s->first_cpl_leak = 0;
1327     }
1328
1329     /* delta bit allocation information */
1330     if (s->dba_syntax && get_bits1(gbc)) {
1331         /* delta bit allocation exists (strategy) */
1332         for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {
1333             s->dba_mode[ch] = get_bits(gbc, 2);
1334             if (s->dba_mode[ch] == DBA_RESERVED) {
1335                 av_log(s->avctx, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
1336                 return AVERROR_INVALIDDATA;
1337             }
1338             bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1339         }
1340         /* channel delta offset, len and bit allocation */
1341         for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {
1342             if (s->dba_mode[ch] == DBA_NEW) {
1343                 s->dba_nsegs[ch] = get_bits(gbc, 3) + 1;
1344                 for (seg = 0; seg < s->dba_nsegs[ch]; seg++) {
1345                     s->dba_offsets[ch][seg] = get_bits(gbc, 5);
1346                     s->dba_lengths[ch][seg] = get_bits(gbc, 4);
1347                     s->dba_values[ch][seg]  = get_bits(gbc, 3);
1348                 }
1349                 /* run last 2 bit allocation stages if new dba values */
1350                 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
1351             }
1352         }
1353     } else if (blk == 0) {
1354         for (ch = 0; ch <= s->channels; ch++) {
1355             s->dba_mode[ch] = DBA_NONE;
1356         }
1357     }
1358
1359     /* Bit allocation */
1360     for (ch = !cpl_in_use; ch <= s->channels; ch++) {
1361         if (bit_alloc_stages[ch] > 2) {
1362             /* Exponent mapping into PSD and PSD integration */
1363             ff_ac3_bit_alloc_calc_psd(s->dexps[ch],
1364                                       s->start_freq[ch], s->end_freq[ch],
1365                                       s->psd[ch], s->band_psd[ch]);
1366         }
1367         if (bit_alloc_stages[ch] > 1) {
1368             /* Compute excitation function, Compute masking curve, and
1369                Apply delta bit allocation */
1370             if (ff_ac3_bit_alloc_calc_mask(&s->bit_alloc_params, s->band_psd[ch],
1371                                            s->start_freq[ch],  s->end_freq[ch],
1372                                            s->fast_gain[ch],   (ch == s->lfe_ch),
1373                                            s->dba_mode[ch],    s->dba_nsegs[ch],
1374                                            s->dba_offsets[ch], s->dba_lengths[ch],
1375                                            s->dba_values[ch],  s->mask[ch])) {
1376                 av_log(s->avctx, AV_LOG_ERROR, "error in bit allocation\n");
1377                 return AVERROR_INVALIDDATA;
1378             }
1379         }
1380         if (bit_alloc_stages[ch] > 0) {
1381             /* Compute bit allocation */
1382             const uint8_t *bap_tab = s->channel_uses_aht[ch] ?
1383                                      ff_eac3_hebap_tab : ff_ac3_bap_tab;
1384             s->ac3dsp.bit_alloc_calc_bap(s->mask[ch], s->psd[ch],
1385                                       s->start_freq[ch], s->end_freq[ch],
1386                                       s->snr_offset[ch],
1387                                       s->bit_alloc_params.floor,
1388                                       bap_tab, s->bap[ch]);
1389         }
1390     }
1391
1392     /* unused dummy data */
1393     if (s->skip_syntax && get_bits1(gbc)) {
1394         int skipl = get_bits(gbc, 9);
1395         skip_bits_long(gbc, 8 * skipl);
1396     }
1397
1398     /* unpack the transform coefficients
1399        this also uncouples channels if coupling is in use. */
1400     decode_transform_coeffs(s, blk);
1401
1402     /* TODO: generate enhanced coupling coordinates and uncouple */
1403
1404     /* recover coefficients if rematrixing is in use */
1405     if (s->channel_mode == AC3_CHMODE_STEREO)
1406         do_rematrixing(s);
1407
1408     /* apply scaling to coefficients (headroom, dynrng) */
1409     for (ch = 1; ch <= s->channels; ch++) {
1410         int audio_channel = 0;
1411         INTFLOAT gain;
1412         if (s->channel_mode == AC3_CHMODE_DUALMONO && ch <= 2)
1413             audio_channel = 2-ch;
1414         if (s->heavy_compression && s->compression_exists[audio_channel])
1415             gain = s->heavy_dynamic_range[audio_channel];
1416         else
1417             gain = s->dynamic_range[audio_channel];
1418
1419 #if USE_FIXED
1420         scale_coefs(s->transform_coeffs[ch], s->fixed_coeffs[ch], gain, 256);
1421 #else
1422         if (s->target_level != 0)
1423           gain = gain * s->level_gain[audio_channel];
1424         gain *= 1.0 / 4194304.0f;
1425         s->fmt_conv.int32_to_float_fmul_scalar(s->transform_coeffs[ch],
1426                                                s->fixed_coeffs[ch], gain, 256);
1427 #endif
1428     }
1429
1430     /* apply spectral extension to high frequency bins */
1431     if (CONFIG_EAC3_DECODER && s->spx_in_use) {
1432         ff_eac3_apply_spectral_extension(s);
1433     }
1434
1435     /* downmix and MDCT. order depends on whether block switching is used for
1436        any channel in this block. this is because coefficients for the long
1437        and short transforms cannot be mixed. */
1438     downmix_output = s->channels != s->out_channels &&
1439                      !((s->output_mode & AC3_OUTPUT_LFEON) &&
1440                      s->fbw_channels == s->out_channels);
1441     if (different_transforms) {
1442         /* the delay samples have already been downmixed, so we upmix the delay
1443            samples in order to reconstruct all channels before downmixing. */
1444         if (s->downmixed) {
1445             s->downmixed = 0;
1446             ac3_upmix_delay(s);
1447         }
1448
1449         do_imdct(s, s->channels, offset);
1450
1451         if (downmix_output) {
1452 #if USE_FIXED
1453             ac3_downmix_c_fixed16(s->outptr, s->downmix_coeffs,
1454                               s->out_channels, s->fbw_channels, 256);
1455 #else
1456             ff_ac3dsp_downmix(&s->ac3dsp, s->outptr, s->downmix_coeffs,
1457                               s->out_channels, s->fbw_channels, 256);
1458 #endif
1459         }
1460     } else {
1461         if (downmix_output) {
1462             AC3_RENAME(ff_ac3dsp_downmix)(&s->ac3dsp, s->xcfptr + 1, s->downmix_coeffs,
1463                                           s->out_channels, s->fbw_channels, 256);
1464         }
1465
1466         if (downmix_output && !s->downmixed) {
1467             s->downmixed = 1;
1468             AC3_RENAME(ff_ac3dsp_downmix)(&s->ac3dsp, s->dlyptr, s->downmix_coeffs,
1469                                           s->out_channels, s->fbw_channels, 128);
1470         }
1471
1472         do_imdct(s, s->out_channels, offset);
1473     }
1474
1475     return 0;
1476 }
1477
1478 /**
1479  * Decode a single AC-3 frame.
1480  */
1481 static int ac3_decode_frame(AVCodecContext * avctx, void *data,
1482                             int *got_frame_ptr, AVPacket *avpkt)
1483 {
1484     AVFrame *frame     = data;
1485     const uint8_t *buf = avpkt->data;
1486     int buf_size, full_buf_size = avpkt->size;
1487     AC3DecodeContext *s = avctx->priv_data;
1488     int blk, ch, err, offset, ret;
1489     int got_independent_frame = 0;
1490     const uint8_t *channel_map;
1491     uint8_t extended_channel_map[EAC3_MAX_CHANNELS];
1492     const SHORTFLOAT *output[AC3_MAX_CHANNELS];
1493     enum AVMatrixEncoding matrix_encoding;
1494     AVDownmixInfo *downmix_info;
1495
1496     s->superframe_size = 0;
1497
1498     buf_size = full_buf_size;
1499     /* copy input buffer to decoder context to avoid reading past the end
1500        of the buffer, which can be caused by a damaged input stream. */
1501     if (buf_size >= 2 && AV_RB16(buf) == 0x770B) {
1502         // seems to be byte-swapped AC-3
1503         int cnt = FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE) >> 1;
1504         s->bdsp.bswap16_buf((uint16_t *) s->input_buffer,
1505                             (const uint16_t *) buf, cnt);
1506     } else
1507         memcpy(s->input_buffer, buf, FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE));
1508
1509     /* if consistent noise generation is enabled, seed the linear feedback generator
1510      * with the contents of the AC-3 frame so that the noise is identical across
1511      * decodes given the same AC-3 frame data, for use with non-linear edititing software. */
1512     if (s->consistent_noise_generation)
1513         av_lfg_init_from_data(&s->dith_state, s->input_buffer, FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE));
1514
1515     buf = s->input_buffer;
1516 dependent_frame:
1517     /* initialize the GetBitContext with the start of valid AC-3 Frame */
1518     if ((ret = init_get_bits8(&s->gbc, buf, buf_size)) < 0)
1519         return ret;
1520
1521     /* parse the syncinfo */
1522     err = parse_frame_header(s);
1523
1524     if (err) {
1525         switch (err) {
1526         case AAC_AC3_PARSE_ERROR_SYNC:
1527             av_log(avctx, AV_LOG_ERROR, "frame sync error\n");
1528             return AVERROR_INVALIDDATA;
1529         case AAC_AC3_PARSE_ERROR_BSID:
1530             av_log(avctx, AV_LOG_ERROR, "invalid bitstream id\n");
1531             break;
1532         case AAC_AC3_PARSE_ERROR_SAMPLE_RATE:
1533             av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1534             break;
1535         case AAC_AC3_PARSE_ERROR_FRAME_SIZE:
1536             av_log(avctx, AV_LOG_ERROR, "invalid frame size\n");
1537             break;
1538         case AAC_AC3_PARSE_ERROR_FRAME_TYPE:
1539             /* skip frame if CRC is ok. otherwise use error concealment. */
1540             /* TODO: add support for substreams */
1541             if (s->substreamid) {
1542                 av_log(avctx, AV_LOG_DEBUG,
1543                        "unsupported substream %d: skipping frame\n",
1544                        s->substreamid);
1545                 *got_frame_ptr = 0;
1546                 return buf_size;
1547             } else {
1548                 av_log(avctx, AV_LOG_ERROR, "invalid frame type\n");
1549             }
1550             break;
1551         case AAC_AC3_PARSE_ERROR_CRC:
1552         case AAC_AC3_PARSE_ERROR_CHANNEL_CFG:
1553             break;
1554         default: // Normal AVERROR do not try to recover.
1555             *got_frame_ptr = 0;
1556             return err;
1557         }
1558     } else {
1559         /* check that reported frame size fits in input buffer */
1560         if (s->frame_size > buf_size) {
1561             av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1562             err = AAC_AC3_PARSE_ERROR_FRAME_SIZE;
1563         } else if (avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_CAREFUL)) {
1564             /* check for crc mismatch */
1565             if (av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, &buf[2],
1566                        s->frame_size - 2)) {
1567                 av_log(avctx, AV_LOG_ERROR, "frame CRC mismatch\n");
1568                 if (avctx->err_recognition & AV_EF_EXPLODE)
1569                     return AVERROR_INVALIDDATA;
1570                 err = AAC_AC3_PARSE_ERROR_CRC;
1571             }
1572         }
1573     }
1574
1575     if (s->frame_type == EAC3_FRAME_TYPE_DEPENDENT && !got_independent_frame) {
1576         av_log(avctx, AV_LOG_WARNING, "Ignoring dependent frame without independent frame.\n");
1577         *got_frame_ptr = 0;
1578         return FFMIN(full_buf_size, s->frame_size);
1579     }
1580
1581     /* channel config */
1582     if (!err || (s->channels && s->out_channels != s->channels)) {
1583         s->out_channels = s->channels;
1584         s->output_mode  = s->channel_mode;
1585         if (s->lfe_on)
1586             s->output_mode |= AC3_OUTPUT_LFEON;
1587         if (s->channels > 1 &&
1588             avctx->request_channel_layout == AV_CH_LAYOUT_MONO) {
1589             s->out_channels = 1;
1590             s->output_mode  = AC3_CHMODE_MONO;
1591         } else if (s->channels > 2 &&
1592                    avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1593             s->out_channels = 2;
1594             s->output_mode  = AC3_CHMODE_STEREO;
1595         }
1596
1597         s->loro_center_mix_level   = gain_levels[s->  center_mix_level];
1598         s->loro_surround_mix_level = gain_levels[s->surround_mix_level];
1599         s->ltrt_center_mix_level   = LEVEL_MINUS_3DB;
1600         s->ltrt_surround_mix_level = LEVEL_MINUS_3DB;
1601         /* set downmixing coefficients if needed */
1602         if (s->channels != s->out_channels && !((s->output_mode & AC3_OUTPUT_LFEON) &&
1603                 s->fbw_channels == s->out_channels)) {
1604             if ((ret = set_downmix_coeffs(s)) < 0) {
1605                 av_log(avctx, AV_LOG_ERROR, "error setting downmix coeffs\n");
1606                 return ret;
1607             }
1608         }
1609     } else if (!s->channels) {
1610         av_log(avctx, AV_LOG_ERROR, "unable to determine channel mode\n");
1611         return AVERROR_INVALIDDATA;
1612     }
1613     avctx->channels = s->out_channels;
1614     avctx->channel_layout = avpriv_ac3_channel_layout_tab[s->output_mode & ~AC3_OUTPUT_LFEON];
1615     if (s->output_mode & AC3_OUTPUT_LFEON)
1616         avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1617
1618     /* set audio service type based on bitstream mode for AC-3 */
1619     avctx->audio_service_type = s->bitstream_mode;
1620     if (s->bitstream_mode == 0x7 && s->channels > 1)
1621         avctx->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
1622
1623     /* decode the audio blocks */
1624     channel_map = ff_ac3_dec_channel_map[s->output_mode & ~AC3_OUTPUT_LFEON][s->lfe_on];
1625     offset = s->frame_type == EAC3_FRAME_TYPE_DEPENDENT ? AC3_MAX_CHANNELS : 0;
1626     for (ch = 0; ch < AC3_MAX_CHANNELS; ch++) {
1627         output[ch] = s->output[ch + offset];
1628         s->outptr[ch] = s->output[ch + offset];
1629     }
1630     for (ch = 0; ch < s->channels; ch++) {
1631         if (ch < s->out_channels)
1632             s->outptr[channel_map[ch]] = s->output_buffer[ch + offset];
1633     }
1634     for (blk = 0; blk < s->num_blocks; blk++) {
1635         if (!err && decode_audio_block(s, blk, offset)) {
1636             av_log(avctx, AV_LOG_ERROR, "error decoding the audio block\n");
1637             err = 1;
1638         }
1639         if (err)
1640             for (ch = 0; ch < s->out_channels; ch++)
1641                 memcpy(s->output_buffer[ch + offset] + AC3_BLOCK_SIZE*blk, output[ch], AC3_BLOCK_SIZE*sizeof(SHORTFLOAT));
1642         for (ch = 0; ch < s->out_channels; ch++)
1643             output[ch] = s->outptr[channel_map[ch]];
1644         for (ch = 0; ch < s->out_channels; ch++) {
1645             if (!ch || channel_map[ch])
1646                 s->outptr[channel_map[ch]] += AC3_BLOCK_SIZE;
1647         }
1648     }
1649
1650     /* keep last block for error concealment in next frame */
1651     for (ch = 0; ch < s->out_channels; ch++)
1652         memcpy(s->output[ch + offset], output[ch], AC3_BLOCK_SIZE*sizeof(SHORTFLOAT));
1653
1654     /* check if there is dependent frame */
1655     if (buf_size > s->frame_size) {
1656         AC3HeaderInfo hdr;
1657         int err;
1658
1659         if ((ret = init_get_bits8(&s->gbc, buf + s->frame_size, buf_size - s->frame_size)) < 0)
1660             return ret;
1661
1662         err = ff_ac3_parse_header(&s->gbc, &hdr);
1663         if (err)
1664             return err;
1665
1666         if (hdr.frame_type == EAC3_FRAME_TYPE_DEPENDENT) {
1667             if (hdr.num_blocks != s->num_blocks || s->sample_rate != hdr.sample_rate) {
1668                 av_log(avctx, AV_LOG_WARNING, "Ignoring non-compatible dependent frame.\n");
1669             } else {
1670                 buf += s->frame_size;
1671                 buf_size -= s->frame_size;
1672                 s->prev_output_mode = s->output_mode;
1673                 s->prev_bit_rate = s->bit_rate;
1674                 got_independent_frame = 1;
1675                 goto dependent_frame;
1676             }
1677         }
1678     }
1679
1680     frame->decode_error_flags = err ? FF_DECODE_ERROR_INVALID_BITSTREAM : 0;
1681
1682     /* if frame is ok, set audio parameters */
1683     if (!err) {
1684         avctx->sample_rate = s->sample_rate;
1685         avctx->bit_rate    = s->bit_rate + s->prev_bit_rate;
1686     }
1687
1688     for (ch = 0; ch < EAC3_MAX_CHANNELS; ch++)
1689         extended_channel_map[ch] = ch;
1690
1691     if (s->frame_type == EAC3_FRAME_TYPE_DEPENDENT) {
1692         uint64_t ich_layout = avpriv_ac3_channel_layout_tab[s->prev_output_mode & ~AC3_OUTPUT_LFEON];
1693         int channel_map_size = ff_ac3_channels_tab[s->output_mode & ~AC3_OUTPUT_LFEON] + s->lfe_on;
1694         uint64_t channel_layout;
1695         int extend = 0;
1696
1697         if (s->prev_output_mode & AC3_OUTPUT_LFEON)
1698             ich_layout |= AV_CH_LOW_FREQUENCY;
1699
1700         channel_layout = ich_layout;
1701         for (ch = 0; ch < 16; ch++) {
1702             if (s->channel_map & (1 << (EAC3_MAX_CHANNELS - ch - 1))) {
1703                 channel_layout |= custom_channel_map_locations[ch][1];
1704             }
1705         }
1706         if (av_get_channel_layout_nb_channels(channel_layout) > EAC3_MAX_CHANNELS) {
1707             av_log(avctx, AV_LOG_ERROR, "Too many channels (%d) coded\n",
1708                    av_get_channel_layout_nb_channels(channel_layout));
1709             return AVERROR_INVALIDDATA;
1710         }
1711
1712         avctx->channel_layout = channel_layout;
1713         avctx->channels = av_get_channel_layout_nb_channels(channel_layout);
1714
1715         for (ch = 0; ch < EAC3_MAX_CHANNELS; ch++) {
1716             if (s->channel_map & (1 << (EAC3_MAX_CHANNELS - ch - 1))) {
1717                 if (custom_channel_map_locations[ch][0]) {
1718                     int index = av_get_channel_layout_channel_index(channel_layout,
1719                                                                     custom_channel_map_locations[ch][1]);
1720                     if (index < 0)
1721                         return AVERROR_INVALIDDATA;
1722                     if (extend >= channel_map_size)
1723                         return AVERROR_INVALIDDATA;
1724
1725                     extended_channel_map[index] = offset + channel_map[extend++];
1726                 } else {
1727                     int i;
1728
1729                     for (i = 0; i < 64; i++) {
1730                         if ((1LL << i) & custom_channel_map_locations[ch][1]) {
1731                             int index = av_get_channel_layout_channel_index(channel_layout,
1732                                                                             1LL << i);
1733                             if (index < 0)
1734                                 return AVERROR_INVALIDDATA;
1735                             if (extend >= channel_map_size)
1736                                 return AVERROR_INVALIDDATA;
1737
1738                             extended_channel_map[index] = offset + channel_map[extend++];
1739                         }
1740                     }
1741                 }
1742             }
1743         }
1744     }
1745
1746     /* get output buffer */
1747     frame->nb_samples = s->num_blocks * AC3_BLOCK_SIZE;
1748     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1749         return ret;
1750
1751     for (ch = 0; ch < avctx->channels; ch++) {
1752         int map = extended_channel_map[ch];
1753         av_assert0(ch>=AV_NUM_DATA_POINTERS || frame->extended_data[ch] == frame->data[ch]);
1754         memcpy((SHORTFLOAT *)frame->extended_data[ch],
1755                s->output_buffer[map],
1756                s->num_blocks * AC3_BLOCK_SIZE * sizeof(SHORTFLOAT));
1757     }
1758
1759     /*
1760      * AVMatrixEncoding
1761      *
1762      * Check whether the input layout is compatible, and make sure we're not
1763      * downmixing (else the matrix encoding is no longer applicable).
1764      */
1765     matrix_encoding = AV_MATRIX_ENCODING_NONE;
1766     if (s->channel_mode == AC3_CHMODE_STEREO &&
1767         s->channel_mode == (s->output_mode & ~AC3_OUTPUT_LFEON)) {
1768         if (s->dolby_surround_mode == AC3_DSURMOD_ON)
1769             matrix_encoding = AV_MATRIX_ENCODING_DOLBY;
1770         else if (s->dolby_headphone_mode == AC3_DHEADPHONMOD_ON)
1771             matrix_encoding = AV_MATRIX_ENCODING_DOLBYHEADPHONE;
1772     } else if (s->channel_mode >= AC3_CHMODE_2F2R &&
1773                s->channel_mode == (s->output_mode & ~AC3_OUTPUT_LFEON)) {
1774         switch (s->dolby_surround_ex_mode) {
1775         case AC3_DSUREXMOD_ON: // EX or PLIIx
1776             matrix_encoding = AV_MATRIX_ENCODING_DOLBYEX;
1777             break;
1778         case AC3_DSUREXMOD_PLIIZ:
1779             matrix_encoding = AV_MATRIX_ENCODING_DPLIIZ;
1780             break;
1781         default: // not indicated or off
1782             break;
1783         }
1784     }
1785     if ((ret = ff_side_data_update_matrix_encoding(frame, matrix_encoding)) < 0)
1786         return ret;
1787
1788     /* AVDownmixInfo */
1789     if ((downmix_info = av_downmix_info_update_side_data(frame))) {
1790         switch (s->preferred_downmix) {
1791         case AC3_DMIXMOD_LTRT:
1792             downmix_info->preferred_downmix_type = AV_DOWNMIX_TYPE_LTRT;
1793             break;
1794         case AC3_DMIXMOD_LORO:
1795             downmix_info->preferred_downmix_type = AV_DOWNMIX_TYPE_LORO;
1796             break;
1797         case AC3_DMIXMOD_DPLII:
1798             downmix_info->preferred_downmix_type = AV_DOWNMIX_TYPE_DPLII;
1799             break;
1800         default:
1801             downmix_info->preferred_downmix_type = AV_DOWNMIX_TYPE_UNKNOWN;
1802             break;
1803         }
1804         downmix_info->center_mix_level        = gain_levels[s->       center_mix_level];
1805         downmix_info->center_mix_level_ltrt   = gain_levels[s->  center_mix_level_ltrt];
1806         downmix_info->surround_mix_level      = gain_levels[s->     surround_mix_level];
1807         downmix_info->surround_mix_level_ltrt = gain_levels[s->surround_mix_level_ltrt];
1808         if (s->lfe_mix_level_exists)
1809             downmix_info->lfe_mix_level       = gain_levels_lfe[s->lfe_mix_level];
1810         else
1811             downmix_info->lfe_mix_level       = 0.0; // -inf dB
1812     } else
1813         return AVERROR(ENOMEM);
1814
1815     *got_frame_ptr = 1;
1816
1817     if (!s->superframe_size)
1818         return FFMIN(full_buf_size, s->frame_size);
1819
1820     return FFMIN(full_buf_size, s->superframe_size);
1821 }
1822
1823 /**
1824  * Uninitialize the AC-3 decoder.
1825  */
1826 static av_cold int ac3_decode_end(AVCodecContext *avctx)
1827 {
1828     AC3DecodeContext *s = avctx->priv_data;
1829     ff_mdct_end(&s->imdct_512);
1830     ff_mdct_end(&s->imdct_256);
1831     av_freep(&s->fdsp);
1832     av_freep(&s->downmix_coeffs[0]);
1833
1834     return 0;
1835 }
1836
1837 #define OFFSET(x) offsetof(AC3DecodeContext, x)
1838 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)