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