]> git.sesse.net Git - ffmpeg/blob - libavcodec/dcadec.c
lavc: add MMAL hardware decoder wrapper
[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 Libav.
11  *
12  * Libav 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  * Libav 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 Libav; 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 "put_bits.h"
53 #include "synth_filter.h"
54
55 #if ARCH_ARM
56 #   include "arm/dca.h"
57 #endif
58
59 enum DCAMode {
60     DCA_MONO = 0,
61     DCA_CHANNEL,
62     DCA_STEREO,
63     DCA_STEREO_SUMDIFF,
64     DCA_STEREO_TOTAL,
65     DCA_3F,
66     DCA_2F1R,
67     DCA_3F1R,
68     DCA_2F2R,
69     DCA_3F2R,
70     DCA_4F2R
71 };
72
73 /* -1 are reserved or unknown */
74 static const int dca_ext_audio_descr_mask[] = {
75     DCA_EXT_XCH,
76     -1,
77     DCA_EXT_X96,
78     DCA_EXT_XCH | DCA_EXT_X96,
79     -1,
80     -1,
81     DCA_EXT_XXCH,
82     -1,
83 };
84
85 /* Tables for mapping dts channel configurations to libavcodec multichannel api.
86  * Some compromises have been made for special configurations. Most configurations
87  * are never used so complete accuracy is not needed.
88  *
89  * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
90  * S  -> side, when both rear and back are configured move one of them to the side channel
91  * OV -> center back
92  * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
93  */
94 static const uint64_t dca_core_channel_layout[] = {
95     AV_CH_FRONT_CENTER,                                                     ///< 1, A
96     AV_CH_LAYOUT_STEREO,                                                    ///< 2, A + B (dual mono)
97     AV_CH_LAYOUT_STEREO,                                                    ///< 2, L + R (stereo)
98     AV_CH_LAYOUT_STEREO,                                                    ///< 2, (L + R) + (L - R) (sum-difference)
99     AV_CH_LAYOUT_STEREO,                                                    ///< 2, LT + RT (left and right total)
100     AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER,                               ///< 3, C + L + R
101     AV_CH_LAYOUT_STEREO | AV_CH_BACK_CENTER,                                ///< 3, L + R + S
102     AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER,           ///< 4, C + L + R + S
103     AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,               ///< 4, L + R + SL + SR
104
105     AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT |
106     AV_CH_SIDE_RIGHT,                                                       ///< 5, C + L + R + SL + SR
107
108     AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
109     AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER,               ///< 6, CL + CR + L + R + SL + SR
110
111     AV_CH_LAYOUT_STEREO | AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT |
112     AV_CH_FRONT_CENTER  | AV_CH_BACK_CENTER,                                ///< 6, C + L + R + LR + RR + OV
113
114     AV_CH_FRONT_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
115     AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_BACK_CENTER   |
116     AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 6, CF + CR + LF + RF + LR + RR
117
118     AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
119     AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
120     AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,                                     ///< 7, CL + C + CR + L + R + SL + SR
121
122     AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
123     AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
124     AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 8, CL + CR + L + R + SL1 + SL2 + SR1 + SR2
125
126     AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
127     AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
128     AV_CH_SIDE_LEFT | AV_CH_BACK_CENTER | AV_CH_SIDE_RIGHT,                 ///< 8, CL + C + CR + L + R + SL + S + SR
129 };
130
131 #define DCA_DOLBY                  101           /* FIXME */
132
133 #define DCA_CHANNEL_BITS             6
134 #define DCA_CHANNEL_MASK          0x3F
135
136 #define DCA_LFE                   0x80
137
138 #define HEADER_SIZE                 14
139
140 #define DCA_NSYNCAUX        0x9A1105A0
141
142 /** Bit allocation */
143 typedef struct BitAlloc {
144     int offset;                 ///< code values offset
145     int maxbits[8];             ///< max bits in VLC
146     int wrap;                   ///< wrap for get_vlc2()
147     VLC vlc[8];                 ///< actual codes
148 } BitAlloc;
149
150 static BitAlloc dca_bitalloc_index;    ///< indexes for samples VLC select
151 static BitAlloc dca_tmode;             ///< transition mode VLCs
152 static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
153 static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
154
155 static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba,
156                                          int idx)
157 {
158     return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) +
159            ba->offset;
160 }
161
162 static av_cold void dca_init_vlcs(void)
163 {
164     static int vlcs_initialized = 0;
165     int i, j, c = 14;
166     static VLC_TYPE dca_table[23622][2];
167
168     if (vlcs_initialized)
169         return;
170
171     dca_bitalloc_index.offset = 1;
172     dca_bitalloc_index.wrap   = 2;
173     for (i = 0; i < 5; i++) {
174         dca_bitalloc_index.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i]];
175         dca_bitalloc_index.vlc[i].table_allocated = ff_dca_vlc_offs[i + 1] - ff_dca_vlc_offs[i];
176         init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
177                  bitalloc_12_bits[i], 1, 1,
178                  bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
179     }
180     dca_scalefactor.offset = -64;
181     dca_scalefactor.wrap   = 2;
182     for (i = 0; i < 5; i++) {
183         dca_scalefactor.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i + 5]];
184         dca_scalefactor.vlc[i].table_allocated = ff_dca_vlc_offs[i + 6] - ff_dca_vlc_offs[i + 5];
185         init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
186                  scales_bits[i], 1, 1,
187                  scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
188     }
189     dca_tmode.offset = 0;
190     dca_tmode.wrap   = 1;
191     for (i = 0; i < 4; i++) {
192         dca_tmode.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i + 10]];
193         dca_tmode.vlc[i].table_allocated = ff_dca_vlc_offs[i + 11] - ff_dca_vlc_offs[i + 10];
194         init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
195                  tmode_bits[i], 1, 1,
196                  tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
197     }
198
199     for (i = 0; i < 10; i++)
200         for (j = 0; j < 7; j++) {
201             if (!bitalloc_codes[i][j])
202                 break;
203             dca_smpl_bitalloc[i + 1].offset                 = bitalloc_offsets[i];
204             dca_smpl_bitalloc[i + 1].wrap                   = 1 + (j > 4);
205             dca_smpl_bitalloc[i + 1].vlc[j].table           = &dca_table[ff_dca_vlc_offs[c]];
206             dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = ff_dca_vlc_offs[c + 1] - ff_dca_vlc_offs[c];
207
208             init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
209                      bitalloc_sizes[i],
210                      bitalloc_bits[i][j], 1, 1,
211                      bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
212             c++;
213         }
214     vlcs_initialized = 1;
215 }
216
217 static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
218 {
219     while (len--)
220         *dst++ = get_bits(gb, bits);
221 }
222
223 static int dca_parse_audio_coding_header(DCAContext *s, int base_channel)
224 {
225     int i, j;
226     static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
227     static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
228     static const int thr[11]    = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
229
230     s->total_channels = get_bits(&s->gb, 3) + 1 + base_channel;
231     s->prim_channels  = s->total_channels;
232
233     if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
234         s->prim_channels = DCA_PRIM_CHANNELS_MAX;
235
236     for (i = base_channel; i < s->prim_channels; i++) {
237         s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
238         if (s->subband_activity[i] > DCA_SUBBANDS)
239             s->subband_activity[i] = DCA_SUBBANDS;
240     }
241     for (i = base_channel; i < s->prim_channels; i++) {
242         s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
243         if (s->vq_start_subband[i] > DCA_SUBBANDS)
244             s->vq_start_subband[i] = DCA_SUBBANDS;
245     }
246     get_array(&s->gb, s->joint_intensity + base_channel,     s->prim_channels - base_channel, 3);
247     get_array(&s->gb, s->transient_huffman + base_channel,   s->prim_channels - base_channel, 2);
248     get_array(&s->gb, s->scalefactor_huffman + base_channel, s->prim_channels - base_channel, 3);
249     get_array(&s->gb, s->bitalloc_huffman + base_channel,    s->prim_channels - base_channel, 3);
250
251     /* Get codebooks quantization indexes */
252     if (!base_channel)
253         memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
254     for (j = 1; j < 11; j++)
255         for (i = base_channel; i < s->prim_channels; i++)
256             s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
257
258     /* Get scale factor adjustment */
259     for (j = 0; j < 11; j++)
260         for (i = base_channel; i < s->prim_channels; i++)
261             s->scalefactor_adj[i][j] = 1;
262
263     for (j = 1; j < 11; j++)
264         for (i = base_channel; i < s->prim_channels; i++)
265             if (s->quant_index_huffman[i][j] < thr[j])
266                 s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
267
268     if (s->crc_present) {
269         /* Audio header CRC check */
270         get_bits(&s->gb, 16);
271     }
272
273     s->current_subframe    = 0;
274     s->current_subsubframe = 0;
275
276     return 0;
277 }
278
279 static int dca_parse_frame_header(DCAContext *s)
280 {
281     init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
282
283     /* Sync code */
284     skip_bits_long(&s->gb, 32);
285
286     /* Frame header */
287     s->frame_type        = get_bits(&s->gb, 1);
288     s->samples_deficit   = get_bits(&s->gb, 5) + 1;
289     s->crc_present       = get_bits(&s->gb, 1);
290     s->sample_blocks     = get_bits(&s->gb, 7) + 1;
291     s->frame_size        = get_bits(&s->gb, 14) + 1;
292     if (s->frame_size < 95)
293         return AVERROR_INVALIDDATA;
294     s->amode             = get_bits(&s->gb, 6);
295     s->sample_rate       = avpriv_dca_sample_rates[get_bits(&s->gb, 4)];
296     if (!s->sample_rate)
297         return AVERROR_INVALIDDATA;
298     s->bit_rate_index    = get_bits(&s->gb, 5);
299     s->bit_rate          = ff_dca_bit_rates[s->bit_rate_index];
300     if (!s->bit_rate)
301         return AVERROR_INVALIDDATA;
302
303     skip_bits1(&s->gb); // always 0 (reserved, cf. ETSI TS 102 114 V1.4.1)
304     s->dynrange          = get_bits(&s->gb, 1);
305     s->timestamp         = get_bits(&s->gb, 1);
306     s->aux_data          = get_bits(&s->gb, 1);
307     s->hdcd              = get_bits(&s->gb, 1);
308     s->ext_descr         = get_bits(&s->gb, 3);
309     s->ext_coding        = get_bits(&s->gb, 1);
310     s->aspf              = get_bits(&s->gb, 1);
311     s->lfe               = get_bits(&s->gb, 2);
312     s->predictor_history = get_bits(&s->gb, 1);
313
314     if (s->lfe > 2) {
315         av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE value: %d\n", s->lfe);
316         return AVERROR_INVALIDDATA;
317     }
318
319     /* TODO: check CRC */
320     if (s->crc_present)
321         s->header_crc    = get_bits(&s->gb, 16);
322
323     s->multirate_inter   = get_bits(&s->gb, 1);
324     s->version           = get_bits(&s->gb, 4);
325     s->copy_history      = get_bits(&s->gb, 2);
326     s->source_pcm_res    = get_bits(&s->gb, 3);
327     s->front_sum         = get_bits(&s->gb, 1);
328     s->surround_sum      = get_bits(&s->gb, 1);
329     s->dialog_norm       = get_bits(&s->gb, 4);
330
331     /* FIXME: channels mixing levels */
332     s->output = s->amode;
333     if (s->lfe)
334         s->output |= DCA_LFE;
335
336     /* Primary audio coding header */
337     s->subframes = get_bits(&s->gb, 4) + 1;
338
339     return dca_parse_audio_coding_header(s, 0);
340 }
341
342 static inline int get_scale(GetBitContext *gb, int level, int value, int log2range)
343 {
344     if (level < 5) {
345         /* huffman encoded */
346         value += get_bitalloc(gb, &dca_scalefactor, level);
347         value  = av_clip(value, 0, (1 << log2range) - 1);
348     } else if (level < 8) {
349         if (level + 1 > log2range) {
350             skip_bits(gb, level + 1 - log2range);
351             value = get_bits(gb, log2range);
352         } else {
353             value = get_bits(gb, level + 1);
354         }
355     }
356     return value;
357 }
358
359 static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)
360 {
361     /* Primary audio coding side information */
362     int j, k;
363
364     if (get_bits_left(&s->gb) < 0)
365         return AVERROR_INVALIDDATA;
366
367     if (!base_channel) {
368         s->subsubframes[s->current_subframe]    = get_bits(&s->gb, 2) + 1;
369         s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
370     }
371
372     for (j = base_channel; j < s->prim_channels; j++) {
373         for (k = 0; k < s->subband_activity[j]; k++)
374             s->prediction_mode[j][k] = get_bits(&s->gb, 1);
375     }
376
377     /* Get prediction codebook */
378     for (j = base_channel; j < s->prim_channels; j++) {
379         for (k = 0; k < s->subband_activity[j]; k++) {
380             if (s->prediction_mode[j][k] > 0) {
381                 /* (Prediction coefficient VQ address) */
382                 s->prediction_vq[j][k] = get_bits(&s->gb, 12);
383             }
384         }
385     }
386
387     /* Bit allocation index */
388     for (j = base_channel; j < s->prim_channels; j++) {
389         for (k = 0; k < s->vq_start_subband[j]; k++) {
390             if (s->bitalloc_huffman[j] == 6)
391                 s->bitalloc[j][k] = get_bits(&s->gb, 5);
392             else if (s->bitalloc_huffman[j] == 5)
393                 s->bitalloc[j][k] = get_bits(&s->gb, 4);
394             else if (s->bitalloc_huffman[j] == 7) {
395                 av_log(s->avctx, AV_LOG_ERROR,
396                        "Invalid bit allocation index\n");
397                 return AVERROR_INVALIDDATA;
398             } else {
399                 s->bitalloc[j][k] =
400                     get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
401             }
402
403             if (s->bitalloc[j][k] > 26) {
404                 av_dlog(s->avctx, "bitalloc index [%i][%i] too big (%i)\n",
405                         j, k, s->bitalloc[j][k]);
406                 return AVERROR_INVALIDDATA;
407             }
408         }
409     }
410
411     /* Transition mode */
412     for (j = base_channel; j < s->prim_channels; j++) {
413         for (k = 0; k < s->subband_activity[j]; k++) {
414             s->transition_mode[j][k] = 0;
415             if (s->subsubframes[s->current_subframe] > 1 &&
416                 k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
417                 s->transition_mode[j][k] =
418                     get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
419             }
420         }
421     }
422
423     if (get_bits_left(&s->gb) < 0)
424         return AVERROR_INVALIDDATA;
425
426     for (j = base_channel; j < s->prim_channels; j++) {
427         const uint32_t *scale_table;
428         int scale_sum, log_size;
429
430         memset(s->scale_factor[j], 0,
431                s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
432
433         if (s->scalefactor_huffman[j] == 6) {
434             scale_table = ff_dca_scale_factor_quant7;
435             log_size    = 7;
436         } else {
437             scale_table = ff_dca_scale_factor_quant6;
438             log_size    = 6;
439         }
440
441         /* When huffman coded, only the difference is encoded */
442         scale_sum = 0;
443
444         for (k = 0; k < s->subband_activity[j]; k++) {
445             if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
446                 scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);
447                 s->scale_factor[j][k][0] = scale_table[scale_sum];
448             }
449
450             if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
451                 /* Get second scale factor */
452                 scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);
453                 s->scale_factor[j][k][1] = scale_table[scale_sum];
454             }
455         }
456     }
457
458     /* Joint subband scale factor codebook select */
459     for (j = base_channel; j < s->prim_channels; j++) {
460         /* Transmitted only if joint subband coding enabled */
461         if (s->joint_intensity[j] > 0)
462             s->joint_huff[j] = get_bits(&s->gb, 3);
463     }
464
465     if (get_bits_left(&s->gb) < 0)
466         return AVERROR_INVALIDDATA;
467
468     /* Scale factors for joint subband coding */
469     for (j = base_channel; j < s->prim_channels; j++) {
470         int source_channel;
471
472         /* Transmitted only if joint subband coding enabled */
473         if (s->joint_intensity[j] > 0) {
474             int scale = 0;
475             source_channel = s->joint_intensity[j] - 1;
476
477             /* When huffman coded, only the difference is encoded
478              * (is this valid as well for joint scales ???) */
479
480             for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
481                 scale = get_scale(&s->gb, s->joint_huff[j], 64 /* bias */, 7);
482                 s->joint_scale_factor[j][k] = scale;    /*joint_scale_table[scale]; */
483             }
484
485             if (!(s->debug_flag & 0x02)) {
486                 av_log(s->avctx, AV_LOG_DEBUG,
487                        "Joint stereo coding not supported\n");
488                 s->debug_flag |= 0x02;
489             }
490         }
491     }
492
493     /* Dynamic range coefficient */
494     if (!base_channel && s->dynrange)
495         s->dynrange_coef = get_bits(&s->gb, 8);
496
497     /* Side information CRC check word */
498     if (s->crc_present) {
499         get_bits(&s->gb, 16);
500     }
501
502     /*
503      * Primary audio data arrays
504      */
505
506     /* VQ encoded high frequency subbands */
507     for (j = base_channel; j < s->prim_channels; j++)
508         for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
509             /* 1 vector -> 32 samples */
510             s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
511
512     /* Low frequency effect data */
513     if (!base_channel && s->lfe) {
514         /* LFE samples */
515         int lfe_samples    = 2 * s->lfe * (4 + block_index);
516         int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
517         float lfe_scale;
518
519         for (j = lfe_samples; j < lfe_end_sample; j++) {
520             /* Signed 8 bits int */
521             s->lfe_data[j] = get_sbits(&s->gb, 8);
522         }
523
524         /* Scale factor index */
525         skip_bits(&s->gb, 1);
526         s->lfe_scale_factor = ff_dca_scale_factor_quant7[get_bits(&s->gb, 7)];
527
528         /* Quantization step size * scale factor */
529         lfe_scale = 0.035 * s->lfe_scale_factor;
530
531         for (j = lfe_samples; j < lfe_end_sample; j++)
532             s->lfe_data[j] *= lfe_scale;
533     }
534
535     return 0;
536 }
537
538 static void qmf_32_subbands(DCAContext *s, int chans,
539                             float samples_in[32][8], float *samples_out,
540                             float scale)
541 {
542     const float *prCoeff;
543
544     int sb_act = s->subband_activity[chans];
545
546     scale *= sqrt(1 / 8.0);
547
548     /* Select filter */
549     if (!s->multirate_inter)    /* Non-perfect reconstruction */
550         prCoeff = ff_dca_fir_32bands_nonperfect;
551     else                        /* Perfect reconstruction */
552         prCoeff = ff_dca_fir_32bands_perfect;
553
554     s->dcadsp.qmf_32_subbands(samples_in, sb_act, &s->synth, &s->imdct,
555                               s->subband_fir_hist[chans],
556                               &s->hist_index[chans],
557                               s->subband_fir_noidea[chans], prCoeff,
558                               samples_out, s->raXin, scale);
559 }
560
561 static QMF64_table *qmf64_precompute(void)
562 {
563     unsigned i, j;
564     QMF64_table *table = av_malloc(sizeof(*table));
565     if (!table)
566         return NULL;
567
568     for (i = 0; i < 32; i++)
569         for (j = 0; j < 32; j++)
570             table->dct4_coeff[i][j] = cos((2 * i + 1) * (2 * j + 1) * M_PI / 128);
571     for (i = 0; i < 32; i++)
572         for (j = 0; j < 32; j++)
573             table->dct2_coeff[i][j] = cos((2 * i + 1) *      j      * M_PI /  64);
574
575     /* FIXME: Is the factor 0.125 = 1/8 right? */
576     for (i = 0; i < 32; i++)
577         table->rcos[i] =  0.125 / cos((2 * i + 1) * M_PI / 256);
578     for (i = 0; i < 32; i++)
579         table->rsin[i] = -0.125 / sin((2 * i + 1) * M_PI / 256);
580
581     return table;
582 }
583
584 /* FIXME: Totally unoptimized. Based on the reference code and
585  * http://multimedia.cx/mirror/dca-transform.pdf, with guessed tweaks
586  * for doubling the size. */
587 static void qmf_64_subbands(DCAContext *s, int chans, float samples_in[64][8],
588                             float *samples_out, float scale)
589 {
590     float raXin[64];
591     float A[32], B[32];
592     float *raX = s->subband_fir_hist[chans];
593     float *raZ = s->subband_fir_noidea[chans];
594     unsigned i, j, k, subindex;
595
596     for (i = s->subband_activity[chans]; i < 64; i++)
597         raXin[i] = 0.0;
598     for (subindex = 0; subindex < 8; subindex++) {
599         for (i = 0; i < s->subband_activity[chans]; i++)
600             raXin[i] = samples_in[i][subindex];
601
602         for (k = 0; k < 32; k++) {
603             A[k] = 0.0;
604             for (i = 0; i < 32; i++)
605                 A[k] += (raXin[2 * i] + raXin[2 * i + 1]) * s->qmf64_table->dct4_coeff[k][i];
606         }
607         for (k = 0; k < 32; k++) {
608             B[k] = raXin[0] * s->qmf64_table->dct2_coeff[k][0];
609             for (i = 1; i < 32; i++)
610                 B[k] += (raXin[2 * i] + raXin[2 * i - 1]) * s->qmf64_table->dct2_coeff[k][i];
611         }
612         for (k = 0; k < 32; k++) {
613             raX[k]      = s->qmf64_table->rcos[k] * (A[k] + B[k]);
614             raX[63 - k] = s->qmf64_table->rsin[k] * (A[k] - B[k]);
615         }
616
617         for (i = 0; i < 64; i++) {
618             float out = raZ[i];
619             for (j = 0; j < 1024; j += 128)
620                 out += ff_dca_fir_64bands[j + i] * (raX[j + i] - raX[j + 63 - i]);
621             *samples_out++ = out * scale;
622         }
623
624         for (i = 0; i < 64; i++) {
625             float hist = 0.0;
626             for (j = 0; j < 1024; j += 128)
627                 hist += ff_dca_fir_64bands[64 + j + i] * (-raX[i + j] - raX[j + 63 - i]);
628
629             raZ[i] = hist;
630         }
631
632         /* FIXME: Make buffer circular, to avoid this move. */
633         memmove(raX + 64, raX, (1024 - 64) * sizeof(*raX));
634     }
635 }
636
637 static void lfe_interpolation_fir(DCAContext *s, const float *samples_in,
638                                   float *samples_out)
639 {
640     /* samples_in: An array holding decimated samples.
641      *   Samples in current subframe starts from samples_in[0],
642      *   while samples_in[-1], samples_in[-2], ..., stores samples
643      *   from last subframe as history.
644      *
645      * samples_out: An array holding interpolated samples
646      */
647
648     int idx;
649     const float *prCoeff;
650     int deciindex;
651
652     /* Select decimation filter */
653     if (s->lfe == 1) {
654         idx     = 1;
655         prCoeff = ff_dca_lfe_fir_128;
656     } else {
657         idx = 0;
658         if (s->exss_ext_mask & DCA_EXT_EXSS_XLL)
659             prCoeff = ff_dca_lfe_xll_fir_64;
660         else
661             prCoeff = ff_dca_lfe_fir_64;
662     }
663     /* Interpolation */
664     for (deciindex = 0; deciindex < 2 * s->lfe; deciindex++) {
665         s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
666         samples_in++;
667         samples_out += 2 * 32 * (1 + idx);
668     }
669 }
670
671 /* downmixing routines */
672 #define MIX_REAR1(samples, s1, rs, coef)            \
673     samples[0][i] += samples[s1][i] * coef[rs][0];  \
674     samples[1][i] += samples[s1][i] * coef[rs][1];
675
676 #define MIX_REAR2(samples, s1, s2, rs, coef)                                          \
677     samples[0][i] += samples[s1][i] * coef[rs][0] + samples[s2][i] * coef[rs + 1][0]; \
678     samples[1][i] += samples[s1][i] * coef[rs][1] + samples[s2][i] * coef[rs + 1][1];
679
680 #define MIX_FRONT3(samples, coef)                                      \
681     t = samples[c][i];                                                 \
682     u = samples[l][i];                                                 \
683     v = samples[r][i];                                                 \
684     samples[0][i] = t * coef[0][0] + u * coef[1][0] + v * coef[2][0];  \
685     samples[1][i] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
686
687 #define DOWNMIX_TO_STEREO(op1, op2)             \
688     for (i = 0; i < 256; i++) {                 \
689         op1                                     \
690         op2                                     \
691     }
692
693 static void dca_downmix(float **samples, int srcfmt, int lfe_present,
694                         float coef[DCA_PRIM_CHANNELS_MAX + 1][2],
695                         const int8_t *channel_mapping)
696 {
697     int c, l, r, sl, sr, s;
698     int i;
699     float t, u, v;
700
701     switch (srcfmt) {
702     case DCA_MONO:
703     case DCA_4F2R:
704         av_log(NULL, 0, "Not implemented!\n");
705         break;
706     case DCA_CHANNEL:
707     case DCA_STEREO:
708     case DCA_STEREO_TOTAL:
709     case DCA_STEREO_SUMDIFF:
710         break;
711     case DCA_3F:
712         c = channel_mapping[0];
713         l = channel_mapping[1];
714         r = channel_mapping[2];
715         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
716         break;
717     case DCA_2F1R:
718         s = channel_mapping[2];
719         DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );
720         break;
721     case DCA_3F1R:
722         c = channel_mapping[0];
723         l = channel_mapping[1];
724         r = channel_mapping[2];
725         s = channel_mapping[3];
726         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
727                           MIX_REAR1(samples, s, 3, coef));
728         break;
729     case DCA_2F2R:
730         sl = channel_mapping[2];
731         sr = channel_mapping[3];
732         DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );
733         break;
734     case DCA_3F2R:
735         c  = channel_mapping[0];
736         l  = channel_mapping[1];
737         r  = channel_mapping[2];
738         sl = channel_mapping[3];
739         sr = channel_mapping[4];
740         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
741                           MIX_REAR2(samples, sl, sr, 3, coef));
742         break;
743     }
744     if (lfe_present) {
745         int lf_buf = ff_dca_lfe_index[srcfmt];
746         int lf_idx =  ff_dca_channels[srcfmt];
747         for (i = 0; i < 256; i++) {
748             samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];
749             samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];
750         }
751     }
752 }
753
754 #ifndef decode_blockcodes
755 /* Very compact version of the block code decoder that does not use table
756  * look-up but is slightly slower */
757 static int decode_blockcode(int code, int levels, int32_t *values)
758 {
759     int i;
760     int offset = (levels - 1) >> 1;
761
762     for (i = 0; i < 4; i++) {
763         int div = FASTDIV(code, levels);
764         values[i] = code - offset - div * levels;
765         code      = div;
766     }
767
768     return code;
769 }
770
771 static int decode_blockcodes(int code1, int code2, int levels, int32_t *values)
772 {
773     return decode_blockcode(code1, levels, values) |
774            decode_blockcode(code2, levels, values + 4);
775 }
776 #endif
777
778 static const uint8_t abits_sizes[7]  = { 7, 10, 12, 13, 15, 17, 19 };
779 static const uint8_t abits_levels[7] = { 3,  5,  7,  9, 13, 17, 25 };
780
781 static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
782 {
783     int k, l;
784     int subsubframe = s->current_subsubframe;
785
786     const float *quant_step_table;
787
788     /* FIXME */
789     float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
790     LOCAL_ALIGNED_16(int32_t, block, [8 * DCA_SUBBANDS]);
791
792     /*
793      * Audio data
794      */
795
796     /* Select quantization step size table */
797     if (s->bit_rate_index == 0x1f)
798         quant_step_table = ff_dca_lossless_quant_d;
799     else
800         quant_step_table = ff_dca_lossy_quant_d;
801
802     for (k = base_channel; k < s->prim_channels; k++) {
803         float rscale[DCA_SUBBANDS];
804
805         if (get_bits_left(&s->gb) < 0)
806             return AVERROR_INVALIDDATA;
807
808         for (l = 0; l < s->vq_start_subband[k]; l++) {
809             int m;
810
811             /* Select the mid-tread linear quantizer */
812             int abits = s->bitalloc[k][l];
813
814             float quant_step_size = quant_step_table[abits];
815
816             /*
817              * Determine quantization index code book and its type
818              */
819
820             /* Select quantization index code book */
821             int sel = s->quant_index_huffman[k][abits];
822
823             /*
824              * Extract bits from the bit stream
825              */
826             if (!abits) {
827                 rscale[l] = 0;
828                 memset(block + 8 * l, 0, 8 * sizeof(block[0]));
829             } else {
830                 /* Deal with transients */
831                 int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];
832                 rscale[l] = quant_step_size * s->scale_factor[k][l][sfi] *
833                             s->scalefactor_adj[k][sel];
834
835                 if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
836                     if (abits <= 7) {
837                         /* Block code */
838                         int block_code1, block_code2, size, levels, err;
839
840                         size   = abits_sizes[abits - 1];
841                         levels = abits_levels[abits - 1];
842
843                         block_code1 = get_bits(&s->gb, size);
844                         block_code2 = get_bits(&s->gb, size);
845                         err         = decode_blockcodes(block_code1, block_code2,
846                                                         levels, block + 8 * l);
847                         if (err) {
848                             av_log(s->avctx, AV_LOG_ERROR,
849                                    "ERROR: block code look-up failed\n");
850                             return AVERROR_INVALIDDATA;
851                         }
852                     } else {
853                         /* no coding */
854                         for (m = 0; m < 8; m++)
855                             block[8 * l + m] = get_sbits(&s->gb, abits - 3);
856                     }
857                 } else {
858                     /* Huffman coded */
859                     for (m = 0; m < 8; m++)
860                         block[8 * l + m] = get_bitalloc(&s->gb,
861                                                         &dca_smpl_bitalloc[abits], sel);
862                 }
863             }
864         }
865
866         s->fmt_conv.int32_to_float_fmul_array8(&s->fmt_conv, subband_samples[k][0],
867                                                block, rscale, 8 * s->vq_start_subband[k]);
868
869         for (l = 0; l < s->vq_start_subband[k]; l++) {
870             int m;
871             /*
872              * Inverse ADPCM if in prediction mode
873              */
874             if (s->prediction_mode[k][l]) {
875                 int n;
876                 if (s->predictor_history)
877                     subband_samples[k][l][0] += (ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
878                                                  s->subband_samples_hist[k][l][3] +
879                                                  ff_dca_adpcm_vb[s->prediction_vq[k][l]][1] *
880                                                  s->subband_samples_hist[k][l][2] +
881                                                  ff_dca_adpcm_vb[s->prediction_vq[k][l]][2] *
882                                                  s->subband_samples_hist[k][l][1] +
883                                                  ff_dca_adpcm_vb[s->prediction_vq[k][l]][3] *
884                                                  s->subband_samples_hist[k][l][0]) *
885                                                 (1.0f / 8192);
886                 for (m = 1; m < 8; m++) {
887                     float sum = ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
888                                 subband_samples[k][l][m - 1];
889                     for (n = 2; n <= 4; n++)
890                         if (m >= n)
891                             sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
892                                    subband_samples[k][l][m - n];
893                         else if (s->predictor_history)
894                             sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
895                                    s->subband_samples_hist[k][l][m - n + 4];
896                     subband_samples[k][l][m] += sum * 1.0f / 8192;
897                 }
898             }
899         }
900
901         /*
902          * Decode VQ encoded high frequencies
903          */
904         if (s->subband_activity[k] > s->vq_start_subband[k]) {
905             if (!s->debug_flag & 0x01) {
906                 av_log(s->avctx, AV_LOG_DEBUG,
907                        "Stream with high frequencies VQ coding\n");
908                 s->debug_flag |= 0x01;
909             }
910             s->dcadsp.decode_hf(subband_samples[k], s->high_freq_vq[k],
911                                 ff_dca_high_freq_vq, subsubframe * 8,
912                                 s->scale_factor[k], s->vq_start_subband[k],
913                                 s->subband_activity[k]);
914         }
915     }
916
917     /* Check for DSYNC after subsubframe */
918     if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
919         if (get_bits(&s->gb, 16) != 0xFFFF) {
920             av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
921             return AVERROR_INVALIDDATA;
922         }
923     }
924
925     /* Backup predictor history for adpcm */
926     for (k = base_channel; k < s->prim_channels; k++)
927         for (l = 0; l < s->vq_start_subband[k]; l++)
928             AV_COPY128(s->subband_samples_hist[k][l], &subband_samples[k][l][4]);
929
930     return 0;
931 }
932
933 static int dca_filter_channels(DCAContext *s, int block_index, int upsample)
934 {
935     float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
936     int k;
937
938     if (upsample) {
939         if (!s->qmf64_table) {
940             s->qmf64_table = qmf64_precompute();
941             if (!s->qmf64_table)
942                 return AVERROR(ENOMEM);
943         }
944
945         /* 64 subbands QMF */
946         for (k = 0; k < s->prim_channels; k++) {
947             if (s->channel_order_tab[k] >= 0)
948                 qmf_64_subbands(s, k, subband_samples[k],
949                                 s->samples_chanptr[s->channel_order_tab[k]],
950                                 /* Upsampling needs a factor 2 here. */
951                                 M_SQRT2 / 32768.0);
952         }
953     } else {
954         /* 32 subbands QMF */
955         for (k = 0; k < s->prim_channels; k++) {
956             if (s->channel_order_tab[k] >= 0)
957                 qmf_32_subbands(s, k, subband_samples[k],
958                                 s->samples_chanptr[s->channel_order_tab[k]],
959                                 M_SQRT1_2 / 32768.0);
960         }
961     }
962
963     /* Generate LFE samples for this subsubframe FIXME!!! */
964     if (s->lfe) {
965         float *samples = s->samples_chanptr[ff_dca_lfe_index[s->amode]];
966         lfe_interpolation_fir(s,
967                               s->lfe_data + 2 * s->lfe * (block_index + 4),
968                               samples);
969         if (upsample) {
970             unsigned i;
971             /* Should apply the filter in Table 6-11 when upsampling. For
972              * now, just duplicate. */
973             for (i = 511; i > 0; i--) {
974                 samples[2 * i]     =
975                 samples[2 * i + 1] = samples[i];
976             }
977             samples[1] = samples[0];
978         }
979     }
980
981     /* FIXME: This downmixing is probably broken with upsample.
982      * Probably totally broken also with XLL in general. */
983     /* Downmixing to Stereo */
984     if (s->prim_channels + !!s->lfe > 2 &&
985         s->avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
986         dca_downmix(s->samples_chanptr, s->amode, !!s->lfe, s->downmix_coef,
987                     s->channel_order_tab);
988     }
989
990     return 0;
991 }
992
993 static int dca_subframe_footer(DCAContext *s, int base_channel)
994 {
995     int in, out, aux_data_count, aux_data_end, reserved;
996     uint32_t nsyncaux;
997
998     /*
999      * Unpack optional information
1000      */
1001
1002     /* presumably optional information only appears in the core? */
1003     if (!base_channel) {
1004         if (s->timestamp)
1005             skip_bits_long(&s->gb, 32);
1006
1007         if (s->aux_data) {
1008             aux_data_count = get_bits(&s->gb, 6);
1009
1010             // align (32-bit)
1011             skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1012
1013             aux_data_end = 8 * aux_data_count + get_bits_count(&s->gb);
1014
1015             if ((nsyncaux = get_bits_long(&s->gb, 32)) != DCA_NSYNCAUX) {
1016                 av_log(s->avctx, AV_LOG_ERROR, "nSYNCAUX mismatch %#"PRIx32"\n",
1017                        nsyncaux);
1018                 return AVERROR_INVALIDDATA;
1019             }
1020
1021             if (get_bits1(&s->gb)) { // bAUXTimeStampFlag
1022                 avpriv_request_sample(s->avctx,
1023                                       "Auxiliary Decode Time Stamp Flag");
1024                 // align (4-bit)
1025                 skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 4);
1026                 // 44 bits: nMSByte (8), nMarker (4), nLSByte (28), nMarker (4)
1027                 skip_bits_long(&s->gb, 44);
1028             }
1029
1030             if ((s->core_downmix = get_bits1(&s->gb))) {
1031                 int am = get_bits(&s->gb, 3);
1032                 switch (am) {
1033                 case 0:
1034                     s->core_downmix_amode = DCA_MONO;
1035                     break;
1036                 case 1:
1037                     s->core_downmix_amode = DCA_STEREO;
1038                     break;
1039                 case 2:
1040                     s->core_downmix_amode = DCA_STEREO_TOTAL;
1041                     break;
1042                 case 3:
1043                     s->core_downmix_amode = DCA_3F;
1044                     break;
1045                 case 4:
1046                     s->core_downmix_amode = DCA_2F1R;
1047                     break;
1048                 case 5:
1049                     s->core_downmix_amode = DCA_2F2R;
1050                     break;
1051                 case 6:
1052                     s->core_downmix_amode = DCA_3F1R;
1053                     break;
1054                 default:
1055                     av_log(s->avctx, AV_LOG_ERROR,
1056                            "Invalid mode %d for embedded downmix coefficients\n",
1057                            am);
1058                     return AVERROR_INVALIDDATA;
1059                 }
1060                 for (out = 0; out < ff_dca_channels[s->core_downmix_amode]; out++) {
1061                     for (in = 0; in < s->prim_channels + !!s->lfe; in++) {
1062                         uint16_t tmp = get_bits(&s->gb, 9);
1063                         if ((tmp & 0xFF) > 241) {
1064                             av_log(s->avctx, AV_LOG_ERROR,
1065                                    "Invalid downmix coefficient code %"PRIu16"\n",
1066                                    tmp);
1067                             return AVERROR_INVALIDDATA;
1068                         }
1069                         s->core_downmix_codes[in][out] = tmp;
1070                     }
1071                 }
1072             }
1073
1074             align_get_bits(&s->gb); // byte align
1075             skip_bits(&s->gb, 16);  // nAUXCRC16
1076
1077             // additional data (reserved, cf. ETSI TS 102 114 V1.4.1)
1078             if ((reserved = (aux_data_end - get_bits_count(&s->gb))) < 0) {
1079                 av_log(s->avctx, AV_LOG_ERROR,
1080                        "Overread auxiliary data by %d bits\n", -reserved);
1081                 return AVERROR_INVALIDDATA;
1082             } else if (reserved) {
1083                 avpriv_request_sample(s->avctx,
1084                                       "Core auxiliary data reserved content");
1085                 skip_bits_long(&s->gb, reserved);
1086             }
1087         }
1088
1089         if (s->crc_present && s->dynrange)
1090             get_bits(&s->gb, 16);
1091     }
1092
1093     return 0;
1094 }
1095
1096 /**
1097  * Decode a dca frame block
1098  *
1099  * @param s     pointer to the DCAContext
1100  */
1101
1102 static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
1103 {
1104     int ret;
1105
1106     /* Sanity check */
1107     if (s->current_subframe >= s->subframes) {
1108         av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1109                s->current_subframe, s->subframes);
1110         return AVERROR_INVALIDDATA;
1111     }
1112
1113     if (!s->current_subsubframe) {
1114         /* Read subframe header */
1115         if ((ret = dca_subframe_header(s, base_channel, block_index)))
1116             return ret;
1117     }
1118
1119     /* Read subsubframe */
1120     if ((ret = dca_subsubframe(s, base_channel, block_index)))
1121         return ret;
1122
1123     /* Update state */
1124     s->current_subsubframe++;
1125     if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
1126         s->current_subsubframe = 0;
1127         s->current_subframe++;
1128     }
1129     if (s->current_subframe >= s->subframes) {
1130         /* Read subframe footer */
1131         if ((ret = dca_subframe_footer(s, base_channel)))
1132             return ret;
1133     }
1134
1135     return 0;
1136 }
1137
1138 static float dca_dmix_code(unsigned code)
1139 {
1140     int sign = (code >> 8) - 1;
1141     code &= 0xff;
1142     return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1U << 15));
1143 }
1144
1145 /**
1146  * Main frame decoding function
1147  * FIXME add arguments
1148  */
1149 static int dca_decode_frame(AVCodecContext *avctx, void *data,
1150                             int *got_frame_ptr, AVPacket *avpkt)
1151 {
1152     AVFrame *frame     = data;
1153     const uint8_t *buf = avpkt->data;
1154     int buf_size       = avpkt->size;
1155
1156     int lfe_samples;
1157     int num_core_channels = 0;
1158     int i, ret;
1159     float  **samples_flt;
1160     DCAContext *s = avctx->priv_data;
1161     int channels, full_channels;
1162     int core_ss_end;
1163     int upsample = 0;
1164
1165     s->exss_ext_mask = 0;
1166     s->xch_present   = 0;
1167
1168     s->dca_buffer_size = ff_dca_convert_bitstream(buf, buf_size, s->dca_buffer,
1169                                                   DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);
1170     if (s->dca_buffer_size == AVERROR_INVALIDDATA) {
1171         av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1172         return AVERROR_INVALIDDATA;
1173     }
1174
1175     if ((ret = dca_parse_frame_header(s)) < 0) {
1176         // seems like the frame is corrupt, try with the next one
1177         return ret;
1178     }
1179     // set AVCodec values with parsed data
1180     avctx->sample_rate = s->sample_rate;
1181     avctx->bit_rate    = s->bit_rate;
1182
1183     s->profile = FF_PROFILE_DTS;
1184
1185     for (i = 0; i < (s->sample_blocks / 8); i++) {
1186         if ((ret = dca_decode_block(s, 0, i))) {
1187             av_log(avctx, AV_LOG_ERROR, "error decoding block\n");
1188             return ret;
1189         }
1190     }
1191
1192     /* record number of core channels incase less than max channels are requested */
1193     num_core_channels = s->prim_channels;
1194
1195     if (s->ext_coding)
1196         s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];
1197     else
1198         s->core_ext_mask = 0;
1199
1200     core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
1201
1202     /* only scan for extensions if ext_descr was unknown or indicated a
1203      * supported XCh extension */
1204     if (s->core_ext_mask < 0 || s->core_ext_mask & DCA_EXT_XCH) {
1205         /* if ext_descr was unknown, clear s->core_ext_mask so that the
1206          * extensions scan can fill it up */
1207         s->core_ext_mask = FFMAX(s->core_ext_mask, 0);
1208
1209         /* extensions start at 32-bit boundaries into bitstream */
1210         skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1211
1212         while (core_ss_end - get_bits_count(&s->gb) >= 32) {
1213             uint32_t bits = get_bits_long(&s->gb, 32);
1214
1215             switch (bits) {
1216             case DCA_SYNCWORD_XCH: {
1217                 int ext_amode, xch_fsize;
1218
1219                 s->xch_base_channel = s->prim_channels;
1220
1221                 /* validate sync word using XCHFSIZE field */
1222                 xch_fsize = show_bits(&s->gb, 10);
1223                 if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
1224                     (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
1225                     continue;
1226
1227                 /* skip length-to-end-of-frame field for the moment */
1228                 skip_bits(&s->gb, 10);
1229
1230                 s->core_ext_mask |= DCA_EXT_XCH;
1231
1232                 /* extension amode(number of channels in extension) should be 1 */
1233                 /* AFAIK XCh is not used for more channels */
1234                 if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
1235                     av_log(avctx, AV_LOG_ERROR,
1236                            "XCh extension amode %d not supported!\n",
1237                            ext_amode);
1238                     continue;
1239                 }
1240
1241                 /* much like core primary audio coding header */
1242                 dca_parse_audio_coding_header(s, s->xch_base_channel);
1243
1244                 for (i = 0; i < (s->sample_blocks / 8); i++)
1245                     if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
1246                         av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
1247                         continue;
1248                     }
1249
1250                 s->xch_present = 1;
1251                 break;
1252             }
1253             case DCA_SYNCWORD_XXCH:
1254                 /* XXCh: extended channels */
1255                 /* usually found either in core or HD part in DTS-HD HRA streams,
1256                  * but not in DTS-ES which contains XCh extensions instead */
1257                 s->core_ext_mask |= DCA_EXT_XXCH;
1258                 break;
1259
1260             case 0x1d95f262: {
1261                 int fsize96 = show_bits(&s->gb, 12) + 1;
1262                 if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
1263                     continue;
1264
1265                 av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",
1266                        get_bits_count(&s->gb));
1267                 skip_bits(&s->gb, 12);
1268                 av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
1269                 av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
1270
1271                 s->core_ext_mask |= DCA_EXT_X96;
1272                 break;
1273             }
1274             }
1275
1276             skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1277         }
1278     } else {
1279         /* no supported extensions, skip the rest of the core substream */
1280         skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
1281     }
1282
1283     if (s->core_ext_mask & DCA_EXT_X96)
1284         s->profile = FF_PROFILE_DTS_96_24;
1285     else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))
1286         s->profile = FF_PROFILE_DTS_ES;
1287
1288     /* check for ExSS (HD part) */
1289     if (s->dca_buffer_size - s->frame_size > 32 &&
1290         get_bits_long(&s->gb, 32) == DCA_SYNCWORD_SUBSTREAM)
1291         ff_dca_exss_parse_header(s);
1292
1293     avctx->profile = s->profile;
1294
1295     full_channels = channels = s->prim_channels + !!s->lfe;
1296
1297     if (s->amode < 16) {
1298         avctx->channel_layout = dca_core_channel_layout[s->amode];
1299
1300         if (s->prim_channels + !!s->lfe > 2 &&
1301             avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1302             /*
1303              * Neither the core's auxiliary data nor our default tables contain
1304              * downmix coefficients for the additional channel coded in the XCh
1305              * extension, so when we're doing a Stereo downmix, don't decode it.
1306              */
1307             s->xch_disable = 1;
1308         }
1309
1310 #if FF_API_REQUEST_CHANNELS
1311 FF_DISABLE_DEPRECATION_WARNINGS
1312         if (s->xch_present && !s->xch_disable &&
1313             (!avctx->request_channels ||
1314              avctx->request_channels > num_core_channels + !!s->lfe)) {
1315 FF_ENABLE_DEPRECATION_WARNINGS
1316 #else
1317         if (s->xch_present && !s->xch_disable) {
1318 #endif
1319             avctx->channel_layout |= AV_CH_BACK_CENTER;
1320             if (s->lfe) {
1321                 avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1322                 s->channel_order_tab = ff_dca_channel_reorder_lfe_xch[s->amode];
1323             } else {
1324                 s->channel_order_tab = ff_dca_channel_reorder_nolfe_xch[s->amode];
1325             }
1326         } else {
1327             channels       = num_core_channels + !!s->lfe;
1328             s->xch_present = 0; /* disable further xch processing */
1329             if (s->lfe) {
1330                 avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1331                 s->channel_order_tab = ff_dca_channel_reorder_lfe[s->amode];
1332             } else
1333                 s->channel_order_tab = ff_dca_channel_reorder_nolfe[s->amode];
1334         }
1335
1336         if (channels > !!s->lfe &&
1337             s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
1338             return AVERROR_INVALIDDATA;
1339
1340         if (num_core_channels + !!s->lfe > 2 &&
1341             avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1342             channels              = 2;
1343             s->output             = s->prim_channels == 2 ? s->amode : DCA_STEREO;
1344             avctx->channel_layout = AV_CH_LAYOUT_STEREO;
1345
1346             /* Stereo downmix coefficients
1347              *
1348              * The decoder can only downmix to 2-channel, so we need to ensure
1349              * embedded downmix coefficients are actually targeting 2-channel.
1350              */
1351             if (s->core_downmix && (s->core_downmix_amode == DCA_STEREO ||
1352                                     s->core_downmix_amode == DCA_STEREO_TOTAL)) {
1353                 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1354                     /* Range checked earlier */
1355                     s->downmix_coef[i][0] = dca_dmix_code(s->core_downmix_codes[i][0]);
1356                     s->downmix_coef[i][1] = dca_dmix_code(s->core_downmix_codes[i][1]);
1357                 }
1358                 s->output = s->core_downmix_amode;
1359             } else {
1360                 int am = s->amode & DCA_CHANNEL_MASK;
1361                 if (am >= FF_ARRAY_ELEMS(ff_dca_default_coeffs)) {
1362                     av_log(s->avctx, AV_LOG_ERROR,
1363                            "Invalid channel mode %d\n", am);
1364                     return AVERROR_INVALIDDATA;
1365                 }
1366                 if (num_core_channels + !!s->lfe >
1367                     FF_ARRAY_ELEMS(ff_dca_default_coeffs[0])) {
1368                     avpriv_request_sample(s->avctx, "Downmixing %d channels",
1369                                           s->prim_channels + !!s->lfe);
1370                     return AVERROR_PATCHWELCOME;
1371                 }
1372                 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1373                     s->downmix_coef[i][0] = ff_dca_default_coeffs[am][i][0];
1374                     s->downmix_coef[i][1] = ff_dca_default_coeffs[am][i][1];
1375                 }
1376             }
1377             av_dlog(s->avctx, "Stereo downmix coeffs:\n");
1378             for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1379                 av_dlog(s->avctx, "L, input channel %d = %f\n", i,
1380                         s->downmix_coef[i][0]);
1381                 av_dlog(s->avctx, "R, input channel %d = %f\n", i,
1382                         s->downmix_coef[i][1]);
1383             }
1384             av_dlog(s->avctx, "\n");
1385         }
1386     } else {
1387         av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n", s->amode);
1388         return AVERROR_INVALIDDATA;
1389     }
1390     avctx->channels = channels;
1391
1392     /* get output buffer */
1393     frame->nb_samples = 256 * (s->sample_blocks / 8);
1394     if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
1395         int xll_nb_samples = s->xll_segments * s->xll_smpl_in_seg;
1396         /* Check for invalid/unsupported conditions first */
1397         if (s->xll_residual_channels > channels) {
1398             av_log(s->avctx, AV_LOG_WARNING,
1399                    "DCA: too many residual channels (%d, core channels %d). Disabling XLL\n",
1400                    s->xll_residual_channels, channels);
1401             s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
1402         } else if (xll_nb_samples != frame->nb_samples &&
1403                    2 * frame->nb_samples != xll_nb_samples) {
1404             av_log(s->avctx, AV_LOG_WARNING,
1405                    "DCA: unsupported upsampling (%d XLL samples, %d core samples). Disabling XLL\n",
1406                    xll_nb_samples, frame->nb_samples);
1407             s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
1408         } else {
1409             if (2 * frame->nb_samples == xll_nb_samples) {
1410                 av_log(s->avctx, AV_LOG_INFO,
1411                        "XLL: upsampling core channels by a factor of 2\n");
1412                 upsample = 1;
1413
1414                 frame->nb_samples = xll_nb_samples;
1415                 // FIXME: Is it good enough to copy from the first channel set?
1416                 avctx->sample_rate = s->xll_chsets[0].sampling_frequency;
1417             }
1418             /* If downmixing to stereo, don't decode additional channels.
1419              * FIXME: Using the xch_disable flag for this doesn't seem right. */
1420             if (!s->xch_disable)
1421                 avctx->channels += s->xll_channels - s->xll_residual_channels;
1422         }
1423     }
1424
1425     /* FIXME: This is an ugly hack, to just revert to the default
1426      * layout if we have additional channels. Need to convert the XLL
1427      * channel masks to libav channel_layout mask. */
1428     if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels)
1429         avctx->channel_layout = 0;
1430
1431     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1432         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1433         return ret;
1434     }
1435     samples_flt = (float **) frame->extended_data;
1436
1437     /* allocate buffer for extra channels if downmixing */
1438     if (avctx->channels < full_channels) {
1439         ret = av_samples_get_buffer_size(NULL, full_channels - channels,
1440                                          frame->nb_samples,
1441                                          avctx->sample_fmt, 0);
1442         if (ret < 0)
1443             return ret;
1444
1445         av_fast_malloc(&s->extra_channels_buffer,
1446                        &s->extra_channels_buffer_size, ret);
1447         if (!s->extra_channels_buffer)
1448             return AVERROR(ENOMEM);
1449
1450         ret = av_samples_fill_arrays((uint8_t **) s->extra_channels, NULL,
1451                                      s->extra_channels_buffer,
1452                                      full_channels - channels,
1453                                      frame->nb_samples, avctx->sample_fmt, 0);
1454         if (ret < 0)
1455             return ret;
1456     }
1457
1458     /* filter to get final output */
1459     for (i = 0; i < (s->sample_blocks / 8); i++) {
1460         int ch;
1461         unsigned block = upsample ? 512 : 256;
1462         for (ch = 0; ch < channels; ch++)
1463             s->samples_chanptr[ch] = samples_flt[ch] + i * block;
1464         for (; ch < full_channels; ch++)
1465             s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * block;
1466
1467         dca_filter_channels(s, i, upsample);
1468
1469         /* If this was marked as a DTS-ES stream we need to subtract back- */
1470         /* channel from SL & SR to remove matrixed back-channel signal */
1471         if ((s->source_pcm_res & 1) && s->xch_present) {
1472             float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];
1473             float *lt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];
1474             float *rt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];
1475             s->fdsp.vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
1476             s->fdsp.vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
1477         }
1478     }
1479
1480     /* update lfe history */
1481     lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);
1482     for (i = 0; i < 2 * s->lfe * 4; i++)
1483         s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1484
1485     if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
1486         ret = ff_dca_xll_decode_audio(s, frame);
1487         if (ret < 0)
1488             return ret;
1489     }
1490     /* AVMatrixEncoding
1491      *
1492      * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */
1493     ret = ff_side_data_update_matrix_encoding(frame,
1494                                               (s->output & ~DCA_LFE) == DCA_STEREO_TOTAL ?
1495                                               AV_MATRIX_ENCODING_DOLBY : AV_MATRIX_ENCODING_NONE);
1496     if (ret < 0)
1497         return ret;
1498
1499     *got_frame_ptr = 1;
1500
1501     return buf_size;
1502 }
1503
1504 /**
1505  * DCA initialization
1506  *
1507  * @param avctx     pointer to the AVCodecContext
1508  */
1509
1510 static av_cold int dca_decode_init(AVCodecContext *avctx)
1511 {
1512     DCAContext *s = avctx->priv_data;
1513
1514     s->avctx = avctx;
1515     dca_init_vlcs();
1516
1517     avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
1518     ff_mdct_init(&s->imdct, 6, 1, 1.0);
1519     ff_synth_filter_init(&s->synth);
1520     ff_dcadsp_init(&s->dcadsp);
1521     ff_fmt_convert_init(&s->fmt_conv, avctx);
1522
1523     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1524
1525     /* allow downmixing to stereo */
1526 #if FF_API_REQUEST_CHANNELS
1527 FF_DISABLE_DEPRECATION_WARNINGS
1528     if (avctx->request_channels == 2)
1529         avctx->request_channel_layout = AV_CH_LAYOUT_STEREO;
1530 FF_ENABLE_DEPRECATION_WARNINGS
1531 #endif
1532     if (avctx->channels > 2 &&
1533         avctx->request_channel_layout == AV_CH_LAYOUT_STEREO)
1534         avctx->channels = 2;
1535
1536     return 0;
1537 }
1538
1539 static av_cold int dca_decode_end(AVCodecContext *avctx)
1540 {
1541     DCAContext *s = avctx->priv_data;
1542     ff_mdct_end(&s->imdct);
1543     av_freep(&s->extra_channels_buffer);
1544     av_freep(&s->xll_sample_buf);
1545     av_freep(&s->qmf64_table);
1546     return 0;
1547 }
1548
1549 static const AVProfile profiles[] = {
1550     { FF_PROFILE_DTS,        "DTS"        },
1551     { FF_PROFILE_DTS_ES,     "DTS-ES"     },
1552     { FF_PROFILE_DTS_96_24,  "DTS 96/24"  },
1553     { FF_PROFILE_DTS_HD_HRA, "DTS-HD HRA" },
1554     { FF_PROFILE_DTS_HD_MA,  "DTS-HD MA"  },
1555     { FF_PROFILE_UNKNOWN },
1556 };
1557
1558 static const AVOption options[] = {
1559     { "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 },
1560     { "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 },
1561     { NULL },
1562 };
1563
1564 static const AVClass dca_decoder_class = {
1565     .class_name = "DCA decoder",
1566     .item_name  = av_default_item_name,
1567     .option     = options,
1568     .version    = LIBAVUTIL_VERSION_INT,
1569 };
1570
1571 AVCodec ff_dca_decoder = {
1572     .name            = "dca",
1573     .long_name       = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1574     .type            = AVMEDIA_TYPE_AUDIO,
1575     .id              = AV_CODEC_ID_DTS,
1576     .priv_data_size  = sizeof(DCAContext),
1577     .init            = dca_decode_init,
1578     .decode          = dca_decode_frame,
1579     .close           = dca_decode_end,
1580     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
1581     .sample_fmts     = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1582                                                        AV_SAMPLE_FMT_NONE },
1583     .profiles        = NULL_IF_CONFIG_SMALL(profiles),
1584     .priv_class      = &dca_decoder_class,
1585 };