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