]> git.sesse.net Git - ffmpeg/blob - libavcodec/dcadec.c
Merge commit '84c4714f397c9c50eb9d49008cc1c08385f68f31'
[ffmpeg] / libavcodec / dcadec.c
1 /*
2  * DCA compatible decoder
3  * Copyright (C) 2004 Gildas Bazin
4  * Copyright (C) 2004 Benjamin Zores
5  * Copyright (C) 2006 Benjamin Larsson
6  * Copyright (C) 2007 Konstantin Shishkov
7  * Copyright (C) 2012 Paul B Mahol
8  * Copyright (C) 2014 Niels Möller
9  *
10  * This file is part of FFmpeg.
11  *
12  * FFmpeg is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * FFmpeg is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with FFmpeg; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26
27 #include <math.h>
28 #include <stddef.h>
29 #include <stdio.h>
30
31 #include "libavutil/attributes.h"
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/common.h"
34 #include "libavutil/float_dsp.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/intreadwrite.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/samplefmt.h"
40
41 #include "avcodec.h"
42 #include "dca.h"
43 #include "dca_syncwords.h"
44 #include "dcadata.h"
45 #include "dcadsp.h"
46 #include "dcahuff.h"
47 #include "fft.h"
48 #include "fmtconvert.h"
49 #include "get_bits.h"
50 #include "internal.h"
51 #include "mathops.h"
52 #include "profiles.h"
53 #include "synth_filter.h"
54
55 #if ARCH_ARM
56 #   include "arm/dca.h"
57 #endif
58
59 enum DCAMode {
60     DCA_MONO = 0,
61     DCA_CHANNEL,
62     DCA_STEREO,
63     DCA_STEREO_SUMDIFF,
64     DCA_STEREO_TOTAL,
65     DCA_3F,
66     DCA_2F1R,
67     DCA_3F1R,
68     DCA_2F2R,
69     DCA_3F2R,
70     DCA_4F2R
71 };
72
73
74 enum DCAXxchSpeakerMask {
75     DCA_XXCH_FRONT_CENTER          = 0x0000001,
76     DCA_XXCH_FRONT_LEFT            = 0x0000002,
77     DCA_XXCH_FRONT_RIGHT           = 0x0000004,
78     DCA_XXCH_SIDE_REAR_LEFT        = 0x0000008,
79     DCA_XXCH_SIDE_REAR_RIGHT       = 0x0000010,
80     DCA_XXCH_LFE1                  = 0x0000020,
81     DCA_XXCH_REAR_CENTER           = 0x0000040,
82     DCA_XXCH_SURROUND_REAR_LEFT    = 0x0000080,
83     DCA_XXCH_SURROUND_REAR_RIGHT   = 0x0000100,
84     DCA_XXCH_SIDE_SURROUND_LEFT    = 0x0000200,
85     DCA_XXCH_SIDE_SURROUND_RIGHT   = 0x0000400,
86     DCA_XXCH_FRONT_CENTER_LEFT     = 0x0000800,
87     DCA_XXCH_FRONT_CENTER_RIGHT    = 0x0001000,
88     DCA_XXCH_FRONT_HIGH_LEFT       = 0x0002000,
89     DCA_XXCH_FRONT_HIGH_CENTER     = 0x0004000,
90     DCA_XXCH_FRONT_HIGH_RIGHT      = 0x0008000,
91     DCA_XXCH_LFE2                  = 0x0010000,
92     DCA_XXCH_SIDE_FRONT_LEFT       = 0x0020000,
93     DCA_XXCH_SIDE_FRONT_RIGHT      = 0x0040000,
94     DCA_XXCH_OVERHEAD              = 0x0080000,
95     DCA_XXCH_SIDE_HIGH_LEFT        = 0x0100000,
96     DCA_XXCH_SIDE_HIGH_RIGHT       = 0x0200000,
97     DCA_XXCH_REAR_HIGH_CENTER      = 0x0400000,
98     DCA_XXCH_REAR_HIGH_LEFT        = 0x0800000,
99     DCA_XXCH_REAR_HIGH_RIGHT       = 0x1000000,
100     DCA_XXCH_REAR_LOW_CENTER       = 0x2000000,
101     DCA_XXCH_REAR_LOW_LEFT         = 0x4000000,
102     DCA_XXCH_REAR_LOW_RIGHT        = 0x8000000,
103 };
104
105 #define DCA_DOLBY                  101           /* FIXME */
106
107 #define DCA_CHANNEL_BITS             6
108 #define DCA_CHANNEL_MASK          0x3F
109
110 #define DCA_LFE                   0x80
111
112 #define HEADER_SIZE                 14
113
114 #define DCA_NSYNCAUX        0x9A1105A0
115
116 /** Bit allocation */
117 typedef struct BitAlloc {
118     int offset;                 ///< code values offset
119     int maxbits[8];             ///< max bits in VLC
120     int wrap;                   ///< wrap for get_vlc2()
121     VLC vlc[8];                 ///< actual codes
122 } BitAlloc;
123
124 static BitAlloc dca_bitalloc_index;    ///< indexes for samples VLC select
125 static BitAlloc dca_tmode;             ///< transition mode VLCs
126 static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
127 static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
128
129 static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba,
130                                          int idx)
131 {
132     return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) +
133            ba->offset;
134 }
135
136 static float dca_dmix_code(unsigned code);
137
138 static av_cold void dca_init_vlcs(void)
139 {
140     static int vlcs_initialized = 0;
141     int i, j, c = 14;
142     static VLC_TYPE dca_table[23622][2];
143
144     if (vlcs_initialized)
145         return;
146
147     dca_bitalloc_index.offset = 1;
148     dca_bitalloc_index.wrap   = 2;
149     for (i = 0; i < 5; i++) {
150         dca_bitalloc_index.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i]];
151         dca_bitalloc_index.vlc[i].table_allocated = ff_dca_vlc_offs[i + 1] - ff_dca_vlc_offs[i];
152         init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
153                  bitalloc_12_bits[i], 1, 1,
154                  bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
155     }
156     dca_scalefactor.offset = -64;
157     dca_scalefactor.wrap   = 2;
158     for (i = 0; i < 5; i++) {
159         dca_scalefactor.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i + 5]];
160         dca_scalefactor.vlc[i].table_allocated = ff_dca_vlc_offs[i + 6] - ff_dca_vlc_offs[i + 5];
161         init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
162                  scales_bits[i], 1, 1,
163                  scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
164     }
165     dca_tmode.offset = 0;
166     dca_tmode.wrap   = 1;
167     for (i = 0; i < 4; i++) {
168         dca_tmode.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i + 10]];
169         dca_tmode.vlc[i].table_allocated = ff_dca_vlc_offs[i + 11] - ff_dca_vlc_offs[i + 10];
170         init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
171                  tmode_bits[i], 1, 1,
172                  tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
173     }
174
175     for (i = 0; i < 10; i++)
176         for (j = 0; j < 7; j++) {
177             if (!bitalloc_codes[i][j])
178                 break;
179             dca_smpl_bitalloc[i + 1].offset                 = bitalloc_offsets[i];
180             dca_smpl_bitalloc[i + 1].wrap                   = 1 + (j > 4);
181             dca_smpl_bitalloc[i + 1].vlc[j].table           = &dca_table[ff_dca_vlc_offs[c]];
182             dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = ff_dca_vlc_offs[c + 1] - ff_dca_vlc_offs[c];
183
184             init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
185                      bitalloc_sizes[i],
186                      bitalloc_bits[i][j], 1, 1,
187                      bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
188             c++;
189         }
190     vlcs_initialized = 1;
191 }
192
193 static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
194 {
195     while (len--)
196         *dst++ = get_bits(gb, bits);
197 }
198
199 static inline int dca_xxch2index(DCAContext *s, int xxch_ch)
200 {
201     int i, base, mask;
202
203     /* locate channel set containing the channel */
204     for (i = -1, base = 0, mask = (s->xxch_core_spkmask & ~DCA_XXCH_LFE1);
205          i <= s->xxch_chset && !(mask & xxch_ch); mask = s->xxch_spk_masks[++i])
206         base += av_popcount(mask);
207
208     return base + av_popcount(mask & (xxch_ch - 1));
209 }
210
211 static int dca_parse_audio_coding_header(DCAContext *s, int base_channel,
212                                          int xxch)
213 {
214     int i, j;
215     static const uint8_t adj_table[4] = { 16, 18, 20, 23 };
216     static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
217     static const int thr[11]    = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
218     int hdr_pos = 0, hdr_size = 0;
219     float scale_factor;
220     int this_chans, acc_mask;
221     int embedded_downmix;
222     int nchans, mask[8];
223     int coeff, ichan;
224
225     /* xxch has arbitrary sized audio coding headers */
226     if (xxch) {
227         hdr_pos  = get_bits_count(&s->gb);
228         hdr_size = get_bits(&s->gb, 7) + 1;
229     }
230
231     nchans = get_bits(&s->gb, 3) + 1;
232     if (xxch && nchans >= 3) {
233         av_log(s->avctx, AV_LOG_ERROR, "nchans %d is too large\n", nchans);
234         return AVERROR_INVALIDDATA;
235     } else if (nchans + base_channel > DCA_PRIM_CHANNELS_MAX) {
236         av_log(s->avctx, AV_LOG_ERROR, "channel sum %d + %d is too large\n", nchans, base_channel);
237         return AVERROR_INVALIDDATA;
238     }
239
240     s->audio_header.total_channels = nchans + base_channel;
241     s->audio_header.prim_channels  = s->audio_header.total_channels;
242
243     /* obtain speaker layout mask & downmix coefficients for XXCH */
244     if (xxch) {
245         acc_mask = s->xxch_core_spkmask;
246
247         this_chans = get_bits(&s->gb, s->xxch_nbits_spk_mask - 6) << 6;
248         s->xxch_spk_masks[s->xxch_chset] = this_chans;
249         s->xxch_chset_nch[s->xxch_chset] = nchans;
250
251         for (i = 0; i <= s->xxch_chset; i++)
252             acc_mask |= s->xxch_spk_masks[i];
253
254         /* check for downmixing information */
255         if (get_bits1(&s->gb)) {
256             embedded_downmix = get_bits1(&s->gb);
257             coeff            = get_bits(&s->gb, 6);
258
259             if (coeff<1 || coeff>61) {
260                 av_log(s->avctx, AV_LOG_ERROR, "6bit coeff %d is out of range\n", coeff);
261                 return AVERROR_INVALIDDATA;
262             }
263
264             scale_factor     = -1.0f / dca_dmix_code((coeff<<2)-3);
265
266             s->xxch_dmix_sf[s->xxch_chset] = scale_factor;
267
268             for (i = base_channel; i < s->audio_header.prim_channels; i++) {
269                 mask[i] = get_bits(&s->gb, s->xxch_nbits_spk_mask);
270             }
271
272             for (j = base_channel; j < s->audio_header.prim_channels; j++) {
273                 memset(s->xxch_dmix_coeff[j], 0, sizeof(s->xxch_dmix_coeff[0]));
274                 s->xxch_dmix_embedded |= (embedded_downmix << j);
275                 for (i = 0; i < s->xxch_nbits_spk_mask; i++) {
276                     if (mask[j] & (1 << i)) {
277                         if ((1 << i) == DCA_XXCH_LFE1) {
278                             av_log(s->avctx, AV_LOG_WARNING,
279                                    "DCA-XXCH: dmix to LFE1 not supported.\n");
280                             continue;
281                         }
282
283                         coeff = get_bits(&s->gb, 7);
284                         ichan = dca_xxch2index(s, 1 << i);
285                         if ((coeff&63)<1 || (coeff&63)>61) {
286                             av_log(s->avctx, AV_LOG_ERROR, "7bit coeff %d is out of range\n", coeff);
287                             return AVERROR_INVALIDDATA;
288                         }
289                         s->xxch_dmix_coeff[j][ichan] = dca_dmix_code((coeff<<2)-3);
290                     }
291                 }
292             }
293         }
294     }
295
296     if (s->audio_header.prim_channels > DCA_PRIM_CHANNELS_MAX)
297         s->audio_header.prim_channels = DCA_PRIM_CHANNELS_MAX;
298
299     for (i = base_channel; i < s->audio_header.prim_channels; i++) {
300         s->audio_header.subband_activity[i] = get_bits(&s->gb, 5) + 2;
301         if (s->audio_header.subband_activity[i] > DCA_SUBBANDS)
302             s->audio_header.subband_activity[i] = DCA_SUBBANDS;
303     }
304     for (i = base_channel; i < s->audio_header.prim_channels; i++) {
305         s->audio_header.vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
306         if (s->audio_header.vq_start_subband[i] > DCA_SUBBANDS)
307             s->audio_header.vq_start_subband[i] = DCA_SUBBANDS;
308     }
309     get_array(&s->gb, s->audio_header.joint_intensity + base_channel,
310               s->audio_header.prim_channels - base_channel, 3);
311     get_array(&s->gb, s->audio_header.transient_huffman + base_channel,
312               s->audio_header.prim_channels - base_channel, 2);
313     get_array(&s->gb, s->audio_header.scalefactor_huffman + base_channel,
314               s->audio_header.prim_channels - base_channel, 3);
315     get_array(&s->gb, s->audio_header.bitalloc_huffman + base_channel,
316               s->audio_header.prim_channels - base_channel, 3);
317
318     /* Get codebooks quantization indexes */
319     if (!base_channel)
320         memset(s->audio_header.quant_index_huffman, 0, sizeof(s->audio_header.quant_index_huffman));
321     for (j = 1; j < 11; j++)
322         for (i = base_channel; i < s->audio_header.prim_channels; i++)
323             s->audio_header.quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
324
325     /* Get scale factor adjustment */
326     for (j = 0; j < 11; j++)
327         for (i = base_channel; i < s->audio_header.prim_channels; i++)
328             s->audio_header.scalefactor_adj[i][j] = 16;
329
330     for (j = 1; j < 11; j++)
331         for (i = base_channel; i < s->audio_header.prim_channels; i++)
332             if (s->audio_header.quant_index_huffman[i][j] < thr[j])
333                 s->audio_header.scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
334
335     if (!xxch) {
336         if (s->crc_present) {
337             /* Audio header CRC check */
338             get_bits(&s->gb, 16);
339         }
340     } else {
341         /* Skip to the end of the header, also ignore CRC if present  */
342         i = get_bits_count(&s->gb);
343         if (hdr_pos + 8 * hdr_size > i)
344             skip_bits_long(&s->gb, hdr_pos + 8 * hdr_size - i);
345     }
346
347     s->current_subframe    = 0;
348     s->current_subsubframe = 0;
349
350     return 0;
351 }
352
353 static int dca_parse_frame_header(DCAContext *s)
354 {
355     init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
356
357     /* Sync code */
358     skip_bits_long(&s->gb, 32);
359
360     /* Frame header */
361     s->frame_type        = get_bits(&s->gb, 1);
362     s->samples_deficit   = get_bits(&s->gb, 5) + 1;
363     s->crc_present       = get_bits(&s->gb, 1);
364     s->sample_blocks     = get_bits(&s->gb, 7) + 1;
365     s->frame_size        = get_bits(&s->gb, 14) + 1;
366     if (s->frame_size < 95)
367         return AVERROR_INVALIDDATA;
368     s->amode             = get_bits(&s->gb, 6);
369     s->sample_rate       = avpriv_dca_sample_rates[get_bits(&s->gb, 4)];
370     if (!s->sample_rate)
371         return AVERROR_INVALIDDATA;
372     s->bit_rate_index    = get_bits(&s->gb, 5);
373     s->bit_rate          = ff_dca_bit_rates[s->bit_rate_index];
374     if (!s->bit_rate)
375         return AVERROR_INVALIDDATA;
376
377     skip_bits1(&s->gb); // always 0 (reserved, cf. ETSI TS 102 114 V1.4.1)
378     s->dynrange          = get_bits(&s->gb, 1);
379     s->timestamp         = get_bits(&s->gb, 1);
380     s->aux_data          = get_bits(&s->gb, 1);
381     s->hdcd              = get_bits(&s->gb, 1);
382     s->ext_descr         = get_bits(&s->gb, 3);
383     s->ext_coding        = get_bits(&s->gb, 1);
384     s->aspf              = get_bits(&s->gb, 1);
385     s->lfe               = get_bits(&s->gb, 2);
386     s->predictor_history = get_bits(&s->gb, 1);
387
388     if (s->lfe > 2) {
389         s->lfe = 0;
390         av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE value: %d\n", s->lfe);
391         return AVERROR_INVALIDDATA;
392     }
393
394     /* TODO: check CRC */
395     if (s->crc_present)
396         s->header_crc    = get_bits(&s->gb, 16);
397
398     s->multirate_inter   = get_bits(&s->gb, 1);
399     s->version           = get_bits(&s->gb, 4);
400     s->copy_history      = get_bits(&s->gb, 2);
401     s->source_pcm_res    = get_bits(&s->gb, 3);
402     s->front_sum         = get_bits(&s->gb, 1);
403     s->surround_sum      = get_bits(&s->gb, 1);
404     s->dialog_norm       = get_bits(&s->gb, 4);
405
406     /* FIXME: channels mixing levels */
407     s->output = s->amode;
408     if (s->lfe)
409         s->output |= DCA_LFE;
410
411     /* Primary audio coding header */
412     s->audio_header.subframes = get_bits(&s->gb, 4) + 1;
413
414     return dca_parse_audio_coding_header(s, 0, 0);
415 }
416
417 static inline int get_scale(GetBitContext *gb, int level, int value, int log2range)
418 {
419     if (level < 5) {
420         /* huffman encoded */
421         value += get_bitalloc(gb, &dca_scalefactor, level);
422         value  = av_clip(value, 0, (1 << log2range) - 1);
423     } else if (level < 8) {
424         if (level + 1 > log2range) {
425             skip_bits(gb, level + 1 - log2range);
426             value = get_bits(gb, log2range);
427         } else {
428             value = get_bits(gb, level + 1);
429         }
430     }
431     return value;
432 }
433
434 static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)
435 {
436     /* Primary audio coding side information */
437     int j, k;
438
439     if (get_bits_left(&s->gb) < 0)
440         return AVERROR_INVALIDDATA;
441
442     if (!base_channel) {
443         s->subsubframes[s->current_subframe]    = get_bits(&s->gb, 2) + 1;
444         if (block_index + s->subsubframes[s->current_subframe] > (s->sample_blocks / SAMPLES_PER_SUBBAND)) {
445             s->subsubframes[s->current_subframe] = 1;
446             return AVERROR_INVALIDDATA;
447         }
448         s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
449     }
450
451     for (j = base_channel; j < s->audio_header.prim_channels; j++) {
452         for (k = 0; k < s->audio_header.subband_activity[j]; k++)
453             s->dca_chan[j].prediction_mode[k] = get_bits(&s->gb, 1);
454     }
455
456     /* Get prediction codebook */
457     for (j = base_channel; j < s->audio_header.prim_channels; j++) {
458         for (k = 0; k < s->audio_header.subband_activity[j]; k++) {
459             if (s->dca_chan[j].prediction_mode[k] > 0) {
460                 /* (Prediction coefficient VQ address) */
461                 s->dca_chan[j].prediction_vq[k] = get_bits(&s->gb, 12);
462             }
463         }
464     }
465
466     /* Bit allocation index */
467     for (j = base_channel; j < s->audio_header.prim_channels; j++) {
468         for (k = 0; k < s->audio_header.vq_start_subband[j]; k++) {
469             if (s->audio_header.bitalloc_huffman[j] == 6)
470                 s->dca_chan[j].bitalloc[k] = get_bits(&s->gb, 5);
471             else if (s->audio_header.bitalloc_huffman[j] == 5)
472                 s->dca_chan[j].bitalloc[k] = get_bits(&s->gb, 4);
473             else if (s->audio_header.bitalloc_huffman[j] == 7) {
474                 av_log(s->avctx, AV_LOG_ERROR,
475                        "Invalid bit allocation index\n");
476                 return AVERROR_INVALIDDATA;
477             } else {
478                 s->dca_chan[j].bitalloc[k] =
479                     get_bitalloc(&s->gb, &dca_bitalloc_index, s->audio_header.bitalloc_huffman[j]);
480             }
481
482             if (s->dca_chan[j].bitalloc[k] > 26) {
483                 ff_dlog(s->avctx, "bitalloc index [%i][%i] too big (%i)\n",
484                         j, k, s->dca_chan[j].bitalloc[k]);
485                 return AVERROR_INVALIDDATA;
486             }
487         }
488     }
489
490     /* Transition mode */
491     for (j = base_channel; j < s->audio_header.prim_channels; j++) {
492         for (k = 0; k < s->audio_header.subband_activity[j]; k++) {
493             s->dca_chan[j].transition_mode[k] = 0;
494             if (s->subsubframes[s->current_subframe] > 1 &&
495                 k < s->audio_header.vq_start_subband[j] && s->dca_chan[j].bitalloc[k] > 0) {
496                 s->dca_chan[j].transition_mode[k] =
497                     get_bitalloc(&s->gb, &dca_tmode, s->audio_header.transient_huffman[j]);
498             }
499         }
500     }
501
502     if (get_bits_left(&s->gb) < 0)
503         return AVERROR_INVALIDDATA;
504
505     for (j = base_channel; j < s->audio_header.prim_channels; j++) {
506         const uint32_t *scale_table;
507         int scale_sum, log_size;
508
509         memset(s->dca_chan[j].scale_factor, 0,
510                s->audio_header.subband_activity[j] * sizeof(s->dca_chan[j].scale_factor[0][0]) * 2);
511
512         if (s->audio_header.scalefactor_huffman[j] == 6) {
513             scale_table = ff_dca_scale_factor_quant7;
514             log_size    = 7;
515         } else {
516             scale_table = ff_dca_scale_factor_quant6;
517             log_size    = 6;
518         }
519
520         /* When huffman coded, only the difference is encoded */
521         scale_sum = 0;
522
523         for (k = 0; k < s->audio_header.subband_activity[j]; k++) {
524             if (k >= s->audio_header.vq_start_subband[j] || s->dca_chan[j].bitalloc[k] > 0) {
525                 scale_sum = get_scale(&s->gb, s->audio_header.scalefactor_huffman[j], scale_sum, log_size);
526                 s->dca_chan[j].scale_factor[k][0] = scale_table[scale_sum];
527             }
528
529             if (k < s->audio_header.vq_start_subband[j] && s->dca_chan[j].transition_mode[k]) {
530                 /* Get second scale factor */
531                 scale_sum = get_scale(&s->gb, s->audio_header.scalefactor_huffman[j], scale_sum, log_size);
532                 s->dca_chan[j].scale_factor[k][1] = scale_table[scale_sum];
533             }
534         }
535     }
536
537     /* Joint subband scale factor codebook select */
538     for (j = base_channel; j < s->audio_header.prim_channels; j++) {
539         /* Transmitted only if joint subband coding enabled */
540         if (s->audio_header.joint_intensity[j] > 0)
541             s->dca_chan[j].joint_huff = get_bits(&s->gb, 3);
542     }
543
544     if (get_bits_left(&s->gb) < 0)
545         return AVERROR_INVALIDDATA;
546
547     /* Scale factors for joint subband coding */
548     for (j = base_channel; j < s->audio_header.prim_channels; j++) {
549         int source_channel;
550
551         /* Transmitted only if joint subband coding enabled */
552         if (s->audio_header.joint_intensity[j] > 0) {
553             int scale = 0;
554             source_channel = s->audio_header.joint_intensity[j] - 1;
555
556             /* When huffman coded, only the difference is encoded
557              * (is this valid as well for joint scales ???) */
558
559             for (k = s->audio_header.subband_activity[j];
560                  k < s->audio_header.subband_activity[source_channel]; k++) {
561                 scale = get_scale(&s->gb, s->dca_chan[j].joint_huff, 64 /* bias */, 7);
562                 s->dca_chan[j].joint_scale_factor[k] = scale;    /*joint_scale_table[scale]; */
563             }
564
565             if (!(s->debug_flag & 0x02)) {
566                 av_log(s->avctx, AV_LOG_DEBUG,
567                        "Joint stereo coding not supported\n");
568                 s->debug_flag |= 0x02;
569             }
570         }
571     }
572
573     /* Dynamic range coefficient */
574     if (!base_channel && s->dynrange)
575         s->dynrange_coef = get_bits(&s->gb, 8);
576
577     /* Side information CRC check word */
578     if (s->crc_present) {
579         get_bits(&s->gb, 16);
580     }
581
582     /*
583      * Primary audio data arrays
584      */
585
586     /* VQ encoded high frequency subbands */
587     for (j = base_channel; j < s->audio_header.prim_channels; j++)
588         for (k = s->audio_header.vq_start_subband[j]; k < s->audio_header.subband_activity[j]; k++)
589             /* 1 vector -> 32 samples */
590             s->dca_chan[j].high_freq_vq[k] = get_bits(&s->gb, 10);
591
592     /* Low frequency effect data */
593     if (!base_channel && s->lfe) {
594         int quant7;
595         /* LFE samples */
596         int lfe_samples    = 2 * s->lfe * (4 + block_index);
597         int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
598         float lfe_scale;
599
600         for (j = lfe_samples; j < lfe_end_sample; j++) {
601             /* Signed 8 bits int */
602             s->lfe_data[j] = get_sbits(&s->gb, 8);
603         }
604
605         /* Scale factor index */
606         quant7 = get_bits(&s->gb, 8);
607         if (quant7 > 127) {
608             avpriv_request_sample(s->avctx, "LFEScaleIndex larger than 127");
609             return AVERROR_INVALIDDATA;
610         }
611         s->lfe_scale_factor = ff_dca_scale_factor_quant7[quant7];
612
613         /* Quantization step size * scale factor */
614         lfe_scale = 0.035 * s->lfe_scale_factor;
615
616         for (j = lfe_samples; j < lfe_end_sample; j++)
617             s->lfe_data[j] *= lfe_scale;
618     }
619
620     return 0;
621 }
622
623 static void qmf_32_subbands(DCAContext *s, int chans,
624                             float samples_in[DCA_SUBBANDS][SAMPLES_PER_SUBBAND], float *samples_out,
625                             float scale)
626 {
627     const float *prCoeff;
628
629     int sb_act = s->audio_header.subband_activity[chans];
630
631     scale *= sqrt(1 / 8.0);
632
633     /* Select filter */
634     if (!s->multirate_inter)    /* Non-perfect reconstruction */
635         prCoeff = ff_dca_fir_32bands_nonperfect;
636     else                        /* Perfect reconstruction */
637         prCoeff = ff_dca_fir_32bands_perfect;
638
639     s->dcadsp.qmf_32_subbands(samples_in, sb_act, &s->synth, &s->imdct,
640                               s->dca_chan[chans].subband_fir_hist,
641                               &s->dca_chan[chans].hist_index,
642                               s->dca_chan[chans].subband_fir_noidea, prCoeff,
643                               samples_out, s->raXin, scale);
644 }
645
646 static QMF64_table *qmf64_precompute(void)
647 {
648     unsigned i, j;
649     QMF64_table *table = av_malloc(sizeof(*table));
650     if (!table)
651         return NULL;
652
653     for (i = 0; i < 32; i++)
654         for (j = 0; j < 32; j++)
655             table->dct4_coeff[i][j] = cos((2 * i + 1) * (2 * j + 1) * M_PI / 128);
656     for (i = 0; i < 32; i++)
657         for (j = 0; j < 32; j++)
658             table->dct2_coeff[i][j] = cos((2 * i + 1) *      j      * M_PI /  64);
659
660     /* FIXME: Is the factor 0.125 = 1/8 right? */
661     for (i = 0; i < 32; i++)
662         table->rcos[i] =  0.125 / cos((2 * i + 1) * M_PI / 256);
663     for (i = 0; i < 32; i++)
664         table->rsin[i] = -0.125 / sin((2 * i + 1) * M_PI / 256);
665
666     return table;
667 }
668
669 /* FIXME: Totally unoptimized. Based on the reference code and
670  * http://multimedia.cx/mirror/dca-transform.pdf, with guessed tweaks
671  * for doubling the size. */
672 static void qmf_64_subbands(DCAContext *s, int chans,
673                             float samples_in[DCA_SUBBANDS_X96K][SAMPLES_PER_SUBBAND],
674                             float *samples_out, float scale)
675 {
676     float raXin[64];
677     float A[32], B[32];
678     float *raX = s->dca_chan[chans].subband_fir_hist;
679     float *raZ = s->dca_chan[chans].subband_fir_noidea;
680     unsigned i, j, k, subindex;
681
682     for (i = s->audio_header.subband_activity[chans]; i < DCA_SUBBANDS_X96K; i++)
683         raXin[i] = 0.0;
684     for (subindex = 0; subindex < SAMPLES_PER_SUBBAND; subindex++) {
685         for (i = 0; i < s->audio_header.subband_activity[chans]; i++)
686             raXin[i] = samples_in[i][subindex];
687
688         for (k = 0; k < 32; k++) {
689             A[k] = 0.0;
690             for (i = 0; i < 32; i++)
691                 A[k] += (raXin[2 * i] + raXin[2 * i + 1]) * s->qmf64_table->dct4_coeff[k][i];
692         }
693         for (k = 0; k < 32; k++) {
694             B[k] = raXin[0] * s->qmf64_table->dct2_coeff[k][0];
695             for (i = 1; i < 32; i++)
696                 B[k] += (raXin[2 * i] + raXin[2 * i - 1]) * s->qmf64_table->dct2_coeff[k][i];
697         }
698         for (k = 0; k < 32; k++) {
699             raX[k]      = s->qmf64_table->rcos[k] * (A[k] + B[k]);
700             raX[63 - k] = s->qmf64_table->rsin[k] * (A[k] - B[k]);
701         }
702
703         for (i = 0; i < DCA_SUBBANDS_X96K; i++) {
704             float out = raZ[i];
705             for (j = 0; j < 1024; j += 128)
706                 out += ff_dca_fir_64bands[j + i] * (raX[j + i] - raX[j + 63 - i]);
707             *samples_out++ = out * scale;
708         }
709
710         for (i = 0; i < DCA_SUBBANDS_X96K; i++) {
711             float hist = 0.0;
712             for (j = 0; j < 1024; j += 128)
713                 hist += ff_dca_fir_64bands[64 + j + i] * (-raX[i + j] - raX[j + 63 - i]);
714
715             raZ[i] = hist;
716         }
717
718         /* FIXME: Make buffer circular, to avoid this move. */
719         memmove(raX + 64, raX, (1024 - 64) * sizeof(*raX));
720     }
721 }
722
723 static void lfe_interpolation_fir(DCAContext *s, const float *samples_in,
724                                   float *samples_out)
725 {
726     /* samples_in: An array holding decimated samples.
727      *   Samples in current subframe starts from samples_in[0],
728      *   while samples_in[-1], samples_in[-2], ..., stores samples
729      *   from last subframe as history.
730      *
731      * samples_out: An array holding interpolated samples
732      */
733
734     int idx;
735     const float *prCoeff;
736     int deciindex;
737
738     /* Select decimation filter */
739     if (s->lfe == 1) {
740         idx     = 1;
741         prCoeff = ff_dca_lfe_fir_128;
742     } else {
743         idx = 0;
744         if (s->exss_ext_mask & DCA_EXT_EXSS_XLL)
745             prCoeff = ff_dca_lfe_xll_fir_64;
746         else
747             prCoeff = ff_dca_lfe_fir_64;
748     }
749     /* Interpolation */
750     for (deciindex = 0; deciindex < 2 * s->lfe; deciindex++) {
751         s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
752         samples_in++;
753         samples_out += 2 * 32 * (1 + idx);
754     }
755 }
756
757 /* downmixing routines */
758 #define MIX_REAR1(samples, s1, rs, coef)            \
759     samples[0][i] += samples[s1][i] * coef[rs][0];  \
760     samples[1][i] += samples[s1][i] * coef[rs][1];
761
762 #define MIX_REAR2(samples, s1, s2, rs, coef)                                          \
763     samples[0][i] += samples[s1][i] * coef[rs][0] + samples[s2][i] * coef[rs + 1][0]; \
764     samples[1][i] += samples[s1][i] * coef[rs][1] + samples[s2][i] * coef[rs + 1][1];
765
766 #define MIX_FRONT3(samples, coef)                                      \
767     t = samples[c][i];                                                 \
768     u = samples[l][i];                                                 \
769     v = samples[r][i];                                                 \
770     samples[0][i] = t * coef[0][0] + u * coef[1][0] + v * coef[2][0];  \
771     samples[1][i] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
772
773 #define DOWNMIX_TO_STEREO(op1, op2)             \
774     for (i = 0; i < 256; i++) {                 \
775         op1                                     \
776         op2                                     \
777     }
778
779 static void dca_downmix(float **samples, int srcfmt, int lfe_present,
780                         float coef[DCA_PRIM_CHANNELS_MAX + 1][2],
781                         const int8_t *channel_mapping)
782 {
783     int c, l, r, sl, sr, s;
784     int i;
785     float t, u, v;
786
787     switch (srcfmt) {
788     case DCA_MONO:
789     case DCA_4F2R:
790         av_log(NULL, AV_LOG_ERROR, "Not implemented!\n");
791         break;
792     case DCA_CHANNEL:
793     case DCA_STEREO:
794     case DCA_STEREO_TOTAL:
795     case DCA_STEREO_SUMDIFF:
796         break;
797     case DCA_3F:
798         c = channel_mapping[0];
799         l = channel_mapping[1];
800         r = channel_mapping[2];
801         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
802         break;
803     case DCA_2F1R:
804         s = channel_mapping[2];
805         DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );
806         break;
807     case DCA_3F1R:
808         c = channel_mapping[0];
809         l = channel_mapping[1];
810         r = channel_mapping[2];
811         s = channel_mapping[3];
812         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
813                           MIX_REAR1(samples, s, 3, coef));
814         break;
815     case DCA_2F2R:
816         sl = channel_mapping[2];
817         sr = channel_mapping[3];
818         DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );
819         break;
820     case DCA_3F2R:
821         c  = channel_mapping[0];
822         l  = channel_mapping[1];
823         r  = channel_mapping[2];
824         sl = channel_mapping[3];
825         sr = channel_mapping[4];
826         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
827                           MIX_REAR2(samples, sl, sr, 3, coef));
828         break;
829     }
830     if (lfe_present) {
831         int lf_buf = ff_dca_lfe_index[srcfmt];
832         int lf_idx =  ff_dca_channels[srcfmt];
833         for (i = 0; i < 256; i++) {
834             samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];
835             samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];
836         }
837     }
838 }
839
840 #ifndef decode_blockcodes
841 /* Very compact version of the block code decoder that does not use table
842  * look-up but is slightly slower */
843 static int decode_blockcode(int code, int levels, int32_t *values)
844 {
845     int i;
846     int offset = (levels - 1) >> 1;
847
848     for (i = 0; i < 4; i++) {
849         int div = FASTDIV(code, levels);
850         values[i] = code - offset - div * levels;
851         code      = div;
852     }
853
854     return code;
855 }
856
857 static int decode_blockcodes(int code1, int code2, int levels, int32_t *values)
858 {
859     return decode_blockcode(code1, levels, values) |
860            decode_blockcode(code2, levels, values + 4);
861 }
862 #endif
863
864 static const uint8_t abits_sizes[7]  = { 7, 10, 12, 13, 15, 17, 19 };
865 static const uint8_t abits_levels[7] = { 3,  5,  7,  9, 13, 17, 25 };
866
867 static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
868 {
869     int k, l;
870     int subsubframe = s->current_subsubframe;
871     const uint32_t *quant_step_table;
872
873     /*
874      * Audio data
875      */
876
877     /* Select quantization step size table */
878     if (s->bit_rate_index == 0x1f)
879         quant_step_table = ff_dca_lossless_quant;
880     else
881         quant_step_table = ff_dca_lossy_quant;
882
883     for (k = base_channel; k < s->audio_header.prim_channels; k++) {
884         int32_t (*subband_samples)[8] = s->dca_chan[k].subband_samples[block_index];
885
886         if (get_bits_left(&s->gb) < 0)
887             return AVERROR_INVALIDDATA;
888
889         for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
890             int m;
891
892             /* Select the mid-tread linear quantizer */
893             int abits = s->dca_chan[k].bitalloc[l];
894
895             uint32_t quant_step_size = quant_step_table[abits];
896
897             /*
898              * Extract bits from the bit stream
899              */
900             if (!abits)
901                 memset(subband_samples[l], 0, SAMPLES_PER_SUBBAND *
902                        sizeof(subband_samples[l][0]));
903             else {
904                 uint32_t rscale;
905                 /* Deal with transients */
906                 int sfi = s->dca_chan[k].transition_mode[l] &&
907                     subsubframe >= s->dca_chan[k].transition_mode[l];
908                 /* Determine quantization index code book and its type.
909                    Select quantization index code book */
910                 int sel = s->audio_header.quant_index_huffman[k][abits];
911
912                 rscale = (s->dca_chan[k].scale_factor[l][sfi] *
913                           s->audio_header.scalefactor_adj[k][sel] + 8) >> 4;
914
915                 if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
916                     if (abits <= 7) {
917                         /* Block code */
918                         int block_code1, block_code2, size, levels, err;
919
920                         size   = abits_sizes[abits - 1];
921                         levels = abits_levels[abits - 1];
922
923                         block_code1 = get_bits(&s->gb, size);
924                         block_code2 = get_bits(&s->gb, size);
925                         err         = decode_blockcodes(block_code1, block_code2,
926                                                         levels, subband_samples[l]);
927                         if (err) {
928                             av_log(s->avctx, AV_LOG_ERROR,
929                                    "ERROR: block code look-up failed\n");
930                             return AVERROR_INVALIDDATA;
931                         }
932                     } else {
933                         /* no coding */
934                         for (m = 0; m < SAMPLES_PER_SUBBAND; m++)
935                             subband_samples[l][m] = get_sbits(&s->gb, abits - 3);
936                     }
937                 } else {
938                     /* Huffman coded */
939                     for (m = 0; m < SAMPLES_PER_SUBBAND; m++)
940                         subband_samples[l][m] = get_bitalloc(&s->gb,
941                                                              &dca_smpl_bitalloc[abits], sel);
942                 }
943                 s->dcadsp.dequantize(subband_samples[l], quant_step_size, rscale);
944             }
945         }
946
947         for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
948             int m;
949             /*
950              * Inverse ADPCM if in prediction mode
951              */
952             if (s->dca_chan[k].prediction_mode[l]) {
953                 int n;
954                 if (s->predictor_history)
955                     subband_samples[l][0] += (ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][0] *
956                                               (int64_t)s->dca_chan[k].subband_samples_hist[l][3] +
957                                               ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][1] *
958                                               (int64_t)s->dca_chan[k].subband_samples_hist[l][2] +
959                                               ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][2] *
960                                               (int64_t)s->dca_chan[k].subband_samples_hist[l][1] +
961                                               ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][3] *
962                                               (int64_t)s->dca_chan[k].subband_samples_hist[l][0]) +
963                                               (1 << 12) >> 13;
964                 for (m = 1; m < SAMPLES_PER_SUBBAND; m++) {
965                     int64_t sum = ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][0] *
966                                   (int64_t)subband_samples[l][m - 1];
967                     for (n = 2; n <= 4; n++)
968                         if (m >= n)
969                             sum += ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][n - 1] *
970                                    (int64_t)subband_samples[l][m - n];
971                         else if (s->predictor_history)
972                             sum += ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][n - 1] *
973                                    (int64_t)s->dca_chan[k].subband_samples_hist[l][m - n + 4];
974                     subband_samples[l][m] += (int32_t)(sum + (1 << 12) >> 13);
975                 }
976             }
977
978         }
979         /* Backup predictor history for adpcm */
980         for (l = 0; l < DCA_SUBBANDS; l++)
981             AV_COPY128(s->dca_chan[k].subband_samples_hist[l], &subband_samples[l][4]);
982
983
984         /*
985          * Decode VQ encoded high frequencies
986          */
987         if (s->audio_header.subband_activity[k] > s->audio_header.vq_start_subband[k]) {
988             if (!(s->debug_flag & 0x01)) {
989                 av_log(s->avctx, AV_LOG_DEBUG,
990                        "Stream with high frequencies VQ coding\n");
991                 s->debug_flag |= 0x01;
992             }
993
994             s->dcadsp.decode_hf(subband_samples, s->dca_chan[k].high_freq_vq,
995                                 ff_dca_high_freq_vq,
996                                 subsubframe * SAMPLES_PER_SUBBAND,
997                                 s->dca_chan[k].scale_factor,
998                                 s->audio_header.vq_start_subband[k],
999                                 s->audio_header.subband_activity[k]);
1000         }
1001     }
1002
1003     /* Check for DSYNC after subsubframe */
1004     if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
1005         if (get_bits(&s->gb, 16) != 0xFFFF) {
1006             av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
1007             return AVERROR_INVALIDDATA;
1008         }
1009     }
1010
1011     return 0;
1012 }
1013
1014 static int dca_filter_channels(DCAContext *s, int block_index, int upsample)
1015 {
1016     int k;
1017
1018     if (upsample) {
1019         LOCAL_ALIGNED(32, float, samples, [DCA_SUBBANDS_X96K], [SAMPLES_PER_SUBBAND]);
1020
1021         if (!s->qmf64_table) {
1022             s->qmf64_table = qmf64_precompute();
1023             if (!s->qmf64_table)
1024                 return AVERROR(ENOMEM);
1025         }
1026
1027         /* 64 subbands QMF */
1028         for (k = 0; k < s->audio_header.prim_channels; k++) {
1029             int32_t (*subband_samples)[SAMPLES_PER_SUBBAND] =
1030                      s->dca_chan[k].subband_samples[block_index];
1031
1032             s->fmt_conv.int32_to_float(samples[0], subband_samples[0],
1033                                        DCA_SUBBANDS_X96K * SAMPLES_PER_SUBBAND);
1034
1035             if (s->channel_order_tab[k] >= 0)
1036                 qmf_64_subbands(s, k, samples,
1037                                 s->samples_chanptr[s->channel_order_tab[k]],
1038                                 /* Upsampling needs a factor 2 here. */
1039                                 M_SQRT2 / 32768.0);
1040         }
1041     } else {
1042         /* 32 subbands QMF */
1043         LOCAL_ALIGNED(32, float, samples, [DCA_SUBBANDS], [SAMPLES_PER_SUBBAND]);
1044
1045         for (k = 0; k < s->audio_header.prim_channels; k++) {
1046             int32_t (*subband_samples)[SAMPLES_PER_SUBBAND] =
1047                      s->dca_chan[k].subband_samples[block_index];
1048
1049             s->fmt_conv.int32_to_float(samples[0], subband_samples[0],
1050                                        DCA_SUBBANDS * SAMPLES_PER_SUBBAND);
1051
1052             if (s->channel_order_tab[k] >= 0)
1053                 qmf_32_subbands(s, k, samples,
1054                                 s->samples_chanptr[s->channel_order_tab[k]],
1055                                 M_SQRT1_2 / 32768.0);
1056         }
1057     }
1058
1059     /* Generate LFE samples for this subsubframe FIXME!!! */
1060     if (s->lfe) {
1061         float *samples = s->samples_chanptr[s->lfe_index];
1062         lfe_interpolation_fir(s,
1063                               s->lfe_data + 2 * s->lfe * (block_index + 4),
1064                               samples);
1065         if (upsample) {
1066             unsigned i;
1067             /* Should apply the filter in Table 6-11 when upsampling. For
1068              * now, just duplicate. */
1069             for (i = 255; i > 0; i--) {
1070                 samples[2 * i]     =
1071                 samples[2 * i + 1] = samples[i];
1072             }
1073             samples[1] = samples[0];
1074         }
1075     }
1076
1077     /* FIXME: This downmixing is probably broken with upsample.
1078      * Probably totally broken also with XLL in general. */
1079     /* Downmixing to Stereo */
1080     if (s->audio_header.prim_channels + !!s->lfe > 2 &&
1081         s->avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1082         dca_downmix(s->samples_chanptr, s->amode, !!s->lfe, s->downmix_coef,
1083                     s->channel_order_tab);
1084     }
1085
1086     return 0;
1087 }
1088
1089 static int dca_subframe_footer(DCAContext *s, int base_channel)
1090 {
1091     int in, out, aux_data_count, aux_data_end, reserved;
1092     uint32_t nsyncaux;
1093
1094     /*
1095      * Unpack optional information
1096      */
1097
1098     /* presumably optional information only appears in the core? */
1099     if (!base_channel) {
1100         if (s->timestamp)
1101             skip_bits_long(&s->gb, 32);
1102
1103         if (s->aux_data) {
1104             aux_data_count = get_bits(&s->gb, 6);
1105
1106             // align (32-bit)
1107             skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1108
1109             aux_data_end = 8 * aux_data_count + get_bits_count(&s->gb);
1110
1111             if ((nsyncaux = get_bits_long(&s->gb, 32)) != DCA_NSYNCAUX) {
1112                 av_log(s->avctx, AV_LOG_ERROR, "nSYNCAUX mismatch %#"PRIx32"\n",
1113                        nsyncaux);
1114                 return AVERROR_INVALIDDATA;
1115             }
1116
1117             if (get_bits1(&s->gb)) { // bAUXTimeStampFlag
1118                 avpriv_request_sample(s->avctx,
1119                                       "Auxiliary Decode Time Stamp Flag");
1120                 // align (4-bit)
1121                 skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 4);
1122                 // 44 bits: nMSByte (8), nMarker (4), nLSByte (28), nMarker (4)
1123                 skip_bits_long(&s->gb, 44);
1124             }
1125
1126             if ((s->core_downmix = get_bits1(&s->gb))) {
1127                 int am = get_bits(&s->gb, 3);
1128                 switch (am) {
1129                 case 0:
1130                     s->core_downmix_amode = DCA_MONO;
1131                     break;
1132                 case 1:
1133                     s->core_downmix_amode = DCA_STEREO;
1134                     break;
1135                 case 2:
1136                     s->core_downmix_amode = DCA_STEREO_TOTAL;
1137                     break;
1138                 case 3:
1139                     s->core_downmix_amode = DCA_3F;
1140                     break;
1141                 case 4:
1142                     s->core_downmix_amode = DCA_2F1R;
1143                     break;
1144                 case 5:
1145                     s->core_downmix_amode = DCA_2F2R;
1146                     break;
1147                 case 6:
1148                     s->core_downmix_amode = DCA_3F1R;
1149                     break;
1150                 default:
1151                     av_log(s->avctx, AV_LOG_ERROR,
1152                            "Invalid mode %d for embedded downmix coefficients\n",
1153                            am);
1154                     return AVERROR_INVALIDDATA;
1155                 }
1156                 for (out = 0; out < ff_dca_channels[s->core_downmix_amode]; out++) {
1157                     for (in = 0; in < s->audio_header.prim_channels + !!s->lfe; in++) {
1158                         uint16_t tmp = get_bits(&s->gb, 9);
1159                         if ((tmp & 0xFF) > 241) {
1160                             av_log(s->avctx, AV_LOG_ERROR,
1161                                    "Invalid downmix coefficient code %"PRIu16"\n",
1162                                    tmp);
1163                             return AVERROR_INVALIDDATA;
1164                         }
1165                         s->core_downmix_codes[in][out] = tmp;
1166                     }
1167                 }
1168             }
1169
1170             align_get_bits(&s->gb); // byte align
1171             skip_bits(&s->gb, 16);  // nAUXCRC16
1172
1173             /*
1174              * additional data (reserved, cf. ETSI TS 102 114 V1.4.1)
1175              *
1176              * Note: don't check for overreads, aux_data_count can't be trusted.
1177              */
1178             if ((reserved = (aux_data_end - get_bits_count(&s->gb))) > 0) {
1179                 avpriv_request_sample(s->avctx,
1180                                       "Core auxiliary data reserved content");
1181                 skip_bits_long(&s->gb, reserved);
1182             }
1183         }
1184
1185         if (s->crc_present && s->dynrange)
1186             get_bits(&s->gb, 16);
1187     }
1188
1189     return 0;
1190 }
1191
1192 /**
1193  * Decode a dca frame block
1194  *
1195  * @param s     pointer to the DCAContext
1196  */
1197
1198 static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
1199 {
1200     int ret;
1201
1202     /* Sanity check */
1203     if (s->current_subframe >= s->audio_header.subframes) {
1204         av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1205                s->current_subframe, s->audio_header.subframes);
1206         return AVERROR_INVALIDDATA;
1207     }
1208
1209     if (!s->current_subsubframe) {
1210         /* Read subframe header */
1211         if ((ret = dca_subframe_header(s, base_channel, block_index)))
1212             return ret;
1213     }
1214
1215     /* Read subsubframe */
1216     if ((ret = dca_subsubframe(s, base_channel, block_index)))
1217         return ret;
1218
1219     /* Update state */
1220     s->current_subsubframe++;
1221     if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
1222         s->current_subsubframe = 0;
1223         s->current_subframe++;
1224     }
1225     if (s->current_subframe >= s->audio_header.subframes) {
1226         /* Read subframe footer */
1227         if ((ret = dca_subframe_footer(s, base_channel)))
1228             return ret;
1229     }
1230
1231     return 0;
1232 }
1233
1234 int ff_dca_xbr_parse_frame(DCAContext *s)
1235 {
1236     int scale_table_high[DCA_CHSET_CHANS_MAX][DCA_SUBBANDS][2];
1237     int active_bands[DCA_CHSETS_MAX][DCA_CHSET_CHANS_MAX];
1238     int abits_high[DCA_CHSET_CHANS_MAX][DCA_SUBBANDS];
1239     int anctemp[DCA_CHSET_CHANS_MAX];
1240     int chset_fsize[DCA_CHSETS_MAX];
1241     int n_xbr_ch[DCA_CHSETS_MAX];
1242     int hdr_size, num_chsets, xbr_tmode, hdr_pos;
1243     int i, j, k, l, chset, chan_base;
1244
1245     av_log(s->avctx, AV_LOG_DEBUG, "DTS-XBR: decoding XBR extension\n");
1246
1247     /* get bit position of sync header */
1248     hdr_pos = get_bits_count(&s->gb) - 32;
1249
1250     hdr_size = get_bits(&s->gb, 6) + 1;
1251     num_chsets = get_bits(&s->gb, 2) + 1;
1252
1253     for(i = 0; i < num_chsets; i++)
1254         chset_fsize[i] = get_bits(&s->gb, 14) + 1;
1255
1256     xbr_tmode = get_bits1(&s->gb);
1257
1258     for(i = 0; i < num_chsets; i++) {
1259         n_xbr_ch[i] = get_bits(&s->gb, 3) + 1;
1260         k = get_bits(&s->gb, 2) + 5;
1261         for(j = 0; j < n_xbr_ch[i]; j++) {
1262             active_bands[i][j] = get_bits(&s->gb, k) + 1;
1263             if (active_bands[i][j] > DCA_SUBBANDS) {
1264                 av_log(s->avctx, AV_LOG_ERROR, "too many active subbands (%d)\n", active_bands[i][j]);
1265                 return AVERROR_INVALIDDATA;
1266             }
1267         }
1268     }
1269
1270     /* skip to the end of the header */
1271     i = get_bits_count(&s->gb);
1272     if(hdr_pos + hdr_size * 8 > i)
1273         skip_bits_long(&s->gb, hdr_pos + hdr_size * 8 - i);
1274
1275     /* loop over the channel data sets */
1276     /* only decode as many channels as we've decoded base data for */
1277     for(chset = 0, chan_base = 0;
1278         chset < num_chsets && chan_base + n_xbr_ch[chset] <= s->audio_header.prim_channels;
1279         chan_base += n_xbr_ch[chset++]) {
1280         int start_posn = get_bits_count(&s->gb);
1281         int subsubframe = 0;
1282         int subframe = 0;
1283
1284         /* loop over subframes */
1285         for (k = 0; k < (s->sample_blocks / 8); k++) {
1286             /* parse header if we're on first subsubframe of a block */
1287             if(subsubframe == 0) {
1288                 /* Parse subframe header */
1289                 for(i = 0; i < n_xbr_ch[chset]; i++) {
1290                     anctemp[i] = get_bits(&s->gb, 2) + 2;
1291                 }
1292
1293                 for(i = 0; i < n_xbr_ch[chset]; i++) {
1294                     get_array(&s->gb, abits_high[i], active_bands[chset][i], anctemp[i]);
1295                 }
1296
1297                 for(i = 0; i < n_xbr_ch[chset]; i++) {
1298                     anctemp[i] = get_bits(&s->gb, 3);
1299                     if(anctemp[i] < 1) {
1300                         av_log(s->avctx, AV_LOG_ERROR, "DTS-XBR: SYNC ERROR\n");
1301                         return AVERROR_INVALIDDATA;
1302                     }
1303                 }
1304
1305                 /* generate scale factors */
1306                 for(i = 0; i < n_xbr_ch[chset]; i++) {
1307                     const uint32_t *scale_table;
1308                     int nbits;
1309                     int scale_table_size;
1310
1311                     if (s->audio_header.scalefactor_huffman[chan_base+i] == 6) {
1312                         scale_table = ff_dca_scale_factor_quant7;
1313                         scale_table_size = FF_ARRAY_ELEMS(ff_dca_scale_factor_quant7);
1314                     } else {
1315                         scale_table = ff_dca_scale_factor_quant6;
1316                         scale_table_size = FF_ARRAY_ELEMS(ff_dca_scale_factor_quant6);
1317                     }
1318
1319                     nbits = anctemp[i];
1320
1321                     for(j = 0; j < active_bands[chset][i]; j++) {
1322                         if(abits_high[i][j] > 0) {
1323                             int index = get_bits(&s->gb, nbits);
1324                             if (index >= scale_table_size) {
1325                                 av_log(s->avctx, AV_LOG_ERROR, "scale table index %d invalid\n", index);
1326                                 return AVERROR_INVALIDDATA;
1327                             }
1328                             scale_table_high[i][j][0] = scale_table[index];
1329
1330                             if(xbr_tmode && s->dca_chan[i].transition_mode[j]) {
1331                                 int index = get_bits(&s->gb, nbits);
1332                                 if (index >= scale_table_size) {
1333                                     av_log(s->avctx, AV_LOG_ERROR, "scale table index %d invalid\n", index);
1334                                     return AVERROR_INVALIDDATA;
1335                                 }
1336                                 scale_table_high[i][j][1] = scale_table[index];
1337                             }
1338                         }
1339                     }
1340                 }
1341             }
1342
1343             /* decode audio array for this block */
1344             for(i = 0; i < n_xbr_ch[chset]; i++) {
1345                 for(j = 0; j < active_bands[chset][i]; j++) {
1346                     const int xbr_abits = abits_high[i][j];
1347                     const uint32_t quant_step_size = ff_dca_lossless_quant[xbr_abits];
1348                     const int sfi = xbr_tmode && s->dca_chan[i].transition_mode[j] && subsubframe >= s->dca_chan[i].transition_mode[j];
1349                     const uint32_t rscale = scale_table_high[i][j][sfi];
1350                     int32_t *subband_samples = s->dca_chan[chan_base+i].subband_samples[k][j];
1351                     int32_t block[SAMPLES_PER_SUBBAND];
1352
1353                     if(xbr_abits <= 0)
1354                         continue;
1355
1356                     if(xbr_abits > 7) {
1357                         get_array(&s->gb, block, SAMPLES_PER_SUBBAND, xbr_abits - 3);
1358                     } else {
1359                         int block_code1, block_code2, size, levels, err;
1360
1361                         size   = abits_sizes[xbr_abits - 1];
1362                         levels = abits_levels[xbr_abits - 1];
1363
1364                         block_code1 = get_bits(&s->gb, size);
1365                         block_code2 = get_bits(&s->gb, size);
1366                         err = decode_blockcodes(block_code1, block_code2,
1367                                                 levels, block);
1368                         if (err) {
1369                             av_log(s->avctx, AV_LOG_ERROR,
1370                                    "ERROR: DTS-XBR: block code look-up failed\n");
1371                             return AVERROR_INVALIDDATA;
1372                         }
1373                     }
1374
1375                     /* scale & sum into subband */
1376                     s->dcadsp.dequantize(block, quant_step_size, rscale);
1377                     for(l = 0; l < SAMPLES_PER_SUBBAND; l++)
1378                         subband_samples[l] += block[l];
1379                 }
1380             }
1381
1382             /* check DSYNC marker */
1383             if(s->aspf || subsubframe == s->subsubframes[subframe] - 1) {
1384                 if(get_bits(&s->gb, 16) != 0xffff) {
1385                     av_log(s->avctx, AV_LOG_ERROR, "DTS-XBR: Didn't get subframe DSYNC\n");
1386                     return AVERROR_INVALIDDATA;
1387                 }
1388             }
1389
1390             /* advance sub-sub-frame index */
1391             if(++subsubframe >= s->subsubframes[subframe]) {
1392                 subsubframe = 0;
1393                 subframe++;
1394             }
1395         }
1396
1397         /* skip to next channel set */
1398         i = get_bits_count(&s->gb);
1399         if(start_posn + chset_fsize[chset] * 8 != i) {
1400             j = start_posn + chset_fsize[chset] * 8 - i;
1401             if(j < 0 || j >= 8)
1402                 av_log(s->avctx, AV_LOG_ERROR, "DTS-XBR: end of channel set,"
1403                        " skipping further than expected (%d bits)\n", j);
1404             skip_bits_long(&s->gb, j);
1405         }
1406     }
1407
1408     return 0;
1409 }
1410
1411
1412 /* parse initial header for XXCH and dump details */
1413 int ff_dca_xxch_decode_frame(DCAContext *s)
1414 {
1415     int hdr_size, spkmsk_bits, num_chsets, core_spk, hdr_pos;
1416     int i, chset, base_channel, chstart, fsize[8];
1417
1418     /* assume header word has already been parsed */
1419     hdr_pos     = get_bits_count(&s->gb) - 32;
1420     hdr_size    = get_bits(&s->gb, 6) + 1;
1421   /*chhdr_crc   =*/ skip_bits1(&s->gb);
1422     spkmsk_bits = get_bits(&s->gb, 5) + 1;
1423     num_chsets  = get_bits(&s->gb, 2) + 1;
1424
1425     for (i = 0; i < num_chsets; i++)
1426         fsize[i] = get_bits(&s->gb, 14) + 1;
1427
1428     core_spk               = get_bits(&s->gb, spkmsk_bits);
1429     s->xxch_core_spkmask   = core_spk;
1430     s->xxch_nbits_spk_mask = spkmsk_bits;
1431     s->xxch_dmix_embedded  = 0;
1432
1433     /* skip to the end of the header */
1434     i = get_bits_count(&s->gb);
1435     if (hdr_pos + hdr_size * 8 > i)
1436         skip_bits_long(&s->gb, hdr_pos + hdr_size * 8 - i);
1437
1438     for (chset = 0; chset < num_chsets; chset++) {
1439         chstart       = get_bits_count(&s->gb);
1440         base_channel  = s->audio_header.prim_channels;
1441         s->xxch_chset = chset;
1442
1443         /* XXCH and Core headers differ, see 6.4.2 "XXCH Channel Set Header" vs.
1444            5.3.2 "Primary Audio Coding Header", DTS Spec 1.3.1 */
1445         dca_parse_audio_coding_header(s, base_channel, 1);
1446
1447         /* decode channel data */
1448         for (i = 0; i < (s->sample_blocks / 8); i++) {
1449             if (dca_decode_block(s, base_channel, i)) {
1450                 av_log(s->avctx, AV_LOG_ERROR,
1451                        "Error decoding DTS-XXCH extension\n");
1452                 continue;
1453             }
1454         }
1455
1456         /* skip to end of this section */
1457         i = get_bits_count(&s->gb);
1458         if (chstart + fsize[chset] * 8 > i)
1459             skip_bits_long(&s->gb, chstart + fsize[chset] * 8 - i);
1460     }
1461     s->xxch_chset = num_chsets;
1462
1463     return 0;
1464 }
1465
1466 static float dca_dmix_code(unsigned code)
1467 {
1468     int sign = (code >> 8) - 1;
1469     code &= 0xff;
1470     return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1 << 15));
1471 }
1472
1473 static int scan_for_extensions(AVCodecContext *avctx)
1474 {
1475     DCAContext *s = avctx->priv_data;
1476     int core_ss_end, ret = 0;
1477
1478     core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
1479
1480     /* only scan for extensions if ext_descr was unknown or indicated a
1481      * supported XCh extension */
1482     if (s->core_ext_mask < 0 || s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH)) {
1483         /* if ext_descr was unknown, clear s->core_ext_mask so that the
1484          * extensions scan can fill it up */
1485         s->core_ext_mask = FFMAX(s->core_ext_mask, 0);
1486
1487         /* extensions start at 32-bit boundaries into bitstream */
1488         skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1489
1490         while (core_ss_end - get_bits_count(&s->gb) >= 32) {
1491             uint32_t bits = get_bits_long(&s->gb, 32);
1492             int i;
1493
1494             switch (bits) {
1495             case DCA_SYNCWORD_XCH: {
1496                 int ext_amode, xch_fsize;
1497
1498                 s->xch_base_channel = s->audio_header.prim_channels;
1499
1500                 /* validate sync word using XCHFSIZE field */
1501                 xch_fsize = show_bits(&s->gb, 10);
1502                 if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
1503                     (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
1504                     continue;
1505
1506                 /* skip length-to-end-of-frame field for the moment */
1507                 skip_bits(&s->gb, 10);
1508
1509                 s->core_ext_mask |= DCA_EXT_XCH;
1510
1511                 /* extension amode(number of channels in extension) should be 1 */
1512                 /* AFAIK XCh is not used for more channels */
1513                 if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
1514                     av_log(avctx, AV_LOG_ERROR,
1515                            "XCh extension amode %d not supported!\n",
1516                            ext_amode);
1517                     continue;
1518                 }
1519
1520                 if (s->xch_base_channel < 2) {
1521                     avpriv_request_sample(avctx, "XCh with fewer than 2 base channels");
1522                     continue;
1523                 }
1524
1525                 /* much like core primary audio coding header */
1526                 dca_parse_audio_coding_header(s, s->xch_base_channel, 0);
1527
1528                 for (i = 0; i < (s->sample_blocks / 8); i++)
1529                     if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
1530                         av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
1531                         continue;
1532                     }
1533
1534                 s->xch_present = 1;
1535                 break;
1536             }
1537             case DCA_SYNCWORD_XXCH:
1538                 /* XXCh: extended channels */
1539                 /* usually found either in core or HD part in DTS-HD HRA streams,
1540                  * but not in DTS-ES which contains XCh extensions instead */
1541                 s->core_ext_mask |= DCA_EXT_XXCH;
1542                 ff_dca_xxch_decode_frame(s);
1543                 break;
1544
1545             case 0x1d95f262: {
1546                 int fsize96 = show_bits(&s->gb, 12) + 1;
1547                 if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
1548                     continue;
1549
1550                 av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",
1551                        get_bits_count(&s->gb));
1552                 skip_bits(&s->gb, 12);
1553                 av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
1554                 av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
1555
1556                 s->core_ext_mask |= DCA_EXT_X96;
1557                 break;
1558             }
1559             }
1560
1561             skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1562         }
1563     } else {
1564         /* no supported extensions, skip the rest of the core substream */
1565         skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
1566     }
1567
1568     if (s->core_ext_mask & DCA_EXT_X96)
1569         s->profile = FF_PROFILE_DTS_96_24;
1570     else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))
1571         s->profile = FF_PROFILE_DTS_ES;
1572
1573     /* check for ExSS (HD part) */
1574     if (s->dca_buffer_size - s->frame_size > 32 &&
1575         get_bits_long(&s->gb, 32) == DCA_SYNCWORD_SUBSTREAM)
1576         ff_dca_exss_parse_header(s);
1577
1578     return ret;
1579 }
1580
1581 static int set_channel_layout(AVCodecContext *avctx, int *channels, int num_core_channels)
1582 {
1583     DCAContext *s = avctx->priv_data;
1584     int i, j, chset, mask;
1585     int channel_layout, channel_mask;
1586     int posn, lavc;
1587
1588     /* If we have XXCH then the channel layout is managed differently */
1589     /* note that XLL will also have another way to do things */
1590     if (!(s->core_ext_mask & DCA_EXT_XXCH)) {
1591         /* xxx should also do MA extensions */
1592         if (s->amode < 16) {
1593             avctx->channel_layout = ff_dca_core_channel_layout[s->amode];
1594
1595             if (s->audio_header.prim_channels + !!s->lfe > 2 &&
1596                 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1597                 /*
1598                  * Neither the core's auxiliary data nor our default tables contain
1599                  * downmix coefficients for the additional channel coded in the XCh
1600                  * extension, so when we're doing a Stereo downmix, don't decode it.
1601                  */
1602                 s->xch_disable = 1;
1603             }
1604
1605             if (s->xch_present && !s->xch_disable) {
1606                 if (avctx->channel_layout & AV_CH_BACK_CENTER) {
1607                     avpriv_request_sample(avctx, "XCh with Back center channel");
1608                     return AVERROR_INVALIDDATA;
1609                 }
1610                 avctx->channel_layout |= AV_CH_BACK_CENTER;
1611                 if (s->lfe) {
1612                     avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1613                     s->channel_order_tab = ff_dca_channel_reorder_lfe_xch[s->amode];
1614                 } else {
1615                     s->channel_order_tab = ff_dca_channel_reorder_nolfe_xch[s->amode];
1616                 }
1617                 if (s->channel_order_tab[s->xch_base_channel] < 0)
1618                     return AVERROR_INVALIDDATA;
1619             } else {
1620                 *channels       = num_core_channels + !!s->lfe;
1621                 s->xch_present = 0; /* disable further xch processing */
1622                 if (s->lfe) {
1623                     avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1624                     s->channel_order_tab = ff_dca_channel_reorder_lfe[s->amode];
1625                 } else
1626                     s->channel_order_tab = ff_dca_channel_reorder_nolfe[s->amode];
1627             }
1628
1629             if (*channels > !!s->lfe &&
1630                 s->channel_order_tab[*channels - 1 - !!s->lfe] < 0)
1631                 return AVERROR_INVALIDDATA;
1632
1633             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != *channels) {
1634                 av_log(avctx, AV_LOG_ERROR, "Number of channels %d mismatches layout %d\n", *channels, av_get_channel_layout_nb_channels(avctx->channel_layout));
1635                 return AVERROR_INVALIDDATA;
1636             }
1637
1638             if (num_core_channels + !!s->lfe > 2 &&
1639                 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1640                 *channels              = 2;
1641                 s->output             = s->audio_header.prim_channels == 2 ? s->amode : DCA_STEREO;
1642                 avctx->channel_layout = AV_CH_LAYOUT_STEREO;
1643             }
1644             else if (avctx->request_channel_layout & AV_CH_LAYOUT_NATIVE) {
1645                 static const int8_t dca_channel_order_native[9] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
1646                 s->channel_order_tab = dca_channel_order_native;
1647             }
1648             s->lfe_index = ff_dca_lfe_index[s->amode];
1649         } else {
1650             av_log(avctx, AV_LOG_ERROR,
1651                    "Non standard configuration %d !\n", s->amode);
1652             return AVERROR_INVALIDDATA;
1653         }
1654
1655         s->xxch_dmix_embedded = 0;
1656     } else {
1657         /* we only get here if an XXCH channel set can be added to the mix */
1658         channel_mask = s->xxch_core_spkmask;
1659
1660         {
1661             *channels = s->audio_header.prim_channels + !!s->lfe;
1662             for (i = 0; i < s->xxch_chset; i++) {
1663                 channel_mask |= s->xxch_spk_masks[i];
1664             }
1665         }
1666
1667         /* Given the DTS spec'ed channel mask, generate an avcodec version */
1668         channel_layout = 0;
1669         for (i = 0; i < s->xxch_nbits_spk_mask; ++i) {
1670             if (channel_mask & (1 << i)) {
1671                 channel_layout |= ff_dca_map_xxch_to_native[i];
1672             }
1673         }
1674
1675         /* make sure that we have managed to get equivalent dts/avcodec channel
1676          * masks in some sense -- unfortunately some channels could overlap */
1677         if (av_popcount(channel_mask) != av_popcount(channel_layout)) {
1678             av_log(avctx, AV_LOG_DEBUG,
1679                    "DTS-XXCH: Inconsistent avcodec/dts channel layouts\n");
1680             return AVERROR_INVALIDDATA;
1681         }
1682
1683         avctx->channel_layout = channel_layout;
1684
1685         if (!(avctx->request_channel_layout & AV_CH_LAYOUT_NATIVE)) {
1686             /* Estimate DTS --> avcodec ordering table */
1687             for (chset = -1, j = 0; chset < s->xxch_chset; ++chset) {
1688                 mask = chset >= 0 ? s->xxch_spk_masks[chset]
1689                                   : s->xxch_core_spkmask;
1690                 for (i = 0; i < s->xxch_nbits_spk_mask; i++) {
1691                     if (mask & ~(DCA_XXCH_LFE1 | DCA_XXCH_LFE2) & (1 << i)) {
1692                         lavc = ff_dca_map_xxch_to_native[i];
1693                         posn = av_popcount(channel_layout & (lavc - 1));
1694                         s->xxch_order_tab[j++] = posn;
1695                     }
1696                 }
1697
1698             }
1699
1700             s->lfe_index = av_popcount(channel_layout & (AV_CH_LOW_FREQUENCY-1));
1701         } else { /* native ordering */
1702             for (i = 0; i < *channels; i++)
1703                 s->xxch_order_tab[i] = i;
1704
1705             s->lfe_index = *channels - 1;
1706         }
1707
1708         s->channel_order_tab = s->xxch_order_tab;
1709     }
1710
1711     return 0;
1712 }
1713
1714 /**
1715  * Main frame decoding function
1716  * FIXME add arguments
1717  */
1718 static int dca_decode_frame(AVCodecContext *avctx, void *data,
1719                             int *got_frame_ptr, AVPacket *avpkt)
1720 {
1721     AVFrame *frame     = data;
1722     const uint8_t *buf = avpkt->data;
1723     int buf_size       = avpkt->size;
1724     int lfe_samples;
1725     int num_core_channels = 0;
1726     int i, ret;
1727     float **samples_flt;
1728     float *src_chan;
1729     float *dst_chan;
1730     DCAContext *s = avctx->priv_data;
1731     int channels, full_channels;
1732     float scale;
1733     int achan;
1734     int chset;
1735     int mask;
1736     int j, k;
1737     int endch;
1738     int upsample = 0;
1739
1740     s->exss_ext_mask = 0;
1741     s->xch_present   = 0;
1742
1743     s->dca_buffer_size = AVERROR_INVALIDDATA;
1744     for (i = 0; i < buf_size - 3 && s->dca_buffer_size == AVERROR_INVALIDDATA; i++)
1745         s->dca_buffer_size = avpriv_dca_convert_bitstream(buf + i, buf_size - i, s->dca_buffer,
1746                                                           DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);
1747
1748     if (s->dca_buffer_size == AVERROR_INVALIDDATA) {
1749         av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1750         return AVERROR_INVALIDDATA;
1751     }
1752
1753     if ((ret = dca_parse_frame_header(s)) < 0) {
1754         // seems like the frame is corrupt, try with the next one
1755         return ret;
1756     }
1757     // set AVCodec values with parsed data
1758     avctx->sample_rate = s->sample_rate;
1759
1760     s->profile = FF_PROFILE_DTS;
1761
1762     for (i = 0; i < (s->sample_blocks / SAMPLES_PER_SUBBAND); i++) {
1763         if ((ret = dca_decode_block(s, 0, i))) {
1764             av_log(avctx, AV_LOG_ERROR, "error decoding block\n");
1765             return ret;
1766         }
1767     }
1768
1769     /* record number of core channels incase less than max channels are requested */
1770     num_core_channels = s->audio_header.prim_channels;
1771
1772     if (s->audio_header.prim_channels + !!s->lfe > 2 &&
1773         avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1774             /* Stereo downmix coefficients
1775              *
1776              * The decoder can only downmix to 2-channel, so we need to ensure
1777              * embedded downmix coefficients are actually targeting 2-channel.
1778              */
1779             if (s->core_downmix && (s->core_downmix_amode == DCA_STEREO ||
1780                                     s->core_downmix_amode == DCA_STEREO_TOTAL)) {
1781                 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1782                     /* Range checked earlier */
1783                     s->downmix_coef[i][0] = dca_dmix_code(s->core_downmix_codes[i][0]);
1784                     s->downmix_coef[i][1] = dca_dmix_code(s->core_downmix_codes[i][1]);
1785                 }
1786                 s->output = s->core_downmix_amode;
1787             } else {
1788                 int am = s->amode & DCA_CHANNEL_MASK;
1789                 if (am >= FF_ARRAY_ELEMS(ff_dca_default_coeffs)) {
1790                     av_log(s->avctx, AV_LOG_ERROR,
1791                            "Invalid channel mode %d\n", am);
1792                     return AVERROR_INVALIDDATA;
1793                 }
1794                 if (num_core_channels + !!s->lfe >
1795                     FF_ARRAY_ELEMS(ff_dca_default_coeffs[0])) {
1796                     avpriv_request_sample(s->avctx, "Downmixing %d channels",
1797                                           s->audio_header.prim_channels + !!s->lfe);
1798                     return AVERROR_PATCHWELCOME;
1799                 }
1800                 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1801                     s->downmix_coef[i][0] = ff_dca_default_coeffs[am][i][0];
1802                     s->downmix_coef[i][1] = ff_dca_default_coeffs[am][i][1];
1803                 }
1804             }
1805             ff_dlog(s->avctx, "Stereo downmix coeffs:\n");
1806             for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1807                 ff_dlog(s->avctx, "L, input channel %d = %f\n", i,
1808                         s->downmix_coef[i][0]);
1809                 ff_dlog(s->avctx, "R, input channel %d = %f\n", i,
1810                         s->downmix_coef[i][1]);
1811             }
1812             ff_dlog(s->avctx, "\n");
1813     }
1814
1815     if (s->ext_coding)
1816         s->core_ext_mask = ff_dca_ext_audio_descr_mask[s->ext_descr];
1817     else
1818         s->core_ext_mask = 0;
1819
1820     ret = scan_for_extensions(avctx);
1821
1822     avctx->profile = s->profile;
1823
1824     full_channels = channels = s->audio_header.prim_channels + !!s->lfe;
1825
1826     ret = set_channel_layout(avctx, &channels, num_core_channels);
1827     if (ret < 0)
1828         return ret;
1829
1830     /* get output buffer */
1831     frame->nb_samples = 256 * (s->sample_blocks / SAMPLES_PER_SUBBAND);
1832     if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
1833         int xll_nb_samples = s->xll_segments * s->xll_smpl_in_seg;
1834         /* Check for invalid/unsupported conditions first */
1835         if (s->xll_residual_channels > channels) {
1836             av_log(s->avctx, AV_LOG_WARNING,
1837                    "DCA: too many residual channels (%d, core channels %d). Disabling XLL\n",
1838                    s->xll_residual_channels, channels);
1839             s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
1840         } else if (xll_nb_samples != frame->nb_samples &&
1841                    2 * frame->nb_samples != xll_nb_samples) {
1842             av_log(s->avctx, AV_LOG_WARNING,
1843                    "DCA: unsupported upsampling (%d XLL samples, %d core samples). Disabling XLL\n",
1844                    xll_nb_samples, frame->nb_samples);
1845             s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
1846         } else {
1847             if (2 * frame->nb_samples == xll_nb_samples) {
1848                 av_log(s->avctx, AV_LOG_INFO,
1849                        "XLL: upsampling core channels by a factor of 2\n");
1850                 upsample = 1;
1851
1852                 frame->nb_samples = xll_nb_samples;
1853                 // FIXME: Is it good enough to copy from the first channel set?
1854                 avctx->sample_rate = s->xll_chsets[0].sampling_frequency;
1855             }
1856             /* If downmixing to stereo, don't decode additional channels.
1857              * FIXME: Using the xch_disable flag for this doesn't seem right. */
1858             if (!s->xch_disable)
1859                 channels = s->xll_channels;
1860         }
1861     }
1862
1863     if (avctx->channels != channels) {
1864         if (avctx->channels)
1865             av_log(avctx, AV_LOG_INFO, "Number of channels changed in DCA decoder (%d -> %d)\n", avctx->channels, channels);
1866         avctx->channels = channels;
1867     }
1868
1869     /* FIXME: This is an ugly hack, to just revert to the default
1870      * layout if we have additional channels. Need to convert the XLL
1871      * channel masks to ffmpeg channel_layout mask. */
1872     if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels)
1873         avctx->channel_layout = 0;
1874
1875     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1876         return ret;
1877     samples_flt = (float **) frame->extended_data;
1878
1879     /* allocate buffer for extra channels if downmixing */
1880     if (avctx->channels < full_channels) {
1881         ret = av_samples_get_buffer_size(NULL, full_channels - channels,
1882                                          frame->nb_samples,
1883                                          avctx->sample_fmt, 0);
1884         if (ret < 0)
1885             return ret;
1886
1887         av_fast_malloc(&s->extra_channels_buffer,
1888                        &s->extra_channels_buffer_size, ret);
1889         if (!s->extra_channels_buffer)
1890             return AVERROR(ENOMEM);
1891
1892         ret = av_samples_fill_arrays((uint8_t **) s->extra_channels, NULL,
1893                                      s->extra_channels_buffer,
1894                                      full_channels - channels,
1895                                      frame->nb_samples, avctx->sample_fmt, 0);
1896         if (ret < 0)
1897             return ret;
1898     }
1899
1900     /* filter to get final output */
1901     for (i = 0; i < (s->sample_blocks / SAMPLES_PER_SUBBAND); i++) {
1902         int ch;
1903         unsigned block = upsample ? 512 : 256;
1904         for (ch = 0; ch < channels; ch++)
1905             s->samples_chanptr[ch] = samples_flt[ch] + i * block;
1906         for (; ch < full_channels; ch++)
1907             s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * block;
1908
1909         dca_filter_channels(s, i, upsample);
1910
1911         /* If this was marked as a DTS-ES stream we need to subtract back- */
1912         /* channel from SL & SR to remove matrixed back-channel signal */
1913         if ((s->source_pcm_res & 1) && s->xch_present) {
1914             float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];
1915             float *lt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];
1916             float *rt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];
1917             s->fdsp->vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
1918             s->fdsp->vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
1919         }
1920
1921         /* If stream contains XXCH, we might need to undo an embedded downmix */
1922         if (s->xxch_dmix_embedded) {
1923             /* Loop over channel sets in turn */
1924             ch = num_core_channels;
1925             for (chset = 0; chset < s->xxch_chset; chset++) {
1926                 endch = ch + s->xxch_chset_nch[chset];
1927                 mask = s->xxch_dmix_embedded;
1928
1929                 /* undo downmix */
1930                 for (j = ch; j < endch; j++) {
1931                     if (mask & (1 << j)) { /* this channel has been mixed-out */
1932                         src_chan = s->samples_chanptr[s->channel_order_tab[j]];
1933                         for (k = 0; k < endch; k++) {
1934                             achan = s->channel_order_tab[k];
1935                             scale = s->xxch_dmix_coeff[j][k];
1936                             if (scale != 0.0) {
1937                                 dst_chan = s->samples_chanptr[achan];
1938                                 s->fdsp->vector_fmac_scalar(dst_chan, src_chan,
1939                                                            -scale, 256);
1940                             }
1941                         }
1942                     }
1943                 }
1944
1945                 /* if a downmix has been embedded then undo the pre-scaling */
1946                 if ((mask & (1 << ch)) && s->xxch_dmix_sf[chset] != 1.0f) {
1947                     scale = s->xxch_dmix_sf[chset];
1948
1949                     for (j = 0; j < ch; j++) {
1950                         src_chan = s->samples_chanptr[s->channel_order_tab[j]];
1951                         for (k = 0; k < 256; k++)
1952                             src_chan[k] *= scale;
1953                     }
1954
1955                     /* LFE channel is always part of core, scale if it exists */
1956                     if (s->lfe) {
1957                         src_chan = s->samples_chanptr[s->lfe_index];
1958                         for (k = 0; k < 256; k++)
1959                             src_chan[k] *= scale;
1960                     }
1961                 }
1962
1963                 ch = endch;
1964             }
1965
1966         }
1967     }
1968
1969     /* update lfe history */
1970     lfe_samples = 2 * s->lfe * (s->sample_blocks / SAMPLES_PER_SUBBAND);
1971     for (i = 0; i < 2 * s->lfe * 4; i++)
1972         s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1973
1974     if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
1975         ret = ff_dca_xll_decode_audio(s, frame);
1976         if (ret < 0)
1977             return ret;
1978     }
1979     /* AVMatrixEncoding
1980      *
1981      * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */
1982     ret = ff_side_data_update_matrix_encoding(frame,
1983                                               (s->output & ~DCA_LFE) == DCA_STEREO_TOTAL ?
1984                                               AV_MATRIX_ENCODING_DOLBY : AV_MATRIX_ENCODING_NONE);
1985     if (ret < 0)
1986         return ret;
1987
1988     if (   avctx->profile != FF_PROFILE_DTS_HD_MA
1989         && avctx->profile != FF_PROFILE_DTS_HD_HRA)
1990         avctx->bit_rate = s->bit_rate;
1991     *got_frame_ptr = 1;
1992
1993     return buf_size;
1994 }
1995
1996 /**
1997  * DCA initialization
1998  *
1999  * @param avctx     pointer to the AVCodecContext
2000  */
2001
2002 static av_cold int dca_decode_init(AVCodecContext *avctx)
2003 {
2004     DCAContext *s = avctx->priv_data;
2005
2006     s->avctx = avctx;
2007     dca_init_vlcs();
2008
2009     s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
2010     if (!s->fdsp)
2011         return AVERROR(ENOMEM);
2012
2013     ff_mdct_init(&s->imdct, 6, 1, 1.0);
2014     ff_synth_filter_init(&s->synth);
2015     ff_dcadsp_init(&s->dcadsp);
2016     ff_fmt_convert_init(&s->fmt_conv, avctx);
2017
2018     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
2019
2020     /* allow downmixing to stereo */
2021     if (avctx->channels > 2 &&
2022         avctx->request_channel_layout == AV_CH_LAYOUT_STEREO)
2023         avctx->channels = 2;
2024
2025     return 0;
2026 }
2027
2028 static av_cold int dca_decode_end(AVCodecContext *avctx)
2029 {
2030     DCAContext *s = avctx->priv_data;
2031     ff_mdct_end(&s->imdct);
2032     av_freep(&s->extra_channels_buffer);
2033     av_freep(&s->fdsp);
2034     av_freep(&s->xll_sample_buf);
2035     av_freep(&s->qmf64_table);
2036     return 0;
2037 }
2038
2039 static const AVOption options[] = {
2040     { "disable_xch", "disable decoding of the XCh extension", offsetof(DCAContext, xch_disable), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM },
2041     { "disable_xll", "disable decoding of the XLL extension", offsetof(DCAContext, xll_disable), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM },
2042     { NULL },
2043 };
2044
2045 static const AVClass dca_decoder_class = {
2046     .class_name = "DCA decoder",
2047     .item_name  = av_default_item_name,
2048     .option     = options,
2049     .version    = LIBAVUTIL_VERSION_INT,
2050     .category   = AV_CLASS_CATEGORY_DECODER,
2051 };
2052
2053 AVCodec ff_dca_decoder = {
2054     .name            = "dca",
2055     .long_name       = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
2056     .type            = AVMEDIA_TYPE_AUDIO,
2057     .id              = AV_CODEC_ID_DTS,
2058     .priv_data_size  = sizeof(DCAContext),
2059     .init            = dca_decode_init,
2060     .decode          = dca_decode_frame,
2061     .close           = dca_decode_end,
2062     .capabilities    = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
2063     .sample_fmts     = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
2064                                                        AV_SAMPLE_FMT_NONE },
2065     .profiles        = NULL_IF_CONFIG_SMALL(ff_dca_profiles),
2066     .priv_class      = &dca_decoder_class,
2067 };