Browse code

avcodec/dca: add new decoder based on libdcadec

foo86 authored on 2016/01/16 17:54:38
Showing 22 changed files
... ...
@@ -61,6 +61,7 @@ version <next>:
61 61
 - support for dvaudio in wav and avi
62 62
 - libaacplus and libvo-aacenc support removed
63 63
 - Cineform HD decoder
64
+- new DCA decoder with full support for DTS-HD extensions
64 65
 
65 66
 
66 67
 version 2.8:
... ...
@@ -2271,6 +2271,7 @@ comfortnoise_encoder_select="lpc"
2271 2271
 cook_decoder_select="audiodsp mdct sinewin"
2272 2272
 cscd_decoder_select="lzo"
2273 2273
 cscd_decoder_suggest="zlib"
2274
+dca_decoder_select="mdct"
2274 2275
 dds_decoder_select="texturedsp"
2275 2276
 dirac_decoder_select="dirac_parse dwt golomb videodsp mpegvideoenc"
2276 2277
 dnxhd_decoder_select="blockdsp idctdsp"
... ...
@@ -222,6 +222,9 @@ OBJS-$(CONFIG_COMFORTNOISE_ENCODER)    += cngenc.o
222 222
 OBJS-$(CONFIG_CPIA_DECODER)            += cpia.o
223 223
 OBJS-$(CONFIG_CSCD_DECODER)            += cscd.o
224 224
 OBJS-$(CONFIG_CYUV_DECODER)            += cyuv.o
225
+OBJS-$(CONFIG_DCA_DECODER)             += dcadec.o dca.o dcadata.o        \
226
+                                          dca_core.o dca_exss.o dca_xll.o \
227
+                                          dcadsp.o dcadct.o synth_filter.o
225 228
 OBJS-$(CONFIG_DCA_ENCODER)             += dcaenc.o dca.o dcadata.o
226 229
 OBJS-$(CONFIG_DDS_DECODER)             += dds.o
227 230
 OBJS-$(CONFIG_DIRAC_DECODER)           += diracdec.o dirac.o diracdsp.o \
... ...
@@ -1,4 +1,4 @@
1
-#OBJS-$(CONFIG_DCA_DECODER)              += aarch64/synth_filter_init.o
1
+OBJS-$(CONFIG_DCA_DECODER)              += aarch64/synth_filter_init.o
2 2
 OBJS-$(CONFIG_FFT)                      += aarch64/fft_init_aarch64.o
3 3
 OBJS-$(CONFIG_FMTCONVERT)               += aarch64/fmtconvert_init.o
4 4
 OBJS-$(CONFIG_H264CHROMA)               += aarch64/h264chroma_init_aarch64.o
... ...
@@ -17,7 +17,7 @@ OBJS-$(CONFIG_VORBIS_DECODER)           += aarch64/vorbisdsp_init.o
17 17
 
18 18
 ARMV8-OBJS-$(CONFIG_VIDEODSP)           += aarch64/videodsp.o
19 19
 
20
-#NEON-OBJS-$(CONFIG_DCA_DECODER)         += aarch64/synth_filter_neon.o
20
+NEON-OBJS-$(CONFIG_DCA_DECODER)         += aarch64/synth_filter_neon.o
21 21
 NEON-OBJS-$(CONFIG_FFT)                 += aarch64/fft_neon.o
22 22
 NEON-OBJS-$(CONFIG_FMTCONVERT)          += aarch64/fmtconvert_neon.o
23 23
 NEON-OBJS-$(CONFIG_H264CHROMA)          += aarch64/h264cmc_neon.o
... ...
@@ -391,7 +391,7 @@ void avcodec_register_all(void)
391 391
     REGISTER_DECODER(BINKAUDIO_RDFT,    binkaudio_rdft);
392 392
     REGISTER_DECODER(BMV_AUDIO,         bmv_audio);
393 393
     REGISTER_DECODER(COOK,              cook);
394
-    REGISTER_ENCODER(DCA,               dca);
394
+    REGISTER_ENCDEC (DCA,               dca);
395 395
     REGISTER_DECODER(DSD_LSBF,          dsd_lsbf);
396 396
     REGISTER_DECODER(DSD_MSBF,          dsd_msbf);
397 397
     REGISTER_DECODER(DSD_LSBF_PLANAR,   dsd_lsbf_planar);
... ...
@@ -36,7 +36,7 @@ OBJS-$(CONFIG_VP8DSP)                  += arm/vp8dsp_init_arm.o
36 36
 # decoders/encoders
37 37
 OBJS-$(CONFIG_AAC_DECODER)             += arm/aacpsdsp_init_arm.o       \
38 38
                                           arm/sbrdsp_init_arm.o
39
-#OBJS-$(CONFIG_DCA_DECODER)             += arm/synth_filter_init_arm.o
39
+OBJS-$(CONFIG_DCA_DECODER)             += arm/synth_filter_init_arm.o
40 40
 OBJS-$(CONFIG_HEVC_DECODER)            += arm/hevcdsp_init_arm.o
41 41
 OBJS-$(CONFIG_MLP_DECODER)             += arm/mlpdsp_init_arm.o
42 42
 OBJS-$(CONFIG_RV40_DECODER)            += arm/rv40dsp_init_arm.o
... ...
@@ -87,7 +87,7 @@ VFP-OBJS-$(CONFIG_FMTCONVERT)          += arm/fmtconvert_vfp.o
87 87
 VFP-OBJS-$(CONFIG_MDCT)                += arm/mdct_vfp.o
88 88
 
89 89
 # decoders/encoders
90
-#VFP-OBJS-$(CONFIG_DCA_DECODER)         += arm/synth_filter_vfp.o
90
+VFP-OBJS-$(CONFIG_DCA_DECODER)         += arm/synth_filter_vfp.o
91 91
 
92 92
 
93 93
 # NEON optimizations
... ...
@@ -126,7 +126,7 @@ NEON-OBJS-$(CONFIG_VP8DSP)             += arm/vp8dsp_init_neon.o        \
126 126
 NEON-OBJS-$(CONFIG_AAC_DECODER)        += arm/aacpsdsp_neon.o           \
127 127
                                           arm/sbrdsp_neon.o
128 128
 NEON-OBJS-$(CONFIG_LLAUDDSP)           += arm/lossless_audiodsp_neon.o
129
-#NEON-OBJS-$(CONFIG_DCA_DECODER)        += arm/synth_filter_neon.o
129
+NEON-OBJS-$(CONFIG_DCA_DECODER)        += arm/synth_filter_neon.o
130 130
 NEON-OBJS-$(CONFIG_HEVC_DECODER)       += arm/hevcdsp_init_neon.o       \
131 131
                                           arm/hevcdsp_deblock_neon.o    \
132 132
                                           arm/hevcdsp_idct_neon.o       \
133 133
new file mode 100644
... ...
@@ -0,0 +1,2603 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include "dcadec.h"
21
+#include "dcadata.h"
22
+#include "dcahuff.h"
23
+#include "dcamath.h"
24
+#include "dca_syncwords.h"
25
+
26
+#if ARCH_ARM
27
+#include "arm/dca.h"
28
+#endif
29
+
30
+enum HeaderType {
31
+    HEADER_CORE,
32
+    HEADER_XCH,
33
+    HEADER_XXCH
34
+};
35
+
36
+enum AudioMode {
37
+    AMODE_MONO,             // Mode 0: A (mono)
38
+    AMODE_MONO_DUAL,        // Mode 1: A + B (dual mono)
39
+    AMODE_STEREO,           // Mode 2: L + R (stereo)
40
+    AMODE_STEREO_SUMDIFF,   // Mode 3: (L+R) + (L-R) (sum-diff)
41
+    AMODE_STEREO_TOTAL,     // Mode 4: LT + RT (left and right total)
42
+    AMODE_3F,               // Mode 5: C + L + R
43
+    AMODE_2F1R,             // Mode 6: L + R + S
44
+    AMODE_3F1R,             // Mode 7: C + L + R + S
45
+    AMODE_2F2R,             // Mode 8: L + R + SL + SR
46
+    AMODE_3F2R,             // Mode 9: C + L + R + SL + SR
47
+
48
+    AMODE_COUNT
49
+};
50
+
51
+enum ExtAudioType {
52
+    EXT_AUDIO_XCH   = 0,
53
+    EXT_AUDIO_X96   = 2,
54
+    EXT_AUDIO_XXCH  = 6
55
+};
56
+
57
+enum LFEFlag {
58
+    LFE_FLAG_NONE,
59
+    LFE_FLAG_128,
60
+    LFE_FLAG_64,
61
+    LFE_FLAG_INVALID
62
+};
63
+
64
+static const int8_t prm_ch_to_spkr_map[AMODE_COUNT][5] = {
65
+    { DCA_SPEAKER_C,            -1,             -1,             -1,             -1 },
66
+    { DCA_SPEAKER_L, DCA_SPEAKER_R,             -1,             -1,             -1 },
67
+    { DCA_SPEAKER_L, DCA_SPEAKER_R,             -1,             -1,             -1 },
68
+    { DCA_SPEAKER_L, DCA_SPEAKER_R,             -1,             -1,             -1 },
69
+    { DCA_SPEAKER_L, DCA_SPEAKER_R,             -1,             -1,             -1 },
70
+    { DCA_SPEAKER_C, DCA_SPEAKER_L, DCA_SPEAKER_R ,             -1,             -1 },
71
+    { DCA_SPEAKER_L, DCA_SPEAKER_R, DCA_SPEAKER_Cs,             -1,             -1 },
72
+    { DCA_SPEAKER_C, DCA_SPEAKER_L, DCA_SPEAKER_R , DCA_SPEAKER_Cs,             -1 },
73
+    { DCA_SPEAKER_L, DCA_SPEAKER_R, DCA_SPEAKER_Ls, DCA_SPEAKER_Rs,             -1 },
74
+    { DCA_SPEAKER_C, DCA_SPEAKER_L, DCA_SPEAKER_R,  DCA_SPEAKER_Ls, DCA_SPEAKER_Rs }
75
+};
76
+
77
+static const uint8_t audio_mode_ch_mask[AMODE_COUNT] = {
78
+    DCA_SPEAKER_LAYOUT_MONO,
79
+    DCA_SPEAKER_LAYOUT_STEREO,
80
+    DCA_SPEAKER_LAYOUT_STEREO,
81
+    DCA_SPEAKER_LAYOUT_STEREO,
82
+    DCA_SPEAKER_LAYOUT_STEREO,
83
+    DCA_SPEAKER_LAYOUT_3_0,
84
+    DCA_SPEAKER_LAYOUT_2_1,
85
+    DCA_SPEAKER_LAYOUT_3_1,
86
+    DCA_SPEAKER_LAYOUT_2_2,
87
+    DCA_SPEAKER_LAYOUT_5POINT0
88
+};
89
+
90
+static const uint8_t block_code_nbits[7] = {
91
+    7, 10, 12, 13, 15, 17, 19
92
+};
93
+
94
+static const uint8_t quant_index_sel_nbits[DCA_CODE_BOOKS] = {
95
+    1, 2, 2, 2, 2, 3, 3, 3, 3, 3
96
+};
97
+
98
+static const uint8_t quant_index_group_size[DCA_CODE_BOOKS] = {
99
+    1, 3, 3, 3, 3, 7, 7, 7, 7, 7
100
+};
101
+
102
+typedef struct DCAVLC {
103
+    int offset;         ///< Code values offset
104
+    int max_depth;      ///< Parameter for get_vlc2()
105
+    VLC vlc[7];         ///< Actual codes
106
+} DCAVLC;
107
+
108
+static DCAVLC   vlc_bit_allocation;
109
+static DCAVLC   vlc_transition_mode;
110
+static DCAVLC   vlc_scale_factor;
111
+static DCAVLC   vlc_quant_index[DCA_CODE_BOOKS];
112
+
113
+static av_cold void dca_init_vlcs(void)
114
+{
115
+    static VLC_TYPE dca_table[23622][2];
116
+    static int vlcs_initialized = 0;
117
+    int i, j, k;
118
+
119
+    if (vlcs_initialized)
120
+        return;
121
+
122
+#define DCA_INIT_VLC(vlc, a, b, c, d)                                      \
123
+    do {                                                                   \
124
+        vlc.table           = &dca_table[ff_dca_vlc_offs[k]];              \
125
+        vlc.table_allocated = ff_dca_vlc_offs[k + 1] - ff_dca_vlc_offs[k]; \
126
+        init_vlc(&vlc, a, b, c, 1, 1, d, 2, 2, INIT_VLC_USE_NEW_STATIC);   \
127
+    } while (0)
128
+
129
+    vlc_bit_allocation.offset    = 1;
130
+    vlc_bit_allocation.max_depth = 2;
131
+    for (i = 0, k = 0; i < 5; i++, k++)
132
+        DCA_INIT_VLC(vlc_bit_allocation.vlc[i], bitalloc_12_vlc_bits[i], 12,
133
+                     bitalloc_12_bits[i], bitalloc_12_codes[i]);
134
+
135
+    vlc_scale_factor.offset    = -64;
136
+    vlc_scale_factor.max_depth = 2;
137
+    for (i = 0; i < 5; i++, k++)
138
+        DCA_INIT_VLC(vlc_scale_factor.vlc[i], SCALES_VLC_BITS, 129,
139
+                     scales_bits[i], scales_codes[i]);
140
+
141
+    vlc_transition_mode.offset    = 0;
142
+    vlc_transition_mode.max_depth = 1;
143
+    for (i = 0; i < 4; i++, k++)
144
+        DCA_INIT_VLC(vlc_transition_mode.vlc[i], tmode_vlc_bits[i], 4,
145
+                     tmode_bits[i], tmode_codes[i]);
146
+
147
+    for (i = 0; i < DCA_CODE_BOOKS; i++) {
148
+        vlc_quant_index[i].offset    = bitalloc_offsets[i];
149
+        vlc_quant_index[i].max_depth = 1 + (i > 4);
150
+        for (j = 0; j < quant_index_group_size[i]; j++, k++)
151
+            DCA_INIT_VLC(vlc_quant_index[i].vlc[j], bitalloc_maxbits[i][j],
152
+                         bitalloc_sizes[i], bitalloc_bits[i][j], bitalloc_codes[i][j]);
153
+    }
154
+
155
+    vlcs_initialized = 1;
156
+}
157
+
158
+static int get_vlc(GetBitContext *s, DCAVLC *v, int i)
159
+{
160
+    return get_vlc2(s, v->vlc[i].table, v->vlc[i].bits, v->max_depth) + v->offset;
161
+}
162
+
163
+static void get_array(GetBitContext *s, int32_t *array, int size, int n)
164
+{
165
+    int i;
166
+
167
+    for (i = 0; i < size; i++)
168
+        array[i] = get_sbits(s, n);
169
+}
170
+
171
+// 5.3.1 - Bit stream header
172
+static int parse_frame_header(DCACoreDecoder *s)
173
+{
174
+    int normal_frame, pcmr_index;
175
+
176
+    // Frame type
177
+    normal_frame = get_bits1(&s->gb);
178
+
179
+    // Deficit sample count
180
+    if (get_bits(&s->gb, 5) != DCA_PCMBLOCK_SAMPLES - 1) {
181
+        av_log(s->avctx, AV_LOG_ERROR, "Deficit samples are not supported\n");
182
+        return normal_frame ? AVERROR_INVALIDDATA : AVERROR_PATCHWELCOME;
183
+    }
184
+
185
+    // CRC present flag
186
+    s->crc_present = get_bits1(&s->gb);
187
+
188
+    // Number of PCM sample blocks
189
+    s->npcmblocks = get_bits(&s->gb, 7) + 1;
190
+    if (s->npcmblocks & (DCA_SUBBAND_SAMPLES - 1)) {
191
+        av_log(s->avctx, AV_LOG_ERROR, "Unsupported number of PCM sample blocks (%d)\n", s->npcmblocks);
192
+        return (s->npcmblocks < 6 || normal_frame) ? AVERROR_INVALIDDATA : AVERROR_PATCHWELCOME;
193
+    }
194
+
195
+    // Primary frame byte size
196
+    s->frame_size = get_bits(&s->gb, 14) + 1;
197
+    if (s->frame_size < 96) {
198
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid core frame size (%d bytes)\n", s->frame_size);
199
+        return AVERROR_INVALIDDATA;
200
+    }
201
+
202
+    // Audio channel arrangement
203
+    s->audio_mode = get_bits(&s->gb, 6);
204
+    if (s->audio_mode >= AMODE_COUNT) {
205
+        av_log(s->avctx, AV_LOG_ERROR, "Unsupported audio channel arrangement (%d)\n", s->audio_mode);
206
+        return AVERROR_PATCHWELCOME;
207
+    }
208
+
209
+    // Core audio sampling frequency
210
+    s->sample_rate = avpriv_dca_sample_rates[get_bits(&s->gb, 4)];
211
+    if (!s->sample_rate) {
212
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid core audio sampling frequency\n");
213
+        return AVERROR_INVALIDDATA;
214
+    }
215
+
216
+    // Transmission bit rate
217
+    s->bit_rate = ff_dca_bit_rates[get_bits(&s->gb, 5)];
218
+
219
+    // Reserved field
220
+    skip_bits1(&s->gb);
221
+
222
+    // Embedded dynamic range flag
223
+    s->drc_present = get_bits1(&s->gb);
224
+
225
+    // Embedded time stamp flag
226
+    s->ts_present = get_bits1(&s->gb);
227
+
228
+    // Auxiliary data flag
229
+    s->aux_present = get_bits1(&s->gb);
230
+
231
+    // HDCD mastering flag
232
+    skip_bits1(&s->gb);
233
+
234
+    // Extension audio descriptor flag
235
+    s->ext_audio_type = get_bits(&s->gb, 3);
236
+
237
+    // Extended coding flag
238
+    s->ext_audio_present = get_bits1(&s->gb);
239
+
240
+    // Audio sync word insertion flag
241
+    s->sync_ssf = get_bits1(&s->gb);
242
+
243
+    // Low frequency effects flag
244
+    s->lfe_present = get_bits(&s->gb, 2);
245
+    if (s->lfe_present == LFE_FLAG_INVALID) {
246
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid low frequency effects flag\n");
247
+        return AVERROR_INVALIDDATA;
248
+    }
249
+
250
+    // Predictor history flag switch
251
+    s->predictor_history = get_bits1(&s->gb);
252
+
253
+    // Header CRC check bytes
254
+    if (s->crc_present)
255
+        skip_bits(&s->gb, 16);
256
+
257
+    // Multirate interpolator switch
258
+    s->filter_perfect = get_bits1(&s->gb);
259
+
260
+    // Encoder software revision
261
+    skip_bits(&s->gb, 4);
262
+
263
+    // Copy history
264
+    skip_bits(&s->gb, 2);
265
+
266
+    // Source PCM resolution
267
+    s->source_pcm_res = ff_dca_bits_per_sample[pcmr_index = get_bits(&s->gb, 3)];
268
+    if (!s->source_pcm_res) {
269
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid source PCM resolution\n");
270
+        return AVERROR_INVALIDDATA;
271
+    }
272
+    s->es_format = pcmr_index & 1;
273
+
274
+    // Front sum/difference flag
275
+    s->sumdiff_front = get_bits1(&s->gb);
276
+
277
+    // Surround sum/difference flag
278
+    s->sumdiff_surround = get_bits1(&s->gb);
279
+
280
+    // Dialog normalization / unspecified
281
+    skip_bits(&s->gb, 4);
282
+
283
+    return 0;
284
+}
285
+
286
+// 5.3.2 - Primary audio coding header
287
+static int parse_coding_header(DCACoreDecoder *s, enum HeaderType header, int xch_base)
288
+{
289
+    int n, ch, nchannels, header_size = 0, header_pos = get_bits_count(&s->gb);
290
+    unsigned int mask, index;
291
+
292
+    if (get_bits_left(&s->gb) < 0)
293
+        return AVERROR_INVALIDDATA;
294
+
295
+    switch (header) {
296
+    case HEADER_CORE:
297
+        // Number of subframes
298
+        s->nsubframes = get_bits(&s->gb, 4) + 1;
299
+
300
+        // Number of primary audio channels
301
+        s->nchannels = get_bits(&s->gb, 3) + 1;
302
+        if (s->nchannels != ff_dca_channels[s->audio_mode]) {
303
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid number of primary audio channels (%d) for audio channel arrangement (%d)\n", s->nchannels, s->audio_mode);
304
+            return AVERROR_INVALIDDATA;
305
+        }
306
+        av_assert1(s->nchannels <= DCA_CHANNELS - 2);
307
+
308
+        s->ch_mask = audio_mode_ch_mask[s->audio_mode];
309
+
310
+        // Add LFE channel if present
311
+        if (s->lfe_present)
312
+            s->ch_mask |= DCA_SPEAKER_MASK_LFE1;
313
+        break;
314
+
315
+    case HEADER_XCH:
316
+        s->nchannels = ff_dca_channels[s->audio_mode] + 1;
317
+        av_assert1(s->nchannels <= DCA_CHANNELS - 1);
318
+        s->ch_mask |= DCA_SPEAKER_MASK_Cs;
319
+        break;
320
+
321
+    case HEADER_XXCH:
322
+        // Channel set header length
323
+        header_size = get_bits(&s->gb, 7) + 1;
324
+
325
+        // Check CRC
326
+        if (s->xxch_crc_present
327
+            && (s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
328
+            && ff_dca_check_crc(&s->gb, header_pos, header_pos + header_size * 8)) {
329
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid XXCH channel set header checksum\n");
330
+            return AVERROR_INVALIDDATA;
331
+        }
332
+
333
+        // Number of channels in a channel set
334
+        nchannels = get_bits(&s->gb, 3) + 1;
335
+        if (nchannels > DCA_XXCH_CHANNELS_MAX) {
336
+            avpriv_request_sample(s->avctx, "%d XXCH channels", nchannels);
337
+            return AVERROR_PATCHWELCOME;
338
+        }
339
+        s->nchannels = ff_dca_channels[s->audio_mode] + nchannels;
340
+        av_assert1(s->nchannels <= DCA_CHANNELS);
341
+
342
+        // Loudspeaker layout mask
343
+        mask = get_bits_long(&s->gb, s->xxch_mask_nbits - DCA_SPEAKER_Cs);
344
+        s->xxch_spkr_mask = mask << DCA_SPEAKER_Cs;
345
+
346
+        if (av_popcount(s->xxch_spkr_mask) != nchannels) {
347
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid XXCH speaker layout mask (%#x)\n", s->xxch_spkr_mask);
348
+            return AVERROR_INVALIDDATA;
349
+        }
350
+
351
+        if (s->xxch_core_mask & s->xxch_spkr_mask) {
352
+            av_log(s->avctx, AV_LOG_ERROR, "XXCH speaker layout mask (%#x) overlaps with core (%#x)\n", s->xxch_spkr_mask, s->xxch_core_mask);
353
+            return AVERROR_INVALIDDATA;
354
+        }
355
+
356
+        // Combine core and XXCH masks together
357
+        s->ch_mask = s->xxch_core_mask | s->xxch_spkr_mask;
358
+
359
+        // Downmix coefficients present in stream
360
+        if (get_bits1(&s->gb)) {
361
+            int *coeff_ptr = s->xxch_dmix_coeff;
362
+
363
+            // Downmix already performed by encoder
364
+            s->xxch_dmix_embedded = get_bits1(&s->gb);
365
+
366
+            // Downmix scale factor
367
+            index = get_bits(&s->gb, 6) * 4 - FF_DCA_DMIXTABLE_OFFSET - 3;
368
+            if (index >= FF_DCA_INV_DMIXTABLE_SIZE) {
369
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid XXCH downmix scale index (%d)\n", index);
370
+                return AVERROR_INVALIDDATA;
371
+            }
372
+            s->xxch_dmix_scale_inv = ff_dca_inv_dmixtable[index];
373
+
374
+            // Downmix channel mapping mask
375
+            for (ch = 0; ch < nchannels; ch++) {
376
+                mask = get_bits_long(&s->gb, s->xxch_mask_nbits);
377
+                if ((mask & s->xxch_core_mask) != mask) {
378
+                    av_log(s->avctx, AV_LOG_ERROR, "Invalid XXCH downmix channel mapping mask (%#x)\n", mask);
379
+                    return AVERROR_INVALIDDATA;
380
+                }
381
+                s->xxch_dmix_mask[ch] = mask;
382
+            }
383
+
384
+            // Downmix coefficients
385
+            for (ch = 0; ch < nchannels; ch++) {
386
+                for (n = 0; n < s->xxch_mask_nbits; n++) {
387
+                    if (s->xxch_dmix_mask[ch] & (1U << n)) {
388
+                        int code = get_bits(&s->gb, 7);
389
+                        int sign = (code >> 6) - 1;
390
+                        if (code &= 63) {
391
+                            index = code * 4 - 3;
392
+                            if (index >= FF_DCA_DMIXTABLE_SIZE) {
393
+                                av_log(s->avctx, AV_LOG_ERROR, "Invalid XXCH downmix coefficient index (%d)\n", index);
394
+                                return AVERROR_INVALIDDATA;
395
+                            }
396
+                            *coeff_ptr++ = (ff_dca_dmixtable[index] ^ sign) - sign;
397
+                        } else {
398
+                            *coeff_ptr++ = 0;
399
+                        }
400
+                    }
401
+                }
402
+            }
403
+        } else {
404
+            s->xxch_dmix_embedded = 0;
405
+        }
406
+
407
+        break;
408
+    }
409
+
410
+    // Subband activity count
411
+    for (ch = xch_base; ch < s->nchannels; ch++) {
412
+        s->nsubbands[ch] = get_bits(&s->gb, 5) + 2;
413
+        if (s->nsubbands[ch] > DCA_SUBBANDS) {
414
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid subband activity count\n");
415
+            return AVERROR_INVALIDDATA;
416
+        }
417
+    }
418
+
419
+    // High frequency VQ start subband
420
+    for (ch = xch_base; ch < s->nchannels; ch++)
421
+        s->subband_vq_start[ch] = get_bits(&s->gb, 5) + 1;
422
+
423
+    // Joint intensity coding index
424
+    for (ch = xch_base; ch < s->nchannels; ch++) {
425
+        if ((n = get_bits(&s->gb, 3)) && header == HEADER_XXCH)
426
+            n += xch_base - 1;
427
+        if (n > s->nchannels) {
428
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid joint intensity coding index\n");
429
+            return AVERROR_INVALIDDATA;
430
+        }
431
+        s->joint_intensity_index[ch] = n;
432
+    }
433
+
434
+    // Transient mode code book
435
+    for (ch = xch_base; ch < s->nchannels; ch++)
436
+        s->transition_mode_sel[ch] = get_bits(&s->gb, 2);
437
+
438
+    // Scale factor code book
439
+    for (ch = xch_base; ch < s->nchannels; ch++) {
440
+        s->scale_factor_sel[ch] = get_bits(&s->gb, 3);
441
+        if (s->scale_factor_sel[ch] == 7) {
442
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid scale factor code book\n");
443
+            return AVERROR_INVALIDDATA;
444
+        }
445
+    }
446
+
447
+    // Bit allocation quantizer select
448
+    for (ch = xch_base; ch < s->nchannels; ch++) {
449
+        s->bit_allocation_sel[ch] = get_bits(&s->gb, 3);
450
+        if (s->bit_allocation_sel[ch] == 7) {
451
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid bit allocation quantizer select\n");
452
+            return AVERROR_INVALIDDATA;
453
+        }
454
+    }
455
+
456
+    // Quantization index codebook select
457
+    for (n = 0; n < DCA_CODE_BOOKS; n++)
458
+        for (ch = xch_base; ch < s->nchannels; ch++)
459
+            s->quant_index_sel[ch][n] = get_bits(&s->gb, quant_index_sel_nbits[n]);
460
+
461
+    // Scale factor adjustment index
462
+    for (n = 0; n < DCA_CODE_BOOKS; n++)
463
+        for (ch = xch_base; ch < s->nchannels; ch++)
464
+            if (s->quant_index_sel[ch][n] < quant_index_group_size[n])
465
+                s->scale_factor_adj[ch][n] = ff_dca_scale_factor_adj[get_bits(&s->gb, 2)];
466
+
467
+    if (header == HEADER_XXCH) {
468
+        // Reserved
469
+        // Byte align
470
+        // CRC16 of channel set header
471
+        if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8)) {
472
+            av_log(s->avctx, AV_LOG_ERROR, "Read past end of XXCH channel set header\n");
473
+            return AVERROR_INVALIDDATA;
474
+        }
475
+    } else {
476
+        // Audio header CRC check word
477
+        if (s->crc_present)
478
+            skip_bits(&s->gb, 16);
479
+    }
480
+
481
+    return 0;
482
+}
483
+
484
+static inline int parse_scale(DCACoreDecoder *s, int *scale_index, int sel)
485
+{
486
+    const uint32_t *scale_table;
487
+    unsigned int scale_size;
488
+
489
+    // Select the root square table
490
+    if (sel > 5) {
491
+        scale_table = ff_dca_scale_factor_quant7;
492
+        scale_size = FF_ARRAY_ELEMS(ff_dca_scale_factor_quant7);
493
+    } else {
494
+        scale_table = ff_dca_scale_factor_quant6;
495
+        scale_size = FF_ARRAY_ELEMS(ff_dca_scale_factor_quant6);
496
+    }
497
+
498
+    // If Huffman code was used, the difference of scales was encoded
499
+    if (sel < 5)
500
+        *scale_index += get_vlc(&s->gb, &vlc_scale_factor, sel);
501
+    else
502
+        *scale_index = get_bits(&s->gb, sel + 1);
503
+
504
+    // Look up scale factor from the root square table
505
+    if ((unsigned int)*scale_index >= scale_size) {
506
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid scale factor index\n");
507
+        return AVERROR_INVALIDDATA;
508
+    }
509
+
510
+    return scale_table[*scale_index];
511
+}
512
+
513
+static inline int parse_joint_scale(DCACoreDecoder *s, int sel)
514
+{
515
+    int scale_index;
516
+
517
+    // Absolute value was encoded even when Huffman code was used
518
+    if (sel < 5)
519
+        scale_index = get_vlc(&s->gb, &vlc_scale_factor, sel);
520
+    else
521
+        scale_index = get_bits(&s->gb, sel + 1);
522
+
523
+    // Bias by 64
524
+    scale_index += 64;
525
+
526
+    // Look up joint scale factor
527
+    if ((unsigned int)scale_index >= FF_ARRAY_ELEMS(ff_dca_joint_scale_factors)) {
528
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid joint scale factor index\n");
529
+        return AVERROR_INVALIDDATA;
530
+    }
531
+
532
+    return ff_dca_joint_scale_factors[scale_index];
533
+}
534
+
535
+// 5.4.1 - Primary audio coding side information
536
+static int parse_subframe_header(DCACoreDecoder *s, int sf,
537
+                                 enum HeaderType header, int xch_base)
538
+{
539
+    int ch, band, ret;
540
+
541
+    if (get_bits_left(&s->gb) < 0)
542
+        return AVERROR_INVALIDDATA;
543
+
544
+    if (header == HEADER_CORE) {
545
+        // Subsubframe count
546
+        s->nsubsubframes[sf] = get_bits(&s->gb, 2) + 1;
547
+
548
+        // Partial subsubframe sample count
549
+        skip_bits(&s->gb, 3);
550
+    }
551
+
552
+    // Prediction mode
553
+    for (ch = xch_base; ch < s->nchannels; ch++)
554
+        for (band = 0; band < s->nsubbands[ch]; band++)
555
+            s->prediction_mode[ch][band] = get_bits1(&s->gb);
556
+
557
+    // Prediction coefficients VQ address
558
+    for (ch = xch_base; ch < s->nchannels; ch++)
559
+        for (band = 0; band < s->nsubbands[ch]; band++)
560
+            if (s->prediction_mode[ch][band])
561
+                s->prediction_vq_index[ch][band] = get_bits(&s->gb, 12);
562
+
563
+    // Bit allocation index
564
+    for (ch = xch_base; ch < s->nchannels; ch++) {
565
+        int sel = s->bit_allocation_sel[ch];
566
+
567
+        for (band = 0; band < s->subband_vq_start[ch]; band++) {
568
+            int abits;
569
+
570
+            if (sel < 5)
571
+                abits = get_vlc(&s->gb, &vlc_bit_allocation, sel);
572
+            else
573
+                abits = get_bits(&s->gb, sel - 1);
574
+
575
+            if (abits > DCA_ABITS_MAX) {
576
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid bit allocation index\n");
577
+                return AVERROR_INVALIDDATA;
578
+            }
579
+
580
+            s->bit_allocation[ch][band] = abits;
581
+        }
582
+    }
583
+
584
+    // Transition mode
585
+    for (ch = xch_base; ch < s->nchannels; ch++) {
586
+        // Clear transition mode for all subbands
587
+        memset(s->transition_mode[sf][ch], 0, sizeof(s->transition_mode[0][0]));
588
+
589
+        // Transient possible only if more than one subsubframe
590
+        if (s->nsubsubframes[sf] > 1) {
591
+            int sel = s->transition_mode_sel[ch];
592
+            for (band = 0; band < s->subband_vq_start[ch]; band++)
593
+                if (s->bit_allocation[ch][band])
594
+                    s->transition_mode[sf][ch][band] = get_vlc(&s->gb, &vlc_transition_mode, sel);
595
+        }
596
+    }
597
+
598
+    // Scale factors
599
+    for (ch = xch_base; ch < s->nchannels; ch++) {
600
+        int sel = s->scale_factor_sel[ch];
601
+        int scale_index = 0;
602
+
603
+        // Extract scales for subbands up to VQ
604
+        for (band = 0; band < s->subband_vq_start[ch]; band++) {
605
+            if (s->bit_allocation[ch][band]) {
606
+                if ((ret = parse_scale(s, &scale_index, sel)) < 0)
607
+                    return ret;
608
+                s->scale_factors[ch][band][0] = ret;
609
+                if (s->transition_mode[sf][ch][band]) {
610
+                    if ((ret = parse_scale(s, &scale_index, sel)) < 0)
611
+                        return ret;
612
+                    s->scale_factors[ch][band][1] = ret;
613
+                }
614
+            } else {
615
+                s->scale_factors[ch][band][0] = 0;
616
+            }
617
+        }
618
+
619
+        // High frequency VQ subbands
620
+        for (band = s->subband_vq_start[ch]; band < s->nsubbands[ch]; band++) {
621
+            if ((ret = parse_scale(s, &scale_index, sel)) < 0)
622
+                return ret;
623
+            s->scale_factors[ch][band][0] = ret;
624
+        }
625
+    }
626
+
627
+    // Joint subband codebook select
628
+    for (ch = xch_base; ch < s->nchannels; ch++) {
629
+        if (s->joint_intensity_index[ch]) {
630
+            s->joint_scale_sel[ch] = get_bits(&s->gb, 3);
631
+            if (s->joint_scale_sel[ch] == 7) {
632
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid joint scale factor code book\n");
633
+                return AVERROR_INVALIDDATA;
634
+            }
635
+        }
636
+    }
637
+
638
+    // Scale factors for joint subband coding
639
+    for (ch = xch_base; ch < s->nchannels; ch++) {
640
+        int src_ch = s->joint_intensity_index[ch] - 1;
641
+        if (src_ch >= 0) {
642
+            int sel = s->joint_scale_sel[ch];
643
+            for (band = s->nsubbands[ch]; band < s->nsubbands[src_ch]; band++) {
644
+                if ((ret = parse_joint_scale(s, sel)) < 0)
645
+                    return ret;
646
+                s->joint_scale_factors[ch][band] = ret;
647
+            }
648
+        }
649
+    }
650
+
651
+    // Dynamic range coefficient
652
+    if (s->drc_present && header == HEADER_CORE)
653
+        skip_bits(&s->gb, 8);
654
+
655
+    // Side information CRC check word
656
+    if (s->crc_present)
657
+        skip_bits(&s->gb, 16);
658
+
659
+    return 0;
660
+}
661
+
662
+#ifndef decode_blockcodes
663
+static inline int decode_blockcodes(int code1, int code2, int levels, int32_t *audio)
664
+{
665
+    int offset = (levels - 1) / 2;
666
+    int n, div;
667
+
668
+    for (n = 0; n < DCA_SUBBAND_SAMPLES / 2; n++) {
669
+        div = FASTDIV(code1, levels);
670
+        audio[n] = code1 - div * levels - offset;
671
+        code1 = div;
672
+    }
673
+    for (; n < DCA_SUBBAND_SAMPLES; n++) {
674
+        div = FASTDIV(code2, levels);
675
+        audio[n] = code2 - div * levels - offset;
676
+        code2 = div;
677
+    }
678
+
679
+    return code1 | code2;
680
+}
681
+#endif
682
+
683
+static inline int parse_block_codes(DCACoreDecoder *s, int32_t *audio, int abits)
684
+{
685
+    // Extract block code indices from the bit stream
686
+    int code1 = get_bits(&s->gb, block_code_nbits[abits - 1]);
687
+    int code2 = get_bits(&s->gb, block_code_nbits[abits - 1]);
688
+    int levels = ff_dca_quant_levels[abits];
689
+
690
+    // Look up samples from the block code book
691
+    if (decode_blockcodes(code1, code2, levels, audio)) {
692
+        av_log(s->avctx, AV_LOG_ERROR, "Failed to decode block code(s)\n");
693
+        return AVERROR_INVALIDDATA;
694
+    }
695
+
696
+    return 0;
697
+}
698
+
699
+static inline int parse_huffman_codes(DCACoreDecoder *s, int32_t *audio, int abits, int sel)
700
+{
701
+    int i;
702
+
703
+    // Extract Huffman codes from the bit stream
704
+    for (i = 0; i < DCA_SUBBAND_SAMPLES; i++)
705
+        audio[i] = get_vlc(&s->gb, &vlc_quant_index[abits - 1], sel);
706
+
707
+    return 1;
708
+}
709
+
710
+static inline int extract_audio(DCACoreDecoder *s, int32_t *audio, int abits, int ch)
711
+{
712
+    av_assert1(abits >= 0 && abits <= DCA_ABITS_MAX);
713
+
714
+    if (abits == 0) {
715
+        // No bits allocated
716
+        memset(audio, 0, DCA_SUBBAND_SAMPLES * sizeof(*audio));
717
+        return 0;
718
+    }
719
+
720
+    if (abits <= DCA_CODE_BOOKS) {
721
+        int sel = s->quant_index_sel[ch][abits - 1];
722
+        if (sel < quant_index_group_size[abits - 1]) {
723
+            // Huffman codes
724
+            return parse_huffman_codes(s, audio, abits, sel);
725
+        }
726
+        if (abits <= 7) {
727
+            // Block codes
728
+            return parse_block_codes(s, audio, abits);
729
+        }
730
+    }
731
+
732
+    // No further encoding
733
+    get_array(&s->gb, audio, DCA_SUBBAND_SAMPLES, abits - 3);
734
+    return 0;
735
+}
736
+
737
+static inline void dequantize(int32_t *output, const int32_t *input,
738
+                              int32_t step_size, int32_t scale, int residual)
739
+{
740
+    // Account for quantizer step size
741
+    int64_t step_scale = (int64_t)step_size * scale;
742
+    int n, shift = 0;
743
+
744
+    // Limit scale factor resolution to 22 bits
745
+    if (step_scale > (1 << 23)) {
746
+        shift = av_log2(step_scale >> 23) + 1;
747
+        step_scale >>= shift;
748
+    }
749
+
750
+    // Scale the samples
751
+    if (residual) {
752
+        for (n = 0; n < DCA_SUBBAND_SAMPLES; n++)
753
+            output[n] += clip23(norm__(input[n] * step_scale, 22 - shift));
754
+    } else {
755
+        for (n = 0; n < DCA_SUBBAND_SAMPLES; n++)
756
+            output[n]  = clip23(norm__(input[n] * step_scale, 22 - shift));
757
+    }
758
+}
759
+
760
+static inline void inverse_adpcm(int32_t **subband_samples,
761
+                                 const int16_t *vq_index,
762
+                                 const int8_t *prediction_mode,
763
+                                 int sb_start, int sb_end,
764
+                                 int ofs, int len)
765
+{
766
+    int i, j, k;
767
+
768
+    for (i = sb_start; i < sb_end; i++) {
769
+        if (prediction_mode[i]) {
770
+            const int16_t *coeff = ff_dca_adpcm_vb[vq_index[i]];
771
+            int32_t *ptr = subband_samples[i] + ofs;
772
+            for (j = 0; j < len; j++) {
773
+                int64_t err = 0;
774
+                for (k = 0; k < DCA_ADPCM_COEFFS; k++)
775
+                    err += (int64_t)ptr[j - k - 1] * coeff[k];
776
+                ptr[j] = clip23(ptr[j] + clip23(norm13(err)));
777
+            }
778
+        }
779
+    }
780
+}
781
+
782
+// 5.5 - Primary audio data arrays
783
+static int parse_subframe_audio(DCACoreDecoder *s, int sf, enum HeaderType header,
784
+                                int xch_base, int *sub_pos, int *lfe_pos)
785
+{
786
+    int32_t audio[16], scale;
787
+    int n, ssf, ofs, ch, band;
788
+
789
+    // Check number of subband samples in this subframe
790
+    int nsamples = s->nsubsubframes[sf] * DCA_SUBBAND_SAMPLES;
791
+    if (*sub_pos + nsamples > s->npcmblocks) {
792
+        av_log(s->avctx, AV_LOG_ERROR, "Subband sample buffer overflow\n");
793
+        return AVERROR_INVALIDDATA;
794
+    }
795
+
796
+    if (get_bits_left(&s->gb) < 0)
797
+        return AVERROR_INVALIDDATA;
798
+
799
+    // VQ encoded subbands
800
+    for (ch = xch_base; ch < s->nchannels; ch++) {
801
+        int32_t vq_index[DCA_SUBBANDS];
802
+
803
+        for (band = s->subband_vq_start[ch]; band < s->nsubbands[ch]; band++)
804
+            // Extract the VQ address from the bit stream
805
+            vq_index[band] = get_bits(&s->gb, 10);
806
+
807
+        if (s->subband_vq_start[ch] < s->nsubbands[ch]) {
808
+            s->dcadsp->decode_hf(s->subband_samples[ch], vq_index,
809
+                                 ff_dca_high_freq_vq, s->scale_factors[ch],
810
+                                 s->subband_vq_start[ch], s->nsubbands[ch],
811
+                                 *sub_pos, nsamples);
812
+        }
813
+    }
814
+
815
+    // Low frequency effect data
816
+    if (s->lfe_present && header == HEADER_CORE) {
817
+        unsigned int index;
818
+
819
+        // Determine number of LFE samples in this subframe
820
+        int nlfesamples = 2 * s->lfe_present * s->nsubsubframes[sf];
821
+        av_assert1((unsigned int)nlfesamples <= FF_ARRAY_ELEMS(audio));
822
+
823
+        // Extract LFE samples from the bit stream
824
+        get_array(&s->gb, audio, nlfesamples, 8);
825
+
826
+        // Extract scale factor index from the bit stream
827
+        index = get_bits(&s->gb, 8);
828
+        if (index >= FF_ARRAY_ELEMS(ff_dca_scale_factor_quant7)) {
829
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE scale factor index\n");
830
+            return AVERROR_INVALIDDATA;
831
+        }
832
+
833
+        // Look up the 7-bit root square quantization table
834
+        scale = ff_dca_scale_factor_quant7[index];
835
+
836
+        // Account for quantizer step size which is 0.035
837
+        scale = mul23(4697620 /* 0.035 * (1 << 27) */, scale);
838
+
839
+        // Scale and take the LFE samples
840
+        for (n = 0, ofs = *lfe_pos; n < nlfesamples; n++, ofs++)
841
+            s->lfe_samples[ofs] = clip23(audio[n] * scale >> 4);
842
+
843
+        // Advance LFE sample pointer for the next subframe
844
+        *lfe_pos = ofs;
845
+    }
846
+
847
+    // Audio data
848
+    for (ssf = 0, ofs = *sub_pos; ssf < s->nsubsubframes[sf]; ssf++) {
849
+        for (ch = xch_base; ch < s->nchannels; ch++) {
850
+            if (get_bits_left(&s->gb) < 0)
851
+                return AVERROR_INVALIDDATA;
852
+
853
+            // Not high frequency VQ subbands
854
+            for (band = 0; band < s->subband_vq_start[ch]; band++) {
855
+                int ret, trans_ssf, abits = s->bit_allocation[ch][band];
856
+                int32_t step_size;
857
+
858
+                // Extract bits from the bit stream
859
+                if ((ret = extract_audio(s, audio, abits, ch)) < 0)
860
+                    return ret;
861
+
862
+                // Select quantization step size table and look up
863
+                // quantization step size
864
+                if (s->bit_rate == 3)
865
+                    step_size = ff_dca_lossless_quant[abits];
866
+                else
867
+                    step_size = ff_dca_lossy_quant[abits];
868
+
869
+                // Identify transient location
870
+                trans_ssf = s->transition_mode[sf][ch][band];
871
+
872
+                // Determine proper scale factor
873
+                if (trans_ssf == 0 || ssf < trans_ssf)
874
+                    scale = s->scale_factors[ch][band][0];
875
+                else
876
+                    scale = s->scale_factors[ch][band][1];
877
+
878
+                // Adjust scale factor when SEL indicates Huffman code
879
+                if (ret > 0) {
880
+                    int64_t adj = s->scale_factor_adj[ch][abits - 1];
881
+                    scale = clip23(adj * scale >> 22);
882
+                }
883
+
884
+                dequantize(s->subband_samples[ch][band] + ofs,
885
+                           audio, step_size, scale, 0);
886
+            }
887
+        }
888
+
889
+        // DSYNC
890
+        if ((ssf == s->nsubsubframes[sf] - 1 || s->sync_ssf) && get_bits(&s->gb, 16) != 0xffff) {
891
+            av_log(s->avctx, AV_LOG_ERROR, "DSYNC check failed\n");
892
+            return AVERROR_INVALIDDATA;
893
+        }
894
+
895
+        ofs += DCA_SUBBAND_SAMPLES;
896
+    }
897
+
898
+    // Inverse ADPCM
899
+    for (ch = xch_base; ch < s->nchannels; ch++) {
900
+        inverse_adpcm(s->subband_samples[ch], s->prediction_vq_index[ch],
901
+                      s->prediction_mode[ch], 0, s->nsubbands[ch],
902
+                      *sub_pos, nsamples);
903
+    }
904
+
905
+    // Joint subband coding
906
+    for (ch = xch_base; ch < s->nchannels; ch++) {
907
+        int src_ch = s->joint_intensity_index[ch] - 1;
908
+        if (src_ch >= 0) {
909
+            s->dcadsp->decode_joint(s->subband_samples[ch], s->subband_samples[src_ch],
910
+                                    s->joint_scale_factors[ch], s->nsubbands[ch],
911
+                                    s->nsubbands[src_ch], *sub_pos, nsamples);
912
+        }
913
+    }
914
+
915
+    // Advance subband sample pointer for the next subframe
916
+    *sub_pos = ofs;
917
+    return 0;
918
+}
919
+
920
+static void erase_adpcm_history(DCACoreDecoder *s)
921
+{
922
+    int ch, band;
923
+
924
+    // Erase ADPCM history from previous frame if
925
+    // predictor history switch was disabled
926
+    for (ch = 0; ch < DCA_CHANNELS; ch++)
927
+        for (band = 0; band < DCA_SUBBANDS; band++)
928
+            AV_ZERO128(s->subband_samples[ch][band] - DCA_ADPCM_COEFFS);
929
+}
930
+
931
+static int alloc_sample_buffer(DCACoreDecoder *s)
932
+{
933
+    int nchsamples = DCA_ADPCM_COEFFS + s->npcmblocks;
934
+    int nframesamples = nchsamples * DCA_CHANNELS * DCA_SUBBANDS;
935
+    int nlfesamples = DCA_LFE_HISTORY + s->npcmblocks / 2;
936
+    unsigned int size = s->subband_size;
937
+    int ch, band;
938
+
939
+    // Reallocate subband sample buffer
940
+    av_fast_mallocz(&s->subband_buffer, &s->subband_size,
941
+                    (nframesamples + nlfesamples) * sizeof(int32_t));
942
+    if (!s->subband_buffer)
943
+        return AVERROR(ENOMEM);
944
+
945
+    if (size != s->subband_size) {
946
+        for (ch = 0; ch < DCA_CHANNELS; ch++)
947
+            for (band = 0; band < DCA_SUBBANDS; band++)
948
+                s->subband_samples[ch][band] = s->subband_buffer +
949
+                    (ch * DCA_SUBBANDS + band) * nchsamples + DCA_ADPCM_COEFFS;
950
+        s->lfe_samples = s->subband_buffer + nframesamples;
951
+    }
952
+
953
+    if (!s->predictor_history)
954
+        erase_adpcm_history(s);
955
+
956
+    return 0;
957
+}
958
+
959
+static int parse_frame_data(DCACoreDecoder *s, enum HeaderType header, int xch_base)
960
+{
961
+    int sf, ch, ret, band, sub_pos, lfe_pos;
962
+
963
+    if ((ret = parse_coding_header(s, header, xch_base)) < 0)
964
+        return ret;
965
+
966
+    for (sf = 0, sub_pos = 0, lfe_pos = DCA_LFE_HISTORY; sf < s->nsubframes; sf++) {
967
+        if ((ret = parse_subframe_header(s, sf, header, xch_base)) < 0)
968
+            return ret;
969
+        if ((ret = parse_subframe_audio(s, sf, header, xch_base, &sub_pos, &lfe_pos)) < 0)
970
+            return ret;
971
+    }
972
+
973
+    for (ch = xch_base; ch < s->nchannels; ch++) {
974
+        // Determine number of active subbands for this channel
975
+        int nsubbands = s->nsubbands[ch];
976
+        if (s->joint_intensity_index[ch])
977
+            nsubbands = FFMAX(nsubbands, s->nsubbands[s->joint_intensity_index[ch] - 1]);
978
+
979
+        // Update history for ADPCM
980
+        for (band = 0; band < nsubbands; band++) {
981
+            int32_t *samples = s->subband_samples[ch][band] - DCA_ADPCM_COEFFS;
982
+            AV_COPY128(samples, samples + s->npcmblocks);
983
+        }
984
+
985
+        // Clear inactive subbands
986
+        for (; band < DCA_SUBBANDS; band++) {
987
+            int32_t *samples = s->subband_samples[ch][band] - DCA_ADPCM_COEFFS;
988
+            memset(samples, 0, (DCA_ADPCM_COEFFS + s->npcmblocks) * sizeof(int32_t));
989
+        }
990
+    }
991
+
992
+    return 0;
993
+}
994
+
995
+static int parse_xch_frame(DCACoreDecoder *s)
996
+{
997
+    int ret;
998
+
999
+    if (s->ch_mask & DCA_SPEAKER_MASK_Cs) {
1000
+        av_log(s->avctx, AV_LOG_ERROR, "XCH with Cs speaker already present\n");
1001
+        return AVERROR_INVALIDDATA;
1002
+    }
1003
+
1004
+    if ((ret = parse_frame_data(s, HEADER_XCH, s->nchannels)) < 0)
1005
+        return ret;
1006
+
1007
+    // Seek to the end of core frame, don't trust XCH frame size
1008
+    if (ff_dca_seek_bits(&s->gb, s->frame_size * 8)) {
1009
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XCH frame\n");
1010
+        return AVERROR_INVALIDDATA;
1011
+    }
1012
+
1013
+    return 0;
1014
+}
1015
+
1016
+static int parse_xxch_frame(DCACoreDecoder *s)
1017
+{
1018
+    int xxch_nchsets, xxch_frame_size;
1019
+    int ret, mask, header_size, header_pos = get_bits_count(&s->gb);
1020
+
1021
+    // XXCH sync word
1022
+    if (get_bits_long(&s->gb, 32) != DCA_SYNCWORD_XXCH) {
1023
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid XXCH sync word\n");
1024
+        return AVERROR_INVALIDDATA;
1025
+    }
1026
+
1027
+    // XXCH frame header length
1028
+    header_size = get_bits(&s->gb, 6) + 1;
1029
+
1030
+    // Check XXCH frame header CRC
1031
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
1032
+        && ff_dca_check_crc(&s->gb, header_pos + 32, header_pos + header_size * 8)) {
1033
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid XXCH frame header checksum\n");
1034
+        return AVERROR_INVALIDDATA;
1035
+    }
1036
+
1037
+    // CRC presence flag for channel set header
1038
+    s->xxch_crc_present = get_bits1(&s->gb);
1039
+
1040
+    // Number of bits for loudspeaker mask
1041
+    s->xxch_mask_nbits = get_bits(&s->gb, 5) + 1;
1042
+    if (s->xxch_mask_nbits <= DCA_SPEAKER_Cs) {
1043
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid number of bits for XXCH speaker mask (%d)\n", s->xxch_mask_nbits);
1044
+        return AVERROR_INVALIDDATA;
1045
+    }
1046
+
1047
+    // Number of channel sets
1048
+    xxch_nchsets = get_bits(&s->gb, 2) + 1;
1049
+    if (xxch_nchsets > 1) {
1050
+        avpriv_request_sample(s->avctx, "%d XXCH channel sets", xxch_nchsets);
1051
+        return AVERROR_PATCHWELCOME;
1052
+    }
1053
+
1054
+    // Channel set 0 data byte size
1055
+    xxch_frame_size = get_bits(&s->gb, 14) + 1;
1056
+
1057
+    // Core loudspeaker activity mask
1058
+    s->xxch_core_mask = get_bits_long(&s->gb, s->xxch_mask_nbits);
1059
+
1060
+    // Validate the core mask
1061
+    mask = s->ch_mask;
1062
+
1063
+    if ((mask & DCA_SPEAKER_MASK_Ls) && (s->xxch_core_mask & DCA_SPEAKER_MASK_Lss))
1064
+        mask = (mask & ~DCA_SPEAKER_MASK_Ls) | DCA_SPEAKER_MASK_Lss;
1065
+
1066
+    if ((mask & DCA_SPEAKER_MASK_Rs) && (s->xxch_core_mask & DCA_SPEAKER_MASK_Rss))
1067
+        mask = (mask & ~DCA_SPEAKER_MASK_Rs) | DCA_SPEAKER_MASK_Rss;
1068
+
1069
+    if (mask != s->xxch_core_mask) {
1070
+        av_log(s->avctx, AV_LOG_ERROR, "XXCH core speaker activity mask (%#x) disagrees with core (%#x)\n", s->xxch_core_mask, mask);
1071
+        return AVERROR_INVALIDDATA;
1072
+    }
1073
+
1074
+    // Reserved
1075
+    // Byte align
1076
+    // CRC16 of XXCH frame header
1077
+    if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8)) {
1078
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XXCH frame header\n");
1079
+        return AVERROR_INVALIDDATA;
1080
+    }
1081
+
1082
+    // Parse XXCH channel set 0
1083
+    if ((ret = parse_frame_data(s, HEADER_XXCH, s->nchannels)) < 0)
1084
+        return ret;
1085
+
1086
+    if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8 + xxch_frame_size * 8)) {
1087
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XXCH channel set\n");
1088
+        return AVERROR_INVALIDDATA;
1089
+    }
1090
+
1091
+    return 0;
1092
+}
1093
+
1094
+static int parse_xbr_subframe(DCACoreDecoder *s, int xbr_base_ch, int xbr_nchannels,
1095
+                              int *xbr_nsubbands, int xbr_transition_mode, int sf, int *sub_pos)
1096
+{
1097
+    int     xbr_nabits[DCA_CHANNELS];
1098
+    int     xbr_bit_allocation[DCA_CHANNELS][DCA_SUBBANDS];
1099
+    int     xbr_scale_nbits[DCA_CHANNELS];
1100
+    int32_t xbr_scale_factors[DCA_CHANNELS][DCA_SUBBANDS][2];
1101
+    int     ssf, ch, band, ofs;
1102
+
1103
+    // Check number of subband samples in this subframe
1104
+    if (*sub_pos + s->nsubsubframes[sf] * DCA_SUBBAND_SAMPLES > s->npcmblocks) {
1105
+        av_log(s->avctx, AV_LOG_ERROR, "Subband sample buffer overflow\n");
1106
+        return AVERROR_INVALIDDATA;
1107
+    }
1108
+
1109
+    if (get_bits_left(&s->gb) < 0)
1110
+        return AVERROR_INVALIDDATA;
1111
+
1112
+    // Number of bits for XBR bit allocation index
1113
+    for (ch = xbr_base_ch; ch < xbr_nchannels; ch++)
1114
+        xbr_nabits[ch] = get_bits(&s->gb, 2) + 2;
1115
+
1116
+    // XBR bit allocation index
1117
+    for (ch = xbr_base_ch; ch < xbr_nchannels; ch++) {
1118
+        for (band = 0; band < xbr_nsubbands[ch]; band++) {
1119
+            xbr_bit_allocation[ch][band] = get_bits(&s->gb, xbr_nabits[ch]);
1120
+            if (xbr_bit_allocation[ch][band] > DCA_ABITS_MAX) {
1121
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid XBR bit allocation index\n");
1122
+                return AVERROR_INVALIDDATA;
1123
+            }
1124
+        }
1125
+    }
1126
+
1127
+    // Number of bits for scale indices
1128
+    for (ch = xbr_base_ch; ch < xbr_nchannels; ch++) {
1129
+        xbr_scale_nbits[ch] = get_bits(&s->gb, 3);
1130
+        if (!xbr_scale_nbits[ch]) {
1131
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid number of bits for XBR scale factor index\n");
1132
+            return AVERROR_INVALIDDATA;
1133
+        }
1134
+    }
1135
+
1136
+    // XBR scale factors
1137
+    for (ch = xbr_base_ch; ch < xbr_nchannels; ch++) {
1138
+        const uint32_t *scale_table;
1139
+        int scale_size;
1140
+
1141
+        // Select the root square table
1142
+        if (s->scale_factor_sel[ch] > 5) {
1143
+            scale_table = ff_dca_scale_factor_quant7;
1144
+            scale_size = FF_ARRAY_ELEMS(ff_dca_scale_factor_quant7);
1145
+        } else {
1146
+            scale_table = ff_dca_scale_factor_quant6;
1147
+            scale_size = FF_ARRAY_ELEMS(ff_dca_scale_factor_quant6);
1148
+        }
1149
+
1150
+        // Parse scale factor indices and look up scale factors from the root
1151
+        // square table
1152
+        for (band = 0; band < xbr_nsubbands[ch]; band++) {
1153
+            if (xbr_bit_allocation[ch][band]) {
1154
+                int scale_index = get_bits(&s->gb, xbr_scale_nbits[ch]);
1155
+                if (scale_index >= scale_size) {
1156
+                    av_log(s->avctx, AV_LOG_ERROR, "Invalid XBR scale factor index\n");
1157
+                    return AVERROR_INVALIDDATA;
1158
+                }
1159
+                xbr_scale_factors[ch][band][0] = scale_table[scale_index];
1160
+                if (xbr_transition_mode && s->transition_mode[sf][ch][band]) {
1161
+                    scale_index = get_bits(&s->gb, xbr_scale_nbits[ch]);
1162
+                    if (scale_index >= scale_size) {
1163
+                        av_log(s->avctx, AV_LOG_ERROR, "Invalid XBR scale factor index\n");
1164
+                        return AVERROR_INVALIDDATA;
1165
+                    }
1166
+                    xbr_scale_factors[ch][band][1] = scale_table[scale_index];
1167
+                }
1168
+            }
1169
+        }
1170
+    }
1171
+
1172
+    // Audio data
1173
+    for (ssf = 0, ofs = *sub_pos; ssf < s->nsubsubframes[sf]; ssf++) {
1174
+        for (ch = xbr_base_ch; ch < xbr_nchannels; ch++) {
1175
+            if (get_bits_left(&s->gb) < 0)
1176
+                return AVERROR_INVALIDDATA;
1177
+
1178
+            for (band = 0; band < xbr_nsubbands[ch]; band++) {
1179
+                int ret, trans_ssf, abits = xbr_bit_allocation[ch][band];
1180
+                int32_t audio[DCA_SUBBAND_SAMPLES], step_size, scale;
1181
+
1182
+                // Extract bits from the bit stream
1183
+                if (abits > 7) {
1184
+                    // No further encoding
1185
+                    get_array(&s->gb, audio, DCA_SUBBAND_SAMPLES, abits - 3);
1186
+                } else if (abits > 0) {
1187
+                    // Block codes
1188
+                    if ((ret = parse_block_codes(s, audio, abits)) < 0)
1189
+                        return ret;
1190
+                } else {
1191
+                    // No bits allocated
1192
+                    continue;
1193
+                }
1194
+
1195
+                // Look up quantization step size
1196
+                step_size = ff_dca_lossless_quant[abits];
1197
+
1198
+                // Identify transient location
1199
+                if (xbr_transition_mode)
1200
+                    trans_ssf = s->transition_mode[sf][ch][band];
1201
+                else
1202
+                    trans_ssf = 0;
1203
+
1204
+                // Determine proper scale factor
1205
+                if (trans_ssf == 0 || ssf < trans_ssf)
1206
+                    scale = xbr_scale_factors[ch][band][0];
1207
+                else
1208
+                    scale = xbr_scale_factors[ch][band][1];
1209
+
1210
+                dequantize(s->subband_samples[ch][band] + ofs,
1211
+                           audio, step_size, scale, 1);
1212
+            }
1213
+        }
1214
+
1215
+        // DSYNC
1216
+        if ((ssf == s->nsubsubframes[sf] - 1 || s->sync_ssf) && get_bits(&s->gb, 16) != 0xffff) {
1217
+            av_log(s->avctx, AV_LOG_ERROR, "XBR-DSYNC check failed\n");
1218
+            return AVERROR_INVALIDDATA;
1219
+        }
1220
+
1221
+        ofs += DCA_SUBBAND_SAMPLES;
1222
+    }
1223
+
1224
+    // Advance subband sample pointer for the next subframe
1225
+    *sub_pos = ofs;
1226
+    return 0;
1227
+}
1228
+
1229
+static int parse_xbr_frame(DCACoreDecoder *s)
1230
+{
1231
+    int     xbr_frame_size[DCA_EXSS_CHSETS_MAX];
1232
+    int     xbr_nchannels[DCA_EXSS_CHSETS_MAX];
1233
+    int     xbr_nsubbands[DCA_EXSS_CHSETS_MAX * DCA_EXSS_CHANNELS_MAX];
1234
+    int     xbr_nchsets, xbr_transition_mode, xbr_band_nbits, xbr_base_ch;
1235
+    int     i, ch1, ch2, ret, header_size, header_pos = get_bits_count(&s->gb);
1236
+
1237
+    // XBR sync word
1238
+    if (get_bits_long(&s->gb, 32) != DCA_SYNCWORD_XBR) {
1239
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid XBR sync word\n");
1240
+        return AVERROR_INVALIDDATA;
1241
+    }
1242
+
1243
+    // XBR frame header length
1244
+    header_size = get_bits(&s->gb, 6) + 1;
1245
+
1246
+    // Check XBR frame header CRC
1247
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
1248
+        && ff_dca_check_crc(&s->gb, header_pos + 32, header_pos + header_size * 8)) {
1249
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid XBR frame header checksum\n");
1250
+        return AVERROR_INVALIDDATA;
1251
+    }
1252
+
1253
+    // Number of channel sets
1254
+    xbr_nchsets = get_bits(&s->gb, 2) + 1;
1255
+
1256
+    // Channel set data byte size
1257
+    for (i = 0; i < xbr_nchsets; i++)
1258
+        xbr_frame_size[i] = get_bits(&s->gb, 14) + 1;
1259
+
1260
+    // Transition mode flag
1261
+    xbr_transition_mode = get_bits1(&s->gb);
1262
+
1263
+    // Channel set headers
1264
+    for (i = 0, ch2 = 0; i < xbr_nchsets; i++) {
1265
+        xbr_nchannels[i] = get_bits(&s->gb, 3) + 1;
1266
+        xbr_band_nbits = get_bits(&s->gb, 2) + 5;
1267
+        for (ch1 = 0; ch1 < xbr_nchannels[i]; ch1++, ch2++) {
1268
+            xbr_nsubbands[ch2] = get_bits(&s->gb, xbr_band_nbits) + 1;
1269
+            if (xbr_nsubbands[ch2] > DCA_SUBBANDS) {
1270
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid number of active XBR subbands (%d)\n", xbr_nsubbands[ch2]);
1271
+                return AVERROR_INVALIDDATA;
1272
+            }
1273
+        }
1274
+    }
1275
+
1276
+    // Reserved
1277
+    // Byte align
1278
+    // CRC16 of XBR frame header
1279
+    if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8)) {
1280
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XBR frame header\n");
1281
+        return AVERROR_INVALIDDATA;
1282
+    }
1283
+
1284
+    // Channel set data
1285
+    for (i = 0, xbr_base_ch = 0; i < xbr_nchsets; i++) {
1286
+        header_pos = get_bits_count(&s->gb);
1287
+
1288
+        if (xbr_base_ch + xbr_nchannels[i] <= s->nchannels) {
1289
+            int sf, sub_pos;
1290
+
1291
+            for (sf = 0, sub_pos = 0; sf < s->nsubframes; sf++) {
1292
+                if ((ret = parse_xbr_subframe(s, xbr_base_ch,
1293
+                                              xbr_base_ch + xbr_nchannels[i],
1294
+                                              xbr_nsubbands, xbr_transition_mode,
1295
+                                              sf, &sub_pos)) < 0)
1296
+                    return ret;
1297
+            }
1298
+        }
1299
+
1300
+        xbr_base_ch += xbr_nchannels[i];
1301
+
1302
+        if (ff_dca_seek_bits(&s->gb, header_pos + xbr_frame_size[i] * 8)) {
1303
+            av_log(s->avctx, AV_LOG_ERROR, "Read past end of XBR channel set\n");
1304
+            return AVERROR_INVALIDDATA;
1305
+        }
1306
+    }
1307
+
1308
+    return 0;
1309
+}
1310
+
1311
+// Modified ISO/IEC 9899 linear congruential generator
1312
+// Returns pseudorandom integer in range [-2^30, 2^30 - 1]
1313
+static int rand_x96(DCACoreDecoder *s)
1314
+{
1315
+    s->x96_rand = 1103515245U * s->x96_rand + 12345U;
1316
+    return (s->x96_rand & 0x7fffffff) - 0x40000000;
1317
+}
1318
+
1319
+static int parse_x96_subframe_audio(DCACoreDecoder *s, int sf, int xch_base, int *sub_pos)
1320
+{
1321
+    int n, ssf, ch, band, ofs;
1322
+
1323
+    // Check number of subband samples in this subframe
1324
+    int nsamples = s->nsubsubframes[sf] * DCA_SUBBAND_SAMPLES;
1325
+    if (*sub_pos + nsamples > s->npcmblocks) {
1326
+        av_log(s->avctx, AV_LOG_ERROR, "Subband sample buffer overflow\n");
1327
+        return AVERROR_INVALIDDATA;
1328
+    }
1329
+
1330
+    if (get_bits_left(&s->gb) < 0)
1331
+        return AVERROR_INVALIDDATA;
1332
+
1333
+    // VQ encoded or unallocated subbands
1334
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1335
+        for (band = s->x96_subband_start; band < s->nsubbands[ch]; band++) {
1336
+            // Get the sample pointer and scale factor
1337
+            int32_t *samples = s->x96_subband_samples[ch][band] + *sub_pos;
1338
+            int32_t scale    = s->scale_factors[ch][band >> 1][band & 1];
1339
+
1340
+            switch (s->bit_allocation[ch][band]) {
1341
+            case 0: // No bits allocated for subband
1342
+                if (scale <= 1)
1343
+                    memset(samples, 0, nsamples * sizeof(int32_t));
1344
+                else for (n = 0; n < nsamples; n++)
1345
+                    // Generate scaled random samples
1346
+                    samples[n] = mul31(rand_x96(s), scale);
1347
+                break;
1348
+
1349
+            case 1: // VQ encoded subband
1350
+                for (ssf = 0; ssf < (s->nsubsubframes[sf] + 1) / 2; ssf++) {
1351
+                    // Extract the VQ address from the bit stream and look up
1352
+                    // the VQ code book for up to 16 subband samples
1353
+                    const int8_t *vq_samples = ff_dca_high_freq_vq[get_bits(&s->gb, 10)];
1354
+                    // Scale and take the samples
1355
+                    for (n = 0; n < FFMIN(nsamples - ssf * 16, 16); n++)
1356
+                        *samples++ = clip23(vq_samples[n] * scale + (1 << 3) >> 4);
1357
+                }
1358
+                break;
1359
+            }
1360
+        }
1361
+    }
1362
+
1363
+    // Audio data
1364
+    for (ssf = 0, ofs = *sub_pos; ssf < s->nsubsubframes[sf]; ssf++) {
1365
+        for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1366
+            if (get_bits_left(&s->gb) < 0)
1367
+                return AVERROR_INVALIDDATA;
1368
+
1369
+            for (band = s->x96_subband_start; band < s->nsubbands[ch]; band++) {
1370
+                int ret, abits = s->bit_allocation[ch][band] - 1;
1371
+                int32_t audio[DCA_SUBBAND_SAMPLES], step_size, scale;
1372
+
1373
+                // Not VQ encoded or unallocated subbands
1374
+                if (abits < 1)
1375
+                    continue;
1376
+
1377
+                // Extract bits from the bit stream
1378
+                if ((ret = extract_audio(s, audio, abits, ch)) < 0)
1379
+                    return ret;
1380
+
1381
+                // Select quantization step size table and look up quantization
1382
+                // step size
1383
+                if (s->bit_rate == 3)
1384
+                    step_size = ff_dca_lossless_quant[abits];
1385
+                else
1386
+                    step_size = ff_dca_lossy_quant[abits];
1387
+
1388
+                // Get the scale factor
1389
+                scale = s->scale_factors[ch][band >> 1][band & 1];
1390
+
1391
+                dequantize(s->x96_subband_samples[ch][band] + ofs,
1392
+                           audio, step_size, scale, 0);
1393
+            }
1394
+        }
1395
+
1396
+        // DSYNC
1397
+        if ((ssf == s->nsubsubframes[sf] - 1 || s->sync_ssf) && get_bits(&s->gb, 16) != 0xffff) {
1398
+            av_log(s->avctx, AV_LOG_ERROR, "X96-DSYNC check failed\n");
1399
+            return AVERROR_INVALIDDATA;
1400
+        }
1401
+
1402
+        ofs += DCA_SUBBAND_SAMPLES;
1403
+    }
1404
+
1405
+    // Inverse ADPCM
1406
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1407
+        inverse_adpcm(s->x96_subband_samples[ch], s->prediction_vq_index[ch],
1408
+                      s->prediction_mode[ch], s->x96_subband_start, s->nsubbands[ch],
1409
+                      *sub_pos, nsamples);
1410
+    }
1411
+
1412
+    // Joint subband coding
1413
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1414
+        int src_ch = s->joint_intensity_index[ch] - 1;
1415
+        if (src_ch >= 0) {
1416
+            s->dcadsp->decode_joint(s->x96_subband_samples[ch], s->x96_subband_samples[src_ch],
1417
+                                    s->joint_scale_factors[ch], s->nsubbands[ch],
1418
+                                    s->nsubbands[src_ch], *sub_pos, nsamples);
1419
+        }
1420
+    }
1421
+
1422
+    // Advance subband sample pointer for the next subframe
1423
+    *sub_pos = ofs;
1424
+    return 0;
1425
+}
1426
+
1427
+static void erase_x96_adpcm_history(DCACoreDecoder *s)
1428
+{
1429
+    int ch, band;
1430
+
1431
+    // Erase ADPCM history from previous frame if
1432
+    // predictor history switch was disabled
1433
+    for (ch = 0; ch < DCA_CHANNELS; ch++)
1434
+        for (band = 0; band < DCA_SUBBANDS_X96; band++)
1435
+            AV_ZERO128(s->x96_subband_samples[ch][band] - DCA_ADPCM_COEFFS);
1436
+}
1437
+
1438
+static int alloc_x96_sample_buffer(DCACoreDecoder *s)
1439
+{
1440
+    int nchsamples = DCA_ADPCM_COEFFS + s->npcmblocks;
1441
+    int nframesamples = nchsamples * DCA_CHANNELS * DCA_SUBBANDS_X96;
1442
+    unsigned int size = s->x96_subband_size;
1443
+    int ch, band;
1444
+
1445
+    // Reallocate subband sample buffer
1446
+    av_fast_mallocz(&s->x96_subband_buffer, &s->x96_subband_size,
1447
+                    nframesamples * sizeof(int32_t));
1448
+    if (!s->x96_subband_buffer)
1449
+        return AVERROR(ENOMEM);
1450
+
1451
+    if (size != s->x96_subband_size) {
1452
+        for (ch = 0; ch < DCA_CHANNELS; ch++)
1453
+            for (band = 0; band < DCA_SUBBANDS_X96; band++)
1454
+                s->x96_subband_samples[ch][band] = s->x96_subband_buffer +
1455
+                    (ch * DCA_SUBBANDS_X96 + band) * nchsamples + DCA_ADPCM_COEFFS;
1456
+    }
1457
+
1458
+    if (!s->predictor_history)
1459
+        erase_x96_adpcm_history(s);
1460
+
1461
+    return 0;
1462
+}
1463
+
1464
+static int parse_x96_subframe_header(DCACoreDecoder *s, int xch_base)
1465
+{
1466
+    int ch, band, ret;
1467
+
1468
+    if (get_bits_left(&s->gb) < 0)
1469
+        return AVERROR_INVALIDDATA;
1470
+
1471
+    // Prediction mode
1472
+    for (ch = xch_base; ch < s->x96_nchannels; ch++)
1473
+        for (band = s->x96_subband_start; band < s->nsubbands[ch]; band++)
1474
+            s->prediction_mode[ch][band] = get_bits1(&s->gb);
1475
+
1476
+    // Prediction coefficients VQ address
1477
+    for (ch = xch_base; ch < s->x96_nchannels; ch++)
1478
+        for (band = s->x96_subband_start; band < s->nsubbands[ch]; band++)
1479
+            if (s->prediction_mode[ch][band])
1480
+                s->prediction_vq_index[ch][band] = get_bits(&s->gb, 12);
1481
+
1482
+    // Bit allocation index
1483
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1484
+        int sel = s->bit_allocation_sel[ch];
1485
+        int abits = 0;
1486
+
1487
+        for (band = s->x96_subband_start; band < s->nsubbands[ch]; band++) {
1488
+            // If Huffman code was used, the difference of abits was encoded
1489
+            if (sel < 7)
1490
+                abits += get_vlc(&s->gb, &vlc_quant_index[5 + 2 * s->x96_high_res], sel);
1491
+            else
1492
+                abits = get_bits(&s->gb, 3 + s->x96_high_res);
1493
+
1494
+            if (abits < 0 || abits > 7 + 8 * s->x96_high_res) {
1495
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 bit allocation index\n");
1496
+                return AVERROR_INVALIDDATA;
1497
+            }
1498
+
1499
+            s->bit_allocation[ch][band] = abits;
1500
+        }
1501
+    }
1502
+
1503
+    // Scale factors
1504
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1505
+        int sel = s->scale_factor_sel[ch];
1506
+        int scale_index = 0;
1507
+
1508
+        // Extract scales for subbands which are transmitted even for
1509
+        // unallocated subbands
1510
+        for (band = s->x96_subband_start; band < s->nsubbands[ch]; band++) {
1511
+            if ((ret = parse_scale(s, &scale_index, sel)) < 0)
1512
+                return ret;
1513
+            s->scale_factors[ch][band >> 1][band & 1] = ret;
1514
+        }
1515
+    }
1516
+
1517
+    // Joint subband codebook select
1518
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1519
+        if (s->joint_intensity_index[ch]) {
1520
+            s->joint_scale_sel[ch] = get_bits(&s->gb, 3);
1521
+            if (s->joint_scale_sel[ch] == 7) {
1522
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 joint scale factor code book\n");
1523
+                return AVERROR_INVALIDDATA;
1524
+            }
1525
+        }
1526
+    }
1527
+
1528
+    // Scale factors for joint subband coding
1529
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1530
+        int src_ch = s->joint_intensity_index[ch] - 1;
1531
+        if (src_ch >= 0) {
1532
+            int sel = s->joint_scale_sel[ch];
1533
+            for (band = s->nsubbands[ch]; band < s->nsubbands[src_ch]; band++) {
1534
+                if ((ret = parse_joint_scale(s, sel)) < 0)
1535
+                    return ret;
1536
+                s->joint_scale_factors[ch][band] = ret;
1537
+            }
1538
+        }
1539
+    }
1540
+
1541
+    // Side information CRC check word
1542
+    if (s->crc_present)
1543
+        skip_bits(&s->gb, 16);
1544
+
1545
+    return 0;
1546
+}
1547
+
1548
+static int parse_x96_coding_header(DCACoreDecoder *s, int exss, int xch_base)
1549
+{
1550
+    int n, ch, header_size = 0, header_pos = get_bits_count(&s->gb);
1551
+
1552
+    if (get_bits_left(&s->gb) < 0)
1553
+        return AVERROR_INVALIDDATA;
1554
+
1555
+    if (exss) {
1556
+        // Channel set header length
1557
+        header_size = get_bits(&s->gb, 7) + 1;
1558
+
1559
+        // Check CRC
1560
+        if (s->x96_crc_present
1561
+            && (s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
1562
+            && ff_dca_check_crc(&s->gb, header_pos, header_pos + header_size * 8)) {
1563
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 channel set header checksum\n");
1564
+            return AVERROR_INVALIDDATA;
1565
+        }
1566
+    }
1567
+
1568
+    // High resolution flag
1569
+    s->x96_high_res = get_bits1(&s->gb);
1570
+
1571
+    // First encoded subband
1572
+    if (s->x96_rev_no < 8) {
1573
+        s->x96_subband_start = get_bits(&s->gb, 5);
1574
+        if (s->x96_subband_start > 27) {
1575
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 subband start index (%d)\n", s->x96_subband_start);
1576
+            return AVERROR_INVALIDDATA;
1577
+        }
1578
+    } else {
1579
+        s->x96_subband_start = DCA_SUBBANDS;
1580
+    }
1581
+
1582
+    // Subband activity count
1583
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1584
+        s->nsubbands[ch] = get_bits(&s->gb, 6) + 1;
1585
+        if (s->nsubbands[ch] < DCA_SUBBANDS) {
1586
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 subband activity count (%d)\n", s->nsubbands[ch]);
1587
+            return AVERROR_INVALIDDATA;
1588
+        }
1589
+    }
1590
+
1591
+    // Joint intensity coding index
1592
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1593
+        if ((n = get_bits(&s->gb, 3)) && xch_base)
1594
+            n += xch_base - 1;
1595
+        if (n > s->x96_nchannels) {
1596
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 joint intensity coding index\n");
1597
+            return AVERROR_INVALIDDATA;
1598
+        }
1599
+        s->joint_intensity_index[ch] = n;
1600
+    }
1601
+
1602
+    // Scale factor code book
1603
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1604
+        s->scale_factor_sel[ch] = get_bits(&s->gb, 3);
1605
+        if (s->scale_factor_sel[ch] >= 6) {
1606
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 scale factor code book\n");
1607
+            return AVERROR_INVALIDDATA;
1608
+        }
1609
+    }
1610
+
1611
+    // Bit allocation quantizer select
1612
+    for (ch = xch_base; ch < s->x96_nchannels; ch++)
1613
+        s->bit_allocation_sel[ch] = get_bits(&s->gb, 3);
1614
+
1615
+    // Quantization index codebook select
1616
+    for (n = 0; n < 6 + 4 * s->x96_high_res; n++)
1617
+        for (ch = xch_base; ch < s->x96_nchannels; ch++)
1618
+            s->quant_index_sel[ch][n] = get_bits(&s->gb, quant_index_sel_nbits[n]);
1619
+
1620
+    if (exss) {
1621
+        // Reserved
1622
+        // Byte align
1623
+        // CRC16 of channel set header
1624
+        if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8)) {
1625
+            av_log(s->avctx, AV_LOG_ERROR, "Read past end of X96 channel set header\n");
1626
+            return AVERROR_INVALIDDATA;
1627
+        }
1628
+    } else {
1629
+        if (s->crc_present)
1630
+            skip_bits(&s->gb, 16);
1631
+    }
1632
+
1633
+    return 0;
1634
+}
1635
+
1636
+static int parse_x96_frame_data(DCACoreDecoder *s, int exss, int xch_base)
1637
+{
1638
+    int sf, ch, ret, band, sub_pos;
1639
+
1640
+    if ((ret = parse_x96_coding_header(s, exss, xch_base)) < 0)
1641
+        return ret;
1642
+
1643
+    for (sf = 0, sub_pos = 0; sf < s->nsubframes; sf++) {
1644
+        if ((ret = parse_x96_subframe_header(s, xch_base)) < 0)
1645
+            return ret;
1646
+        if ((ret = parse_x96_subframe_audio(s, sf, xch_base, &sub_pos)) < 0)
1647
+            return ret;
1648
+    }
1649
+
1650
+    for (ch = xch_base; ch < s->x96_nchannels; ch++) {
1651
+        // Determine number of active subbands for this channel
1652
+        int nsubbands = s->nsubbands[ch];
1653
+        if (s->joint_intensity_index[ch])
1654
+            nsubbands = FFMAX(nsubbands, s->nsubbands[s->joint_intensity_index[ch] - 1]);
1655
+
1656
+        // Update history for ADPCM and clear inactive subbands
1657
+        for (band = 0; band < DCA_SUBBANDS_X96; band++) {
1658
+            int32_t *samples = s->x96_subband_samples[ch][band] - DCA_ADPCM_COEFFS;
1659
+            if (band >= s->x96_subband_start && band < nsubbands)
1660
+                AV_COPY128(samples, samples + s->npcmblocks);
1661
+            else
1662
+                memset(samples, 0, (DCA_ADPCM_COEFFS + s->npcmblocks) * sizeof(int32_t));
1663
+        }
1664
+    }
1665
+
1666
+    return 0;
1667
+}
1668
+
1669
+static int parse_x96_frame(DCACoreDecoder *s)
1670
+{
1671
+    int ret;
1672
+
1673
+    // Revision number
1674
+    s->x96_rev_no = get_bits(&s->gb, 4);
1675
+    if (s->x96_rev_no < 1 || s->x96_rev_no > 8) {
1676
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 revision (%d)\n", s->x96_rev_no);
1677
+        return AVERROR_INVALIDDATA;
1678
+    }
1679
+
1680
+    s->x96_crc_present = 0;
1681
+    s->x96_nchannels = s->nchannels;
1682
+
1683
+    if ((ret = alloc_x96_sample_buffer(s)) < 0)
1684
+        return ret;
1685
+
1686
+    if ((ret = parse_x96_frame_data(s, 0, 0)) < 0)
1687
+        return ret;
1688
+
1689
+    // Seek to the end of core frame
1690
+    if (ff_dca_seek_bits(&s->gb, s->frame_size * 8)) {
1691
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of X96 frame\n");
1692
+        return AVERROR_INVALIDDATA;
1693
+    }
1694
+
1695
+    return 0;
1696
+}
1697
+
1698
+static int parse_x96_frame_exss(DCACoreDecoder *s)
1699
+{
1700
+    int     x96_frame_size[DCA_EXSS_CHSETS_MAX];
1701
+    int     x96_nchannels[DCA_EXSS_CHSETS_MAX];
1702
+    int     x96_nchsets, x96_base_ch;
1703
+    int     i, ret, header_size, header_pos = get_bits_count(&s->gb);
1704
+
1705
+    // X96 sync word
1706
+    if (get_bits_long(&s->gb, 32) != DCA_SYNCWORD_X96) {
1707
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 sync word\n");
1708
+        return AVERROR_INVALIDDATA;
1709
+    }
1710
+
1711
+    // X96 frame header length
1712
+    header_size = get_bits(&s->gb, 6) + 1;
1713
+
1714
+    // Check X96 frame header CRC
1715
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
1716
+        && ff_dca_check_crc(&s->gb, header_pos + 32, header_pos + header_size * 8)) {
1717
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 frame header checksum\n");
1718
+        return AVERROR_INVALIDDATA;
1719
+    }
1720
+
1721
+    // Revision number
1722
+    s->x96_rev_no = get_bits(&s->gb, 4);
1723
+    if (s->x96_rev_no < 1 || s->x96_rev_no > 8) {
1724
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid X96 revision (%d)\n", s->x96_rev_no);
1725
+        return AVERROR_INVALIDDATA;
1726
+    }
1727
+
1728
+    // CRC presence flag for channel set header
1729
+    s->x96_crc_present = get_bits1(&s->gb);
1730
+
1731
+    // Number of channel sets
1732
+    x96_nchsets = get_bits(&s->gb, 2) + 1;
1733
+
1734
+    // Channel set data byte size
1735
+    for (i = 0; i < x96_nchsets; i++)
1736
+        x96_frame_size[i] = get_bits(&s->gb, 12) + 1;
1737
+
1738
+    // Number of channels in channel set
1739
+    for (i = 0; i < x96_nchsets; i++)
1740
+        x96_nchannels[i] = get_bits(&s->gb, 3) + 1;
1741
+
1742
+    // Reserved
1743
+    // Byte align
1744
+    // CRC16 of X96 frame header
1745
+    if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8)) {
1746
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of X96 frame header\n");
1747
+        return AVERROR_INVALIDDATA;
1748
+    }
1749
+
1750
+    if ((ret = alloc_x96_sample_buffer(s)) < 0)
1751
+        return ret;
1752
+
1753
+    // Channel set data
1754
+    for (i = 0, x96_base_ch = 0; i < x96_nchsets; i++) {
1755
+        header_pos = get_bits_count(&s->gb);
1756
+
1757
+        if (x96_base_ch + x96_nchannels[i] <= s->nchannels) {
1758
+            s->x96_nchannels = x96_base_ch + x96_nchannels[i];
1759
+            if ((ret = parse_x96_frame_data(s, 1, x96_base_ch)) < 0)
1760
+                return ret;
1761
+        }
1762
+
1763
+        x96_base_ch += x96_nchannels[i];
1764
+
1765
+        if (ff_dca_seek_bits(&s->gb, header_pos + x96_frame_size[i] * 8)) {
1766
+            av_log(s->avctx, AV_LOG_ERROR, "Read past end of X96 channel set\n");
1767
+            return AVERROR_INVALIDDATA;
1768
+        }
1769
+    }
1770
+
1771
+    return 0;
1772
+}
1773
+
1774
+static int parse_aux_data(DCACoreDecoder *s)
1775
+{
1776
+    int aux_pos;
1777
+
1778
+    if (get_bits_left(&s->gb) < 0)
1779
+        return AVERROR_INVALIDDATA;
1780
+
1781
+    // Auxiliary data byte count (can't be trusted)
1782
+    skip_bits(&s->gb, 6);
1783
+
1784
+    // 4-byte align
1785
+    skip_bits_long(&s->gb, -get_bits_count(&s->gb) & 31);
1786
+
1787
+    // Auxiliary data sync word
1788
+    if (get_bits_long(&s->gb, 32) != DCA_SYNCWORD_REV1AUX) {
1789
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid auxiliary data sync word\n");
1790
+        return AVERROR_INVALIDDATA;
1791
+    }
1792
+
1793
+    aux_pos = get_bits_count(&s->gb);
1794
+
1795
+    // Auxiliary decode time stamp flag
1796
+    if (get_bits1(&s->gb))
1797
+        skip_bits_long(&s->gb, 47);
1798
+
1799
+    // Auxiliary dynamic downmix flag
1800
+    if (s->prim_dmix_embedded = get_bits1(&s->gb)) {
1801
+        int i, m, n;
1802
+
1803
+        // Auxiliary primary channel downmix type
1804
+        s->prim_dmix_type = get_bits(&s->gb, 3);
1805
+        if (s->prim_dmix_type >= DCA_DMIX_TYPE_COUNT) {
1806
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid primary channel set downmix type\n");
1807
+            return AVERROR_INVALIDDATA;
1808
+        }
1809
+
1810
+        // Size of downmix coefficients matrix
1811
+        m = ff_dca_dmix_primary_nch[s->prim_dmix_type];
1812
+        n = ff_dca_channels[s->audio_mode] + !!s->lfe_present;
1813
+
1814
+        // Dynamic downmix code coefficients
1815
+        for (i = 0; i < m * n; i++) {
1816
+            int code = get_bits(&s->gb, 9);
1817
+            int sign = (code >> 8) - 1;
1818
+            unsigned int index = code & 0xff;
1819
+            if (index >= FF_DCA_DMIXTABLE_SIZE) {
1820
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid downmix coefficient index\n");
1821
+                return AVERROR_INVALIDDATA;
1822
+            }
1823
+            s->prim_dmix_coeff[i] = (ff_dca_dmixtable[index] ^ sign) - sign;
1824
+        }
1825
+    }
1826
+
1827
+    // Byte align
1828
+    skip_bits(&s->gb, -get_bits_count(&s->gb) & 7);
1829
+
1830
+    // CRC16 of auxiliary data
1831
+    skip_bits(&s->gb, 16);
1832
+
1833
+    // Check CRC
1834
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
1835
+        && ff_dca_check_crc(&s->gb, aux_pos, get_bits_count(&s->gb))) {
1836
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid auxiliary data checksum\n");
1837
+        return AVERROR_INVALIDDATA;
1838
+    }
1839
+
1840
+    return 0;
1841
+}
1842
+
1843
+static int parse_optional_info(DCACoreDecoder *s)
1844
+{
1845
+    DCAContext *dca = s->avctx->priv_data;
1846
+    int ret = -1;
1847
+
1848
+    // Time code stamp
1849
+    if (s->ts_present)
1850
+        skip_bits_long(&s->gb, 32);
1851
+
1852
+    // Auxiliary data
1853
+    if (s->aux_present && (ret = parse_aux_data(s)) < 0
1854
+        && (s->avctx->err_recognition & AV_EF_EXPLODE))
1855
+        return ret;
1856
+
1857
+    if (ret < 0)
1858
+        s->prim_dmix_embedded = 0;
1859
+
1860
+    // Core extensions
1861
+    if (s->ext_audio_present && !dca->core_only) {
1862
+        int sync_pos = FFMIN(s->frame_size / 4, s->gb.size_in_bits / 32) - 1;
1863
+        int last_pos = get_bits_count(&s->gb) / 32;
1864
+        int size, dist;
1865
+
1866
+        // Search for extension sync words aligned on 4-byte boundary. Search
1867
+        // must be done backwards from the end of core frame to work around
1868
+        // sync word aliasing issues.
1869
+        switch (s->ext_audio_type) {
1870
+        case EXT_AUDIO_XCH:
1871
+            if (dca->request_channel_layout)
1872
+                break;
1873
+
1874
+            // The distance between XCH sync word and end of the core frame
1875
+            // must be equal to XCH frame size. Off by one error is allowed for
1876
+            // compatibility with legacy bitstreams. Minimum XCH frame size is
1877
+            // 96 bytes. AMODE and PCHS are further checked to reduce
1878
+            // probability of alias sync detection.
1879
+            for (; sync_pos >= last_pos; sync_pos--) {
1880
+                if (AV_RB32(s->gb.buffer + sync_pos * 4) == DCA_SYNCWORD_XCH) {
1881
+                    s->gb.index = (sync_pos + 1) * 32;
1882
+                    size = get_bits(&s->gb, 10) + 1;
1883
+                    dist = s->frame_size - sync_pos * 4;
1884
+                    if (size >= 96
1885
+                        && (size == dist || size - 1 == dist)
1886
+                        && get_bits(&s->gb, 7) == 0x08) {
1887
+                        s->xch_pos = get_bits_count(&s->gb);
1888
+                        break;
1889
+                    }
1890
+                }
1891
+            }
1892
+
1893
+            if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1894
+                av_log(s->avctx, AV_LOG_ERROR, "XCH sync word not found\n");
1895
+                return AVERROR_INVALIDDATA;
1896
+            }
1897
+            break;
1898
+
1899
+        case EXT_AUDIO_X96:
1900
+            // The distance between X96 sync word and end of the core frame
1901
+            // must be equal to X96 frame size. Minimum X96 frame size is 96
1902
+            // bytes.
1903
+            for (; sync_pos >= last_pos; sync_pos--) {
1904
+                if (AV_RB32(s->gb.buffer + sync_pos * 4) == DCA_SYNCWORD_X96) {
1905
+                    s->gb.index = (sync_pos + 1) * 32;
1906
+                    size = get_bits(&s->gb, 12) + 1;
1907
+                    dist = s->frame_size - sync_pos * 4;
1908
+                    if (size >= 96 && size == dist) {
1909
+                        s->x96_pos = get_bits_count(&s->gb);
1910
+                        break;
1911
+                    }
1912
+                }
1913
+            }
1914
+
1915
+            if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1916
+                av_log(s->avctx, AV_LOG_ERROR, "X96 sync word not found\n");
1917
+                return AVERROR_INVALIDDATA;
1918
+            }
1919
+            break;
1920
+
1921
+        case EXT_AUDIO_XXCH:
1922
+            if (dca->request_channel_layout)
1923
+                break;
1924
+
1925
+            // XXCH frame header CRC must be valid. Minimum XXCH frame header
1926
+            // size is 11 bytes.
1927
+            for (; sync_pos >= last_pos; sync_pos--) {
1928
+                if (AV_RB32(s->gb.buffer + sync_pos * 4) == DCA_SYNCWORD_XXCH) {
1929
+                    s->gb.index = (sync_pos + 1) * 32;
1930
+                    size = get_bits(&s->gb, 6) + 1;
1931
+                    if (size >= 11 &&
1932
+                        !ff_dca_check_crc(&s->gb, (sync_pos + 1) * 32,
1933
+                                          sync_pos * 32 + size * 8)) {
1934
+                        s->xxch_pos = sync_pos * 32;
1935
+                        break;
1936
+                    }
1937
+                }
1938
+            }
1939
+
1940
+            if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1941
+                av_log(s->avctx, AV_LOG_ERROR, "XXCH sync word not found\n");
1942
+                return AVERROR_INVALIDDATA;
1943
+            }
1944
+            break;
1945
+        }
1946
+    }
1947
+
1948
+    return 0;
1949
+}
1950
+
1951
+int ff_dca_core_parse(DCACoreDecoder *s, uint8_t *data, int size)
1952
+{
1953
+    int ret;
1954
+
1955
+    s->ext_audio_mask = 0;
1956
+    s->xch_pos = s->xxch_pos = s->x96_pos = 0;
1957
+
1958
+    if ((ret = init_get_bits8(&s->gb, data, size)) < 0)
1959
+        return ret;
1960
+
1961
+    skip_bits_long(&s->gb, 32);
1962
+    if ((ret = parse_frame_header(s)) < 0)
1963
+        return ret;
1964
+    if ((ret = alloc_sample_buffer(s)) < 0)
1965
+        return ret;
1966
+    if ((ret = parse_frame_data(s, HEADER_CORE, 0)) < 0)
1967
+        return ret;
1968
+    if ((ret = parse_optional_info(s)) < 0)
1969
+        return ret;
1970
+
1971
+    // Workaround for DTS in WAV
1972
+    if (s->frame_size > size && s->frame_size < size + 4) {
1973
+        av_log(s->avctx, AV_LOG_DEBUG, "Working around excessive core frame size (%d > %d)\n", s->frame_size, size);
1974
+        s->frame_size = size;
1975
+    }
1976
+
1977
+    if (ff_dca_seek_bits(&s->gb, s->frame_size * 8)) {
1978
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of core frame\n");
1979
+        if (s->avctx->err_recognition & AV_EF_EXPLODE)
1980
+            return AVERROR_INVALIDDATA;
1981
+    }
1982
+
1983
+    return 0;
1984
+}
1985
+
1986
+int ff_dca_core_parse_exss(DCACoreDecoder *s, uint8_t *data, DCAExssAsset *asset)
1987
+{
1988
+    AVCodecContext *avctx = s->avctx;
1989
+    DCAContext *dca = avctx->priv_data;
1990
+    GetBitContext gb = s->gb;
1991
+    int exss_mask = asset ? asset->extension_mask : 0;
1992
+    int ret = 0, ext = 0;
1993
+
1994
+    // Parse (X)XCH unless downmixing
1995
+    if (!dca->request_channel_layout) {
1996
+        if (exss_mask & DCA_EXSS_XXCH) {
1997
+            if ((ret = init_get_bits8(&s->gb, data + asset->xxch_offset, asset->xxch_size)) < 0)
1998
+                return ret;
1999
+            ret = parse_xxch_frame(s);
2000
+            ext = DCA_EXSS_XXCH;
2001
+        } else if (s->xxch_pos) {
2002
+            s->gb.index = s->xxch_pos;
2003
+            ret = parse_xxch_frame(s);
2004
+            ext = DCA_CSS_XXCH;
2005
+        } else if (s->xch_pos) {
2006
+            s->gb.index = s->xch_pos;
2007
+            ret = parse_xch_frame(s);
2008
+            ext = DCA_CSS_XCH;
2009
+        }
2010
+
2011
+        // Revert to primary channel set in case (X)XCH parsing fails
2012
+        if (ret < 0) {
2013
+            if (avctx->err_recognition & AV_EF_EXPLODE)
2014
+                return ret;
2015
+            s->nchannels = ff_dca_channels[s->audio_mode];
2016
+            s->ch_mask = audio_mode_ch_mask[s->audio_mode];
2017
+            if (s->lfe_present)
2018
+                s->ch_mask |= DCA_SPEAKER_MASK_LFE1;
2019
+        } else {
2020
+            s->ext_audio_mask |= ext;
2021
+        }
2022
+    }
2023
+
2024
+    // Parse XBR
2025
+    if (exss_mask & DCA_EXSS_XBR) {
2026
+        if ((ret = init_get_bits8(&s->gb, data + asset->xbr_offset, asset->xbr_size)) < 0)
2027
+            return ret;
2028
+        if ((ret = parse_xbr_frame(s)) < 0) {
2029
+            if (avctx->err_recognition & AV_EF_EXPLODE)
2030
+                return ret;
2031
+        } else {
2032
+            s->ext_audio_mask |= DCA_EXSS_XBR;
2033
+        }
2034
+    }
2035
+
2036
+    // Parse X96 unless decoding XLL
2037
+    if (!(dca->packet & DCA_PACKET_XLL)) {
2038
+        if (exss_mask & DCA_EXSS_X96) {
2039
+            if ((ret = init_get_bits8(&s->gb, data + asset->x96_offset, asset->x96_size)) < 0)
2040
+                return ret;
2041
+            if ((ret = parse_x96_frame_exss(s)) < 0) {
2042
+                if (ret == AVERROR(ENOMEM) || (avctx->err_recognition & AV_EF_EXPLODE))
2043
+                    return ret;
2044
+            } else {
2045
+                s->ext_audio_mask |= DCA_EXSS_X96;
2046
+            }
2047
+        } else if (s->x96_pos) {
2048
+            s->gb = gb;
2049
+            s->gb.index = s->x96_pos;
2050
+            if ((ret = parse_x96_frame(s)) < 0) {
2051
+                if (ret == AVERROR(ENOMEM) || (avctx->err_recognition & AV_EF_EXPLODE))
2052
+                    return ret;
2053
+            } else {
2054
+                s->ext_audio_mask |= DCA_CSS_X96;
2055
+            }
2056
+        }
2057
+    }
2058
+
2059
+    return 0;
2060
+}
2061
+
2062
+static int map_prm_ch_to_spkr(DCACoreDecoder *s, int ch)
2063
+{
2064
+    int pos, spkr;
2065
+
2066
+    // Try to map this channel to core first
2067
+    pos = ff_dca_channels[s->audio_mode];
2068
+    if (ch < pos) {
2069
+        spkr = prm_ch_to_spkr_map[s->audio_mode][ch];
2070
+        if (s->ext_audio_mask & (DCA_CSS_XXCH | DCA_EXSS_XXCH)) {
2071
+            if (s->xxch_core_mask & (1U << spkr))
2072
+                return spkr;
2073
+            if (spkr == DCA_SPEAKER_Ls && (s->xxch_core_mask & DCA_SPEAKER_MASK_Lss))
2074
+                return DCA_SPEAKER_Lss;
2075
+            if (spkr == DCA_SPEAKER_Rs && (s->xxch_core_mask & DCA_SPEAKER_MASK_Rss))
2076
+                return DCA_SPEAKER_Rss;
2077
+            return -1;
2078
+        }
2079
+        return spkr;
2080
+    }
2081
+
2082
+    // Then XCH
2083
+    if ((s->ext_audio_mask & DCA_CSS_XCH) && ch == pos)
2084
+        return DCA_SPEAKER_Cs;
2085
+
2086
+    // Then XXCH
2087
+    if (s->ext_audio_mask & (DCA_CSS_XXCH | DCA_EXSS_XXCH)) {
2088
+        for (spkr = DCA_SPEAKER_Cs; spkr < s->xxch_mask_nbits; spkr++)
2089
+            if (s->xxch_spkr_mask & (1U << spkr))
2090
+                if (pos++ == ch)
2091
+                    return spkr;
2092
+    }
2093
+
2094
+    // No mapping
2095
+    return -1;
2096
+}
2097
+
2098
+static void erase_dsp_history(DCACoreDecoder *s)
2099
+{
2100
+    memset(s->dcadsp_data, 0, sizeof(s->dcadsp_data));
2101
+    s->output_history_lfe_fixed = 0;
2102
+    s->output_history_lfe_float = 0;
2103
+}
2104
+
2105
+static void set_filter_mode(DCACoreDecoder *s, int mode)
2106
+{
2107
+    if (s->filter_mode != mode) {
2108
+        erase_dsp_history(s);
2109
+        s->filter_mode = mode;
2110
+    }
2111
+}
2112
+
2113
+int ff_dca_core_filter_fixed(DCACoreDecoder *s, int x96_synth)
2114
+{
2115
+    int n, ch, spkr, nsamples, x96_nchannels = 0;
2116
+    const int32_t *filter_coeff;
2117
+    int32_t *ptr;
2118
+
2119
+    // Externally set x96_synth flag implies that X96 synthesis should be
2120
+    // enabled, yet actual X96 subband data should be discarded. This is a
2121
+    // special case for lossless residual decoder that ignores X96 data if
2122
+    // present.
2123
+    if (!x96_synth && (s->ext_audio_mask & (DCA_CSS_X96 | DCA_EXSS_X96))) {
2124
+        x96_nchannels = s->x96_nchannels;
2125
+        x96_synth = 1;
2126
+    }
2127
+    if (x96_synth < 0)
2128
+        x96_synth = 0;
2129
+
2130
+    s->output_rate = s->sample_rate << x96_synth;
2131
+    s->npcmsamples = nsamples = (s->npcmblocks * DCA_PCMBLOCK_SAMPLES) << x96_synth;
2132
+
2133
+    // Reallocate PCM output buffer
2134
+    av_fast_malloc(&s->output_buffer, &s->output_size,
2135
+                   nsamples * av_popcount(s->ch_mask) * sizeof(int32_t));
2136
+    if (!s->output_buffer)
2137
+        return AVERROR(ENOMEM);
2138
+
2139
+    ptr = (int32_t *)s->output_buffer;
2140
+    for (spkr = 0; spkr < DCA_SPEAKER_COUNT; spkr++) {
2141
+        if (s->ch_mask & (1U << spkr)) {
2142
+            s->output_samples[spkr] = ptr;
2143
+            ptr += nsamples;
2144
+        } else {
2145
+            s->output_samples[spkr] = NULL;
2146
+        }
2147
+    }
2148
+
2149
+    // Handle change of filtering mode
2150
+    set_filter_mode(s, x96_synth | DCA_FILTER_MODE_FIXED);
2151
+
2152
+    // Select filter
2153
+    if (x96_synth)
2154
+        filter_coeff = ff_dca_fir_64bands_fixed;
2155
+    else if (s->filter_perfect)
2156
+        filter_coeff = ff_dca_fir_32bands_perfect_fixed;
2157
+    else
2158
+        filter_coeff = ff_dca_fir_32bands_nonperfect_fixed;
2159
+
2160
+    // Filter primary channels
2161
+    for (ch = 0; ch < s->nchannels; ch++) {
2162
+        // Map this primary channel to speaker
2163
+        spkr = map_prm_ch_to_spkr(s, ch);
2164
+        if (spkr < 0)
2165
+            return AVERROR(EINVAL);
2166
+
2167
+        // Filter bank reconstruction
2168
+        s->dcadsp->sub_qmf_fixed[x96_synth](
2169
+            &s->synth,
2170
+            &s->dcadct,
2171
+            s->output_samples[spkr],
2172
+            s->subband_samples[ch],
2173
+            ch < x96_nchannels ? s->x96_subband_samples[ch] : NULL,
2174
+            s->dcadsp_data[ch].u.fix.hist1,
2175
+            &s->dcadsp_data[ch].offset,
2176
+            s->dcadsp_data[ch].u.fix.hist2,
2177
+            filter_coeff,
2178
+            s->npcmblocks);
2179
+    }
2180
+
2181
+    // Filter LFE channel
2182
+    if (s->lfe_present) {
2183
+        int32_t *samples = s->output_samples[DCA_SPEAKER_LFE1];
2184
+        int nlfesamples = s->npcmblocks >> 1;
2185
+
2186
+        // Check LFF
2187
+        if (s->lfe_present == LFE_FLAG_128) {
2188
+            av_log(s->avctx, AV_LOG_ERROR, "Fixed point mode doesn't support LFF=1\n");
2189
+            return AVERROR(EINVAL);
2190
+        }
2191
+
2192
+        // Offset intermediate buffer for X96
2193
+        if (x96_synth)
2194
+            samples += nsamples / 2;
2195
+
2196
+        // Interpolate LFE channel
2197
+        s->dcadsp->lfe_fir_fixed(samples, s->lfe_samples + DCA_LFE_HISTORY,
2198
+                                 ff_dca_lfe_fir_64_fixed, s->npcmblocks);
2199
+
2200
+        if (x96_synth) {
2201
+            // Filter 96 kHz oversampled LFE PCM to attenuate high frequency
2202
+            // (47.6 - 48.0 kHz) components of interpolation image
2203
+            s->dcadsp->lfe_x96_fixed(s->output_samples[DCA_SPEAKER_LFE1],
2204
+                                     samples, &s->output_history_lfe_fixed,
2205
+                                     nsamples / 2);
2206
+
2207
+        }
2208
+
2209
+        // Update LFE history
2210
+        for (n = DCA_LFE_HISTORY - 1; n >= 0; n--)
2211
+            s->lfe_samples[n] = s->lfe_samples[nlfesamples + n];
2212
+    }
2213
+
2214
+    return 0;
2215
+}
2216
+
2217
+static int filter_frame_fixed(DCACoreDecoder *s, AVFrame *frame)
2218
+{
2219
+    AVCodecContext *avctx = s->avctx;
2220
+    DCAContext *dca = avctx->priv_data;
2221
+    int i, n, ch, ret, spkr, nsamples;
2222
+
2223
+    // Don't filter twice when falling back from XLL
2224
+    if (!(dca->packet & DCA_PACKET_XLL) && (ret = ff_dca_core_filter_fixed(s, 0)) < 0)
2225
+        return ret;
2226
+
2227
+    avctx->sample_rate = s->output_rate;
2228
+    avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
2229
+    avctx->bits_per_raw_sample = 24;
2230
+
2231
+    frame->nb_samples = nsamples = s->npcmsamples;
2232
+    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
2233
+        return ret;
2234
+
2235
+    // Undo embedded XCH downmix
2236
+    if (s->es_format && (s->ext_audio_mask & DCA_CSS_XCH)
2237
+        && s->audio_mode >= AMODE_2F2R) {
2238
+        s->dcadsp->dmix_sub_xch(s->output_samples[DCA_SPEAKER_Ls],
2239
+                                s->output_samples[DCA_SPEAKER_Rs],
2240
+                                s->output_samples[DCA_SPEAKER_Cs],
2241
+                                nsamples);
2242
+
2243
+    }
2244
+
2245
+    // Undo embedded XXCH downmix
2246
+    if ((s->ext_audio_mask & (DCA_CSS_XXCH | DCA_EXSS_XXCH))
2247
+        && s->xxch_dmix_embedded) {
2248
+        int scale_inv   = s->xxch_dmix_scale_inv;
2249
+        int *coeff_ptr  = s->xxch_dmix_coeff;
2250
+        int xch_base    = ff_dca_channels[s->audio_mode];
2251
+        av_assert1(s->nchannels - xch_base <= DCA_XXCH_CHANNELS_MAX);
2252
+
2253
+        // Undo embedded core downmix pre-scaling
2254
+        for (spkr = 0; spkr < s->xxch_mask_nbits; spkr++) {
2255
+            if (s->xxch_core_mask & (1U << spkr)) {
2256
+                s->dcadsp->dmix_scale_inv(s->output_samples[spkr],
2257
+                                          scale_inv, nsamples);
2258
+            }
2259
+        }
2260
+
2261
+        // Undo downmix
2262
+        for (ch = xch_base; ch < s->nchannels; ch++) {
2263
+            int src_spkr = map_prm_ch_to_spkr(s, ch);
2264
+            if (src_spkr < 0)
2265
+                return AVERROR(EINVAL);
2266
+            for (spkr = 0; spkr < s->xxch_mask_nbits; spkr++) {
2267
+                if (s->xxch_dmix_mask[ch - xch_base] & (1U << spkr)) {
2268
+                    int coeff = mul16(*coeff_ptr++, scale_inv);
2269
+                    if (coeff) {
2270
+                        s->dcadsp->dmix_sub(s->output_samples[spkr    ],
2271
+                                            s->output_samples[src_spkr],
2272
+                                            coeff, nsamples);
2273
+                    }
2274
+                }
2275
+            }
2276
+        }
2277
+    }
2278
+
2279
+    if (!(s->ext_audio_mask & (DCA_CSS_XXCH | DCA_CSS_XCH | DCA_EXSS_XXCH))) {
2280
+        // Front sum/difference decoding
2281
+        if ((s->sumdiff_front && s->audio_mode > AMODE_MONO)
2282
+            || s->audio_mode == AMODE_STEREO_SUMDIFF) {
2283
+            s->fixed_dsp->butterflies_fixed(s->output_samples[DCA_SPEAKER_L],
2284
+                                            s->output_samples[DCA_SPEAKER_R],
2285
+                                            nsamples);
2286
+        }
2287
+
2288
+        // Surround sum/difference decoding
2289
+        if (s->sumdiff_surround && s->audio_mode >= AMODE_2F2R) {
2290
+            s->fixed_dsp->butterflies_fixed(s->output_samples[DCA_SPEAKER_Ls],
2291
+                                            s->output_samples[DCA_SPEAKER_Rs],
2292
+                                            nsamples);
2293
+        }
2294
+    }
2295
+
2296
+    // Downmix primary channel set to stereo
2297
+    if (s->request_mask != s->ch_mask) {
2298
+        ff_dca_downmix_to_stereo_fixed(s->dcadsp,
2299
+                                       s->output_samples,
2300
+                                       s->prim_dmix_coeff,
2301
+                                       nsamples, s->ch_mask);
2302
+    }
2303
+
2304
+    for (i = 0; i < avctx->channels; i++) {
2305
+        int32_t *samples = s->output_samples[s->ch_remap[i]];
2306
+        int32_t *plane = (int32_t *)frame->extended_data[i];
2307
+        for (n = 0; n < nsamples; n++)
2308
+            plane[n] = clip23(samples[n]) * (1 << 8);
2309
+    }
2310
+
2311
+    return 0;
2312
+}
2313
+
2314
+static int filter_frame_float(DCACoreDecoder *s, AVFrame *frame)
2315
+{
2316
+    AVCodecContext *avctx = s->avctx;
2317
+    int x96_nchannels = 0, x96_synth = 0;
2318
+    int i, n, ch, ret, spkr, nsamples, nchannels;
2319
+    float *output_samples[DCA_SPEAKER_COUNT] = { NULL }, *ptr;
2320
+    const float *filter_coeff;
2321
+
2322
+    if (s->ext_audio_mask & (DCA_CSS_X96 | DCA_EXSS_X96)) {
2323
+        x96_nchannels = s->x96_nchannels;
2324
+        x96_synth = 1;
2325
+    }
2326
+
2327
+    avctx->sample_rate = s->sample_rate << x96_synth;
2328
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
2329
+    avctx->bits_per_raw_sample = 0;
2330
+
2331
+    frame->nb_samples = nsamples = (s->npcmblocks * DCA_PCMBLOCK_SAMPLES) << x96_synth;
2332
+    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
2333
+        return ret;
2334
+
2335
+    // Build reverse speaker to channel mapping
2336
+    for (i = 0; i < avctx->channels; i++)
2337
+        output_samples[s->ch_remap[i]] = (float *)frame->extended_data[i];
2338
+
2339
+    // Allocate space for extra channels
2340
+    nchannels = av_popcount(s->ch_mask) - avctx->channels;
2341
+    if (nchannels > 0) {
2342
+        av_fast_malloc(&s->output_buffer, &s->output_size,
2343
+                       nsamples * nchannels * sizeof(float));
2344
+        if (!s->output_buffer)
2345
+            return AVERROR(ENOMEM);
2346
+
2347
+        ptr = (float *)s->output_buffer;
2348
+        for (spkr = 0; spkr < DCA_SPEAKER_COUNT; spkr++) {
2349
+            if (!(s->ch_mask & (1U << spkr)))
2350
+                continue;
2351
+            if (output_samples[spkr])
2352
+                continue;
2353
+            output_samples[spkr] = ptr;
2354
+            ptr += nsamples;
2355
+        }
2356
+    }
2357
+
2358
+    // Handle change of filtering mode
2359
+    set_filter_mode(s, x96_synth);
2360
+
2361
+    // Select filter
2362
+    if (x96_synth)
2363
+        filter_coeff = ff_dca_fir_64bands;
2364
+    else if (s->filter_perfect)
2365
+        filter_coeff = ff_dca_fir_32bands_perfect;
2366
+    else
2367
+        filter_coeff = ff_dca_fir_32bands_nonperfect;
2368
+
2369
+    // Filter primary channels
2370
+    for (ch = 0; ch < s->nchannels; ch++) {
2371
+        // Map this primary channel to speaker
2372
+        spkr = map_prm_ch_to_spkr(s, ch);
2373
+        if (spkr < 0)
2374
+            return AVERROR(EINVAL);
2375
+
2376
+        // Filter bank reconstruction
2377
+        s->dcadsp->sub_qmf_float[x96_synth](
2378
+            &s->synth,
2379
+            &s->imdct[x96_synth],
2380
+            output_samples[spkr],
2381
+            s->subband_samples[ch],
2382
+            ch < x96_nchannels ? s->x96_subband_samples[ch] : NULL,
2383
+            s->dcadsp_data[ch].u.flt.hist1,
2384
+            &s->dcadsp_data[ch].offset,
2385
+            s->dcadsp_data[ch].u.flt.hist2,
2386
+            filter_coeff,
2387
+            s->npcmblocks,
2388
+            1.0f / (1 << (17 - x96_synth)));
2389
+    }
2390
+
2391
+    // Filter LFE channel
2392
+    if (s->lfe_present) {
2393
+        int dec_select = (s->lfe_present == LFE_FLAG_128);
2394
+        float *samples = output_samples[DCA_SPEAKER_LFE1];
2395
+        int nlfesamples = s->npcmblocks >> (dec_select + 1);
2396
+
2397
+        // Offset intermediate buffer for X96
2398
+        if (x96_synth)
2399
+            samples += nsamples / 2;
2400
+
2401
+        // Select filter
2402
+        if (dec_select)
2403
+            filter_coeff = ff_dca_lfe_fir_128;
2404
+        else
2405
+            filter_coeff = ff_dca_lfe_fir_64;
2406
+
2407
+        // Interpolate LFE channel
2408
+        s->dcadsp->lfe_fir_float[dec_select](
2409
+            samples, s->lfe_samples + DCA_LFE_HISTORY,
2410
+            filter_coeff, s->npcmblocks);
2411
+
2412
+        if (x96_synth) {
2413
+            // Filter 96 kHz oversampled LFE PCM to attenuate high frequency
2414
+            // (47.6 - 48.0 kHz) components of interpolation image
2415
+            s->dcadsp->lfe_x96_float(output_samples[DCA_SPEAKER_LFE1],
2416
+                                     samples, &s->output_history_lfe_float,
2417
+                                     nsamples / 2);
2418
+        }
2419
+
2420
+        // Update LFE history
2421
+        for (n = DCA_LFE_HISTORY - 1; n >= 0; n--)
2422
+            s->lfe_samples[n] = s->lfe_samples[nlfesamples + n];
2423
+    }
2424
+
2425
+    // Undo embedded XCH downmix
2426
+    if (s->es_format && (s->ext_audio_mask & DCA_CSS_XCH)
2427
+        && s->audio_mode >= AMODE_2F2R) {
2428
+        s->float_dsp->vector_fmac_scalar(output_samples[DCA_SPEAKER_Ls],
2429
+                                         output_samples[DCA_SPEAKER_Cs],
2430
+                                         -M_SQRT1_2, nsamples);
2431
+        s->float_dsp->vector_fmac_scalar(output_samples[DCA_SPEAKER_Rs],
2432
+                                         output_samples[DCA_SPEAKER_Cs],
2433
+                                         -M_SQRT1_2, nsamples);
2434
+    }
2435
+
2436
+    // Undo embedded XXCH downmix
2437
+    if ((s->ext_audio_mask & (DCA_CSS_XXCH | DCA_EXSS_XXCH))
2438
+        && s->xxch_dmix_embedded) {
2439
+        float scale_inv = s->xxch_dmix_scale_inv * (1.0f / (1 << 16));
2440
+        int *coeff_ptr  = s->xxch_dmix_coeff;
2441
+        int xch_base    = ff_dca_channels[s->audio_mode];
2442
+        av_assert1(s->nchannels - xch_base <= DCA_XXCH_CHANNELS_MAX);
2443
+
2444
+        // Undo downmix
2445
+        for (ch = xch_base; ch < s->nchannels; ch++) {
2446
+            int src_spkr = map_prm_ch_to_spkr(s, ch);
2447
+            if (src_spkr < 0)
2448
+                return AVERROR(EINVAL);
2449
+            for (spkr = 0; spkr < s->xxch_mask_nbits; spkr++) {
2450
+                if (s->xxch_dmix_mask[ch - xch_base] & (1U << spkr)) {
2451
+                    int coeff = *coeff_ptr++;
2452
+                    if (coeff) {
2453
+                        s->float_dsp->vector_fmac_scalar(output_samples[    spkr],
2454
+                                                         output_samples[src_spkr],
2455
+                                                         coeff * (-1.0f / (1 << 15)),
2456
+                                                         nsamples);
2457
+                    }
2458
+                }
2459
+            }
2460
+        }
2461
+
2462
+        // Undo embedded core downmix pre-scaling
2463
+        for (spkr = 0; spkr < s->xxch_mask_nbits; spkr++) {
2464
+            if (s->xxch_core_mask & (1U << spkr)) {
2465
+                s->float_dsp->vector_fmul_scalar(output_samples[spkr],
2466
+                                                 output_samples[spkr],
2467
+                                                 scale_inv, nsamples);
2468
+            }
2469
+        }
2470
+    }
2471
+
2472
+    if (!(s->ext_audio_mask & (DCA_CSS_XXCH | DCA_CSS_XCH | DCA_EXSS_XXCH))) {
2473
+        // Front sum/difference decoding
2474
+        if ((s->sumdiff_front && s->audio_mode > AMODE_MONO)
2475
+            || s->audio_mode == AMODE_STEREO_SUMDIFF) {
2476
+            s->float_dsp->butterflies_float(output_samples[DCA_SPEAKER_L],
2477
+                                            output_samples[DCA_SPEAKER_R],
2478
+                                            nsamples);
2479
+        }
2480
+
2481
+        // Surround sum/difference decoding
2482
+        if (s->sumdiff_surround && s->audio_mode >= AMODE_2F2R) {
2483
+            s->float_dsp->butterflies_float(output_samples[DCA_SPEAKER_Ls],
2484
+                                            output_samples[DCA_SPEAKER_Rs],
2485
+                                            nsamples);
2486
+        }
2487
+    }
2488
+
2489
+    // Downmix primary channel set to stereo
2490
+    if (s->request_mask != s->ch_mask) {
2491
+        ff_dca_downmix_to_stereo_float(s->float_dsp, output_samples,
2492
+                                       s->prim_dmix_coeff,
2493
+                                       nsamples, s->ch_mask);
2494
+    }
2495
+
2496
+    return 0;
2497
+}
2498
+
2499
+int ff_dca_core_filter_frame(DCACoreDecoder *s, AVFrame *frame)
2500
+{
2501
+    AVCodecContext *avctx = s->avctx;
2502
+    DCAContext *dca = avctx->priv_data;
2503
+    DCAExssAsset *asset = &dca->exss.assets[0];
2504
+    enum AVMatrixEncoding matrix_encoding;
2505
+    int ret;
2506
+
2507
+    // Handle downmixing to stereo request
2508
+    if (dca->request_channel_layout == DCA_SPEAKER_LAYOUT_STEREO
2509
+        && s->audio_mode > AMODE_MONO && s->prim_dmix_embedded
2510
+        && (s->prim_dmix_type == DCA_DMIX_TYPE_LoRo ||
2511
+            s->prim_dmix_type == DCA_DMIX_TYPE_LtRt))
2512
+        s->request_mask = DCA_SPEAKER_LAYOUT_STEREO;
2513
+    else
2514
+        s->request_mask = s->ch_mask;
2515
+    if (!ff_dca_set_channel_layout(avctx, s->ch_remap, s->request_mask))
2516
+        return AVERROR(EINVAL);
2517
+
2518
+    // Force fixed point mode when falling back from XLL
2519
+    if ((avctx->flags & AV_CODEC_FLAG_BITEXACT) || ((dca->packet & DCA_PACKET_EXSS)
2520
+                                                    && (asset->extension_mask & DCA_EXSS_XLL)))
2521
+        ret = filter_frame_fixed(s, frame);
2522
+    else
2523
+        ret = filter_frame_float(s, frame);
2524
+    if (ret < 0)
2525
+        return ret;
2526
+
2527
+    // Set profile, bit rate, etc
2528
+    if (s->ext_audio_mask & DCA_EXSS_MASK)
2529
+        avctx->profile = FF_PROFILE_DTS_HD_HRA;
2530
+    else if (s->ext_audio_mask & (DCA_CSS_XXCH | DCA_CSS_XCH))
2531
+        avctx->profile = FF_PROFILE_DTS_ES;
2532
+    else if (s->ext_audio_mask & DCA_CSS_X96)
2533
+        avctx->profile = FF_PROFILE_DTS_96_24;
2534
+    else
2535
+        avctx->profile = FF_PROFILE_DTS;
2536
+
2537
+    if (s->bit_rate > 3 && !(s->ext_audio_mask & DCA_EXSS_MASK))
2538
+        avctx->bit_rate = s->bit_rate;
2539
+    else
2540
+        avctx->bit_rate = 0;
2541
+
2542
+    if (s->audio_mode == AMODE_STEREO_TOTAL || (s->request_mask != s->ch_mask &&
2543
+                                                s->prim_dmix_type == DCA_DMIX_TYPE_LtRt))
2544
+        matrix_encoding = AV_MATRIX_ENCODING_DOLBY;
2545
+    else
2546
+        matrix_encoding = AV_MATRIX_ENCODING_NONE;
2547
+    if ((ret = ff_side_data_update_matrix_encoding(frame, matrix_encoding)) < 0)
2548
+        return ret;
2549
+
2550
+    return 0;
2551
+}
2552
+
2553
+av_cold void ff_dca_core_flush(DCACoreDecoder *s)
2554
+{
2555
+    if (s->subband_buffer) {
2556
+        erase_adpcm_history(s);
2557
+        memset(s->lfe_samples, 0, DCA_LFE_HISTORY * sizeof(int32_t));
2558
+    }
2559
+
2560
+    if (s->x96_subband_buffer)
2561
+        erase_x96_adpcm_history(s);
2562
+
2563
+    erase_dsp_history(s);
2564
+}
2565
+
2566
+av_cold int ff_dca_core_init(DCACoreDecoder *s)
2567
+{
2568
+    dca_init_vlcs();
2569
+
2570
+    if (!(s->float_dsp = avpriv_float_dsp_alloc(0)))
2571
+        return -1;
2572
+    if (!(s->fixed_dsp = avpriv_alloc_fixed_dsp(0)))
2573
+        return -1;
2574
+
2575
+    ff_dcadct_init(&s->dcadct);
2576
+    if (ff_mdct_init(&s->imdct[0], 6, 1, 1.0) < 0)
2577
+        return -1;
2578
+    if (ff_mdct_init(&s->imdct[1], 7, 1, 1.0) < 0)
2579
+        return -1;
2580
+    ff_synth_filter_init(&s->synth);
2581
+
2582
+    s->x96_rand = 1;
2583
+    return 0;
2584
+}
2585
+
2586
+av_cold void ff_dca_core_close(DCACoreDecoder *s)
2587
+{
2588
+    av_freep(&s->float_dsp);
2589
+    av_freep(&s->fixed_dsp);
2590
+
2591
+    ff_mdct_end(&s->imdct[0]);
2592
+    ff_mdct_end(&s->imdct[1]);
2593
+
2594
+    av_freep(&s->subband_buffer);
2595
+    s->subband_size = 0;
2596
+
2597
+    av_freep(&s->x96_subband_buffer);
2598
+    s->x96_subband_size = 0;
2599
+
2600
+    av_freep(&s->output_buffer);
2601
+    s->output_size = 0;
2602
+}
0 2603
new file mode 100644
... ...
@@ -0,0 +1,206 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#ifndef AVCODEC_DCA_CORE_H
21
+#define AVCODEC_DCA_CORE_H
22
+
23
+#include "libavutil/common.h"
24
+#include "libavutil/float_dsp.h"
25
+#include "libavutil/fixed_dsp.h"
26
+#include "libavutil/mem.h"
27
+
28
+#include "avcodec.h"
29
+#include "internal.h"
30
+#include "get_bits.h"
31
+#include "dca.h"
32
+#include "dca_exss.h"
33
+#include "dcadsp.h"
34
+#include "dcadct.h"
35
+#include "fft.h"
36
+#include "synth_filter.h"
37
+
38
+#define DCA_CHANNELS            7
39
+#define DCA_SUBBANDS            32
40
+#define DCA_SUBBANDS_X96        64
41
+#define DCA_SUBFRAMES           16
42
+#define DCA_SUBBAND_SAMPLES     8
43
+#define DCA_PCMBLOCK_SAMPLES    32
44
+#define DCA_ADPCM_COEFFS        4
45
+#define DCA_LFE_HISTORY         8
46
+#define DCA_CODE_BOOKS          10
47
+#define DCA_ABITS_MAX           26
48
+
49
+#define DCA_CORE_CHANNELS_MAX       6
50
+#define DCA_DMIX_CHANNELS_MAX       4
51
+#define DCA_XXCH_CHANNELS_MAX       2
52
+#define DCA_EXSS_CHANNELS_MAX       8
53
+#define DCA_EXSS_CHSETS_MAX         4
54
+
55
+#define DCA_FILTER_MODE_X96     0x01
56
+#define DCA_FILTER_MODE_FIXED   0x02
57
+
58
+typedef struct DCADSPData {
59
+    union {
60
+        struct {
61
+            DECLARE_ALIGNED(32, float, hist1)[1024];
62
+            DECLARE_ALIGNED(32, float, hist2)[64];
63
+        } flt;
64
+        struct {
65
+            DECLARE_ALIGNED(32, int32_t, hist1)[1024];
66
+            DECLARE_ALIGNED(32, int32_t, hist2)[64];
67
+        } fix;
68
+    } u;
69
+    int offset;
70
+} DCADSPData;
71
+
72
+typedef struct DCACoreDecoder {
73
+    AVCodecContext  *avctx;
74
+    GetBitContext   gb;
75
+
76
+    // Bit stream header
77
+    int     crc_present;        ///< CRC present flag
78
+    int     npcmblocks;         ///< Number of PCM sample blocks
79
+    int     frame_size;         ///< Primary frame byte size
80
+    int     audio_mode;         ///< Audio channel arrangement
81
+    int     sample_rate;        ///< Core audio sampling frequency
82
+    int     bit_rate;           ///< Transmission bit rate
83
+    int     drc_present;        ///< Embedded dynamic range flag
84
+    int     ts_present;         ///< Embedded time stamp flag
85
+    int     aux_present;        ///< Auxiliary data flag
86
+    int     ext_audio_type;     ///< Extension audio descriptor flag
87
+    int     ext_audio_present;  ///< Extended coding flag
88
+    int     sync_ssf;           ///< Audio sync word insertion flag
89
+    int     lfe_present;        ///< Low frequency effects flag
90
+    int     predictor_history;  ///< Predictor history flag switch
91
+    int     filter_perfect;     ///< Multirate interpolator switch
92
+    int     source_pcm_res;     ///< Source PCM resolution
93
+    int     es_format;          ///< Extended surround (ES) mastering flag
94
+    int     sumdiff_front;      ///< Front sum/difference flag
95
+    int     sumdiff_surround;   ///< Surround sum/difference flag
96
+
97
+    // Primary audio coding header
98
+    int         nsubframes;     ///< Number of subframes
99
+    int         nchannels;      ///< Number of primary audio channels (incl. extension channels)
100
+    int         ch_mask;        ///< Speaker layout mask (incl. LFE and extension channels)
101
+    int8_t      nsubbands[DCA_CHANNELS];                ///< Subband activity count
102
+    int8_t      subband_vq_start[DCA_CHANNELS];         ///< High frequency VQ start subband
103
+    int8_t      joint_intensity_index[DCA_CHANNELS];    ///< Joint intensity coding index
104
+    int8_t      transition_mode_sel[DCA_CHANNELS];      ///< Transient mode code book
105
+    int8_t      scale_factor_sel[DCA_CHANNELS];         ///< Scale factor code book
106
+    int8_t      bit_allocation_sel[DCA_CHANNELS];       ///< Bit allocation quantizer select
107
+    int8_t      quant_index_sel[DCA_CHANNELS][DCA_CODE_BOOKS];  ///< Quantization index codebook select
108
+    int32_t     scale_factor_adj[DCA_CHANNELS][DCA_CODE_BOOKS]; ///< Scale factor adjustment
109
+
110
+    // Primary audio coding side information
111
+    int8_t      nsubsubframes[DCA_SUBFRAMES];   ///< Subsubframe count for each subframe
112
+    int8_t      prediction_mode[DCA_CHANNELS][DCA_SUBBANDS_X96];            ///< Prediction mode
113
+    int16_t     prediction_vq_index[DCA_CHANNELS][DCA_SUBBANDS_X96];        ///< Prediction coefficients VQ address
114
+    int8_t      bit_allocation[DCA_CHANNELS][DCA_SUBBANDS_X96];             ///< Bit allocation index
115
+    int8_t      transition_mode[DCA_SUBFRAMES][DCA_CHANNELS][DCA_SUBBANDS]; ///< Transition mode
116
+    int32_t     scale_factors[DCA_CHANNELS][DCA_SUBBANDS][2];               ///< Scale factors (2x for transients and X96)
117
+    int8_t      joint_scale_sel[DCA_CHANNELS];                              ///< Joint subband codebook select
118
+    int32_t     joint_scale_factors[DCA_CHANNELS][DCA_SUBBANDS_X96];        ///< Scale factors for joint subband coding
119
+
120
+    // Auxiliary data
121
+    int     prim_dmix_embedded; ///< Auxiliary dynamic downmix flag
122
+    int     prim_dmix_type;     ///< Auxiliary primary channel downmix type
123
+    int     prim_dmix_coeff[DCA_DMIX_CHANNELS_MAX * DCA_CORE_CHANNELS_MAX]; ///< Dynamic downmix code coefficients
124
+
125
+    // Core extensions
126
+    int     ext_audio_mask;     ///< Bit mask of fully decoded core extensions
127
+
128
+    // XCH extension data
129
+    int     xch_pos;    ///< Bit position of XCH frame in core substream
130
+
131
+    // XXCH extension data
132
+    int     xxch_crc_present;       ///< CRC presence flag for XXCH channel set header
133
+    int     xxch_mask_nbits;        ///< Number of bits for loudspeaker mask
134
+    int     xxch_core_mask;         ///< Core loudspeaker activity mask
135
+    int     xxch_spkr_mask;         ///< Loudspeaker layout mask
136
+    int     xxch_dmix_embedded;     ///< Downmix already performed by encoder
137
+    int     xxch_dmix_scale_inv;    ///< Downmix scale factor
138
+    int     xxch_dmix_mask[DCA_XXCH_CHANNELS_MAX];  ///< Downmix channel mapping mask
139
+    int     xxch_dmix_coeff[DCA_XXCH_CHANNELS_MAX * DCA_CORE_CHANNELS_MAX];     ///< Downmix coefficients
140
+    int     xxch_pos;   ///< Bit position of XXCH frame in core substream
141
+
142
+    // X96 extension data
143
+    int     x96_rev_no;         ///< X96 revision number
144
+    int     x96_crc_present;    ///< CRC presence flag for X96 channel set header
145
+    int     x96_nchannels;      ///< Number of primary channels in X96 extension
146
+    int     x96_high_res;       ///< X96 high resolution flag
147
+    int     x96_subband_start;  ///< First encoded subband in X96 extension
148
+    int     x96_rand;           ///< Random seed for generating samples for unallocated X96 subbands
149
+    int     x96_pos;            ///< Bit position of X96 frame in core substream
150
+
151
+    // Sample buffers
152
+    unsigned int    x96_subband_size;
153
+    int32_t         *x96_subband_buffer;    ///< X96 subband sample buffer base
154
+    int32_t         *x96_subband_samples[DCA_CHANNELS][DCA_SUBBANDS_X96];   ///< X96 subband samples
155
+
156
+    unsigned int    subband_size;
157
+    int32_t         *subband_buffer;    ///< Subband sample buffer base
158
+    int32_t         *subband_samples[DCA_CHANNELS][DCA_SUBBANDS];   ///< Subband samples
159
+    int32_t         *lfe_samples;    ///< Decimated LFE samples
160
+
161
+    // DSP contexts
162
+    DCADSPData              dcadsp_data[DCA_CHANNELS];    ///< FIR history buffers
163
+    DCADSPContext           *dcadsp;
164
+    DCADCTContext           dcadct;
165
+    FFTContext              imdct[2];
166
+    SynthFilterContext      synth;
167
+    AVFloatDSPContext       *float_dsp;
168
+    AVFixedDSPContext       *fixed_dsp;
169
+
170
+    // PCM output data
171
+    unsigned int    output_size;
172
+    void            *output_buffer;                         ///< PCM output buffer base
173
+    int32_t         *output_samples[DCA_SPEAKER_COUNT];     ///< PCM output for fixed point mode
174
+    int32_t         output_history_lfe_fixed;               ///< LFE PCM history for X96 filter
175
+    float           output_history_lfe_float;               ///< LFE PCM history for X96 filter
176
+
177
+    int     ch_remap[DCA_SPEAKER_COUNT];   ///< Channel to speaker map
178
+    int     request_mask;   ///< Requested channel layout (for stereo downmix)
179
+
180
+    int     npcmsamples;    ///< Number of PCM samples per channel
181
+    int     output_rate;    ///< Output sample rate (1x or 2x header rate)
182
+
183
+    int     filter_mode;    ///< Previous filtering mode for detecting changes
184
+} DCACoreDecoder;
185
+
186
+static inline int ff_dca_core_map_spkr(DCACoreDecoder *core, int spkr)
187
+{
188
+    if (core->ch_mask & (1U << spkr))
189
+        return spkr;
190
+    if (spkr == DCA_SPEAKER_Lss && (core->ch_mask & DCA_SPEAKER_MASK_Ls))
191
+        return DCA_SPEAKER_Ls;
192
+    if (spkr == DCA_SPEAKER_Rss && (core->ch_mask & DCA_SPEAKER_MASK_Rs))
193
+        return DCA_SPEAKER_Rs;
194
+    return -1;
195
+}
196
+
197
+int ff_dca_core_parse(DCACoreDecoder *s, uint8_t *data, int size);
198
+int ff_dca_core_parse_exss(DCACoreDecoder *s, uint8_t *data, DCAExssAsset *asset);
199
+int ff_dca_core_filter_fixed(DCACoreDecoder *s, int x96_synth);
200
+int ff_dca_core_filter_frame(DCACoreDecoder *s, AVFrame *frame);
201
+av_cold void ff_dca_core_flush(DCACoreDecoder *s);
202
+av_cold int ff_dca_core_init(DCACoreDecoder *s);
203
+av_cold void ff_dca_core_close(DCACoreDecoder *s);
204
+
205
+#endif
0 206
new file mode 100644
... ...
@@ -0,0 +1,514 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include "dcadec.h"
21
+#include "dcadata.h"
22
+
23
+static int count_chs_for_mask(int mask)
24
+{
25
+    return av_popcount(mask) + av_popcount(mask & 0xae66);
26
+}
27
+
28
+static void parse_xll_parameters(DCAExssParser *s, DCAExssAsset *asset)
29
+{
30
+    // Size of XLL data in extension substream
31
+    asset->xll_size = get_bits(&s->gb, s->exss_size_nbits) + 1;
32
+
33
+    // XLL sync word present flag
34
+    if (asset->xll_sync_present = get_bits1(&s->gb)) {
35
+        int xll_delay_nbits;
36
+
37
+        // Peak bit rate smoothing buffer size
38
+        skip_bits(&s->gb, 4);
39
+
40
+        // Number of bits for XLL decoding delay
41
+        xll_delay_nbits = get_bits(&s->gb, 5) + 1;
42
+
43
+        // Initial XLL decoding delay in frames
44
+        asset->xll_delay_nframes = get_bits_long(&s->gb, xll_delay_nbits);
45
+
46
+        // Number of bytes offset to XLL sync
47
+        asset->xll_sync_offset = get_bits(&s->gb, s->exss_size_nbits);
48
+    } else {
49
+        asset->xll_delay_nframes = 0;
50
+        asset->xll_sync_offset = 0;
51
+    }
52
+}
53
+
54
+static void parse_lbr_parameters(DCAExssParser *s, DCAExssAsset *asset)
55
+{
56
+    // Size of LBR component in extension substream
57
+    asset->lbr_size = get_bits(&s->gb, 14) + 1;
58
+
59
+    // LBR sync word present flag
60
+    if (get_bits1(&s->gb))
61
+        // LBR sync distance
62
+        skip_bits(&s->gb, 2);
63
+}
64
+
65
+static int parse_descriptor(DCAExssParser *s, DCAExssAsset *asset)
66
+{
67
+    int i, j, drc_present, descr_size, descr_pos = get_bits_count(&s->gb);
68
+
69
+    // Size of audio asset descriptor in bytes
70
+    descr_size = get_bits(&s->gb, 9) + 1;
71
+
72
+    // Audio asset identifier
73
+    asset->asset_index = get_bits(&s->gb, 3);
74
+
75
+    //
76
+    // Per stream static metadata
77
+    //
78
+
79
+    if (s->static_fields_present) {
80
+        // Asset type descriptor presence
81
+        if (get_bits1(&s->gb))
82
+            // Asset type descriptor
83
+            skip_bits(&s->gb, 4);
84
+
85
+        // Language descriptor presence
86
+        if (get_bits1(&s->gb))
87
+            // Language descriptor
88
+            skip_bits(&s->gb, 24);
89
+
90
+        // Additional textual information presence
91
+        if (get_bits1(&s->gb)) {
92
+            // Byte size of additional text info
93
+            int text_size = get_bits(&s->gb, 10) + 1;
94
+
95
+            // Sanity check available size
96
+            if (get_bits_left(&s->gb) < text_size * 8)
97
+                return AVERROR_INVALIDDATA;
98
+
99
+            // Additional textual information string
100
+            skip_bits_long(&s->gb, text_size * 8);
101
+        }
102
+
103
+        // PCM bit resolution
104
+        asset->pcm_bit_res = get_bits(&s->gb, 5) + 1;
105
+
106
+        // Maximum sample rate
107
+        asset->max_sample_rate = ff_dca_sampling_freqs[get_bits(&s->gb, 4)];
108
+
109
+        // Total number of channels
110
+        asset->nchannels_total = get_bits(&s->gb, 8) + 1;
111
+
112
+        // One to one map channel to speakers
113
+        if (asset->one_to_one_map_ch_to_spkr = get_bits1(&s->gb)) {
114
+            int spkr_mask_nbits = 0;
115
+            int spkr_remap_nsets;
116
+            int nspeakers[8];
117
+
118
+            // Embedded stereo flag
119
+            if (asset->nchannels_total > 2)
120
+                asset->embedded_stereo = get_bits1(&s->gb);
121
+
122
+            // Embedded 6 channels flag
123
+            if (asset->nchannels_total > 6)
124
+                asset->embedded_6ch = get_bits1(&s->gb);
125
+
126
+            // Speaker mask enabled flag
127
+            if (asset->spkr_mask_enabled = get_bits1(&s->gb)) {
128
+                // Number of bits for speaker activity mask
129
+                spkr_mask_nbits = (get_bits(&s->gb, 2) + 1) << 2;
130
+
131
+                // Loudspeaker activity mask
132
+                asset->spkr_mask = get_bits(&s->gb, spkr_mask_nbits);
133
+            }
134
+
135
+            // Number of speaker remapping sets
136
+            if ((spkr_remap_nsets = get_bits(&s->gb, 3)) && !spkr_mask_nbits) {
137
+                av_log(s->avctx, AV_LOG_ERROR, "Speaker mask disabled yet there are remapping sets\n");
138
+                return AVERROR_INVALIDDATA;
139
+            }
140
+
141
+            // Standard loudspeaker layout mask
142
+            for (i = 0; i < spkr_remap_nsets; i++)
143
+                nspeakers[i] = count_chs_for_mask(get_bits(&s->gb, spkr_mask_nbits));
144
+
145
+            for (i = 0; i < spkr_remap_nsets; i++) {
146
+                // Number of channels to be decoded for speaker remapping
147
+                int nch_for_remaps = get_bits(&s->gb, 5) + 1;
148
+
149
+                for (j = 0; j < nspeakers[i]; j++) {
150
+                    // Decoded channels to output speaker mapping mask
151
+                    int remap_ch_mask = get_bits_long(&s->gb, nch_for_remaps);
152
+
153
+                    // Loudspeaker remapping codes
154
+                    skip_bits_long(&s->gb, av_popcount(remap_ch_mask) * 5);
155
+                }
156
+            }
157
+        } else {
158
+            asset->embedded_stereo = 0;
159
+            asset->embedded_6ch = 0;
160
+            asset->spkr_mask_enabled = 0;
161
+            asset->spkr_mask = 0;
162
+
163
+            // Representation type
164
+            asset->representation_type = get_bits(&s->gb, 3);
165
+        }
166
+    }
167
+
168
+    //
169
+    // DRC, DNC and mixing metadata
170
+    //
171
+
172
+    // Dynamic range coefficient presence flag
173
+    drc_present = get_bits1(&s->gb);
174
+
175
+    // Code for dynamic range coefficient
176
+    if (drc_present)
177
+        skip_bits(&s->gb, 8);
178
+
179
+    // Dialog normalization presence flag
180
+    if (get_bits1(&s->gb))
181
+        // Dialog normalization code
182
+        skip_bits(&s->gb, 5);
183
+
184
+    // DRC for stereo downmix
185
+    if (drc_present && asset->embedded_stereo)
186
+        skip_bits(&s->gb, 8);
187
+
188
+    // Mixing metadata presence flag
189
+    if (s->mix_metadata_enabled && get_bits1(&s->gb)) {
190
+        int nchannels_dmix;
191
+
192
+        // External mixing flag
193
+        skip_bits1(&s->gb);
194
+
195
+        // Post mixing / replacement gain adjustment
196
+        skip_bits(&s->gb, 6);
197
+
198
+        // DRC prior to mixing
199
+        if (get_bits(&s->gb, 2) == 3)
200
+            // Custom code for mixing DRC
201
+            skip_bits(&s->gb, 8);
202
+        else
203
+            // Limit for mixing DRC
204
+            skip_bits(&s->gb, 3);
205
+
206
+        // Scaling type for channels of main audio
207
+        // Scaling parameters of main audio
208
+        if (get_bits1(&s->gb))
209
+            for (i = 0; i < s->nmixoutconfigs; i++)
210
+                skip_bits_long(&s->gb, 6 * s->nmixoutchs[i]);
211
+        else
212
+            skip_bits_long(&s->gb, 6 * s->nmixoutconfigs);
213
+
214
+        nchannels_dmix = asset->nchannels_total;
215
+        if (asset->embedded_6ch)
216
+            nchannels_dmix += 6;
217
+        if (asset->embedded_stereo)
218
+            nchannels_dmix += 2;
219
+
220
+        for (i = 0; i < s->nmixoutconfigs; i++) {
221
+            if (!s->nmixoutchs[i]) {
222
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid speaker layout mask for mixing configuration\n");
223
+                return AVERROR_INVALIDDATA;
224
+            }
225
+            for (j = 0; j < nchannels_dmix; j++) {
226
+                // Mix output mask
227
+                int mix_map_mask = get_bits(&s->gb, s->nmixoutchs[i]);
228
+
229
+                // Mixing coefficients
230
+                skip_bits_long(&s->gb, av_popcount(mix_map_mask) * 6);
231
+            }
232
+        }
233
+    }
234
+
235
+    //
236
+    // Decoder navigation data
237
+    //
238
+
239
+    // Coding mode for the asset
240
+    asset->coding_mode = get_bits(&s->gb, 2);
241
+
242
+    // Coding components used in asset
243
+    switch (asset->coding_mode) {
244
+    case 0: // Coding mode that may contain multiple coding components
245
+        asset->extension_mask = get_bits(&s->gb, 12);
246
+
247
+        if (asset->extension_mask & DCA_EXSS_CORE) {
248
+            // Size of core component in extension substream
249
+            asset->core_size = get_bits(&s->gb, 14) + 1;
250
+            // Core sync word present flag
251
+            if (get_bits1(&s->gb))
252
+                // Core sync distance
253
+                skip_bits(&s->gb, 2);
254
+        }
255
+
256
+        if (asset->extension_mask & DCA_EXSS_XBR)
257
+            // Size of XBR extension in extension substream
258
+            asset->xbr_size = get_bits(&s->gb, 14) + 1;
259
+
260
+        if (asset->extension_mask & DCA_EXSS_XXCH)
261
+            // Size of XXCH extension in extension substream
262
+            asset->xxch_size = get_bits(&s->gb, 14) + 1;
263
+
264
+        if (asset->extension_mask & DCA_EXSS_X96)
265
+            // Size of X96 extension in extension substream
266
+            asset->x96_size = get_bits(&s->gb, 12) + 1;
267
+
268
+        if (asset->extension_mask & DCA_EXSS_LBR)
269
+            parse_lbr_parameters(s, asset);
270
+
271
+        if (asset->extension_mask & DCA_EXSS_XLL)
272
+            parse_xll_parameters(s, asset);
273
+
274
+        if (asset->extension_mask & DCA_EXSS_RSV1)
275
+            skip_bits(&s->gb, 16);
276
+
277
+        if (asset->extension_mask & DCA_EXSS_RSV2)
278
+            skip_bits(&s->gb, 16);
279
+        break;
280
+
281
+    case 1: // Loss-less coding mode without CBR component
282
+        asset->extension_mask = DCA_EXSS_XLL;
283
+        parse_xll_parameters(s, asset);
284
+        break;
285
+
286
+    case 2: // Low bit rate mode
287
+        asset->extension_mask = DCA_EXSS_LBR;
288
+        parse_lbr_parameters(s, asset);
289
+        break;
290
+
291
+    case 3: // Auxiliary coding mode
292
+        asset->extension_mask = 0;
293
+
294
+        // Size of auxiliary coded data
295
+        skip_bits(&s->gb, 14);
296
+
297
+        // Auxiliary codec identification
298
+        skip_bits(&s->gb, 8);
299
+
300
+        // Aux sync word present flag
301
+        if (get_bits1(&s->gb))
302
+            // Aux sync distance
303
+            skip_bits(&s->gb, 3);
304
+        break;
305
+    }
306
+
307
+    if (asset->extension_mask & DCA_EXSS_XLL)
308
+        // DTS-HD stream ID
309
+        asset->hd_stream_id = get_bits(&s->gb, 3);
310
+
311
+    // One to one mixing flag
312
+    // Per channel main audio scaling flag
313
+    // Main audio scaling codes
314
+    // Decode asset in secondary decoder flag
315
+    // Revision 2 DRC metadata
316
+    // Reserved
317
+    // Zero pad
318
+    if (ff_dca_seek_bits(&s->gb, descr_pos + descr_size * 8)) {
319
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of EXSS asset descriptor\n");
320
+        return AVERROR_INVALIDDATA;
321
+    }
322
+
323
+    return 0;
324
+}
325
+
326
+static int set_exss_offsets(DCAExssAsset *asset)
327
+{
328
+    int offs = asset->asset_offset;
329
+    int size = asset->asset_size;
330
+
331
+    if (asset->extension_mask & DCA_EXSS_CORE) {
332
+        asset->core_offset = offs;
333
+        if (asset->core_size > size)
334
+            return AVERROR_INVALIDDATA;
335
+        offs += asset->core_size;
336
+        size -= asset->core_size;
337
+    }
338
+
339
+    if (asset->extension_mask & DCA_EXSS_XBR) {
340
+        asset->xbr_offset = offs;
341
+        if (asset->xbr_size > size)
342
+            return AVERROR_INVALIDDATA;
343
+        offs += asset->xbr_size;
344
+        size -= asset->xbr_size;
345
+    }
346
+
347
+    if (asset->extension_mask & DCA_EXSS_XXCH) {
348
+        asset->xxch_offset = offs;
349
+        if (asset->xxch_size > size)
350
+            return AVERROR_INVALIDDATA;
351
+        offs += asset->xxch_size;
352
+        size -= asset->xxch_size;
353
+    }
354
+
355
+    if (asset->extension_mask & DCA_EXSS_X96) {
356
+        asset->x96_offset = offs;
357
+        if (asset->x96_size > size)
358
+            return AVERROR_INVALIDDATA;
359
+        offs += asset->x96_size;
360
+        size -= asset->x96_size;
361
+    }
362
+
363
+    if (asset->extension_mask & DCA_EXSS_LBR) {
364
+        asset->lbr_offset = offs;
365
+        if (asset->lbr_size > size)
366
+            return AVERROR_INVALIDDATA;
367
+        offs += asset->lbr_size;
368
+        size -= asset->lbr_size;
369
+    }
370
+
371
+    if (asset->extension_mask & DCA_EXSS_XLL) {
372
+        asset->xll_offset = offs;
373
+        if (asset->xll_size > size)
374
+            return AVERROR_INVALIDDATA;
375
+        offs += asset->xll_size;
376
+        size -= asset->xll_size;
377
+    }
378
+
379
+    return 0;
380
+}
381
+
382
+int ff_dca_exss_parse(DCAExssParser *s, uint8_t *data, int size)
383
+{
384
+    int i, ret, offset, wide_hdr, header_size;
385
+
386
+    if ((ret = init_get_bits8(&s->gb, data, size)) < 0)
387
+        return ret;
388
+
389
+    // Extension substream sync word
390
+    skip_bits_long(&s->gb, 32);
391
+
392
+    // User defined bits
393
+    skip_bits(&s->gb, 8);
394
+
395
+    // Extension substream index
396
+    s->exss_index = get_bits(&s->gb, 2);
397
+
398
+    // Flag indicating short or long header size
399
+    wide_hdr = get_bits1(&s->gb);
400
+
401
+    // Extension substream header length
402
+    header_size = get_bits(&s->gb, 8 + 4 * wide_hdr) + 1;
403
+
404
+    // Check CRC
405
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
406
+        && ff_dca_check_crc(&s->gb, 32 + 8, header_size * 8)) {
407
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid EXSS header checksum\n");
408
+        return AVERROR_INVALIDDATA;
409
+    }
410
+
411
+    s->exss_size_nbits = 16 + 4 * wide_hdr;
412
+
413
+    // Number of bytes of extension substream
414
+    s->exss_size = get_bits(&s->gb, s->exss_size_nbits) + 1;
415
+    if (s->exss_size > size) {
416
+        av_log(s->avctx, AV_LOG_ERROR, "Packet too short for EXSS frame\n");
417
+        return AVERROR_INVALIDDATA;
418
+    }
419
+
420
+    // Per stream static fields presence flag
421
+    if (s->static_fields_present = get_bits1(&s->gb)) {
422
+        int active_exss_mask[8];
423
+
424
+        // Reference clock code
425
+        skip_bits(&s->gb, 2);
426
+
427
+        // Extension substream frame duration
428
+        skip_bits(&s->gb, 3);
429
+
430
+        // Timecode presence flag
431
+        if (get_bits1(&s->gb))
432
+            // Timecode data
433
+            skip_bits_long(&s->gb, 36);
434
+
435
+        // Number of defined audio presentations
436
+        s->npresents = get_bits(&s->gb, 3) + 1;
437
+        if (s->npresents > 1) {
438
+            avpriv_request_sample(s->avctx, "%d audio presentations", s->npresents);
439
+            return AVERROR_PATCHWELCOME;
440
+        }
441
+
442
+        // Number of audio assets in extension substream
443
+        s->nassets = get_bits(&s->gb, 3) + 1;
444
+        if (s->nassets > 1) {
445
+            avpriv_request_sample(s->avctx, "%d audio assets", s->nassets);
446
+            return AVERROR_PATCHWELCOME;
447
+        }
448
+
449
+        // Active extension substream mask for audio presentation
450
+        for (i = 0; i < s->npresents; i++)
451
+            active_exss_mask[i] = get_bits(&s->gb, s->exss_index + 1);
452
+
453
+        // Active audio asset mask
454
+        for (i = 0; i < s->npresents; i++)
455
+            skip_bits_long(&s->gb, av_popcount(active_exss_mask[i]) * 8);
456
+
457
+        // Mixing metadata enable flag
458
+        if (s->mix_metadata_enabled = get_bits1(&s->gb)) {
459
+            int spkr_mask_nbits;
460
+
461
+            // Mixing metadata adjustment level
462
+            skip_bits(&s->gb, 2);
463
+
464
+            // Number of bits for mixer output speaker activity mask
465
+            spkr_mask_nbits = (get_bits(&s->gb, 2) + 1) << 2;
466
+
467
+            // Number of mixing configurations
468
+            s->nmixoutconfigs = get_bits(&s->gb, 2) + 1;
469
+
470
+            // Speaker layout mask for mixer output channels
471
+            for (i = 0; i < s->nmixoutconfigs; i++)
472
+                s->nmixoutchs[i] = count_chs_for_mask(get_bits(&s->gb, spkr_mask_nbits));
473
+        }
474
+    } else {
475
+        s->npresents = 1;
476
+        s->nassets = 1;
477
+    }
478
+
479
+    // Size of encoded asset data in bytes
480
+    offset = header_size;
481
+    for (i = 0; i < s->nassets; i++) {
482
+        s->assets[i].asset_offset = offset;
483
+        s->assets[i].asset_size = get_bits(&s->gb, s->exss_size_nbits) + 1;
484
+        offset += s->assets[i].asset_size;
485
+        if (offset > s->exss_size) {
486
+            av_log(s->avctx, AV_LOG_ERROR, "EXSS asset out of bounds\n");
487
+            return AVERROR_INVALIDDATA;
488
+        }
489
+    }
490
+
491
+    // Audio asset descriptor
492
+    for (i = 0; i < s->nassets; i++) {
493
+        if ((ret = parse_descriptor(s, &s->assets[i])) < 0)
494
+            return ret;
495
+        if ((ret = set_exss_offsets(&s->assets[i])) < 0) {
496
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid extension size in EXSS asset descriptor\n");
497
+            return ret;
498
+        }
499
+    }
500
+
501
+    // Backward compatible core present
502
+    // Backward compatible core substream index
503
+    // Backward compatible core asset index
504
+    // Reserved
505
+    // Byte align
506
+    // CRC16 of extension substream header
507
+    if (ff_dca_seek_bits(&s->gb, header_size * 8)) {
508
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of EXSS header\n");
509
+        return AVERROR_INVALIDDATA;
510
+    }
511
+
512
+    return 0;
513
+}
0 514
new file mode 100644
... ...
@@ -0,0 +1,92 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#ifndef AVCODEC_DCA_EXSS_H
21
+#define AVCODEC_DCA_EXSS_H
22
+
23
+#include "libavutil/common.h"
24
+
25
+#include "avcodec.h"
26
+#include "get_bits.h"
27
+
28
+typedef struct DCAExssAsset {
29
+    int     asset_offset;   ///< Offset to asset data from start of substream
30
+    int     asset_size;     ///< Size of encoded asset data
31
+    int     asset_index;    ///< Audio asset identifier
32
+
33
+    int     pcm_bit_res;                ///< PCM bit resolution
34
+    int     max_sample_rate;            ///< Maximum sample rate
35
+    int     nchannels_total;            ///< Total number of channels
36
+    int     one_to_one_map_ch_to_spkr;  ///< One to one channel to speaker mapping flag
37
+    int     embedded_stereo;            ///< Embedded stereo flag
38
+    int     embedded_6ch;               ///< Embedded 6 channels flag
39
+    int     spkr_mask_enabled;          ///< Speaker mask enabled flag
40
+    int     spkr_mask;                  ///< Loudspeaker activity mask
41
+    int     representation_type;        ///< Representation type
42
+
43
+    int     coding_mode;        ///< Coding mode for the asset
44
+    int     extension_mask;     ///< Coding components used in asset
45
+
46
+    int     core_offset;    ///< Offset to core component from start of substream
47
+    int     core_size;      ///< Size of core component in extension substream
48
+
49
+    int     xbr_offset;     ///< Offset to XBR extension from start of substream
50
+    int     xbr_size;       ///< Size of XBR extension in extension substream
51
+
52
+    int     xxch_offset;    ///< Offset to XXCH extension from start of substream
53
+    int     xxch_size;      ///< Size of XXCH extension in extension substream
54
+
55
+    int     x96_offset;     ///< Offset to X96 extension from start of substream
56
+    int     x96_size;       ///< Size of X96 extension in extension substream
57
+
58
+    int     lbr_offset;     ///< Offset to LBR component from start of substream
59
+    int     lbr_size;       ///< Size of LBR component in extension substream
60
+
61
+    int     xll_offset;         ///< Offset to XLL data from start of substream
62
+    int     xll_size;           ///< Size of XLL data in extension substream
63
+    int     xll_sync_present;   ///< XLL sync word present flag
64
+    int     xll_delay_nframes;  ///< Initial XLL decoding delay in frames
65
+    int     xll_sync_offset;    ///< Number of bytes offset to XLL sync
66
+
67
+    int     hd_stream_id;   ///< DTS-HD stream ID
68
+} DCAExssAsset;
69
+
70
+typedef struct DCAExssParser {
71
+    AVCodecContext  *avctx;
72
+    GetBitContext   gb;
73
+
74
+    int     exss_index;         ///< Extension substream index
75
+    int     exss_size_nbits;    ///< Number of bits for extension substream size
76
+    int     exss_size;          ///< Number of bytes of extension substream
77
+
78
+    int     static_fields_present;  ///< Per stream static fields presence flag
79
+    int     npresents;  ///< Number of defined audio presentations
80
+    int     nassets;    ///< Number of audio assets in extension substream
81
+
82
+    int     mix_metadata_enabled;   ///< Mixing metadata enable flag
83
+    int     nmixoutconfigs;         ///< Number of mixing configurations
84
+    int     nmixoutchs[4];          ///< Speaker layout mask for mixer output channels
85
+
86
+    DCAExssAsset   assets[1];    ///< Audio asset descriptors
87
+} DCAExssParser;
88
+
89
+int ff_dca_exss_parse(DCAExssParser *s, uint8_t *data, int size);
90
+
91
+#endif
0 92
new file mode 100644
... ...
@@ -0,0 +1,1499 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include "dcadec.h"
21
+#include "dcadata.h"
22
+#include "dcamath.h"
23
+#include "dca_syncwords.h"
24
+#include "unary.h"
25
+
26
+static int get_linear(GetBitContext *gb, int n)
27
+{
28
+    unsigned int v = get_bits_long(gb, n);
29
+    return (v >> 1) ^ -(v & 1);
30
+}
31
+
32
+static int get_rice_un(GetBitContext *gb, int k)
33
+{
34
+    unsigned int v = get_unary(gb, 1, 128);
35
+    return (v << k) | get_bits_long(gb, k);
36
+}
37
+
38
+static int get_rice(GetBitContext *gb, int k)
39
+{
40
+    unsigned int v = get_rice_un(gb, k);
41
+    return (v >> 1) ^ -(v & 1);
42
+}
43
+
44
+static void get_array(GetBitContext *gb, int32_t *array, int size, int n)
45
+{
46
+    int i;
47
+
48
+    for (i = 0; i < size; i++)
49
+        array[i] = get_bits(gb, n);
50
+}
51
+
52
+static void get_linear_array(GetBitContext *gb, int32_t *array, int size, int n)
53
+{
54
+    int i;
55
+
56
+    if (n == 0)
57
+        memset(array, 0, sizeof(*array) * size);
58
+    else for (i = 0; i < size; i++)
59
+        array[i] = get_linear(gb, n);
60
+}
61
+
62
+static void get_rice_array(GetBitContext *gb, int32_t *array, int size, int k)
63
+{
64
+    int i;
65
+
66
+    for (i = 0; i < size; i++)
67
+        array[i] = get_rice(gb, k);
68
+}
69
+
70
+static int parse_dmix_coeffs(DCAXllDecoder *s, DCAXllChSet *c)
71
+{
72
+    // Size of downmix coefficient matrix
73
+    int m = c->primary_chset ? ff_dca_dmix_primary_nch[c->dmix_type] : c->hier_ofs;
74
+    int i, j, *coeff_ptr = c->dmix_coeff;
75
+
76
+    for (i = 0; i < m; i++) {
77
+        int code, sign, coeff, scale, scale_inv = 0;
78
+        unsigned int index;
79
+
80
+        // Downmix scale (only for non-primary channel sets)
81
+        if (!c->primary_chset) {
82
+            code = get_bits(&s->gb, 9);
83
+            sign = (code >> 8) - 1;
84
+            index = (code & 0xff) - FF_DCA_DMIXTABLE_OFFSET;
85
+            if (index >= FF_DCA_INV_DMIXTABLE_SIZE) {
86
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL downmix scale index\n");
87
+                return AVERROR_INVALIDDATA;
88
+            }
89
+            scale = ff_dca_dmixtable[index + FF_DCA_DMIXTABLE_OFFSET];
90
+            scale_inv = ff_dca_inv_dmixtable[index];
91
+            c->dmix_scale[i] = (scale ^ sign) - sign;
92
+            c->dmix_scale_inv[i] = (scale_inv ^ sign) - sign;
93
+        }
94
+
95
+        // Downmix coefficients
96
+        for (j = 0; j < c->nchannels; j++) {
97
+            code = get_bits(&s->gb, 9);
98
+            sign = (code >> 8) - 1;
99
+            index = code & 0xff;
100
+            if (index >= FF_DCA_DMIXTABLE_SIZE) {
101
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL downmix coefficient index\n");
102
+                return AVERROR_INVALIDDATA;
103
+            }
104
+            coeff = ff_dca_dmixtable[index];
105
+            if (!c->primary_chset)
106
+                // Multiply by |InvDmixScale| to get |UndoDmixScale|
107
+                coeff = mul16(scale_inv, coeff);
108
+            *coeff_ptr++ = (coeff ^ sign) - sign;
109
+        }
110
+    }
111
+
112
+    return 0;
113
+}
114
+
115
+static int chs_parse_header(DCAXllDecoder *s, DCAXllChSet *c, DCAExssAsset *asset)
116
+{
117
+    int i, j, k, ret, band, header_size, header_pos = get_bits_count(&s->gb);
118
+    DCAXllChSet *p = &s->chset[0];
119
+    DCAXllBand *b;
120
+
121
+    // Size of channel set sub-header
122
+    header_size = get_bits(&s->gb, 10) + 1;
123
+
124
+    // Check CRC
125
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
126
+        && ff_dca_check_crc(&s->gb, header_pos, header_pos + header_size * 8)) {
127
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL sub-header checksum\n");
128
+        return AVERROR_INVALIDDATA;
129
+    }
130
+
131
+    // Number of channels in the channel set
132
+    c->nchannels = get_bits(&s->gb, 4) + 1;
133
+    if (c->nchannels > DCA_XLL_CHANNELS_MAX) {
134
+        avpriv_request_sample(s->avctx, "%d XLL channels", c->nchannels);
135
+        return AVERROR_PATCHWELCOME;
136
+    }
137
+
138
+    // Residual type
139
+    c->residual_encode = get_bits(&s->gb, c->nchannels);
140
+
141
+    // PCM bit resolution
142
+    c->pcm_bit_res = get_bits(&s->gb, 5) + 1;
143
+
144
+    // Storage unit width
145
+    c->storage_bit_res = get_bits(&s->gb, 5) + 1;
146
+    if (c->storage_bit_res != 16 && c->storage_bit_res != 24) {
147
+        avpriv_request_sample(s->avctx, "%d-bit XLL storage resolution", c->storage_bit_res);
148
+        return AVERROR_PATCHWELCOME;
149
+    }
150
+
151
+    if (c->pcm_bit_res > c->storage_bit_res) {
152
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid PCM bit resolution for XLL channel set (%d > %d)\n", c->pcm_bit_res, c->storage_bit_res);
153
+        return AVERROR_INVALIDDATA;
154
+    }
155
+
156
+    // Original sampling frequency
157
+    c->freq = ff_dca_sampling_freqs[get_bits(&s->gb, 4)];
158
+    if (c->freq > 192000) {
159
+        avpriv_request_sample(s->avctx, "%d Hz XLL sampling frequency", c->freq);
160
+        return AVERROR_PATCHWELCOME;
161
+    }
162
+
163
+    // Sampling frequency modifier
164
+    if (get_bits(&s->gb, 2)) {
165
+        avpriv_request_sample(s->avctx, "XLL sampling frequency modifier");
166
+        return AVERROR_PATCHWELCOME;
167
+    }
168
+
169
+    // Which replacement set this channel set is member of
170
+    if (get_bits(&s->gb, 2)) {
171
+        avpriv_request_sample(s->avctx, "XLL replacement set");
172
+        return AVERROR_PATCHWELCOME;
173
+    }
174
+
175
+    if (asset->one_to_one_map_ch_to_spkr) {
176
+        // Primary channel set flag
177
+        c->primary_chset = get_bits1(&s->gb);
178
+        if (c->primary_chset != (c == p)) {
179
+            av_log(s->avctx, AV_LOG_ERROR, "The first (and only) XLL channel set must be primary\n");
180
+            return AVERROR_INVALIDDATA;
181
+        }
182
+
183
+        // Downmix coefficients present in stream
184
+        c->dmix_coeffs_present = get_bits1(&s->gb);
185
+
186
+        // Downmix already performed by encoder
187
+        c->dmix_embedded = c->dmix_coeffs_present && get_bits1(&s->gb);
188
+
189
+        // Downmix type
190
+        if (c->dmix_coeffs_present && c->primary_chset) {
191
+            c->dmix_type = get_bits(&s->gb, 3);
192
+            if (c->dmix_type >= DCA_DMIX_TYPE_COUNT) {
193
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL primary channel set downmix type\n");
194
+                return AVERROR_INVALIDDATA;
195
+            }
196
+        }
197
+
198
+        // Whether the channel set is part of a hierarchy
199
+        c->hier_chset = get_bits1(&s->gb);
200
+        if (!c->hier_chset && s->nchsets != 1) {
201
+            avpriv_request_sample(s->avctx, "XLL channel set outside of hierarchy");
202
+            return AVERROR_PATCHWELCOME;
203
+        }
204
+
205
+        // Downmix coefficients
206
+        if (c->dmix_coeffs_present && (ret = parse_dmix_coeffs(s, c)) < 0)
207
+            return ret;
208
+
209
+        // Channel mask enabled
210
+        if (!get_bits1(&s->gb)) {
211
+            avpriv_request_sample(s->avctx, "Disabled XLL channel mask");
212
+            return AVERROR_PATCHWELCOME;
213
+        }
214
+
215
+        // Channel mask for set
216
+        c->ch_mask = get_bits_long(&s->gb, s->ch_mask_nbits);
217
+        if (av_popcount(c->ch_mask) != c->nchannels) {
218
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL channel mask\n");
219
+            return AVERROR_INVALIDDATA;
220
+        }
221
+
222
+        // Build the channel to speaker map
223
+        for (i = 0, j = 0; i < s->ch_mask_nbits; i++)
224
+            if (c->ch_mask & (1U << i))
225
+                c->ch_remap[j++] = i;
226
+    } else {
227
+        // Mapping coeffs present flag
228
+        if (c->nchannels != 2 || s->nchsets != 1 || get_bits1(&s->gb)) {
229
+            avpriv_request_sample(s->avctx, "Custom XLL channel to speaker mapping");
230
+            return AVERROR_PATCHWELCOME;
231
+        }
232
+
233
+        // Setup for LtRt decoding
234
+        c->primary_chset = 1;
235
+        c->dmix_coeffs_present = 0;
236
+        c->dmix_embedded = 0;
237
+        c->hier_chset = 0;
238
+        c->ch_mask = DCA_SPEAKER_LAYOUT_STEREO;
239
+        c->ch_remap[0] = DCA_SPEAKER_L;
240
+        c->ch_remap[1] = DCA_SPEAKER_R;
241
+    }
242
+
243
+    if (c->freq > 96000) {
244
+        // Extra frequency bands flag
245
+        if (get_bits1(&s->gb)) {
246
+            avpriv_request_sample(s->avctx, "Extra XLL frequency bands");
247
+            return AVERROR_PATCHWELCOME;
248
+        }
249
+        c->nfreqbands = 2;
250
+    } else {
251
+        c->nfreqbands = 1;
252
+    }
253
+
254
+    // Set the sampling frequency to that of the first frequency band.
255
+    // Frequency will be doubled again after bands assembly.
256
+    c->freq >>= c->nfreqbands - 1;
257
+
258
+    // Verify that all channel sets have the same audio characteristics
259
+    if (c != p && (c->nfreqbands != p->nfreqbands || c->freq != p->freq
260
+                   || c->pcm_bit_res != p->pcm_bit_res
261
+                   || c->storage_bit_res != p->storage_bit_res)) {
262
+        avpriv_request_sample(s->avctx, "Different XLL audio characteristics");
263
+        return AVERROR_PATCHWELCOME;
264
+    }
265
+
266
+    // Determine number of bits to read bit allocation coding parameter
267
+    if (c->storage_bit_res > 16)
268
+        c->nabits = 5;
269
+    else if (c->storage_bit_res > 8)
270
+        c->nabits = 4;
271
+    else
272
+        c->nabits = 3;
273
+
274
+    // Account for embedded downmix and decimator saturation
275
+    if ((s->nchsets > 1 || c->nfreqbands > 1) && c->nabits < 5)
276
+        c->nabits++;
277
+
278
+    for (band = 0, b = c->bands; band < c->nfreqbands; band++, b++) {
279
+        // Pairwise channel decorrelation
280
+        if ((b->decor_enabled = get_bits1(&s->gb)) && c->nchannels > 1) {
281
+            int ch_nbits = av_ceil_log2(c->nchannels);
282
+
283
+            // Original channel order
284
+            for (i = 0; i < c->nchannels; i++) {
285
+                b->orig_order[i] = get_bits(&s->gb, ch_nbits);
286
+                if (b->orig_order[i] >= c->nchannels) {
287
+                    av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL original channel order\n");
288
+                    return AVERROR_INVALIDDATA;
289
+                }
290
+            }
291
+
292
+            // Pairwise channel coefficients
293
+            for (i = 0; i < c->nchannels / 2; i++)
294
+                b->decor_coeff[i] = get_bits1(&s->gb) ? get_linear(&s->gb, 7) : 0;
295
+        } else {
296
+            for (i = 0; i < c->nchannels; i++)
297
+                b->orig_order[i] = i;
298
+            for (i = 0; i < c->nchannels / 2; i++)
299
+                b->decor_coeff[i] = 0;
300
+        }
301
+
302
+        // Adaptive predictor order
303
+        b->highest_pred_order = 0;
304
+        for (i = 0; i < c->nchannels; i++) {
305
+            b->adapt_pred_order[i] = get_bits(&s->gb, 4);
306
+            if (b->adapt_pred_order[i] > b->highest_pred_order)
307
+                b->highest_pred_order = b->adapt_pred_order[i];
308
+        }
309
+        if (b->highest_pred_order > s->nsegsamples) {
310
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL adaptive predicition order\n");
311
+            return AVERROR_INVALIDDATA;
312
+        }
313
+
314
+        // Fixed predictor order
315
+        for (i = 0; i < c->nchannels; i++)
316
+            b->fixed_pred_order[i] = b->adapt_pred_order[i] ? 0 : get_bits(&s->gb, 2);
317
+
318
+        // Adaptive predictor quantized reflection coefficients
319
+        for (i = 0; i < c->nchannels; i++) {
320
+            for (j = 0; j < b->adapt_pred_order[i]; j++) {
321
+                k = get_linear(&s->gb, 8);
322
+                if (k == -128) {
323
+                    av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL reflection coefficient index\n");
324
+                    return AVERROR_INVALIDDATA;
325
+                }
326
+                if (k < 0)
327
+                    b->adapt_refl_coeff[i][j] = -(int)ff_dca_xll_refl_coeff[-k];
328
+                else
329
+                    b->adapt_refl_coeff[i][j] =  (int)ff_dca_xll_refl_coeff[ k];
330
+            }
331
+        }
332
+
333
+        // Downmix performed by encoder in extension frequency band
334
+        b->dmix_embedded = c->dmix_embedded && (band == 0 || get_bits1(&s->gb));
335
+
336
+        // MSB/LSB split flag in extension frequency band
337
+        if ((band == 0 && s->scalable_lsbs) || (band != 0 && get_bits1(&s->gb))) {
338
+            // Size of LSB section in any segment
339
+            b->lsb_section_size = get_bits_long(&s->gb, s->seg_size_nbits);
340
+            if (b->lsb_section_size < 0 || b->lsb_section_size > s->frame_size) {
341
+                av_log(s->avctx, AV_LOG_ERROR, "Invalid LSB section size\n");
342
+                return AVERROR_INVALIDDATA;
343
+            }
344
+
345
+            // Account for optional CRC bytes after LSB section
346
+            if (b->lsb_section_size && (s->band_crc_present > 2 ||
347
+                                        (band == 0 && s->band_crc_present > 1)))
348
+                b->lsb_section_size += 2;
349
+
350
+            // Number of bits to represent the samples in LSB part
351
+            for (i = 0; i < c->nchannels; i++) {
352
+                b->nscalablelsbs[i] = get_bits(&s->gb, 4);
353
+                if (b->nscalablelsbs[i] && !b->lsb_section_size) {
354
+                    av_log(s->avctx, AV_LOG_ERROR, "LSB section missing with non-zero LSB width\n");
355
+                    return AVERROR_INVALIDDATA;
356
+                }
357
+            }
358
+        } else {
359
+            b->lsb_section_size = 0;
360
+            for (i = 0; i < c->nchannels; i++)
361
+                b->nscalablelsbs[i] = 0;
362
+        }
363
+
364
+        // Scalable resolution flag in extension frequency band
365
+        if ((band == 0 && s->scalable_lsbs) || (band != 0 && get_bits1(&s->gb))) {
366
+            // Number of bits discarded by authoring
367
+            for (i = 0; i < c->nchannels; i++)
368
+                b->bit_width_adjust[i] = get_bits(&s->gb, 4);
369
+        } else {
370
+            for (i = 0; i < c->nchannels; i++)
371
+                b->bit_width_adjust[i] = 0;
372
+        }
373
+    }
374
+
375
+    // Reserved
376
+    // Byte align
377
+    // CRC16 of channel set sub-header
378
+    if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8)) {
379
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL sub-header\n");
380
+        return AVERROR_INVALIDDATA;
381
+    }
382
+
383
+    return 0;
384
+}
385
+
386
+static int chs_alloc_msb_band_data(DCAXllDecoder *s, DCAXllChSet *c)
387
+{
388
+    int ndecisamples = c->nfreqbands > 1 ? DCA_XLL_DECI_HISTORY_MAX : 0;
389
+    int nchsamples = s->nframesamples + ndecisamples;
390
+    int i, j, nsamples = nchsamples * c->nchannels * c->nfreqbands;
391
+    int32_t *ptr;
392
+
393
+    // Reallocate MSB sample buffer
394
+    av_fast_malloc(&c->sample_buffer[0], &c->sample_size[0], nsamples * sizeof(int32_t));
395
+    if (!c->sample_buffer[0])
396
+        return AVERROR(ENOMEM);
397
+
398
+    ptr = c->sample_buffer[0] + ndecisamples;
399
+    for (i = 0; i < c->nfreqbands; i++) {
400
+        for (j = 0; j < c->nchannels; j++) {
401
+            c->bands[i].msb_sample_buffer[j] = ptr;
402
+            ptr += nchsamples;
403
+        }
404
+    }
405
+
406
+    return 0;
407
+}
408
+
409
+static int chs_alloc_lsb_band_data(DCAXllDecoder *s, DCAXllChSet *c)
410
+{
411
+    int i, j, nsamples = 0;
412
+    int32_t *ptr;
413
+
414
+    // Determine number of frequency bands that have MSB/LSB split
415
+    for (i = 0; i < c->nfreqbands; i++)
416
+        if (c->bands[i].lsb_section_size)
417
+            nsamples += s->nframesamples * c->nchannels;
418
+    if (!nsamples)
419
+        return 0;
420
+
421
+    // Reallocate LSB sample buffer
422
+    av_fast_malloc(&c->sample_buffer[1], &c->sample_size[1], nsamples * sizeof(int32_t));
423
+    if (!c->sample_buffer[1])
424
+        return AVERROR(ENOMEM);
425
+
426
+    ptr = c->sample_buffer[1];
427
+    for (i = 0; i < c->nfreqbands; i++) {
428
+        if (c->bands[i].lsb_section_size) {
429
+            for (j = 0; j < c->nchannels; j++) {
430
+                c->bands[i].lsb_sample_buffer[j] = ptr;
431
+                ptr += s->nframesamples;
432
+            }
433
+        } else {
434
+            for (j = 0; j < c->nchannels; j++)
435
+                c->bands[i].lsb_sample_buffer[j] = NULL;
436
+        }
437
+    }
438
+
439
+    return 0;
440
+}
441
+
442
+static int chs_parse_band_data(DCAXllDecoder *s, DCAXllChSet *c, int band, int seg, int band_data_end)
443
+{
444
+    DCAXllBand *b = &c->bands[band];
445
+    int i, j, k;
446
+
447
+    // Start unpacking MSB portion of the segment
448
+    if (!(seg && get_bits1(&s->gb))) {
449
+        // Unpack segment type
450
+        // 0 - distinct coding parameters for each channel
451
+        // 1 - common coding parameters for all channels
452
+        c->seg_common = get_bits1(&s->gb);
453
+
454
+        // Determine number of coding parameters encoded in segment
455
+        k = c->seg_common ? 1 : c->nchannels;
456
+
457
+        // Unpack Rice coding parameters
458
+        for (i = 0; i < k; i++) {
459
+            // Unpack Rice coding flag
460
+            // 0 - linear code, 1 - Rice code
461
+            c->rice_code_flag[i] = get_bits1(&s->gb);
462
+            if (!c->seg_common && c->rice_code_flag[i]) {
463
+                // Unpack Hybrid Rice coding flag
464
+                // 0 - Rice code, 1 - Hybrid Rice code
465
+                if (get_bits1(&s->gb))
466
+                    // Unpack binary code length for isolated samples
467
+                    c->bitalloc_hybrid_linear[i] = get_bits(&s->gb, c->nabits) + 1;
468
+                else
469
+                    // 0 indicates no Hybrid Rice coding
470
+                    c->bitalloc_hybrid_linear[i] = 0;
471
+            } else {
472
+                // 0 indicates no Hybrid Rice coding
473
+                c->bitalloc_hybrid_linear[i] = 0;
474
+            }
475
+        }
476
+
477
+        // Unpack coding parameters
478
+        for (i = 0; i < k; i++) {
479
+            if (seg == 0) {
480
+                // Unpack coding parameter for part A of segment 0
481
+                c->bitalloc_part_a[i] = get_bits(&s->gb, c->nabits);
482
+
483
+                // Adjust for the linear code
484
+                if (!c->rice_code_flag[i] && c->bitalloc_part_a[i])
485
+                    c->bitalloc_part_a[i]++;
486
+
487
+                if (!c->seg_common)
488
+                    c->nsamples_part_a[i] = b->adapt_pred_order[i];
489
+                else
490
+                    c->nsamples_part_a[i] = b->highest_pred_order;
491
+            } else {
492
+                c->bitalloc_part_a[i] = 0;
493
+                c->nsamples_part_a[i] = 0;
494
+            }
495
+
496
+            // Unpack coding parameter for part B of segment
497
+            c->bitalloc_part_b[i] = get_bits(&s->gb, c->nabits);
498
+
499
+            // Adjust for the linear code
500
+            if (!c->rice_code_flag[i] && c->bitalloc_part_b[i])
501
+                c->bitalloc_part_b[i]++;
502
+        }
503
+    }
504
+
505
+    // Unpack entropy codes
506
+    for (i = 0; i < c->nchannels; i++) {
507
+        int32_t *part_a, *part_b;
508
+        int nsamples_part_b;
509
+
510
+        // Select index of coding parameters
511
+        k = c->seg_common ? 0 : i;
512
+
513
+        // Slice the segment into parts A and B
514
+        part_a = b->msb_sample_buffer[i] + seg * s->nsegsamples;
515
+        part_b = part_a + c->nsamples_part_a[k];
516
+        nsamples_part_b = s->nsegsamples - c->nsamples_part_a[k];
517
+
518
+        if (get_bits_left(&s->gb) < 0)
519
+            return AVERROR_INVALIDDATA;
520
+
521
+        if (!c->rice_code_flag[k]) {
522
+            // Linear codes
523
+            // Unpack all residuals of part A of segment 0
524
+            get_linear_array(&s->gb, part_a, c->nsamples_part_a[k],
525
+                             c->bitalloc_part_a[k]);
526
+
527
+            // Unpack all residuals of part B of segment 0 and others
528
+            get_linear_array(&s->gb, part_b, nsamples_part_b,
529
+                             c->bitalloc_part_b[k]);
530
+        } else {
531
+            // Rice codes
532
+            // Unpack all residuals of part A of segment 0
533
+            get_rice_array(&s->gb, part_a, c->nsamples_part_a[k],
534
+                           c->bitalloc_part_a[k]);
535
+
536
+            if (c->bitalloc_hybrid_linear[k]) {
537
+                // Hybrid Rice codes
538
+                // Unpack the number of isolated samples
539
+                int nisosamples = get_bits(&s->gb, s->nsegsamples_log2);
540
+
541
+                // Set all locations to 0
542
+                memset(part_b, 0, sizeof(*part_b) * nsamples_part_b);
543
+
544
+                // Extract the locations of isolated samples and flag by -1
545
+                for (j = 0; j < nisosamples; j++) {
546
+                    int loc = get_bits(&s->gb, s->nsegsamples_log2);
547
+                    if (loc >= nsamples_part_b) {
548
+                        av_log(s->avctx, AV_LOG_ERROR, "Invalid isolated sample location\n");
549
+                        return AVERROR_INVALIDDATA;
550
+                    }
551
+                    part_b[loc] = -1;
552
+                }
553
+
554
+                // Unpack all residuals of part B of segment 0 and others
555
+                for (j = 0; j < nsamples_part_b; j++) {
556
+                    if (part_b[j])
557
+                        part_b[j] = get_linear(&s->gb, c->bitalloc_hybrid_linear[k]);
558
+                    else
559
+                        part_b[j] = get_rice(&s->gb, c->bitalloc_part_b[k]);
560
+                }
561
+            } else {
562
+                // Rice codes
563
+                // Unpack all residuals of part B of segment 0 and others
564
+                get_rice_array(&s->gb, part_b, nsamples_part_b, c->bitalloc_part_b[k]);
565
+            }
566
+        }
567
+    }
568
+
569
+    // Unpack decimator history for frequency band 1
570
+    if (seg == 0 && band == 1) {
571
+        int nbits = get_bits(&s->gb, 5) + 1;
572
+        for (i = 0; i < c->nchannels; i++)
573
+            for (j = 1; j < DCA_XLL_DECI_HISTORY_MAX; j++)
574
+                c->deci_history[i][j] = get_sbits_long(&s->gb, nbits);
575
+    }
576
+
577
+    // Start unpacking LSB portion of the segment
578
+    if (b->lsb_section_size) {
579
+        // Skip to the start of LSB portion
580
+        if (ff_dca_seek_bits(&s->gb, band_data_end - b->lsb_section_size * 8)) {
581
+            av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL band data\n");
582
+            return AVERROR_INVALIDDATA;
583
+        }
584
+
585
+        // Unpack all LSB parts of residuals of this segment
586
+        for (i = 0; i < c->nchannels; i++) {
587
+            if (b->nscalablelsbs[i]) {
588
+                get_array(&s->gb,
589
+                          b->lsb_sample_buffer[i] + seg * s->nsegsamples,
590
+                          s->nsegsamples, b->nscalablelsbs[i]);
591
+            }
592
+        }
593
+    }
594
+
595
+    // Skip to the end of band data
596
+    if (ff_dca_seek_bits(&s->gb, band_data_end)) {
597
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL band data\n");
598
+        return AVERROR_INVALIDDATA;
599
+    }
600
+
601
+    return 0;
602
+}
603
+
604
+static void av_cold chs_clear_band_data(DCAXllDecoder *s, DCAXllChSet *c, int band, int seg)
605
+{
606
+    DCAXllBand *b = &c->bands[band];
607
+    int i, offset, nsamples;
608
+
609
+    if (seg < 0) {
610
+        offset = 0;
611
+        nsamples = s->nframesamples;
612
+    } else {
613
+        offset = seg * s->nsegsamples;
614
+        nsamples = s->nsegsamples;
615
+    }
616
+
617
+    for (i = 0; i < c->nchannels; i++) {
618
+        memset(b->msb_sample_buffer[i] + offset, 0, nsamples * sizeof(int32_t));
619
+        if (b->lsb_section_size)
620
+            memset(b->lsb_sample_buffer[i] + offset, 0, nsamples * sizeof(int32_t));
621
+    }
622
+
623
+    if (seg <= 0 && band)
624
+        memset(c->deci_history, 0, sizeof(c->deci_history));
625
+
626
+    if (seg < 0) {
627
+        memset(b->nscalablelsbs, 0, sizeof(b->nscalablelsbs));
628
+        memset(b->bit_width_adjust, 0, sizeof(b->bit_width_adjust));
629
+    }
630
+}
631
+
632
+static void chs_filter_band_data(DCAXllDecoder *s, DCAXllChSet *c, int band)
633
+{
634
+    DCAXllBand *b = &c->bands[band];
635
+    int nsamples = s->nframesamples;
636
+    int i, j, k;
637
+
638
+    // Inverse adaptive or fixed prediction
639
+    for (i = 0; i < c->nchannels; i++) {
640
+        int32_t *buf = b->msb_sample_buffer[i];
641
+        int order = b->adapt_pred_order[i];
642
+        if (order > 0) {
643
+            int coeff[DCA_XLL_ADAPT_PRED_ORDER_MAX];
644
+            // Conversion from reflection coefficients to direct form coefficients
645
+            for (j = 0; j < order; j++) {
646
+                int rc = b->adapt_refl_coeff[i][j];
647
+                for (k = 0; k < (j + 1) / 2; k++) {
648
+                    int tmp1 = coeff[    k    ];
649
+                    int tmp2 = coeff[j - k - 1];
650
+                    coeff[    k    ] = tmp1 + mul16(rc, tmp2);
651
+                    coeff[j - k - 1] = tmp2 + mul16(rc, tmp1);
652
+                }
653
+                coeff[j] = rc;
654
+            }
655
+            // Inverse adaptive prediction
656
+            for (j = 0; j < nsamples - order; j++) {
657
+                int64_t err = 0;
658
+                for (k = 0; k < order; k++)
659
+                    err += (int64_t)buf[j + k] * coeff[order - k - 1];
660
+                buf[j + k] -= clip23(norm16(err));
661
+            }
662
+        } else {
663
+            // Inverse fixed coefficient prediction
664
+            for (j = 0; j < b->fixed_pred_order[i]; j++)
665
+                for (k = 1; k < nsamples; k++)
666
+                    buf[k] += buf[k - 1];
667
+        }
668
+    }
669
+
670
+    // Inverse pairwise channel decorrellation
671
+    if (b->decor_enabled) {
672
+        int32_t *tmp[DCA_XLL_CHANNELS_MAX];
673
+
674
+        for (i = 0; i < c->nchannels / 2; i++) {
675
+            int coeff = b->decor_coeff[i];
676
+            if (coeff) {
677
+                s->dcadsp->decor(b->msb_sample_buffer[i * 2 + 1],
678
+                                 b->msb_sample_buffer[i * 2    ],
679
+                                 coeff, nsamples);
680
+            }
681
+        }
682
+
683
+        // Reorder channel pointers to the original order
684
+        for (i = 0; i < c->nchannels; i++)
685
+            tmp[i] = b->msb_sample_buffer[i];
686
+
687
+        for (i = 0; i < c->nchannels; i++)
688
+            b->msb_sample_buffer[b->orig_order[i]] = tmp[i];
689
+    }
690
+
691
+    // Map output channel pointers for frequency band 0
692
+    if (c->nfreqbands == 1)
693
+        for (i = 0; i < c->nchannels; i++)
694
+            s->output_samples[c->ch_remap[i]] = b->msb_sample_buffer[i];
695
+}
696
+
697
+static int chs_get_lsb_width(DCAXllDecoder *s, DCAXllChSet *c, int band, int ch)
698
+{
699
+    int adj = c->bands[band].bit_width_adjust[ch];
700
+    int shift = c->bands[band].nscalablelsbs[ch];
701
+
702
+    if (s->fixed_lsb_width)
703
+        shift = s->fixed_lsb_width;
704
+    else if (shift && adj)
705
+        shift += adj - 1;
706
+    else
707
+        shift += adj;
708
+
709
+    return shift;
710
+}
711
+
712
+static void chs_assemble_msbs_lsbs(DCAXllDecoder *s, DCAXllChSet *c, int band)
713
+{
714
+    DCAXllBand *b = &c->bands[band];
715
+    int n, ch, nsamples = s->nframesamples;
716
+
717
+    for (ch = 0; ch < c->nchannels; ch++) {
718
+        int shift = chs_get_lsb_width(s, c, band, ch);
719
+        if (shift) {
720
+            int32_t *msb = b->msb_sample_buffer[ch];
721
+            if (b->nscalablelsbs[ch]) {
722
+                int32_t *lsb = b->lsb_sample_buffer[ch];
723
+                int adj = b->bit_width_adjust[ch];
724
+                for (n = 0; n < nsamples; n++)
725
+                    msb[n] = msb[n] * (1 << shift) + (lsb[n] << adj);
726
+            } else {
727
+                for (n = 0; n < nsamples; n++)
728
+                    msb[n] = msb[n] * (1 << shift);
729
+            }
730
+        }
731
+    }
732
+}
733
+
734
+static int chs_assemble_freq_bands(DCAXllDecoder *s, DCAXllChSet *c)
735
+{
736
+    int ch, nsamples = s->nframesamples;
737
+    int32_t *ptr;
738
+
739
+    av_assert1(c->nfreqbands > 1);
740
+
741
+    // Reallocate frequency band assembly buffer
742
+    av_fast_malloc(&c->sample_buffer[2], &c->sample_size[2],
743
+                   2 * nsamples * c->nchannels * sizeof(int32_t));
744
+    if (!c->sample_buffer[2])
745
+        return AVERROR(ENOMEM);
746
+
747
+    // Assemble frequency bands 0 and 1
748
+    ptr = c->sample_buffer[2];
749
+    for (ch = 0; ch < c->nchannels; ch++) {
750
+        int32_t *band0 = c->bands[0].msb_sample_buffer[ch];
751
+        int32_t *band1 = c->bands[1].msb_sample_buffer[ch];
752
+
753
+        // Copy decimator history
754
+        memcpy(band0 - DCA_XLL_DECI_HISTORY_MAX,
755
+               c->deci_history[ch], sizeof(c->deci_history[0]));
756
+
757
+        // Filter
758
+        s->dcadsp->assemble_freq_bands(ptr, band0, band1,
759
+                                       ff_dca_xll_band_coeff,
760
+                                       nsamples);
761
+
762
+        // Remap output channel pointer to assembly buffer
763
+        s->output_samples[c->ch_remap[ch]] = ptr;
764
+        ptr += nsamples * 2;
765
+    }
766
+
767
+    return 0;
768
+}
769
+
770
+static int parse_common_header(DCAXllDecoder *s)
771
+{
772
+    int stream_ver, header_size, frame_size_nbits, nframesegs_log2;
773
+
774
+    // XLL extension sync word
775
+    if (get_bits_long(&s->gb, 32) != DCA_SYNCWORD_XLL) {
776
+        av_log(s->avctx, AV_LOG_VERBOSE, "Invalid XLL sync word\n");
777
+        return AVERROR(EAGAIN);
778
+    }
779
+
780
+    // Version number
781
+    stream_ver = get_bits(&s->gb, 4) + 1;
782
+    if (stream_ver > 1) {
783
+        avpriv_request_sample(s->avctx, "XLL stream version %d", stream_ver);
784
+        return AVERROR_PATCHWELCOME;
785
+    }
786
+
787
+    // Lossless frame header length
788
+    header_size = get_bits(&s->gb, 8) + 1;
789
+
790
+    // Check CRC
791
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
792
+        && ff_dca_check_crc(&s->gb, 32, header_size * 8)) {
793
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL common header checksum\n");
794
+        return AVERROR_INVALIDDATA;
795
+    }
796
+
797
+    // Number of bits used to read frame size
798
+    frame_size_nbits = get_bits(&s->gb, 5) + 1;
799
+
800
+    // Number of bytes in a lossless frame
801
+    s->frame_size = get_bits_long(&s->gb, frame_size_nbits);
802
+    if (s->frame_size < 0 || s->frame_size >= DCA_XLL_PBR_BUFFER_MAX) {
803
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL frame size (%d bytes)\n", s->frame_size);
804
+        return AVERROR_INVALIDDATA;
805
+    }
806
+    s->frame_size++;
807
+
808
+    // Number of channels sets per frame
809
+    s->nchsets = get_bits(&s->gb, 4) + 1;
810
+    if (s->nchsets > DCA_XLL_CHSETS_MAX) {
811
+        avpriv_request_sample(s->avctx, "%d XLL channel sets", s->nchsets);
812
+        return AVERROR_PATCHWELCOME;
813
+    }
814
+
815
+    // Number of segments per frame
816
+    nframesegs_log2 = get_bits(&s->gb, 4);
817
+    s->nframesegs = 1 << nframesegs_log2;
818
+    if (s->nframesegs > 1024) {
819
+        av_log(s->avctx, AV_LOG_ERROR, "Too many segments per XLL frame\n");
820
+        return AVERROR_INVALIDDATA;
821
+    }
822
+
823
+    // Samples in segment per one frequency band for the first channel set
824
+    // Maximum value is 256 for sampling frequencies <= 48 kHz
825
+    // Maximum value is 512 for sampling frequencies > 48 kHz
826
+    s->nsegsamples_log2 = get_bits(&s->gb, 4);
827
+    if (!s->nsegsamples_log2) {
828
+        av_log(s->avctx, AV_LOG_ERROR, "Too few samples per XLL segment\n");
829
+        return AVERROR_INVALIDDATA;
830
+    }
831
+    s->nsegsamples = 1 << s->nsegsamples_log2;
832
+    if (s->nsegsamples > 512) {
833
+        av_log(s->avctx, AV_LOG_ERROR, "Too many samples per XLL segment\n");
834
+        return AVERROR_INVALIDDATA;
835
+    }
836
+
837
+    // Samples in frame per one frequency band for the first channel set
838
+    s->nframesamples_log2 = s->nsegsamples_log2 + nframesegs_log2;
839
+    s->nframesamples = 1 << s->nframesamples_log2;
840
+    if (s->nframesamples > 65536) {
841
+        av_log(s->avctx, AV_LOG_ERROR, "Too many samples per XLL frame\n");
842
+        return AVERROR_INVALIDDATA;
843
+    }
844
+
845
+    // Number of bits used to read segment size
846
+    s->seg_size_nbits = get_bits(&s->gb, 5) + 1;
847
+
848
+    // Presence of CRC16 within each frequency band
849
+    // 0 - No CRC16 within band
850
+    // 1 - CRC16 placed at the end of MSB0
851
+    // 2 - CRC16 placed at the end of MSB0 and LSB0
852
+    // 3 - CRC16 placed at the end of MSB0 and LSB0 and other frequency bands
853
+    s->band_crc_present = get_bits(&s->gb, 2);
854
+
855
+    // MSB/LSB split flag
856
+    s->scalable_lsbs = get_bits1(&s->gb);
857
+
858
+    // Channel position mask
859
+    s->ch_mask_nbits = get_bits(&s->gb, 5) + 1;
860
+
861
+    // Fixed LSB width
862
+    if (s->scalable_lsbs)
863
+        s->fixed_lsb_width = get_bits(&s->gb, 4);
864
+    else
865
+        s->fixed_lsb_width = 0;
866
+
867
+    // Reserved
868
+    // Byte align
869
+    // Header CRC16 protection
870
+    if (ff_dca_seek_bits(&s->gb, header_size * 8)) {
871
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL common header\n");
872
+        return AVERROR_INVALIDDATA;
873
+    }
874
+
875
+    return 0;
876
+}
877
+
878
+static int is_hier_dmix_chset(DCAXllChSet *c)
879
+{
880
+    return !c->primary_chset && c->dmix_embedded && c->hier_chset;
881
+}
882
+
883
+static DCAXllChSet *find_next_hier_dmix_chset(DCAXllDecoder *s, DCAXllChSet *c)
884
+{
885
+    if (c->hier_chset)
886
+        while (++c < &s->chset[s->nchsets])
887
+            if (is_hier_dmix_chset(c))
888
+                return c;
889
+
890
+    return NULL;
891
+}
892
+
893
+static void prescale_down_mix(DCAXllChSet *c, DCAXllChSet *o)
894
+{
895
+    int i, j, *coeff_ptr = c->dmix_coeff;
896
+
897
+    for (i = 0; i < c->hier_ofs; i++) {
898
+        int scale = o->dmix_scale[i];
899
+        int scale_inv = o->dmix_scale_inv[i];
900
+        c->dmix_scale[i] = mul15(c->dmix_scale[i], scale);
901
+        c->dmix_scale_inv[i] = mul16(c->dmix_scale_inv[i], scale_inv);
902
+        for (j = 0; j < c->nchannels; j++) {
903
+            int coeff = mul16(*coeff_ptr, scale_inv);
904
+            *coeff_ptr++ = mul15(coeff, o->dmix_scale[c->hier_ofs + j]);
905
+        }
906
+    }
907
+}
908
+
909
+static int parse_sub_headers(DCAXllDecoder *s, DCAExssAsset *asset)
910
+{
911
+    DCAContext *dca = s->avctx->priv_data;
912
+    DCAXllChSet *c;
913
+    int i, ret;
914
+
915
+    // Parse channel set headers
916
+    s->nfreqbands = 0;
917
+    s->nchannels = 0;
918
+    s->nreschsets = 0;
919
+    for (i = 0, c = s->chset; i < s->nchsets; i++, c++) {
920
+        c->hier_ofs = s->nchannels;
921
+        if ((ret = chs_parse_header(s, c, asset)) < 0)
922
+            return ret;
923
+        if (c->nfreqbands > s->nfreqbands)
924
+            s->nfreqbands = c->nfreqbands;
925
+        if (c->hier_chset)
926
+            s->nchannels += c->nchannels;
927
+        if (c->residual_encode != (1 << c->nchannels) - 1)
928
+            s->nreschsets++;
929
+    }
930
+
931
+    // Pre-scale downmixing coefficients for all non-primary channel sets
932
+    for (i = s->nchsets - 1, c = &s->chset[i]; i > 0; i--, c--) {
933
+        if (is_hier_dmix_chset(c)) {
934
+            DCAXllChSet *o = find_next_hier_dmix_chset(s, c);
935
+            if (o)
936
+                prescale_down_mix(c, o);
937
+        }
938
+    }
939
+
940
+    // Determine number of active channel sets to decode
941
+    switch (dca->request_channel_layout) {
942
+    case DCA_SPEAKER_LAYOUT_STEREO:
943
+        s->nactivechsets = 1;
944
+        break;
945
+    case DCA_SPEAKER_LAYOUT_5POINT0:
946
+    case DCA_SPEAKER_LAYOUT_5POINT1:
947
+        s->nactivechsets = (s->chset[0].nchannels < 5 && s->nchsets > 1) ? 2 : 1;
948
+        break;
949
+    default:
950
+        s->nactivechsets = s->nchsets;
951
+        break;
952
+    }
953
+
954
+    return 0;
955
+}
956
+
957
+static int parse_navi_table(DCAXllDecoder *s)
958
+{
959
+    int chs, seg, band, navi_nb, navi_pos, *navi_ptr;
960
+    DCAXllChSet *c;
961
+
962
+    // Determine size of NAVI table
963
+    navi_nb = s->nfreqbands * s->nframesegs * s->nchsets;
964
+    if (navi_nb > 1024) {
965
+        av_log(s->avctx, AV_LOG_ERROR, "Too many NAVI entries (%d)\n", navi_nb);
966
+        return AVERROR_INVALIDDATA;
967
+    }
968
+
969
+    // Reallocate NAVI table
970
+    av_fast_malloc(&s->navi, &s->navi_size, navi_nb * sizeof(*s->navi));
971
+    if (!s->navi)
972
+        return AVERROR(ENOMEM);
973
+
974
+    // Parse NAVI
975
+    navi_pos = get_bits_count(&s->gb);
976
+    navi_ptr = s->navi;
977
+    for (band = 0; band < s->nfreqbands; band++) {
978
+        for (seg = 0; seg < s->nframesegs; seg++) {
979
+            for (chs = 0, c = s->chset; chs < s->nchsets; chs++, c++) {
980
+                int size = 0;
981
+                if (c->nfreqbands > band) {
982
+                    size = get_bits_long(&s->gb, s->seg_size_nbits);
983
+                    if (size < 0 || size >= s->frame_size) {
984
+                        av_log(s->avctx, AV_LOG_ERROR, "Invalid NAVI segment size (%d bytes)\n", size);
985
+                        return AVERROR_INVALIDDATA;
986
+                    }
987
+                    size++;
988
+                }
989
+                *navi_ptr++ = size;
990
+            }
991
+        }
992
+    }
993
+
994
+    // Byte align
995
+    // CRC16
996
+    skip_bits(&s->gb, -get_bits_count(&s->gb) & 7);
997
+    skip_bits(&s->gb, 16);
998
+
999
+    // Check CRC
1000
+    if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
1001
+        && ff_dca_check_crc(&s->gb, navi_pos, get_bits_count(&s->gb))) {
1002
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid NAVI checksum\n");
1003
+        return AVERROR_INVALIDDATA;
1004
+    }
1005
+
1006
+    return 0;
1007
+}
1008
+
1009
+static int parse_band_data(DCAXllDecoder *s)
1010
+{
1011
+    int ret, chs, seg, band, navi_pos, *navi_ptr;
1012
+    DCAXllChSet *c;
1013
+
1014
+    for (chs = 0, c = s->chset; chs < s->nactivechsets; chs++, c++) {
1015
+        if ((ret = chs_alloc_msb_band_data(s, c)) < 0)
1016
+            return ret;
1017
+        if ((ret = chs_alloc_lsb_band_data(s, c)) < 0)
1018
+            return ret;
1019
+    }
1020
+
1021
+    navi_pos = get_bits_count(&s->gb);
1022
+    navi_ptr = s->navi;
1023
+    for (band = 0; band < s->nfreqbands; band++) {
1024
+        for (seg = 0; seg < s->nframesegs; seg++) {
1025
+            for (chs = 0, c = s->chset; chs < s->nchsets; chs++, c++) {
1026
+                if (c->nfreqbands > band) {
1027
+                    navi_pos += *navi_ptr * 8;
1028
+                    if (navi_pos > s->gb.size_in_bits) {
1029
+                        av_log(s->avctx, AV_LOG_ERROR, "Invalid NAVI position\n");
1030
+                        return AVERROR_INVALIDDATA;
1031
+                    }
1032
+                    if (chs < s->nactivechsets &&
1033
+                        (ret = chs_parse_band_data(s, c, band, seg, navi_pos)) < 0) {
1034
+                        if (s->avctx->err_recognition & AV_EF_EXPLODE)
1035
+                            return ret;
1036
+                        chs_clear_band_data(s, c, band, seg);
1037
+                    }
1038
+                    s->gb.index = navi_pos;
1039
+                }
1040
+                navi_ptr++;
1041
+            }
1042
+        }
1043
+    }
1044
+
1045
+    return 0;
1046
+}
1047
+
1048
+static int parse_frame(DCAXllDecoder *s, uint8_t *data, int size, DCAExssAsset *asset)
1049
+{
1050
+    int ret;
1051
+
1052
+    if ((ret = init_get_bits8(&s->gb, data, size)) < 0)
1053
+        return ret;
1054
+    if ((ret = parse_common_header(s)) < 0)
1055
+        return ret;
1056
+    if ((ret = parse_sub_headers(s, asset)) < 0)
1057
+        return ret;
1058
+    if ((ret = parse_navi_table(s)) < 0)
1059
+        return ret;
1060
+    if ((ret = parse_band_data(s)) < 0)
1061
+        return ret;
1062
+    if (ff_dca_seek_bits(&s->gb, s->frame_size * 8)) {
1063
+        av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL frame\n");
1064
+        return AVERROR_INVALIDDATA;
1065
+    }
1066
+    return ret;
1067
+}
1068
+
1069
+static void clear_pbr(DCAXllDecoder *s)
1070
+{
1071
+    s->pbr_length = 0;
1072
+    s->pbr_delay = 0;
1073
+}
1074
+
1075
+static int copy_to_pbr(DCAXllDecoder *s, uint8_t *data, int size, int delay)
1076
+{
1077
+    if (size > DCA_XLL_PBR_BUFFER_MAX)
1078
+        return AVERROR(ENOSPC);
1079
+
1080
+    if (!s->pbr_buffer && !(s->pbr_buffer = av_malloc(DCA_XLL_PBR_BUFFER_MAX + DCA_BUFFER_PADDING_SIZE)))
1081
+        return AVERROR(ENOMEM);
1082
+
1083
+    memcpy(s->pbr_buffer, data, size);
1084
+    s->pbr_length = size;
1085
+    s->pbr_delay = delay;
1086
+    return 0;
1087
+}
1088
+
1089
+static int parse_frame_no_pbr(DCAXllDecoder *s, uint8_t *data, int size, DCAExssAsset *asset)
1090
+{
1091
+    int ret = parse_frame(s, data, size, asset);
1092
+
1093
+    // If XLL packet data didn't start with a sync word, we must have jumped
1094
+    // right into the middle of PBR smoothing period
1095
+    if (ret == AVERROR(EAGAIN) && asset->xll_sync_present && asset->xll_sync_offset < size) {
1096
+        // Skip to the next sync word in this packet
1097
+        data += asset->xll_sync_offset;
1098
+        size -= asset->xll_sync_offset;
1099
+
1100
+        // If decoding delay is set, put the frame into PBR buffer and return
1101
+        // failure code. Higher level decoder is expected to switch to lossy
1102
+        // core decoding or mute its output until decoding delay expires.
1103
+        if (asset->xll_delay_nframes > 0) {
1104
+            if ((ret = copy_to_pbr(s, data, size, asset->xll_delay_nframes)) < 0)
1105
+                return ret;
1106
+            return AVERROR(EAGAIN);
1107
+        }
1108
+
1109
+        // No decoding delay, just parse the frame in place
1110
+        ret = parse_frame(s, data, size, asset);
1111
+    }
1112
+
1113
+    if (ret < 0)
1114
+        return ret;
1115
+
1116
+    if (s->frame_size > size)
1117
+        return AVERROR(EINVAL);
1118
+
1119
+    // If the XLL decoder didn't consume full packet, start PBR smoothing period
1120
+    if (s->frame_size < size)
1121
+        if ((ret = copy_to_pbr(s, data + s->frame_size, size - s->frame_size, 0)) < 0)
1122
+            return ret;
1123
+
1124
+    return 0;
1125
+}
1126
+
1127
+static int parse_frame_pbr(DCAXllDecoder *s, uint8_t *data, int size, DCAExssAsset *asset)
1128
+{
1129
+    int ret;
1130
+
1131
+    if (size > DCA_XLL_PBR_BUFFER_MAX - s->pbr_length) {
1132
+        ret = AVERROR(ENOSPC);
1133
+        goto fail;
1134
+    }
1135
+
1136
+    memcpy(s->pbr_buffer + s->pbr_length, data, size);
1137
+    s->pbr_length += size;
1138
+
1139
+    // Respect decoding delay after synchronization error
1140
+    if (s->pbr_delay > 0 && --s->pbr_delay)
1141
+        return AVERROR(EAGAIN);
1142
+
1143
+    if ((ret = parse_frame(s, s->pbr_buffer, s->pbr_length, asset)) < 0)
1144
+        goto fail;
1145
+
1146
+    if (s->frame_size > s->pbr_length) {
1147
+        ret = AVERROR(EINVAL);
1148
+        goto fail;
1149
+    }
1150
+
1151
+    if (s->frame_size == s->pbr_length) {
1152
+        // End of PBR smoothing period
1153
+        clear_pbr(s);
1154
+    } else {
1155
+        s->pbr_length -= s->frame_size;
1156
+        memmove(s->pbr_buffer, s->pbr_buffer + s->frame_size, s->pbr_length);
1157
+    }
1158
+
1159
+    return 0;
1160
+
1161
+fail:
1162
+    // For now, throw out all PBR state on failure.
1163
+    // Perhaps we can be smarter and try to resync somehow.
1164
+    clear_pbr(s);
1165
+    return ret;
1166
+}
1167
+
1168
+int ff_dca_xll_parse(DCAXllDecoder *s, uint8_t *data, DCAExssAsset *asset)
1169
+{
1170
+    int ret;
1171
+
1172
+    if (s->hd_stream_id != asset->hd_stream_id) {
1173
+        clear_pbr(s);
1174
+        s->hd_stream_id = asset->hd_stream_id;
1175
+    }
1176
+
1177
+    if (s->pbr_length)
1178
+        ret = parse_frame_pbr(s, data + asset->xll_offset, asset->xll_size, asset);
1179
+    else
1180
+        ret = parse_frame_no_pbr(s, data + asset->xll_offset, asset->xll_size, asset);
1181
+
1182
+    return ret;
1183
+}
1184
+
1185
+static void undo_down_mix(DCAXllDecoder *s, DCAXllChSet *o, int band)
1186
+{
1187
+    int i, j, k, nchannels = 0, *coeff_ptr = o->dmix_coeff;
1188
+    DCAXllChSet *c;
1189
+
1190
+    for (i = 0, c = s->chset; i < s->nactivechsets; i++, c++) {
1191
+        if (!c->hier_chset)
1192
+            continue;
1193
+
1194
+        av_assert1(band < c->nfreqbands);
1195
+        for (j = 0; j < c->nchannels; j++) {
1196
+            for (k = 0; k < o->nchannels; k++) {
1197
+                int coeff = *coeff_ptr++;
1198
+                if (coeff) {
1199
+                    s->dcadsp->dmix_sub(c->bands[band].msb_sample_buffer[j],
1200
+                                        o->bands[band].msb_sample_buffer[k],
1201
+                                        coeff, s->nframesamples);
1202
+                    if (band)
1203
+                        s->dcadsp->dmix_sub(c->deci_history[j],
1204
+                                            o->deci_history[k],
1205
+                                            coeff, DCA_XLL_DECI_HISTORY_MAX);
1206
+                }
1207
+            }
1208
+        }
1209
+
1210
+        nchannels += c->nchannels;
1211
+        if (nchannels >= o->hier_ofs)
1212
+            break;
1213
+    }
1214
+}
1215
+
1216
+static void scale_down_mix(DCAXllDecoder *s, DCAXllChSet *o, int band)
1217
+{
1218
+    int i, j, nchannels = 0;
1219
+    DCAXllChSet *c;
1220
+
1221
+    for (i = 0, c = s->chset; i < s->nactivechsets; i++, c++) {
1222
+        if (!c->hier_chset)
1223
+            continue;
1224
+
1225
+        av_assert1(band < c->nfreqbands);
1226
+        for (j = 0; j < c->nchannels; j++) {
1227
+            int scale = o->dmix_scale[nchannels++];
1228
+            if (scale != (1 << 15)) {
1229
+                s->dcadsp->dmix_scale(c->bands[band].msb_sample_buffer[j],
1230
+                                      scale, s->nframesamples);
1231
+                if (band)
1232
+                    s->dcadsp->dmix_scale(c->deci_history[j],
1233
+                                          scale, DCA_XLL_DECI_HISTORY_MAX);
1234
+            }
1235
+        }
1236
+
1237
+        if (nchannels >= o->hier_ofs)
1238
+            break;
1239
+    }
1240
+}
1241
+
1242
+// Clear all band data and replace non-residual encoded channels with lossy
1243
+// counterparts
1244
+static void av_cold force_lossy_output(DCAXllDecoder *s, DCAXllChSet *c)
1245
+{
1246
+    DCAContext *dca = s->avctx->priv_data;
1247
+    int band, ch;
1248
+
1249
+    for (band = 0; band < c->nfreqbands; band++)
1250
+        chs_clear_band_data(s, c, band, -1);
1251
+
1252
+    for (ch = 0; ch < c->nchannels; ch++) {
1253
+        if (!(c->residual_encode & (1 << ch)))
1254
+            continue;
1255
+        if (ff_dca_core_map_spkr(&dca->core, c->ch_remap[ch]) < 0)
1256
+            continue;
1257
+        c->residual_encode &= ~(1 << ch);
1258
+    }
1259
+}
1260
+
1261
+static int combine_residual_frame(DCAXllDecoder *s, DCAXllChSet *c)
1262
+{
1263
+    DCAContext *dca = s->avctx->priv_data;
1264
+    int ch, nsamples = s->nframesamples;
1265
+    DCAXllChSet *o;
1266
+
1267
+    // Verify that core is compatible
1268
+    if (!(dca->packet & DCA_PACKET_CORE)) {
1269
+        av_log(s->avctx, AV_LOG_ERROR, "Residual encoded channels are present without core\n");
1270
+        return AVERROR(EINVAL);
1271
+    }
1272
+
1273
+    if (c->freq != dca->core.output_rate) {
1274
+        av_log(s->avctx, AV_LOG_WARNING, "Sample rate mismatch between core (%d Hz) and XLL (%d Hz)\n", dca->core.output_rate, c->freq);
1275
+        return AVERROR_INVALIDDATA;
1276
+    }
1277
+
1278
+    if (nsamples != dca->core.npcmsamples) {
1279
+        av_log(s->avctx, AV_LOG_WARNING, "Number of samples per frame mismatch between core (%d) and XLL (%d)\n", dca->core.npcmsamples, nsamples);
1280
+        return AVERROR_INVALIDDATA;
1281
+    }
1282
+
1283
+    // See if this channel set is downmixed and find the next channel set in
1284
+    // hierarchy. If downmixed, undo core pre-scaling before combining with
1285
+    // residual (residual is not scaled).
1286
+    o = find_next_hier_dmix_chset(s, c);
1287
+
1288
+    // Reduce core bit width and combine with residual
1289
+    for (ch = 0; ch < c->nchannels; ch++) {
1290
+        int n, spkr, shift, round;
1291
+        int32_t *src, *dst;
1292
+
1293
+        if (c->residual_encode & (1 << ch))
1294
+            continue;
1295
+
1296
+        // Map this channel to core speaker
1297
+        spkr = ff_dca_core_map_spkr(&dca->core, c->ch_remap[ch]);
1298
+        if (spkr < 0) {
1299
+            av_log(s->avctx, AV_LOG_WARNING, "Residual encoded channel (%d) references unavailable core channel\n", c->ch_remap[ch]);
1300
+            return AVERROR_INVALIDDATA;
1301
+        }
1302
+
1303
+        // Account for LSB width
1304
+        shift = 24 - c->pcm_bit_res + chs_get_lsb_width(s, c, 0, ch);
1305
+        if (shift > 24) {
1306
+            av_log(s->avctx, AV_LOG_WARNING, "Invalid core shift (%d bits)\n", shift);
1307
+            return AVERROR_INVALIDDATA;
1308
+        }
1309
+
1310
+        round = shift > 0 ? 1 << (shift - 1) : 0;
1311
+
1312
+        src = dca->core.output_samples[spkr];
1313
+        dst = c->bands[0].msb_sample_buffer[ch];
1314
+        if (o) {
1315
+            // Undo embedded core downmix pre-scaling
1316
+            int scale_inv = o->dmix_scale_inv[c->hier_ofs + ch];
1317
+            for (n = 0; n < nsamples; n++)
1318
+                dst[n] += clip23((mul16(src[n], scale_inv) + round) >> shift);
1319
+        } else {
1320
+            // No downmix scaling
1321
+            for (n = 0; n < nsamples; n++)
1322
+                dst[n] += (src[n] + round) >> shift;
1323
+        }
1324
+    }
1325
+
1326
+    return 0;
1327
+}
1328
+
1329
+int ff_dca_xll_filter_frame(DCAXllDecoder *s, AVFrame *frame)
1330
+{
1331
+    AVCodecContext *avctx = s->avctx;
1332
+    DCAContext *dca = avctx->priv_data;
1333
+    DCAExssAsset *asset = &dca->exss.assets[0];
1334
+    DCAXllChSet *p = &s->chset[0], *c;
1335
+    enum AVMatrixEncoding matrix_encoding = AV_MATRIX_ENCODING_NONE;
1336
+    int i, j, k, ret, shift, nsamples, request_mask;
1337
+    int ch_remap[DCA_SPEAKER_COUNT];
1338
+
1339
+    // Force lossy downmixed output during recovery
1340
+    if (dca->packet & DCA_PACKET_RECOVERY) {
1341
+        for (i = 0, c = s->chset; i < s->nchsets; i++, c++) {
1342
+            if (i < s->nactivechsets)
1343
+                force_lossy_output(s, c);
1344
+
1345
+            if (!c->primary_chset)
1346
+                c->dmix_embedded = 0;
1347
+        }
1348
+
1349
+        s->scalable_lsbs = 0;
1350
+        s->fixed_lsb_width = 0;
1351
+    }
1352
+
1353
+    // Filter frequency bands for active channel sets
1354
+    s->output_mask = 0;
1355
+    for (i = 0, c = s->chset; i < s->nactivechsets; i++, c++) {
1356
+        chs_filter_band_data(s, c, 0);
1357
+
1358
+        if (c->residual_encode != (1 << c->nchannels) - 1
1359
+            && (ret = combine_residual_frame(s, c)) < 0)
1360
+            return ret;
1361
+
1362
+        if (s->scalable_lsbs)
1363
+            chs_assemble_msbs_lsbs(s, c, 0);
1364
+
1365
+        if (c->nfreqbands > 1) {
1366
+            chs_filter_band_data(s, c, 1);
1367
+            chs_assemble_msbs_lsbs(s, c, 1);
1368
+        }
1369
+
1370
+        s->output_mask |= c->ch_mask;
1371
+    }
1372
+
1373
+    // Undo hierarchial downmix and/or apply scaling
1374
+    for (i = 1, c = &s->chset[1]; i < s->nchsets; i++, c++) {
1375
+        if (!is_hier_dmix_chset(c))
1376
+            continue;
1377
+
1378
+        if (i >= s->nactivechsets) {
1379
+            for (j = 0; j < c->nfreqbands; j++)
1380
+                if (c->bands[j].dmix_embedded)
1381
+                    scale_down_mix(s, c, j);
1382
+            break;
1383
+        }
1384
+
1385
+        for (j = 0; j < c->nfreqbands; j++)
1386
+            if (c->bands[j].dmix_embedded)
1387
+                undo_down_mix(s, c, j);
1388
+    }
1389
+
1390
+    // Assemble frequency bands for active channel sets
1391
+    if (s->nfreqbands > 1) {
1392
+        for (i = 0; i < s->nactivechsets; i++)
1393
+            if ((ret = chs_assemble_freq_bands(s, &s->chset[i])) < 0)
1394
+                return ret;
1395
+    }
1396
+
1397
+    // Normalize to regular 5.1 layout if downmixing
1398
+    if (dca->request_channel_layout) {
1399
+        if (s->output_mask & DCA_SPEAKER_MASK_Lss) {
1400
+            s->output_samples[DCA_SPEAKER_Ls] = s->output_samples[DCA_SPEAKER_Lss];
1401
+            s->output_mask = (s->output_mask & ~DCA_SPEAKER_MASK_Lss) | DCA_SPEAKER_MASK_Ls;
1402
+        }
1403
+        if (s->output_mask & DCA_SPEAKER_MASK_Rss) {
1404
+            s->output_samples[DCA_SPEAKER_Rs] = s->output_samples[DCA_SPEAKER_Rss];
1405
+            s->output_mask = (s->output_mask & ~DCA_SPEAKER_MASK_Rss) | DCA_SPEAKER_MASK_Rs;
1406
+        }
1407
+    }
1408
+
1409
+    // Handle downmixing to stereo request
1410
+    if (dca->request_channel_layout == DCA_SPEAKER_LAYOUT_STEREO
1411
+        && DCA_HAS_STEREO(s->output_mask) && p->dmix_embedded
1412
+        && (p->dmix_type == DCA_DMIX_TYPE_LoRo ||
1413
+            p->dmix_type == DCA_DMIX_TYPE_LtRt))
1414
+        request_mask = DCA_SPEAKER_LAYOUT_STEREO;
1415
+    else
1416
+        request_mask = s->output_mask;
1417
+    if (!ff_dca_set_channel_layout(avctx, ch_remap, request_mask))
1418
+        return AVERROR(EINVAL);
1419
+
1420
+    avctx->sample_rate = p->freq << (s->nfreqbands - 1);
1421
+
1422
+    switch (p->storage_bit_res) {
1423
+    case 16:
1424
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
1425
+        break;
1426
+    case 24:
1427
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1428
+        break;
1429
+    default:
1430
+        return AVERROR(EINVAL);
1431
+    }
1432
+
1433
+    avctx->bits_per_raw_sample = p->storage_bit_res;
1434
+    avctx->profile = FF_PROFILE_DTS_HD_MA;
1435
+    avctx->bit_rate = 0;
1436
+
1437
+    frame->nb_samples = nsamples = s->nframesamples << (s->nfreqbands - 1);
1438
+    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1439
+        return ret;
1440
+
1441
+    // Downmix primary channel set to stereo
1442
+    if (request_mask != s->output_mask) {
1443
+        ff_dca_downmix_to_stereo_fixed(s->dcadsp, s->output_samples,
1444
+                                       p->dmix_coeff, nsamples,
1445
+                                       s->output_mask);
1446
+    }
1447
+
1448
+    shift = p->storage_bit_res - p->pcm_bit_res;
1449
+    for (i = 0; i < avctx->channels; i++) {
1450
+        int32_t *samples = s->output_samples[ch_remap[i]];
1451
+        if (frame->format == AV_SAMPLE_FMT_S16P) {
1452
+            int16_t *plane = (int16_t *)frame->extended_data[i];
1453
+            for (k = 0; k < nsamples; k++)
1454
+                plane[k] = av_clip_int16(samples[k] * (1 << shift));
1455
+        } else {
1456
+            int32_t *plane = (int32_t *)frame->extended_data[i];
1457
+            for (k = 0; k < nsamples; k++)
1458
+                plane[k] = clip23(samples[k] * (1 << shift)) * (1 << 8);
1459
+        }
1460
+    }
1461
+
1462
+    if (!asset->one_to_one_map_ch_to_spkr) {
1463
+        if (asset->representation_type == DCA_REPR_TYPE_LtRt)
1464
+            matrix_encoding = AV_MATRIX_ENCODING_DOLBY;
1465
+        else if (asset->representation_type == DCA_REPR_TYPE_LhRh)
1466
+            matrix_encoding = AV_MATRIX_ENCODING_DOLBYHEADPHONE;
1467
+    } else if (request_mask != s->output_mask && p->dmix_type == DCA_DMIX_TYPE_LtRt) {
1468
+        matrix_encoding = AV_MATRIX_ENCODING_DOLBY;
1469
+    }
1470
+    if ((ret = ff_side_data_update_matrix_encoding(frame, matrix_encoding)) < 0)
1471
+        return ret;
1472
+
1473
+    return 0;
1474
+}
1475
+
1476
+av_cold void ff_dca_xll_flush(DCAXllDecoder *s)
1477
+{
1478
+    clear_pbr(s);
1479
+}
1480
+
1481
+av_cold void ff_dca_xll_close(DCAXllDecoder *s)
1482
+{
1483
+    DCAXllChSet *c;
1484
+    int i, j;
1485
+
1486
+    for (i = 0, c = s->chset; i < DCA_XLL_CHSETS_MAX; i++, c++) {
1487
+        for (j = 0; j < DCA_XLL_SAMPLE_BUFFERS_MAX; j++) {
1488
+            av_freep(&c->sample_buffer[j]);
1489
+            c->sample_size[j] = 0;
1490
+        }
1491
+    }
1492
+
1493
+    av_freep(&s->navi);
1494
+    s->navi_size = 0;
1495
+
1496
+    av_freep(&s->pbr_buffer);
1497
+    clear_pbr(s);
1498
+}
0 1499
new file mode 100644
... ...
@@ -0,0 +1,149 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#ifndef AVCODEC_DCA_XLL_H
21
+#define AVCODEC_DCA_XLL_H
22
+
23
+#include "libavutil/common.h"
24
+#include "libavutil/mem.h"
25
+
26
+#include "avcodec.h"
27
+#include "internal.h"
28
+#include "get_bits.h"
29
+#include "dca.h"
30
+#include "dcadsp.h"
31
+#include "dca_exss.h"
32
+
33
+#define DCA_XLL_CHSETS_MAX              3
34
+#define DCA_XLL_CHANNELS_MAX            8
35
+#define DCA_XLL_BANDS_MAX               2
36
+#define DCA_XLL_ADAPT_PRED_ORDER_MAX    16
37
+#define DCA_XLL_DECI_HISTORY_MAX        8
38
+#define DCA_XLL_DMIX_SCALES_MAX         ((DCA_XLL_CHSETS_MAX - 1) * DCA_XLL_CHANNELS_MAX)
39
+#define DCA_XLL_DMIX_COEFFS_MAX         (DCA_XLL_DMIX_SCALES_MAX * DCA_XLL_CHANNELS_MAX)
40
+#define DCA_XLL_PBR_BUFFER_MAX          (240 << 10)
41
+#define DCA_XLL_SAMPLE_BUFFERS_MAX      3
42
+
43
+typedef struct DCAXllBand {
44
+    int     decor_enabled;                          ///< Pairwise channel decorrelation flag
45
+    int     orig_order[DCA_XLL_CHANNELS_MAX];       ///< Original channel order
46
+    int     decor_coeff[DCA_XLL_CHANNELS_MAX / 2];  ///< Pairwise channel coefficients
47
+
48
+    int     adapt_pred_order[DCA_XLL_CHANNELS_MAX]; ///< Adaptive predictor order
49
+    int     highest_pred_order;                     ///< Highest adaptive predictor order
50
+    int     fixed_pred_order[DCA_XLL_CHANNELS_MAX]; ///< Fixed predictor order
51
+    int     adapt_refl_coeff[DCA_XLL_CHANNELS_MAX][DCA_XLL_ADAPT_PRED_ORDER_MAX];   ///< Adaptive predictor reflection coefficients
52
+
53
+    int     dmix_embedded;  ///< Downmix performed by encoder in frequency band
54
+
55
+    int     lsb_section_size;                       ///< Size of LSB section in any segment
56
+    int     nscalablelsbs[DCA_XLL_CHANNELS_MAX];    ///< Number of bits to represent the samples in LSB part
57
+    int     bit_width_adjust[DCA_XLL_CHANNELS_MAX]; ///< Number of bits discarded by authoring
58
+
59
+    int32_t *msb_sample_buffer[DCA_XLL_CHANNELS_MAX];   ///< MSB sample buffer pointers
60
+    int32_t *lsb_sample_buffer[DCA_XLL_CHANNELS_MAX];   ///< LSB sample buffer pointers or NULL
61
+} DCAXllBand;
62
+
63
+typedef struct DCAXllChSet {
64
+    // Channel set header
65
+    int     nchannels;          ///< Number of channels in the channel set (N)
66
+    int     residual_encode;    ///< Residual encoding mask (0 - residual, 1 - full channel)
67
+    int     pcm_bit_res;        ///< PCM bit resolution (variable)
68
+    int     storage_bit_res;    ///< Storage bit resolution (16 or 24)
69
+    int     freq;               ///< Original sampling frequency (max. 96000 Hz)
70
+
71
+    int     primary_chset;          ///< Primary channel set flag
72
+    int     dmix_coeffs_present;    ///< Downmix coefficients present in stream
73
+    int     dmix_embedded;          ///< Downmix already performed by encoder
74
+    int     dmix_type;              ///< Primary channel set downmix type
75
+    int     hier_chset;             ///< Whether the channel set is part of a hierarchy
76
+    int     hier_ofs;               ///< Number of preceding channels in a hierarchy (M)
77
+    int     dmix_coeff[DCA_XLL_DMIX_COEFFS_MAX];       ///< Downmixing coefficients
78
+    int     dmix_scale[DCA_XLL_DMIX_SCALES_MAX];       ///< Downmixing scales
79
+    int     dmix_scale_inv[DCA_XLL_DMIX_SCALES_MAX];   ///< Inverse downmixing scales
80
+    int     ch_mask;                ///< Channel mask for set
81
+    int     ch_remap[DCA_XLL_CHANNELS_MAX];    ///< Channel to speaker map
82
+
83
+    int     nfreqbands; ///< Number of frequency bands (1 or 2)
84
+    int     nabits;     ///< Number of bits to read bit allocation coding parameter
85
+
86
+    DCAXllBand     bands[DCA_XLL_BANDS_MAX];   ///< Frequency bands
87
+
88
+    // Frequency band coding parameters
89
+    int     seg_common;                                     ///< Segment type
90
+    int     rice_code_flag[DCA_XLL_CHANNELS_MAX];           ///< Rice coding flag
91
+    int     bitalloc_hybrid_linear[DCA_XLL_CHANNELS_MAX];   ///< Binary code length for isolated samples
92
+    int     bitalloc_part_a[DCA_XLL_CHANNELS_MAX];          ///< Coding parameter for part A of segment
93
+    int     bitalloc_part_b[DCA_XLL_CHANNELS_MAX];          ///< Coding parameter for part B of segment
94
+    int     nsamples_part_a[DCA_XLL_CHANNELS_MAX];          ///< Number of samples in part A of segment
95
+
96
+    // Decimator history
97
+    DECLARE_ALIGNED(32, int32_t, deci_history)[DCA_XLL_CHANNELS_MAX][DCA_XLL_DECI_HISTORY_MAX]; ///< Decimator history for frequency band 1
98
+
99
+    // Sample buffers
100
+    unsigned int    sample_size[DCA_XLL_SAMPLE_BUFFERS_MAX];
101
+    int32_t         *sample_buffer[DCA_XLL_SAMPLE_BUFFERS_MAX];
102
+} DCAXllChSet;
103
+
104
+typedef struct DCAXllDecoder {
105
+    AVCodecContext  *avctx;
106
+    GetBitContext   gb;
107
+
108
+    int     frame_size;             ///< Number of bytes in a lossless frame
109
+    int     nchsets;                ///< Number of channels sets per frame
110
+    int     nframesegs;             ///< Number of segments per frame
111
+    int     nsegsamples_log2;       ///< log2(nsegsamples)
112
+    int     nsegsamples;            ///< Samples in segment per one frequency band
113
+    int     nframesamples_log2;     ///< log2(nframesamples)
114
+    int     nframesamples;          ///< Samples in frame per one frequency band
115
+    int     seg_size_nbits;         ///< Number of bits used to read segment size
116
+    int     band_crc_present;       ///< Presence of CRC16 within each frequency band
117
+    int     scalable_lsbs;          ///< MSB/LSB split flag
118
+    int     ch_mask_nbits;          ///< Number of bits used to read channel mask
119
+    int     fixed_lsb_width;        ///< Fixed LSB width
120
+
121
+    DCAXllChSet    chset[DCA_XLL_CHSETS_MAX]; ///< Channel sets
122
+
123
+    int             *navi;          ///< NAVI table
124
+    unsigned int    navi_size;
125
+
126
+    int     nfreqbands;     ///< Highest number of frequency bands
127
+    int     nchannels;      ///< Total number of channels in a hierarchy
128
+    int     nreschsets;     ///< Number of channel sets that have residual encoded channels
129
+    int     nactivechsets;  ///< Number of active channel sets to decode
130
+
131
+    int     hd_stream_id;   ///< Previous DTS-HD stream ID for detecting changes
132
+
133
+    uint8_t     *pbr_buffer;        ///< Peak bit rate (PBR) smoothing buffer
134
+    int         pbr_length;         ///< Length in bytes of data currently buffered
135
+    int         pbr_delay;          ///< Delay in frames before decoding buffered data
136
+
137
+    DCADSPContext   *dcadsp;
138
+
139
+    int     output_mask;
140
+    int32_t *output_samples[DCA_SPEAKER_COUNT];
141
+} DCAXllDecoder;
142
+
143
+int ff_dca_xll_parse(DCAXllDecoder *s, uint8_t *data, DCAExssAsset *asset);
144
+int ff_dca_xll_filter_frame(DCAXllDecoder *s, AVFrame *frame);
145
+av_cold void ff_dca_xll_flush(DCAXllDecoder *s);
146
+av_cold void ff_dca_xll_close(DCAXllDecoder *s);
147
+
148
+#endif
0 149
new file mode 100644
... ...
@@ -0,0 +1,417 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include "libavutil/opt.h"
21
+#include "libavutil/channel_layout.h"
22
+
23
+#include "dcadec.h"
24
+#include "dcamath.h"
25
+#include "dca_syncwords.h"
26
+#include "profiles.h"
27
+
28
+#define MIN_PACKET_SIZE     16
29
+#define MAX_PACKET_SIZE     0x104000
30
+
31
+int ff_dca_set_channel_layout(AVCodecContext *avctx, int *ch_remap, int dca_mask)
32
+{
33
+    static const uint8_t dca2wav_norm[28] = {
34
+         2,  0, 1, 9, 10,  3,  8,  4,  5,  9, 10, 6, 7, 12,
35
+        13, 14, 3, 6,  7, 11, 12, 14, 16, 15, 17, 8, 4,  5,
36
+    };
37
+
38
+    static const uint8_t dca2wav_wide[28] = {
39
+         2,  0, 1, 4,  5,  3,  8,  4,  5,  9, 10, 6, 7, 12,
40
+        13, 14, 3, 9, 10, 11, 12, 14, 16, 15, 17, 8, 4,  5,
41
+    };
42
+
43
+    int dca_ch, wav_ch, nchannels = 0;
44
+
45
+    if (avctx->request_channel_layout & AV_CH_LAYOUT_NATIVE) {
46
+        for (dca_ch = 0; dca_ch < DCA_SPEAKER_COUNT; dca_ch++)
47
+            if (dca_mask & (1U << dca_ch))
48
+                ch_remap[nchannels++] = dca_ch;
49
+        avctx->channel_layout = dca_mask;
50
+    } else {
51
+        int wav_mask = 0;
52
+        int wav_map[18];
53
+        const uint8_t *dca2wav;
54
+        if (dca_mask == DCA_SPEAKER_LAYOUT_7POINT0_WIDE ||
55
+            dca_mask == DCA_SPEAKER_LAYOUT_7POINT1_WIDE)
56
+            dca2wav = dca2wav_wide;
57
+        else
58
+            dca2wav = dca2wav_norm;
59
+        for (dca_ch = 0; dca_ch < 28; dca_ch++) {
60
+            if (dca_mask & (1 << dca_ch)) {
61
+                wav_ch = dca2wav[dca_ch];
62
+                if (!(wav_mask & (1 << wav_ch))) {
63
+                    wav_map[wav_ch] = dca_ch;
64
+                    wav_mask |= 1 << wav_ch;
65
+                }
66
+            }
67
+        }
68
+        for (wav_ch = 0; wav_ch < 18; wav_ch++)
69
+            if (wav_mask & (1 << wav_ch))
70
+                ch_remap[nchannels++] = wav_map[wav_ch];
71
+        avctx->channel_layout = wav_mask;
72
+    }
73
+
74
+    avctx->channels = nchannels;
75
+    return nchannels;
76
+}
77
+
78
+static uint16_t crc16(const uint8_t *data, int size)
79
+{
80
+    static const uint16_t crctab[16] = {
81
+        0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
82
+        0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
83
+    };
84
+
85
+    uint16_t res = 0xffff;
86
+    int i;
87
+
88
+    for (i = 0; i < size; i++) {
89
+        res = (res << 4) ^ crctab[(data[i] >> 4) ^ (res >> 12)];
90
+        res = (res << 4) ^ crctab[(data[i] & 15) ^ (res >> 12)];
91
+    }
92
+
93
+    return res;
94
+}
95
+
96
+int ff_dca_check_crc(GetBitContext *s, int p1, int p2)
97
+{
98
+    if (((p1 | p2) & 7) || p1 < 0 || p2 > s->size_in_bits || p2 - p1 < 16)
99
+        return -1;
100
+    if (crc16(s->buffer + p1 / 8, (p2 - p1) / 8))
101
+        return -1;
102
+    return 0;
103
+}
104
+
105
+void ff_dca_downmix_to_stereo_fixed(DCADSPContext *dcadsp, int32_t **samples,
106
+                                    int *coeff_l, int nsamples, int ch_mask)
107
+{
108
+    int pos, spkr, max_spkr = av_log2(ch_mask);
109
+    int *coeff_r = coeff_l + av_popcount(ch_mask);
110
+
111
+    av_assert0(DCA_HAS_STEREO(ch_mask));
112
+
113
+    // Scale left and right channels
114
+    pos = (ch_mask & DCA_SPEAKER_MASK_C);
115
+    dcadsp->dmix_scale(samples[DCA_SPEAKER_L], coeff_l[pos    ], nsamples);
116
+    dcadsp->dmix_scale(samples[DCA_SPEAKER_R], coeff_r[pos + 1], nsamples);
117
+
118
+    // Downmix remaining channels
119
+    for (spkr = 0; spkr <= max_spkr; spkr++) {
120
+        if (!(ch_mask & (1U << spkr)))
121
+            continue;
122
+
123
+        if (*coeff_l && spkr != DCA_SPEAKER_L)
124
+            dcadsp->dmix_add(samples[DCA_SPEAKER_L], samples[spkr],
125
+                             *coeff_l, nsamples);
126
+
127
+        if (*coeff_r && spkr != DCA_SPEAKER_R)
128
+            dcadsp->dmix_add(samples[DCA_SPEAKER_R], samples[spkr],
129
+                             *coeff_r, nsamples);
130
+
131
+        coeff_l++;
132
+        coeff_r++;
133
+    }
134
+}
135
+
136
+void ff_dca_downmix_to_stereo_float(AVFloatDSPContext *fdsp, float **samples,
137
+                                    int *coeff_l, int nsamples, int ch_mask)
138
+{
139
+    int pos, spkr, max_spkr = av_log2(ch_mask);
140
+    int *coeff_r = coeff_l + av_popcount(ch_mask);
141
+    const float scale = 1.0f / (1 << 15);
142
+
143
+    av_assert0(DCA_HAS_STEREO(ch_mask));
144
+
145
+    // Scale left and right channels
146
+    pos = (ch_mask & DCA_SPEAKER_MASK_C);
147
+    fdsp->vector_fmul_scalar(samples[DCA_SPEAKER_L], samples[DCA_SPEAKER_L],
148
+                             coeff_l[pos    ] * scale, nsamples);
149
+    fdsp->vector_fmul_scalar(samples[DCA_SPEAKER_R], samples[DCA_SPEAKER_R],
150
+                             coeff_r[pos + 1] * scale, nsamples);
151
+
152
+    // Downmix remaining channels
153
+    for (spkr = 0; spkr <= max_spkr; spkr++) {
154
+        if (!(ch_mask & (1U << spkr)))
155
+            continue;
156
+
157
+        if (*coeff_l && spkr != DCA_SPEAKER_L)
158
+            fdsp->vector_fmac_scalar(samples[DCA_SPEAKER_L], samples[spkr],
159
+                                     *coeff_l * scale, nsamples);
160
+
161
+        if (*coeff_r && spkr != DCA_SPEAKER_R)
162
+            fdsp->vector_fmac_scalar(samples[DCA_SPEAKER_R], samples[spkr],
163
+                                     *coeff_r * scale, nsamples);
164
+
165
+        coeff_l++;
166
+        coeff_r++;
167
+    }
168
+}
169
+
170
+static int convert_bitstream(const uint8_t *src, int src_size, uint8_t *dst, int max_size)
171
+{
172
+    switch (AV_RB32(src)) {
173
+    case DCA_SYNCWORD_CORE_BE:
174
+    case DCA_SYNCWORD_SUBSTREAM:
175
+        memcpy(dst, src, src_size);
176
+        return src_size;
177
+    case DCA_SYNCWORD_CORE_LE:
178
+    case DCA_SYNCWORD_CORE_14B_BE:
179
+    case DCA_SYNCWORD_CORE_14B_LE:
180
+        return avpriv_dca_convert_bitstream(src, src_size, dst, max_size);
181
+    default:
182
+        return AVERROR_INVALIDDATA;
183
+    }
184
+}
185
+
186
+static int dcadec_decode_frame(AVCodecContext *avctx, void *data,
187
+                               int *got_frame_ptr, AVPacket *avpkt)
188
+{
189
+    DCAContext *s = avctx->priv_data;
190
+    AVFrame *frame = data;
191
+    uint8_t *input = avpkt->data;
192
+    int input_size = avpkt->size;
193
+    int i, ret, prev_packet = s->packet;
194
+
195
+    if (input_size < MIN_PACKET_SIZE || input_size > MAX_PACKET_SIZE) {
196
+        av_log(avctx, AV_LOG_ERROR, "Invalid packet size\n");
197
+        return AVERROR_INVALIDDATA;
198
+    }
199
+
200
+    av_fast_malloc(&s->buffer, &s->buffer_size,
201
+                   FFALIGN(input_size, 4096) + DCA_BUFFER_PADDING_SIZE);
202
+    if (!s->buffer)
203
+        return AVERROR(ENOMEM);
204
+
205
+    for (i = 0, ret = AVERROR_INVALIDDATA; i < input_size - MIN_PACKET_SIZE + 1 && ret < 0; i++)
206
+        ret = convert_bitstream(input + i, input_size - i, s->buffer, s->buffer_size);
207
+
208
+    if (ret < 0)
209
+        return ret;
210
+
211
+    input      = s->buffer;
212
+    input_size = ret;
213
+
214
+    s->packet = 0;
215
+
216
+    // Parse backward compatible core sub-stream
217
+    if (AV_RB32(input) == DCA_SYNCWORD_CORE_BE) {
218
+        int frame_size;
219
+
220
+        if ((ret = ff_dca_core_parse(&s->core, input, input_size)) < 0) {
221
+            s->core_residual_valid = 0;
222
+            return ret;
223
+        }
224
+
225
+        s->packet |= DCA_PACKET_CORE;
226
+
227
+        // EXXS data must be aligned on 4-byte boundary
228
+        frame_size = FFALIGN(s->core.frame_size, 4);
229
+        if (input_size - 4 > frame_size) {
230
+            input      += frame_size;
231
+            input_size -= frame_size;
232
+        }
233
+    }
234
+
235
+    if (!s->core_only) {
236
+        DCAExssAsset *asset = NULL;
237
+
238
+        // Parse extension sub-stream (EXSS)
239
+        if (AV_RB32(input) == DCA_SYNCWORD_SUBSTREAM) {
240
+            if ((ret = ff_dca_exss_parse(&s->exss, input, input_size)) < 0) {
241
+                if (avctx->err_recognition & AV_EF_EXPLODE)
242
+                    return ret;
243
+            } else {
244
+                s->packet |= DCA_PACKET_EXSS;
245
+                asset = &s->exss.assets[0];
246
+            }
247
+        }
248
+
249
+        // Parse XLL component in EXSS
250
+        if (asset && (asset->extension_mask & DCA_EXSS_XLL)) {
251
+            if ((ret = ff_dca_xll_parse(&s->xll, input, asset)) < 0) {
252
+                // Conceal XLL synchronization error
253
+                if (ret == AVERROR(EAGAIN)
254
+                    && (prev_packet & DCA_PACKET_XLL)
255
+                    && (s->packet & DCA_PACKET_CORE))
256
+                    s->packet |= DCA_PACKET_XLL | DCA_PACKET_RECOVERY;
257
+                else if (ret == AVERROR(ENOMEM) || (avctx->err_recognition & AV_EF_EXPLODE))
258
+                    return ret;
259
+            } else {
260
+                s->packet |= DCA_PACKET_XLL;
261
+            }
262
+        }
263
+
264
+        // Parse core extensions in EXSS or backward compatible core sub-stream
265
+        if ((s->packet & DCA_PACKET_CORE)
266
+            && (ret = ff_dca_core_parse_exss(&s->core, input, asset)) < 0)
267
+            return ret;
268
+    }
269
+
270
+    // Filter the frame
271
+    if (s->packet & DCA_PACKET_XLL) {
272
+        if (s->packet & DCA_PACKET_CORE) {
273
+            int x96_synth = -1;
274
+
275
+            // Enable X96 synthesis if needed
276
+            if (s->xll.chset[0].freq == 96000 && s->core.sample_rate == 48000)
277
+                x96_synth = 1;
278
+
279
+            if ((ret = ff_dca_core_filter_fixed(&s->core, x96_synth)) < 0) {
280
+                s->core_residual_valid = 0;
281
+                return ret;
282
+            }
283
+
284
+            // Force lossy downmixed output on the first core frame filtered.
285
+            // This prevents audible clicks when seeking and is consistent with
286
+            // what reference decoder does when there are multiple channel sets.
287
+            if (!s->core_residual_valid) {
288
+                if (s->xll.nreschsets > 0 && s->xll.nchsets > 1)
289
+                    s->packet |= DCA_PACKET_RECOVERY;
290
+                s->core_residual_valid = 1;
291
+            }
292
+        }
293
+
294
+        if ((ret = ff_dca_xll_filter_frame(&s->xll, frame)) < 0) {
295
+            // Fall back to core unless hard error
296
+            if (!(s->packet & DCA_PACKET_CORE))
297
+                return ret;
298
+            if (ret != AVERROR_INVALIDDATA || (avctx->err_recognition & AV_EF_EXPLODE))
299
+                return ret;
300
+            if ((ret = ff_dca_core_filter_frame(&s->core, frame)) < 0) {
301
+                s->core_residual_valid = 0;
302
+                return ret;
303
+            }
304
+        }
305
+    } else if (s->packet & DCA_PACKET_CORE) {
306
+        if ((ret = ff_dca_core_filter_frame(&s->core, frame)) < 0) {
307
+            s->core_residual_valid = 0;
308
+            return ret;
309
+        }
310
+        s->core_residual_valid = !!(s->core.filter_mode & DCA_FILTER_MODE_FIXED);
311
+    } else {
312
+        return AVERROR_INVALIDDATA;
313
+    }
314
+
315
+    *got_frame_ptr = 1;
316
+
317
+    return avpkt->size;
318
+}
319
+
320
+static av_cold void dcadec_flush(AVCodecContext *avctx)
321
+{
322
+    DCAContext *s = avctx->priv_data;
323
+
324
+    ff_dca_core_flush(&s->core);
325
+    ff_dca_xll_flush(&s->xll);
326
+
327
+    s->core_residual_valid = 0;
328
+}
329
+
330
+static av_cold int dcadec_close(AVCodecContext *avctx)
331
+{
332
+    DCAContext *s = avctx->priv_data;
333
+
334
+    ff_dca_core_close(&s->core);
335
+    ff_dca_xll_close(&s->xll);
336
+
337
+    av_freep(&s->buffer);
338
+    s->buffer_size = 0;
339
+
340
+    return 0;
341
+}
342
+
343
+static av_cold int dcadec_init(AVCodecContext *avctx)
344
+{
345
+    DCAContext *s = avctx->priv_data;
346
+
347
+    s->avctx = avctx;
348
+    s->core.avctx = avctx;
349
+    s->exss.avctx = avctx;
350
+    s->xll.avctx = avctx;
351
+
352
+    if (ff_dca_core_init(&s->core) < 0)
353
+        return AVERROR(ENOMEM);
354
+
355
+    ff_dcadsp_init(&s->dcadsp);
356
+    s->core.dcadsp = &s->dcadsp;
357
+    s->xll.dcadsp = &s->dcadsp;
358
+
359
+    switch (avctx->request_channel_layout & ~AV_CH_LAYOUT_NATIVE) {
360
+    case 0:
361
+        s->request_channel_layout = 0;
362
+        break;
363
+    case AV_CH_LAYOUT_STEREO:
364
+    case AV_CH_LAYOUT_STEREO_DOWNMIX:
365
+        s->request_channel_layout = DCA_SPEAKER_LAYOUT_STEREO;
366
+        break;
367
+    case AV_CH_LAYOUT_5POINT0:
368
+        s->request_channel_layout = DCA_SPEAKER_LAYOUT_5POINT0;
369
+        break;
370
+    case AV_CH_LAYOUT_5POINT1:
371
+        s->request_channel_layout = DCA_SPEAKER_LAYOUT_5POINT1;
372
+        break;
373
+    default:
374
+        av_log(avctx, AV_LOG_WARNING, "Invalid request_channel_layout\n");
375
+        break;
376
+    }
377
+
378
+    avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
379
+    avctx->bits_per_raw_sample = 24;
380
+
381
+    return 0;
382
+}
383
+
384
+#define OFFSET(x) offsetof(DCAContext, x)
385
+#define PARAM AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
386
+
387
+static const AVOption dcadec_options[] = {
388
+    { "core_only", "Decode core only without extensions", OFFSET(core_only), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, PARAM },
389
+    { NULL }
390
+};
391
+
392
+static const AVClass dcadec_class = {
393
+    .class_name = "DCA decoder",
394
+    .item_name  = av_default_item_name,
395
+    .option     = dcadec_options,
396
+    .version    = LIBAVUTIL_VERSION_INT,
397
+    .category   = AV_CLASS_CATEGORY_DECODER,
398
+};
399
+
400
+AVCodec ff_dca_decoder = {
401
+    .name           = "dca",
402
+    .long_name      = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
403
+    .type           = AVMEDIA_TYPE_AUDIO,
404
+    .id             = AV_CODEC_ID_DTS,
405
+    .priv_data_size = sizeof(DCAContext),
406
+    .init           = dcadec_init,
407
+    .decode         = dcadec_decode_frame,
408
+    .close          = dcadec_close,
409
+    .flush          = dcadec_flush,
410
+    .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_CHANNEL_CONF,
411
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S32P,
412
+                                                      AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE },
413
+    .priv_class     = &dcadec_class,
414
+    .profiles       = NULL_IF_CONFIG_SMALL(ff_dca_profiles),
415
+    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
416
+};
0 417
new file mode 100644
... ...
@@ -0,0 +1,80 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#ifndef AVCODEC_DCADEC_H
21
+#define AVCODEC_DCADEC_H
22
+
23
+#include "libavutil/common.h"
24
+#include "libavutil/float_dsp.h"
25
+
26
+#include "avcodec.h"
27
+#include "get_bits.h"
28
+#include "dca.h"
29
+#include "dcadsp.h"
30
+#include "dca_core.h"
31
+#include "dca_exss.h"
32
+#include "dca_xll.h"
33
+
34
+#define DCA_BUFFER_PADDING_SIZE     1024
35
+
36
+#define DCA_PACKET_CORE         0x01
37
+#define DCA_PACKET_EXSS         0x02
38
+#define DCA_PACKET_XLL          0x04
39
+#define DCA_PACKET_RECOVERY     0x08
40
+
41
+typedef struct DCAContext {
42
+    const AVClass   *class;       ///< class for AVOptions
43
+    AVCodecContext  *avctx;
44
+
45
+    DCACoreDecoder core;  ///< Core decoder context
46
+    DCAExssParser  exss;  ///< EXSS parser context
47
+    DCAXllDecoder  xll;   ///< XLL decoder context
48
+
49
+    DCADSPContext   dcadsp;
50
+
51
+    uint8_t         *buffer;    ///< Packet buffer
52
+    unsigned int    buffer_size;
53
+
54
+    int     packet; ///< Packet flags
55
+
56
+    int     core_residual_valid;    ///< Core valid for residual decoding
57
+
58
+    int     request_channel_layout; ///< Converted from avctx.request_channel_layout
59
+    int     core_only;              ///< Core only decoding flag
60
+} DCAContext;
61
+
62
+int ff_dca_set_channel_layout(AVCodecContext *avctx, int *ch_remap, int dca_mask);
63
+
64
+int ff_dca_check_crc(GetBitContext *s, int p1, int p2);
65
+
66
+void ff_dca_downmix_to_stereo_fixed(DCADSPContext *dcadsp, int32_t **samples,
67
+                                    int *coeff_l, int nsamples, int ch_mask);
68
+void ff_dca_downmix_to_stereo_float(AVFloatDSPContext *fdsp, float **samples,
69
+                                    int *coeff_l, int nsamples, int ch_mask);
70
+
71
+static inline int ff_dca_seek_bits(GetBitContext *s, int p)
72
+{
73
+    if (p < s->index || p > s->size_in_bits)
74
+        return -1;
75
+    s->index = p;
76
+    return 0;
77
+}
78
+
79
+#endif
0 80
new file mode 100644
... ...
@@ -0,0 +1,413 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include "libavutil/mem.h"
21
+
22
+#include "dcadsp.h"
23
+#include "dcamath.h"
24
+
25
+static void decode_hf_c(int32_t **dst,
26
+                        const int32_t *vq_index,
27
+                        const int8_t hf_vq[1024][32],
28
+                        int32_t scale_factors[32][2],
29
+                        intptr_t sb_start, intptr_t sb_end,
30
+                        intptr_t ofs, intptr_t len)
31
+{
32
+    int i, j;
33
+
34
+    for (i = sb_start; i < sb_end; i++) {
35
+        const int8_t *coeff = hf_vq[vq_index[i]];
36
+        int32_t scale = scale_factors[i][0];
37
+        for (j = 0; j < len; j++)
38
+            dst[i][j + ofs] = clip23(coeff[j] * scale + (1 << 3) >> 4);
39
+    }
40
+}
41
+
42
+static void decode_joint_c(int32_t **dst, int32_t **src,
43
+                           const int32_t *scale_factors,
44
+                           intptr_t sb_start, intptr_t sb_end,
45
+                           intptr_t ofs, intptr_t len)
46
+{
47
+    int i, j;
48
+
49
+    for (i = sb_start; i < sb_end; i++) {
50
+        int32_t scale = scale_factors[i];
51
+        for (j = 0; j < len; j++)
52
+            dst[i][j + ofs] = clip23(mul17(src[i][j + ofs], scale));
53
+    }
54
+}
55
+
56
+static void lfe_fir_float_c(float *pcm_samples, int32_t *lfe_samples,
57
+                            const float *filter_coeff, intptr_t npcmblocks,
58
+                            int dec_select)
59
+{
60
+    // Select decimation factor
61
+    int factor = 64 << dec_select;
62
+    int ncoeffs = 8 >> dec_select;
63
+    int nlfesamples = npcmblocks >> (dec_select + 1);
64
+    int i, j, k;
65
+
66
+    for (i = 0; i < nlfesamples; i++) {
67
+        // One decimated sample generates 64 or 128 interpolated ones
68
+        for (j = 0; j < factor / 2; j++) {
69
+            float a = 0;
70
+            float b = 0;
71
+
72
+            for (k = 0; k < ncoeffs; k++) {
73
+                a += filter_coeff[      j * ncoeffs + k] * lfe_samples[-k];
74
+                b += filter_coeff[255 - j * ncoeffs - k] * lfe_samples[-k];
75
+            }
76
+
77
+            pcm_samples[             j] = a;
78
+            pcm_samples[factor / 2 + j] = b;
79
+        }
80
+
81
+        lfe_samples++;
82
+        pcm_samples += factor;
83
+    }
84
+}
85
+
86
+static void lfe_fir1_float_c(float *pcm_samples, int32_t *lfe_samples,
87
+                             const float *filter_coeff, intptr_t npcmblocks)
88
+{
89
+    lfe_fir_float_c(pcm_samples, lfe_samples, filter_coeff, npcmblocks, 0);
90
+}
91
+
92
+static void lfe_fir2_float_c(float *pcm_samples, int32_t *lfe_samples,
93
+                             const float *filter_coeff, intptr_t npcmblocks)
94
+{
95
+    lfe_fir_float_c(pcm_samples, lfe_samples, filter_coeff, npcmblocks, 1);
96
+}
97
+
98
+static void lfe_x96_float_c(float *dst, const float *src,
99
+                            float *hist, intptr_t len)
100
+{
101
+    float prev = *hist;
102
+    int i;
103
+
104
+    for (i = 0; i < len; i++) {
105
+        float a = 0.25f * src[i] + 0.75f * prev;
106
+        float b = 0.75f * src[i] + 0.25f * prev;
107
+        prev = src[i];
108
+        *dst++ = a;
109
+        *dst++ = b;
110
+    }
111
+
112
+    *hist = prev;
113
+}
114
+
115
+static void sub_qmf32_float_c(SynthFilterContext *synth,
116
+                              FFTContext *imdct,
117
+                              float *pcm_samples,
118
+                              int32_t **subband_samples_lo,
119
+                              int32_t **subband_samples_hi,
120
+                              float *hist1, int *offset, float *hist2,
121
+                              const float *filter_coeff, intptr_t npcmblocks,
122
+                              float scale)
123
+{
124
+    LOCAL_ALIGNED(32, float, input, [32]);
125
+    int i, j;
126
+
127
+    for (j = 0; j < npcmblocks; j++) {
128
+        // Load in one sample from each subband
129
+        for (i = 0; i < 32; i++) {
130
+            if ((i - 1) & 2)
131
+                input[i] = -subband_samples_lo[i][j];
132
+            else
133
+                input[i] =  subband_samples_lo[i][j];
134
+        }
135
+
136
+        // One subband sample generates 32 interpolated ones
137
+        synth->synth_filter_float(imdct, hist1, offset,
138
+                                  hist2, filter_coeff,
139
+                                  pcm_samples, input, scale);
140
+        pcm_samples += 32;
141
+    }
142
+}
143
+
144
+static void sub_qmf64_float_c(SynthFilterContext *synth,
145
+                              FFTContext *imdct,
146
+                              float *pcm_samples,
147
+                              int32_t **subband_samples_lo,
148
+                              int32_t **subband_samples_hi,
149
+                              float *hist1, int *offset, float *hist2,
150
+                              const float *filter_coeff, intptr_t npcmblocks,
151
+                              float scale)
152
+{
153
+    LOCAL_ALIGNED(32, float, input, [64]);
154
+    int i, j;
155
+
156
+    if (!subband_samples_hi)
157
+        memset(&input[32], 0, sizeof(input[0]) * 32);
158
+
159
+    for (j = 0; j < npcmblocks; j++) {
160
+        // Load in one sample from each subband
161
+        if (subband_samples_hi) {
162
+            // Full 64 subbands, first 32 are residual coded
163
+            for (i =  0; i < 32; i++) {
164
+                if ((i - 1) & 2)
165
+                    input[i] = -subband_samples_lo[i][j] - subband_samples_hi[i][j];
166
+                else
167
+                    input[i] =  subband_samples_lo[i][j] + subband_samples_hi[i][j];
168
+            }
169
+            for (i = 32; i < 64; i++) {
170
+                if ((i - 1) & 2)
171
+                    input[i] = -subband_samples_hi[i][j];
172
+                else
173
+                    input[i] =  subband_samples_hi[i][j];
174
+            }
175
+        } else {
176
+            // Only first 32 subbands
177
+            for (i =  0; i < 32; i++) {
178
+                if ((i - 1) & 2)
179
+                    input[i] = -subband_samples_lo[i][j];
180
+                else
181
+                    input[i] =  subband_samples_lo[i][j];
182
+            }
183
+        }
184
+
185
+        // One subband sample generates 64 interpolated ones
186
+        synth->synth_filter_float_64(imdct, hist1, offset,
187
+                                     hist2, filter_coeff,
188
+                                     pcm_samples, input, scale);
189
+        pcm_samples += 64;
190
+    }
191
+}
192
+
193
+static void lfe_fir_fixed_c(int32_t *pcm_samples, int32_t *lfe_samples,
194
+                            const int32_t *filter_coeff, intptr_t npcmblocks)
195
+{
196
+    // Select decimation factor
197
+    int nlfesamples = npcmblocks >> 1;
198
+    int i, j, k;
199
+
200
+    for (i = 0; i < nlfesamples; i++) {
201
+        // One decimated sample generates 64 interpolated ones
202
+        for (j = 0; j < 32; j++) {
203
+            int64_t a = 0;
204
+            int64_t b = 0;
205
+
206
+            for (k = 0; k < 8; k++) {
207
+                a += (int64_t)filter_coeff[      j * 8 + k] * lfe_samples[-k];
208
+                b += (int64_t)filter_coeff[255 - j * 8 - k] * lfe_samples[-k];
209
+            }
210
+
211
+            pcm_samples[     j] = clip23(norm23(a));
212
+            pcm_samples[32 + j] = clip23(norm23(b));
213
+        }
214
+
215
+        lfe_samples++;
216
+        pcm_samples += 64;
217
+    }
218
+}
219
+
220
+static void lfe_x96_fixed_c(int32_t *dst, const int32_t *src,
221
+                            int32_t *hist, intptr_t len)
222
+{
223
+    int32_t prev = *hist;
224
+    int i;
225
+
226
+    for (i = 0; i < len; i++) {
227
+        int64_t a = INT64_C(2097471) * src[i] + INT64_C(6291137) * prev;
228
+        int64_t b = INT64_C(6291137) * src[i] + INT64_C(2097471) * prev;
229
+        prev = src[i];
230
+        *dst++ = clip23(norm23(a));
231
+        *dst++ = clip23(norm23(b));
232
+    }
233
+
234
+    *hist = prev;
235
+}
236
+
237
+static void sub_qmf32_fixed_c(SynthFilterContext *synth,
238
+                              DCADCTContext *imdct,
239
+                              int32_t *pcm_samples,
240
+                              int32_t **subband_samples_lo,
241
+                              int32_t **subband_samples_hi,
242
+                              int32_t *hist1, int *offset, int32_t *hist2,
243
+                              const int32_t *filter_coeff, intptr_t npcmblocks)
244
+{
245
+    LOCAL_ALIGNED(32, int32_t, input, [32]);
246
+    int i, j;
247
+
248
+    for (j = 0; j < npcmblocks; j++) {
249
+        // Load in one sample from each subband
250
+        for (i = 0; i < 32; i++)
251
+            input[i] = subband_samples_lo[i][j];
252
+
253
+        // One subband sample generates 32 interpolated ones
254
+        synth->synth_filter_fixed(imdct, hist1, offset,
255
+                                  hist2, filter_coeff,
256
+                                  pcm_samples, input);
257
+        pcm_samples += 32;
258
+    }
259
+}
260
+
261
+static void sub_qmf64_fixed_c(SynthFilterContext *synth,
262
+                              DCADCTContext *imdct,
263
+                              int32_t *pcm_samples,
264
+                              int32_t **subband_samples_lo,
265
+                              int32_t **subband_samples_hi,
266
+                              int32_t *hist1, int *offset, int32_t *hist2,
267
+                              const int32_t *filter_coeff, intptr_t npcmblocks)
268
+{
269
+    LOCAL_ALIGNED(32, int32_t, input, [64]);
270
+    int i, j;
271
+
272
+    if (!subband_samples_hi)
273
+        memset(&input[32], 0, sizeof(input[0]) * 32);
274
+
275
+    for (j = 0; j < npcmblocks; j++) {
276
+        // Load in one sample from each subband
277
+        if (subband_samples_hi) {
278
+            // Full 64 subbands, first 32 are residual coded
279
+            for (i =  0; i < 32; i++)
280
+                input[i] = subband_samples_lo[i][j] + subband_samples_hi[i][j];
281
+            for (i = 32; i < 64; i++)
282
+                input[i] = subband_samples_hi[i][j];
283
+        } else {
284
+            // Only first 32 subbands
285
+            for (i =  0; i < 32; i++)
286
+                input[i] = subband_samples_lo[i][j];
287
+        }
288
+
289
+        // One subband sample generates 64 interpolated ones
290
+        synth->synth_filter_fixed_64(imdct, hist1, offset,
291
+                                     hist2, filter_coeff,
292
+                                     pcm_samples, input);
293
+        pcm_samples += 64;
294
+    }
295
+}
296
+
297
+static void decor_c(int32_t *dst, const int32_t *src, intptr_t coeff, intptr_t len)
298
+{
299
+    int i;
300
+
301
+    for (i = 0; i < len; i++)
302
+        dst[i] += src[i] * coeff + (1 << 2) >> 3;
303
+}
304
+
305
+static void dmix_sub_xch_c(int32_t *dst1, int32_t *dst2,
306
+                           const int32_t *src, intptr_t len)
307
+{
308
+    int i;
309
+
310
+    for (i = 0; i < len; i++) {
311
+        int32_t cs = mul23(src[i], 5931520 /* M_SQRT1_2 * (1 << 23) */);
312
+        dst1[i] -= cs;
313
+        dst2[i] -= cs;
314
+    }
315
+}
316
+
317
+static void dmix_sub_c(int32_t *dst, const int32_t *src, intptr_t coeff, intptr_t len)
318
+{
319
+    int i;
320
+
321
+    for (i = 0; i < len; i++)
322
+        dst[i] -= mul15(src[i], coeff);
323
+}
324
+
325
+static void dmix_add_c(int32_t *dst, const int32_t *src, intptr_t coeff, intptr_t len)
326
+{
327
+    int i;
328
+
329
+    for (i = 0; i < len; i++)
330
+        dst[i] += mul15(src[i], coeff);
331
+}
332
+
333
+static void dmix_scale_c(int32_t *dst, intptr_t scale, intptr_t len)
334
+{
335
+    int i;
336
+
337
+    for (i = 0; i < len; i++)
338
+        dst[i] = mul15(dst[i], scale);
339
+}
340
+
341
+static void dmix_scale_inv_c(int32_t *dst, intptr_t scale_inv, intptr_t len)
342
+{
343
+    int i;
344
+
345
+    for (i = 0; i < len; i++)
346
+        dst[i] = mul16(dst[i], scale_inv);
347
+}
348
+
349
+static void filter0(int32_t *dst, const int32_t *src, int32_t coeff, intptr_t len)
350
+{
351
+    int i;
352
+
353
+    for (i = 0; i < len; i++)
354
+        dst[i] -= mul22(src[i], coeff);
355
+}
356
+
357
+static void filter1(int32_t *dst, const int32_t *src, int32_t coeff, intptr_t len)
358
+{
359
+    int i;
360
+
361
+    for (i = 0; i < len; i++)
362
+        dst[i] -= mul23(src[i], coeff);
363
+}
364
+
365
+static void assemble_freq_bands_c(int32_t *dst, int32_t *src0, int32_t *src1,
366
+                                  const int32_t *coeff, intptr_t len)
367
+{
368
+    int i;
369
+
370
+    filter0(src0, src1, coeff[0], len);
371
+    filter0(src1, src0, coeff[1], len);
372
+    filter0(src0, src1, coeff[2], len);
373
+    filter0(src1, src0, coeff[3], len);
374
+
375
+    for (i = 0; i < 8; i++, src0--) {
376
+        filter1(src0, src1, coeff[i +  4], len);
377
+        filter1(src1, src0, coeff[i + 12], len);
378
+        filter1(src0, src1, coeff[i +  4], len);
379
+    }
380
+
381
+    for (i = 0; i < len; i++) {
382
+        *dst++ = *src1++;
383
+        *dst++ = *++src0;
384
+    }
385
+}
386
+
387
+av_cold void ff_dcadsp_init(DCADSPContext *s)
388
+{
389
+    s->decode_hf     = decode_hf_c;
390
+    s->decode_joint  = decode_joint_c;
391
+
392
+    s->lfe_fir_float[0] = lfe_fir1_float_c;
393
+    s->lfe_fir_float[1] = lfe_fir2_float_c;
394
+    s->lfe_x96_float    = lfe_x96_float_c;
395
+    s->sub_qmf_float[0] = sub_qmf32_float_c;
396
+    s->sub_qmf_float[1] = sub_qmf64_float_c;
397
+
398
+    s->lfe_fir_fixed    = lfe_fir_fixed_c;
399
+    s->lfe_x96_fixed    = lfe_x96_fixed_c;
400
+    s->sub_qmf_fixed[0] = sub_qmf32_fixed_c;
401
+    s->sub_qmf_fixed[1] = sub_qmf64_fixed_c;
402
+
403
+    s->decor   = decor_c;
404
+
405
+    s->dmix_sub_xch   = dmix_sub_xch_c;
406
+    s->dmix_sub       = dmix_sub_c;
407
+    s->dmix_add       = dmix_add_c;
408
+    s->dmix_scale     = dmix_scale_c;
409
+    s->dmix_scale_inv = dmix_scale_inv_c;
410
+
411
+    s->assemble_freq_bands = assemble_freq_bands_c;
412
+}
0 413
new file mode 100644
... ...
@@ -0,0 +1,91 @@
0
+/*
1
+ * Copyright (C) 2016 foo86
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#ifndef AVCODEC_DCADSP_H
21
+#define AVCODEC_DCADSP_H
22
+
23
+#include "libavutil/common.h"
24
+
25
+#include "fft.h"
26
+#include "dcadct.h"
27
+#include "synth_filter.h"
28
+
29
+typedef struct DCADSPContext {
30
+    void (*decode_hf)(int32_t **dst,
31
+                      const int32_t *vq_index,
32
+                      const int8_t hf_vq[1024][32],
33
+                      int32_t scale_factors[32][2],
34
+                      intptr_t sb_start, intptr_t sb_end,
35
+                      intptr_t ofs, intptr_t len);
36
+
37
+    void (*decode_joint)(int32_t **dst, int32_t **src,
38
+                         const int32_t *scale_factors,
39
+                         intptr_t sb_start, intptr_t sb_end,
40
+                         intptr_t ofs, intptr_t len);
41
+
42
+    void (*lfe_fir_float[2])(float *pcm_samples, int32_t *lfe_samples,
43
+                             const float *filter_coeff, intptr_t npcmblocks);
44
+
45
+    void (*lfe_x96_float)(float *dst, const float *src,
46
+                          float *hist, intptr_t len);
47
+
48
+    void (*sub_qmf_float[2])(SynthFilterContext *synth,
49
+                             FFTContext *imdct,
50
+                             float *pcm_samples,
51
+                             int32_t **subband_samples_lo,
52
+                             int32_t **subband_samples_hi,
53
+                             float *hist1, int *offset, float *hist2,
54
+                             const float *filter_coeff, intptr_t npcmblocks,
55
+                             float scale);
56
+
57
+    void (*lfe_fir_fixed)(int32_t *pcm_samples, int32_t *lfe_samples,
58
+                          const int32_t *filter_coeff, intptr_t npcmblocks);
59
+
60
+    void (*lfe_x96_fixed)(int32_t *dst, const int32_t *src,
61
+                          int32_t *hist, intptr_t len);
62
+
63
+    void (*sub_qmf_fixed[2])(SynthFilterContext *synth,
64
+                             DCADCTContext *imdct,
65
+                             int32_t *pcm_samples,
66
+                             int32_t **subband_samples_lo,
67
+                             int32_t **subband_samples_hi,
68
+                             int32_t *hist1, int *offset, int32_t *hist2,
69
+                             const int32_t *filter_coeff, intptr_t npcmblocks);
70
+
71
+    void (*decor)(int32_t *dst, const int32_t *src, intptr_t coeff, intptr_t len);
72
+
73
+    void (*dmix_sub_xch)(int32_t *dst1, int32_t *dst2,
74
+                         const int32_t *src, intptr_t len);
75
+
76
+    void (*dmix_sub)(int32_t *dst, const int32_t *src, intptr_t coeff, intptr_t len);
77
+
78
+    void (*dmix_add)(int32_t *dst, const int32_t *src, intptr_t coeff, intptr_t len);
79
+
80
+    void (*dmix_scale)(int32_t *dst, intptr_t scale, intptr_t len);
81
+
82
+    void (*dmix_scale_inv)(int32_t *dst, intptr_t scale_inv, intptr_t len);
83
+
84
+    void (*assemble_freq_bands)(int32_t *dst, int32_t *src0, int32_t *src1,
85
+                                const int32_t *coeff, intptr_t len);
86
+} DCADSPContext;
87
+
88
+av_cold void ff_dcadsp_init(DCADSPContext *s);
89
+
90
+#endif
... ...
@@ -30,7 +30,7 @@
30 30
 
31 31
 #define LIBAVCODEC_VERSION_MAJOR  57
32 32
 #define LIBAVCODEC_VERSION_MINOR  24
33
-#define LIBAVCODEC_VERSION_MICRO 100
33
+#define LIBAVCODEC_VERSION_MICRO 101
34 34
 
35 35
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
36 36
                                                LIBAVCODEC_VERSION_MINOR, \
... ...
@@ -44,7 +44,7 @@ OBJS-$(CONFIG_ADPCM_G722_ENCODER)      += x86/g722dsp_init.o
44 44
 OBJS-$(CONFIG_ALAC_DECODER)            += x86/alacdsp_init.o
45 45
 OBJS-$(CONFIG_APNG_DECODER)            += x86/pngdsp_init.o
46 46
 OBJS-$(CONFIG_CAVS_DECODER)            += x86/cavsdsp.o
47
-#OBJS-$(CONFIG_DCA_DECODER)             += x86/synth_filter_init.o
47
+OBJS-$(CONFIG_DCA_DECODER)             += x86/synth_filter_init.o
48 48
 OBJS-$(CONFIG_DNXHD_ENCODER)           += x86/dnxhdenc_init.o
49 49
 OBJS-$(CONFIG_HEVC_DECODER)            += x86/hevcdsp_init.o
50 50
 OBJS-$(CONFIG_JPEG2000_DECODER)        += x86/jpeg2000dsp_init.o
... ...
@@ -132,7 +132,7 @@ YASM-OBJS-$(CONFIG_ADPCM_G722_DECODER) += x86/g722dsp.o
132 132
 YASM-OBJS-$(CONFIG_ADPCM_G722_ENCODER) += x86/g722dsp.o
133 133
 YASM-OBJS-$(CONFIG_ALAC_DECODER)       += x86/alacdsp.o
134 134
 YASM-OBJS-$(CONFIG_APNG_DECODER)       += x86/pngdsp.o
135
-#YASM-OBJS-$(CONFIG_DCA_DECODER)        += x86/synth_filter.o
135
+YASM-OBJS-$(CONFIG_DCA_DECODER)        += x86/synth_filter.o
136 136
 YASM-OBJS-$(CONFIG_DIRAC_DECODER)      += x86/diracdsp_mmx.o x86/diracdsp_yasm.o \
137 137
                                           x86/dwt_yasm.o
138 138
 YASM-OBJS-$(CONFIG_DNXHD_ENCODER)      += x86/dnxhdenc.o
... ...
@@ -1,7 +1,7 @@
1 1
 # libavcodec tests
2 2
 AVCODECOBJS-$(CONFIG_ALAC_DECODER) += alacdsp.o
3 3
 AVCODECOBJS-$(CONFIG_BSWAPDSP) += bswapdsp.o
4
-#AVCODECOBJS-$(CONFIG_DCA_DECODER) += synth_filter.o
4
+AVCODECOBJS-$(CONFIG_DCA_DECODER) += synth_filter.o
5 5
 AVCODECOBJS-$(CONFIG_FLACDSP)  += flacdsp.o
6 6
 AVCODECOBJS-$(CONFIG_FMTCONVERT)   += fmtconvert.o
7 7
 AVCODECOBJS-$(CONFIG_H264PRED) += h264pred.o
... ...
@@ -71,9 +71,9 @@ static const struct {
71 71
     #if CONFIG_BSWAPDSP
72 72
         { "bswapdsp", checkasm_check_bswapdsp },
73 73
     #endif
74
-/*    #if CONFIG_DCA_DECODER
74
+    #if CONFIG_DCA_DECODER
75 75
         { "synth_filter", checkasm_check_synth_filter },
76
-    #endif*/
76
+    #endif
77 77
     #if CONFIG_FLACDSP
78 78
         { "flacdsp", checkasm_check_flacdsp },
79 79
     #endif
... ...
@@ -99,14 +99,14 @@ FATE_ACODEC-$(call ENCDEC, ALAC, MOV) += fate-acodec-alac
99 99
 fate-acodec-alac: FMT = mov
100 100
 fate-acodec-alac: CODEC = alac -compression_level 1
101 101
 
102
-#FATE_ACODEC-$(call ENCDEC, DCA, DTS) += fate-acodec-dca
102
+FATE_ACODEC-$(call ENCDEC, DCA, DTS) += fate-acodec-dca
103 103
 fate-acodec-dca: tests/data/asynth-44100-2.wav
104 104
 fate-acodec-dca: SRC = tests/data/asynth-44100-2.wav
105 105
 fate-acodec-dca: CMD = md5 -i $(TARGET_PATH)/$(SRC) -c:a dca -strict -2 -f dts -flags +bitexact
106 106
 fate-acodec-dca: CMP = oneline
107 107
 fate-acodec-dca: REF = 7ffdefdf47069289990755c79387cc90
108 108
 
109
-#FATE_ACODEC-$(call ENCDEC, DCA, WAV) += fate-acodec-dca2
109
+FATE_ACODEC-$(call ENCDEC, DCA, WAV) += fate-acodec-dca2
110 110
 fate-acodec-dca2: CMD = enc_dec_pcm dts wav s16le $(SRC) -c:a dca -strict -2 -flags +bitexact
111 111
 fate-acodec-dca2: REF = $(SRC)
112 112
 fate-acodec-dca2: CMP = stddev
... ...
@@ -21,7 +21,7 @@ fate-dca-core: CMD = pcm -i $(TARGET_SAMPLES)/dts/dts.ts
21 21
 fate-dca-core: CMP = oneoff
22 22
 fate-dca-core: REF = $(SAMPLES)/dts/dts.pcm
23 23
 
24
-#FATE_SAMPLES_AUDIO-$(CONFIG_DCA_DECODER) += $(FATE_DCA-yes)
24
+FATE_SAMPLES_AUDIO-$(CONFIG_DCA_DECODER) += $(FATE_DCA-yes)
25 25
 fate-dca: $(FATE_DCA-yes)
26 26
 
27 27
 FATE_SAMPLES_AUDIO-$(call DEMDEC, DSICIN, DSICINAUDIO) += fate-delphine-cin-audio
... ...
@@ -31,7 +31,7 @@ FATE_SAMPLES_AUDIO-$(call DEMDEC, DSS, DSS_SP) += fate-dss-lp fate-dss-sp
31 31
 fate-dss-lp: CMD = framecrc -i $(TARGET_SAMPLES)/dss/lp.dss -frames 30
32 32
 fate-dss-sp: CMD = framecrc -i $(TARGET_SAMPLES)/dss/sp.dss -frames 30
33 33
 
34
-#FATE_SAMPLES_AUDIO-$(call DEMDEC, DTS, DCA) += fate-dts_es
34
+FATE_SAMPLES_AUDIO-$(call DEMDEC, DTS, DCA) += fate-dts_es
35 35
 fate-dts_es: CMD = pcm -i $(TARGET_SAMPLES)/dts/dts_es.dts
36 36
 fate-dts_es: CMP = oneoff
37 37
 fate-dts_es: REF = $(SAMPLES)/dts/dts_es_2.pcm