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