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