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