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