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
10 * This file is part of Libav.
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.
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.
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
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"
43 #include "dca_syncwords.h"
48 #include "fmtconvert.h"
53 #include "synth_filter.h"
73 /* -1 are reserved or unknown */
74 static const int dca_ext_audio_descr_mask[] = {
78 DCA_EXT_XCH | DCA_EXT_X96,
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.
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
92 * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
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
105 AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT |
106 AV_CH_SIDE_RIGHT, ///< 5, C + L + R + SL + SR
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
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
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
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
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
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
131 #define DCA_DOLBY 101 /* FIXME */
133 #define DCA_CHANNEL_BITS 6
134 #define DCA_CHANNEL_MASK 0x3F
138 #define HEADER_SIZE 14
140 #define DCA_NSYNCAUX 0x9A1105A0
142 #define SAMPLES_PER_SUBBAND 8 // number of samples per subband per subsubframe
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
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
157 static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba,
160 return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) +
164 static av_cold void dca_init_vlcs(void)
166 static int vlcs_initialized = 0;
168 static VLC_TYPE dca_table[23622][2];
170 if (vlcs_initialized)
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);
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);
191 dca_tmode.offset = 0;
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,
198 tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
201 for (i = 0; i < 10; i++)
202 for (j = 0; j < 7; j++) {
203 if (!bitalloc_codes[i][j])
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];
210 init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
212 bitalloc_bits[i][j], 1, 1,
213 bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
216 vlcs_initialized = 1;
219 static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
222 *dst++ = get_bits(gb, bits);
225 static int dca_parse_audio_coding_header(DCAContext *s, int base_channel)
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 };
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;
235 if (s->audio_header.prim_channels > DCA_PRIM_CHANNELS_MAX)
236 s->audio_header.prim_channels = DCA_PRIM_CHANNELS_MAX;
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;
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;
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);
257 /* Get codebooks quantization indexes */
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]);
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;
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)];
274 if (s->crc_present) {
275 /* Audio header CRC check */
276 get_bits(&s->gb, 16);
279 s->current_subframe = 0;
280 s->current_subsubframe = 0;
285 static int dca_parse_frame_header(DCAContext *s)
287 init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
290 skip_bits_long(&s->gb, 32);
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)];
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];
307 return AVERROR_INVALIDDATA;
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);
321 av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE value: %d\n", s->lfe);
322 return AVERROR_INVALIDDATA;
325 /* TODO: check CRC */
327 s->header_crc = get_bits(&s->gb, 16);
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);
337 /* FIXME: channels mixing levels */
338 s->output = s->amode;
340 s->output |= DCA_LFE;
342 /* Primary audio coding header */
343 s->audio_header.subframes = get_bits(&s->gb, 4) + 1;
345 return dca_parse_audio_coding_header(s, 0);
348 static inline int get_scale(GetBitContext *gb, int level, int value, int log2range)
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);
359 value = get_bits(gb, level + 1);
365 static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)
367 /* Primary audio coding side information */
370 if (get_bits_left(&s->gb) < 0)
371 return AVERROR_INVALIDDATA;
374 s->subsubframes[s->current_subframe] = get_bits(&s->gb, 2) + 1;
375 s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
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);
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);
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;
405 s->dca_chan[j].bitalloc[k] =
406 get_bitalloc(&s->gb, &dca_bitalloc_index, s->audio_header.bitalloc_huffman[j]);
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;
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]);
429 if (get_bits_left(&s->gb) < 0)
430 return AVERROR_INVALIDDATA;
432 for (j = base_channel; j < s->audio_header.prim_channels; j++) {
433 const uint32_t *scale_table;
434 int scale_sum, log_size;
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);
439 if (s->audio_header.scalefactor_huffman[j] == 6) {
440 scale_table = ff_dca_scale_factor_quant7;
443 scale_table = ff_dca_scale_factor_quant6;
447 /* When huffman coded, only the difference is encoded */
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];
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];
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);
471 if (get_bits_left(&s->gb) < 0)
472 return AVERROR_INVALIDDATA;
474 /* Scale factors for joint subband coding */
475 for (j = base_channel; j < s->audio_header.prim_channels; j++) {
478 /* Transmitted only if joint subband coding enabled */
479 if (s->audio_header.joint_intensity[j] > 0) {
481 source_channel = s->audio_header.joint_intensity[j] - 1;
483 /* When huffman coded, only the difference is encoded
484 * (is this valid as well for joint scales ???) */
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]; */
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;
500 /* Dynamic range coefficient */
501 if (!base_channel && s->dynrange)
502 s->dynrange_coef = get_bits(&s->gb, 8);
504 /* Side information CRC check word */
505 if (s->crc_present) {
506 get_bits(&s->gb, 16);
510 * Primary audio data arrays
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);
519 /* Low frequency effect data */
520 if (!base_channel && s->lfe) {
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]);
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);
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)];
535 /* Quantization step size * scale factor */
536 lfe_scale = 0.035 * s->lfe_scale_factor;
538 for (j = lfe_samples; j < lfe_end_sample; j++)
539 s->lfe_data[j] *= lfe_scale;
545 static void qmf_32_subbands(DCAContext *s, int chans,
546 float samples_in[32][SAMPLES_PER_SUBBAND], float *samples_out,
549 const float *prCoeff;
551 int sb_act = s->audio_header.subband_activity[chans];
553 scale *= sqrt(1 / 8.0);
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;
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);
568 static QMF64_table *qmf64_precompute(void)
571 QMF64_table *table = av_malloc(sizeof(*table));
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);
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);
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)
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;
603 for (i = s->audio_header.subband_activity[chans]; i < 64; i++)
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];
609 for (k = 0; k < 32; k++) {
611 for (i = 0; i < 32; i++)
612 A[k] += (raXin[2 * i] + raXin[2 * i + 1]) * s->qmf64_table->dct4_coeff[k][i];
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];
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]);
624 for (i = 0; i < 64; 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;
631 for (i = 0; i < 64; i++) {
633 for (j = 0; j < 1024; j += 128)
634 hist += ff_dca_fir_64bands[64 + j + i] * (-raX[i + j] - raX[j + 63 - i]);
639 /* FIXME: Make buffer circular, to avoid this move. */
640 memmove(raX + 64, raX, (1024 - 64) * sizeof(*raX));
644 static void lfe_interpolation_fir(DCAContext *s, const float *samples_in,
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.
652 * samples_out: An array holding interpolated samples
656 const float *prCoeff;
659 /* Select decimation filter */
662 prCoeff = ff_dca_lfe_fir_128;
665 if (s->exss_ext_mask & DCA_EXT_EXSS_XLL)
666 prCoeff = ff_dca_lfe_xll_fir_64;
668 prCoeff = ff_dca_lfe_fir_64;
671 for (deciindex = 0; deciindex < 2 * s->lfe; deciindex++) {
672 s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
674 samples_out += 2 * 32 * (1 + idx);
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];
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];
687 #define MIX_FRONT3(samples, coef) \
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];
694 #define DOWNMIX_TO_STEREO(op1, op2) \
695 for (i = 0; i < 256; i++) { \
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)
704 int c, l, r, sl, sr, s;
711 av_log(NULL, 0, "Not implemented!\n");
715 case DCA_STEREO_TOTAL:
716 case DCA_STEREO_SUMDIFF:
719 c = channel_mapping[0];
720 l = channel_mapping[1];
721 r = channel_mapping[2];
722 DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
725 s = channel_mapping[2];
726 DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );
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));
737 sl = channel_mapping[2];
738 sr = channel_mapping[3];
739 DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );
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));
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];
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)
767 int offset = (levels - 1) >> 1;
769 for (i = 0; i < 4; i++) {
770 int div = FASTDIV(code, levels);
771 values[i] = code - offset - div * levels;
778 static int decode_blockcodes(int code1, int code2, int levels, int32_t *values)
780 return decode_blockcode(code1, levels, values) |
781 decode_blockcode(code2, levels, values + 4);
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 };
788 static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
791 int subsubframe = s->current_subsubframe;
793 const float *quant_step_table;
795 LOCAL_ALIGNED_16(int32_t, block, [SAMPLES_PER_SUBBAND * DCA_SUBBANDS]);
801 /* Select quantization step size table */
802 if (s->bit_rate_index == 0x1f)
803 quant_step_table = ff_dca_lossless_quant_d;
805 quant_step_table = ff_dca_lossy_quant_d;
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];
811 if (get_bits_left(&s->gb) < 0)
812 return AVERROR_INVALIDDATA;
814 for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
817 /* Select the mid-tread linear quantizer */
818 int abits = s->dca_chan[k].bitalloc[l];
820 float quant_step_size = quant_step_table[abits];
823 * Determine quantization index code book and its type
826 /* Select quantization index code book */
827 int sel = s->audio_header.quant_index_huffman[k][abits];
830 * Extract bits from the bit stream
834 memset(block + SAMPLES_PER_SUBBAND * l, 0, SAMPLES_PER_SUBBAND * sizeof(block[0]));
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];
842 if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
845 int block_code1, block_code2, size, levels, err;
847 size = abits_sizes[abits - 1];
848 levels = abits_levels[abits - 1];
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);
855 av_log(s->avctx, AV_LOG_ERROR,
856 "ERROR: block code look-up failed\n");
857 return AVERROR_INVALIDDATA;
861 for (m = 0; m < SAMPLES_PER_SUBBAND; m++)
862 block[SAMPLES_PER_SUBBAND * l + m] = get_sbits(&s->gb, abits - 3);
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);
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]);
876 for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
879 * Inverse ADPCM if in prediction mode
881 if (s->dca_chan[k].prediction_mode[l]) {
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]) *
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++)
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;
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]);
914 * Decode VQ encoded high frequencies
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;
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]);
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;
942 static int dca_filter_channels(DCAContext *s, int block_index, int upsample)
947 if (!s->qmf64_table) {
948 s->qmf64_table = qmf64_precompute();
950 return AVERROR(ENOMEM);
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];
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. */
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];
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);
975 /* Generate LFE samples for this subsubframe FIXME!!! */
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),
983 /* Should apply the filter in Table 6-11 when upsampling. For
984 * now, just duplicate. */
985 for (i = 511; i > 0; i--) {
987 samples[2 * i + 1] = samples[i];
989 samples[1] = samples[0];
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);
1005 static int dca_subframe_footer(DCAContext *s, int base_channel)
1007 int in, out, aux_data_count, aux_data_end, reserved;
1011 * Unpack optional information
1014 /* presumably optional information only appears in the core? */
1015 if (!base_channel) {
1017 skip_bits_long(&s->gb, 32);
1020 aux_data_count = get_bits(&s->gb, 6);
1023 skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1025 aux_data_end = 8 * aux_data_count + get_bits_count(&s->gb);
1027 if ((nsyncaux = get_bits_long(&s->gb, 32)) != DCA_NSYNCAUX) {
1028 av_log(s->avctx, AV_LOG_ERROR, "nSYNCAUX mismatch %#"PRIx32"\n",
1030 return AVERROR_INVALIDDATA;
1033 if (get_bits1(&s->gb)) { // bAUXTimeStampFlag
1034 avpriv_request_sample(s->avctx,
1035 "Auxiliary Decode Time Stamp Flag");
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);
1042 if ((s->core_downmix = get_bits1(&s->gb))) {
1043 int am = get_bits(&s->gb, 3);
1046 s->core_downmix_amode = DCA_MONO;
1049 s->core_downmix_amode = DCA_STEREO;
1052 s->core_downmix_amode = DCA_STEREO_TOTAL;
1055 s->core_downmix_amode = DCA_3F;
1058 s->core_downmix_amode = DCA_2F1R;
1061 s->core_downmix_amode = DCA_2F2R;
1064 s->core_downmix_amode = DCA_3F1R;
1067 av_log(s->avctx, AV_LOG_ERROR,
1068 "Invalid mode %d for embedded downmix coefficients\n",
1070 return AVERROR_INVALIDDATA;
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",
1079 return AVERROR_INVALIDDATA;
1081 s->core_downmix_codes[in][out] = tmp;
1086 align_get_bits(&s->gb); // byte align
1087 skip_bits(&s->gb, 16); // nAUXCRC16
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);
1101 if (s->crc_present && s->dynrange)
1102 get_bits(&s->gb, 16);
1109 * Decode a dca frame block
1111 * @param s pointer to the DCAContext
1114 static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
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;
1125 if (!s->current_subsubframe) {
1126 /* Read subframe header */
1127 if ((ret = dca_subframe_header(s, base_channel, block_index)))
1131 /* Read subsubframe */
1132 if ((ret = dca_subsubframe(s, base_channel, block_index)))
1136 s->current_subsubframe++;
1137 if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
1138 s->current_subsubframe = 0;
1139 s->current_subframe++;
1141 if (s->current_subframe >= s->audio_header.subframes) {
1142 /* Read subframe footer */
1143 if ((ret = dca_subframe_footer(s, base_channel)))
1150 static float dca_dmix_code(unsigned code)
1152 int sign = (code >> 8) - 1;
1154 return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1U << 15));
1157 static int scan_for_extensions(AVCodecContext *avctx)
1159 DCAContext *s = avctx->priv_data;
1160 int core_ss_end, ret = 0;
1162 core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
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);
1171 /* extensions start at 32-bit boundaries into bitstream */
1172 skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1174 while (core_ss_end - get_bits_count(&s->gb) >= 32) {
1175 uint32_t bits = get_bits_long(&s->gb, 32);
1179 case DCA_SYNCWORD_XCH: {
1180 int ext_amode, xch_fsize;
1182 s->xch_base_channel = s->audio_header.prim_channels;
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))
1190 /* skip length-to-end-of-frame field for the moment */
1191 skip_bits(&s->gb, 10);
1193 s->core_ext_mask |= DCA_EXT_XCH;
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",
1204 /* much like core primary audio coding header */
1205 dca_parse_audio_coding_header(s, s->xch_base_channel);
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");
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;
1224 int fsize96 = show_bits(&s->gb, 12) + 1;
1225 if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
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));
1234 s->core_ext_mask |= DCA_EXT_X96;
1239 skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
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));
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;
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);
1259 static int set_channel_layout(AVCodecContext *avctx, int channels, int num_core_channels)
1261 DCAContext *s = avctx->priv_data;
1264 if (s->amode < 16) {
1265 avctx->channel_layout = dca_core_channel_layout[s->amode];
1267 if (s->audio_header.prim_channels + !!s->lfe > 2 &&
1268 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
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.
1277 if (s->xch_present && !s->xch_disable) {
1278 avctx->channel_layout |= AV_CH_BACK_CENTER;
1280 avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1281 s->channel_order_tab = ff_dca_channel_reorder_lfe_xch[s->amode];
1283 s->channel_order_tab = ff_dca_channel_reorder_nolfe_xch[s->amode];
1286 channels = num_core_channels + !!s->lfe;
1287 s->xch_present = 0; /* disable further xch processing */
1289 avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1290 s->channel_order_tab = ff_dca_channel_reorder_lfe[s->amode];
1292 s->channel_order_tab = ff_dca_channel_reorder_nolfe[s->amode];
1295 if (channels > !!s->lfe &&
1296 s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
1297 return AVERROR_INVALIDDATA;
1299 if (num_core_channels + !!s->lfe > 2 &&
1300 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1302 s->output = s->audio_header.prim_channels == 2 ? s->amode : DCA_STEREO;
1303 avctx->channel_layout = AV_CH_LAYOUT_STEREO;
1305 /* Stereo downmix coefficients
1307 * The decoder can only downmix to 2-channel, so we need to ensure
1308 * embedded downmix coefficients are actually targeting 2-channel.
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]);
1317 s->output = s->core_downmix_amode;
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;
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;
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];
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]);
1343 ff_dlog(s->avctx, "\n");
1346 av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n", s->amode);
1347 return AVERROR_INVALIDDATA;
1354 * Main frame decoding function
1355 * FIXME add arguments
1357 static int dca_decode_frame(AVCodecContext *avctx, void *data,
1358 int *got_frame_ptr, AVPacket *avpkt)
1360 AVFrame *frame = data;
1361 const uint8_t *buf = avpkt->data;
1362 int buf_size = avpkt->size;
1365 int num_core_channels = 0;
1367 float **samples_flt;
1368 DCAContext *s = avctx->priv_data;
1369 int channels, full_channels;
1372 s->exss_ext_mask = 0;
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;
1382 if ((ret = dca_parse_frame_header(s)) < 0) {
1383 // seems like the frame is corrupt, try with the next one
1386 // set AVCodec values with parsed data
1387 avctx->sample_rate = s->sample_rate;
1388 avctx->bit_rate = s->bit_rate;
1390 s->profile = FF_PROFILE_DTS;
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");
1399 /* record number of core channels incase less than max channels are requested */
1400 num_core_channels = s->audio_header.prim_channels;
1403 s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];
1405 s->core_ext_mask = 0;
1407 ret = scan_for_extensions(avctx);
1409 avctx->profile = s->profile;
1411 full_channels = channels = s->audio_header.prim_channels + !!s->lfe;
1413 ret = set_channel_layout(avctx, channels, num_core_channels);
1416 avctx->channels = channels;
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;
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");
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;
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;
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;
1457 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1458 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1461 samples_flt = (float **) frame->extended_data;
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,
1467 avctx->sample_fmt, 0);
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);
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);
1484 /* filter to get final output */
1485 for (i = 0; i < (s->sample_blocks / SAMPLES_PER_SUBBAND); i++) {
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;
1493 dca_filter_channels(s, i, upsample);
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);
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];
1511 if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
1512 ret = ff_dca_xll_decode_audio(s, frame);
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);
1531 * DCA initialization
1533 * @param avctx pointer to the AVCodecContext
1536 static av_cold int dca_decode_init(AVCodecContext *avctx)
1538 DCAContext *s = avctx->priv_data;
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);
1549 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1551 /* allow downmixing to stereo */
1552 if (avctx->channels > 2 &&
1553 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO)
1554 avctx->channels = 2;
1559 static av_cold int dca_decode_end(AVCodecContext *avctx)
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);
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 },
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 },
1584 static const AVClass dca_decoder_class = {
1585 .class_name = "DCA decoder",
1586 .item_name = av_default_item_name,
1588 .version = LIBAVUTIL_VERSION_INT,
1591 AVCodec ff_dca_decoder = {
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,