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