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 /** Bit allocation */
143 typedef struct BitAlloc {
144 int offset; ///< code values offset
145 int maxbits[8]; ///< max bits in VLC
146 int wrap; ///< wrap for get_vlc2()
147 VLC vlc[8]; ///< actual codes
150 static BitAlloc dca_bitalloc_index; ///< indexes for samples VLC select
151 static BitAlloc dca_tmode; ///< transition mode VLCs
152 static BitAlloc dca_scalefactor; ///< scalefactor VLCs
153 static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
155 static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba,
158 return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) +
162 static av_cold void dca_init_vlcs(void)
164 static int vlcs_initialized = 0;
166 static VLC_TYPE dca_table[23622][2];
168 if (vlcs_initialized)
171 dca_bitalloc_index.offset = 1;
172 dca_bitalloc_index.wrap = 2;
173 for (i = 0; i < 5; i++) {
174 dca_bitalloc_index.vlc[i].table = &dca_table[ff_dca_vlc_offs[i]];
175 dca_bitalloc_index.vlc[i].table_allocated = ff_dca_vlc_offs[i + 1] - ff_dca_vlc_offs[i];
176 init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
177 bitalloc_12_bits[i], 1, 1,
178 bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
180 dca_scalefactor.offset = -64;
181 dca_scalefactor.wrap = 2;
182 for (i = 0; i < 5; i++) {
183 dca_scalefactor.vlc[i].table = &dca_table[ff_dca_vlc_offs[i + 5]];
184 dca_scalefactor.vlc[i].table_allocated = ff_dca_vlc_offs[i + 6] - ff_dca_vlc_offs[i + 5];
185 init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
186 scales_bits[i], 1, 1,
187 scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
189 dca_tmode.offset = 0;
191 for (i = 0; i < 4; i++) {
192 dca_tmode.vlc[i].table = &dca_table[ff_dca_vlc_offs[i + 10]];
193 dca_tmode.vlc[i].table_allocated = ff_dca_vlc_offs[i + 11] - ff_dca_vlc_offs[i + 10];
194 init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
196 tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
199 for (i = 0; i < 10; i++)
200 for (j = 0; j < 7; j++) {
201 if (!bitalloc_codes[i][j])
203 dca_smpl_bitalloc[i + 1].offset = bitalloc_offsets[i];
204 dca_smpl_bitalloc[i + 1].wrap = 1 + (j > 4);
205 dca_smpl_bitalloc[i + 1].vlc[j].table = &dca_table[ff_dca_vlc_offs[c]];
206 dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = ff_dca_vlc_offs[c + 1] - ff_dca_vlc_offs[c];
208 init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
210 bitalloc_bits[i][j], 1, 1,
211 bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
214 vlcs_initialized = 1;
217 static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
220 *dst++ = get_bits(gb, bits);
223 static int dca_parse_audio_coding_header(DCAContext *s, int base_channel)
226 static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
227 static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
228 static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
230 s->total_channels = get_bits(&s->gb, 3) + 1 + base_channel;
231 s->prim_channels = s->total_channels;
233 if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
234 s->prim_channels = DCA_PRIM_CHANNELS_MAX;
236 for (i = base_channel; i < s->prim_channels; i++) {
237 s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
238 if (s->subband_activity[i] > DCA_SUBBANDS)
239 s->subband_activity[i] = DCA_SUBBANDS;
241 for (i = base_channel; i < s->prim_channels; i++) {
242 s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
243 if (s->vq_start_subband[i] > DCA_SUBBANDS)
244 s->vq_start_subband[i] = DCA_SUBBANDS;
246 get_array(&s->gb, s->joint_intensity + base_channel, s->prim_channels - base_channel, 3);
247 get_array(&s->gb, s->transient_huffman + base_channel, s->prim_channels - base_channel, 2);
248 get_array(&s->gb, s->scalefactor_huffman + base_channel, s->prim_channels - base_channel, 3);
249 get_array(&s->gb, s->bitalloc_huffman + base_channel, s->prim_channels - base_channel, 3);
251 /* Get codebooks quantization indexes */
253 memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
254 for (j = 1; j < 11; j++)
255 for (i = base_channel; i < s->prim_channels; i++)
256 s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
258 /* Get scale factor adjustment */
259 for (j = 0; j < 11; j++)
260 for (i = base_channel; i < s->prim_channels; i++)
261 s->scalefactor_adj[i][j] = 1;
263 for (j = 1; j < 11; j++)
264 for (i = base_channel; i < s->prim_channels; i++)
265 if (s->quant_index_huffman[i][j] < thr[j])
266 s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
268 if (s->crc_present) {
269 /* Audio header CRC check */
270 get_bits(&s->gb, 16);
273 s->current_subframe = 0;
274 s->current_subsubframe = 0;
279 static int dca_parse_frame_header(DCAContext *s)
281 init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
284 skip_bits_long(&s->gb, 32);
287 s->frame_type = get_bits(&s->gb, 1);
288 s->samples_deficit = get_bits(&s->gb, 5) + 1;
289 s->crc_present = get_bits(&s->gb, 1);
290 s->sample_blocks = get_bits(&s->gb, 7) + 1;
291 s->frame_size = get_bits(&s->gb, 14) + 1;
292 if (s->frame_size < 95)
293 return AVERROR_INVALIDDATA;
294 s->amode = get_bits(&s->gb, 6);
295 s->sample_rate = avpriv_dca_sample_rates[get_bits(&s->gb, 4)];
297 return AVERROR_INVALIDDATA;
298 s->bit_rate_index = get_bits(&s->gb, 5);
299 s->bit_rate = ff_dca_bit_rates[s->bit_rate_index];
301 return AVERROR_INVALIDDATA;
303 skip_bits1(&s->gb); // always 0 (reserved, cf. ETSI TS 102 114 V1.4.1)
304 s->dynrange = get_bits(&s->gb, 1);
305 s->timestamp = get_bits(&s->gb, 1);
306 s->aux_data = get_bits(&s->gb, 1);
307 s->hdcd = get_bits(&s->gb, 1);
308 s->ext_descr = get_bits(&s->gb, 3);
309 s->ext_coding = get_bits(&s->gb, 1);
310 s->aspf = get_bits(&s->gb, 1);
311 s->lfe = get_bits(&s->gb, 2);
312 s->predictor_history = get_bits(&s->gb, 1);
315 av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE value: %d\n", s->lfe);
316 return AVERROR_INVALIDDATA;
319 /* TODO: check CRC */
321 s->header_crc = get_bits(&s->gb, 16);
323 s->multirate_inter = get_bits(&s->gb, 1);
324 s->version = get_bits(&s->gb, 4);
325 s->copy_history = get_bits(&s->gb, 2);
326 s->source_pcm_res = get_bits(&s->gb, 3);
327 s->front_sum = get_bits(&s->gb, 1);
328 s->surround_sum = get_bits(&s->gb, 1);
329 s->dialog_norm = get_bits(&s->gb, 4);
331 /* FIXME: channels mixing levels */
332 s->output = s->amode;
334 s->output |= DCA_LFE;
336 /* Primary audio coding header */
337 s->subframes = get_bits(&s->gb, 4) + 1;
339 return dca_parse_audio_coding_header(s, 0);
342 static inline int get_scale(GetBitContext *gb, int level, int value, int log2range)
345 /* huffman encoded */
346 value += get_bitalloc(gb, &dca_scalefactor, level);
347 value = av_clip(value, 0, (1 << log2range) - 1);
348 } else if (level < 8) {
349 if (level + 1 > log2range) {
350 skip_bits(gb, level + 1 - log2range);
351 value = get_bits(gb, log2range);
353 value = get_bits(gb, level + 1);
359 static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)
361 /* Primary audio coding side information */
364 if (get_bits_left(&s->gb) < 0)
365 return AVERROR_INVALIDDATA;
368 s->subsubframes[s->current_subframe] = get_bits(&s->gb, 2) + 1;
369 s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
372 for (j = base_channel; j < s->prim_channels; j++) {
373 for (k = 0; k < s->subband_activity[j]; k++)
374 s->prediction_mode[j][k] = get_bits(&s->gb, 1);
377 /* Get prediction codebook */
378 for (j = base_channel; j < s->prim_channels; j++) {
379 for (k = 0; k < s->subband_activity[j]; k++) {
380 if (s->prediction_mode[j][k] > 0) {
381 /* (Prediction coefficient VQ address) */
382 s->prediction_vq[j][k] = get_bits(&s->gb, 12);
387 /* Bit allocation index */
388 for (j = base_channel; j < s->prim_channels; j++) {
389 for (k = 0; k < s->vq_start_subband[j]; k++) {
390 if (s->bitalloc_huffman[j] == 6)
391 s->bitalloc[j][k] = get_bits(&s->gb, 5);
392 else if (s->bitalloc_huffman[j] == 5)
393 s->bitalloc[j][k] = get_bits(&s->gb, 4);
394 else if (s->bitalloc_huffman[j] == 7) {
395 av_log(s->avctx, AV_LOG_ERROR,
396 "Invalid bit allocation index\n");
397 return AVERROR_INVALIDDATA;
400 get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
403 if (s->bitalloc[j][k] > 26) {
404 ff_dlog(s->avctx, "bitalloc index [%i][%i] too big (%i)\n",
405 j, k, s->bitalloc[j][k]);
406 return AVERROR_INVALIDDATA;
411 /* Transition mode */
412 for (j = base_channel; j < s->prim_channels; j++) {
413 for (k = 0; k < s->subband_activity[j]; k++) {
414 s->transition_mode[j][k] = 0;
415 if (s->subsubframes[s->current_subframe] > 1 &&
416 k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
417 s->transition_mode[j][k] =
418 get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
423 if (get_bits_left(&s->gb) < 0)
424 return AVERROR_INVALIDDATA;
426 for (j = base_channel; j < s->prim_channels; j++) {
427 const uint32_t *scale_table;
428 int scale_sum, log_size;
430 memset(s->scale_factor[j], 0,
431 s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
433 if (s->scalefactor_huffman[j] == 6) {
434 scale_table = ff_dca_scale_factor_quant7;
437 scale_table = ff_dca_scale_factor_quant6;
441 /* When huffman coded, only the difference is encoded */
444 for (k = 0; k < s->subband_activity[j]; k++) {
445 if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
446 scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);
447 s->scale_factor[j][k][0] = scale_table[scale_sum];
450 if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
451 /* Get second scale factor */
452 scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);
453 s->scale_factor[j][k][1] = scale_table[scale_sum];
458 /* Joint subband scale factor codebook select */
459 for (j = base_channel; j < s->prim_channels; j++) {
460 /* Transmitted only if joint subband coding enabled */
461 if (s->joint_intensity[j] > 0)
462 s->joint_huff[j] = get_bits(&s->gb, 3);
465 if (get_bits_left(&s->gb) < 0)
466 return AVERROR_INVALIDDATA;
468 /* Scale factors for joint subband coding */
469 for (j = base_channel; j < s->prim_channels; j++) {
472 /* Transmitted only if joint subband coding enabled */
473 if (s->joint_intensity[j] > 0) {
475 source_channel = s->joint_intensity[j] - 1;
477 /* When huffman coded, only the difference is encoded
478 * (is this valid as well for joint scales ???) */
480 for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
481 scale = get_scale(&s->gb, s->joint_huff[j], 64 /* bias */, 7);
482 s->joint_scale_factor[j][k] = scale; /*joint_scale_table[scale]; */
485 if (!(s->debug_flag & 0x02)) {
486 av_log(s->avctx, AV_LOG_DEBUG,
487 "Joint stereo coding not supported\n");
488 s->debug_flag |= 0x02;
493 /* Dynamic range coefficient */
494 if (!base_channel && s->dynrange)
495 s->dynrange_coef = get_bits(&s->gb, 8);
497 /* Side information CRC check word */
498 if (s->crc_present) {
499 get_bits(&s->gb, 16);
503 * Primary audio data arrays
506 /* VQ encoded high frequency subbands */
507 for (j = base_channel; j < s->prim_channels; j++)
508 for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
509 /* 1 vector -> 32 samples */
510 s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
512 /* Low frequency effect data */
513 if (!base_channel && s->lfe) {
515 int lfe_samples = 2 * s->lfe * (4 + block_index);
516 int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
519 for (j = lfe_samples; j < lfe_end_sample; j++) {
520 /* Signed 8 bits int */
521 s->lfe_data[j] = get_sbits(&s->gb, 8);
524 /* Scale factor index */
525 skip_bits(&s->gb, 1);
526 s->lfe_scale_factor = ff_dca_scale_factor_quant7[get_bits(&s->gb, 7)];
528 /* Quantization step size * scale factor */
529 lfe_scale = 0.035 * s->lfe_scale_factor;
531 for (j = lfe_samples; j < lfe_end_sample; j++)
532 s->lfe_data[j] *= lfe_scale;
538 static void qmf_32_subbands(DCAContext *s, int chans,
539 float samples_in[32][8], float *samples_out,
542 const float *prCoeff;
544 int sb_act = s->subband_activity[chans];
546 scale *= sqrt(1 / 8.0);
549 if (!s->multirate_inter) /* Non-perfect reconstruction */
550 prCoeff = ff_dca_fir_32bands_nonperfect;
551 else /* Perfect reconstruction */
552 prCoeff = ff_dca_fir_32bands_perfect;
554 s->dcadsp.qmf_32_subbands(samples_in, sb_act, &s->synth, &s->imdct,
555 s->subband_fir_hist[chans],
556 &s->hist_index[chans],
557 s->subband_fir_noidea[chans], prCoeff,
558 samples_out, s->raXin, scale);
561 static QMF64_table *qmf64_precompute(void)
564 QMF64_table *table = av_malloc(sizeof(*table));
568 for (i = 0; i < 32; i++)
569 for (j = 0; j < 32; j++)
570 table->dct4_coeff[i][j] = cos((2 * i + 1) * (2 * j + 1) * M_PI / 128);
571 for (i = 0; i < 32; i++)
572 for (j = 0; j < 32; j++)
573 table->dct2_coeff[i][j] = cos((2 * i + 1) * j * M_PI / 64);
575 /* FIXME: Is the factor 0.125 = 1/8 right? */
576 for (i = 0; i < 32; i++)
577 table->rcos[i] = 0.125 / cos((2 * i + 1) * M_PI / 256);
578 for (i = 0; i < 32; i++)
579 table->rsin[i] = -0.125 / sin((2 * i + 1) * M_PI / 256);
584 /* FIXME: Totally unoptimized. Based on the reference code and
585 * http://multimedia.cx/mirror/dca-transform.pdf, with guessed tweaks
586 * for doubling the size. */
587 static void qmf_64_subbands(DCAContext *s, int chans, float samples_in[64][8],
588 float *samples_out, float scale)
592 float *raX = s->subband_fir_hist[chans];
593 float *raZ = s->subband_fir_noidea[chans];
594 unsigned i, j, k, subindex;
596 for (i = s->subband_activity[chans]; i < 64; i++)
598 for (subindex = 0; subindex < 8; subindex++) {
599 for (i = 0; i < s->subband_activity[chans]; i++)
600 raXin[i] = samples_in[i][subindex];
602 for (k = 0; k < 32; k++) {
604 for (i = 0; i < 32; i++)
605 A[k] += (raXin[2 * i] + raXin[2 * i + 1]) * s->qmf64_table->dct4_coeff[k][i];
607 for (k = 0; k < 32; k++) {
608 B[k] = raXin[0] * s->qmf64_table->dct2_coeff[k][0];
609 for (i = 1; i < 32; i++)
610 B[k] += (raXin[2 * i] + raXin[2 * i - 1]) * s->qmf64_table->dct2_coeff[k][i];
612 for (k = 0; k < 32; k++) {
613 raX[k] = s->qmf64_table->rcos[k] * (A[k] + B[k]);
614 raX[63 - k] = s->qmf64_table->rsin[k] * (A[k] - B[k]);
617 for (i = 0; i < 64; i++) {
619 for (j = 0; j < 1024; j += 128)
620 out += ff_dca_fir_64bands[j + i] * (raX[j + i] - raX[j + 63 - i]);
621 *samples_out++ = out * scale;
624 for (i = 0; i < 64; i++) {
626 for (j = 0; j < 1024; j += 128)
627 hist += ff_dca_fir_64bands[64 + j + i] * (-raX[i + j] - raX[j + 63 - i]);
632 /* FIXME: Make buffer circular, to avoid this move. */
633 memmove(raX + 64, raX, (1024 - 64) * sizeof(*raX));
637 static void lfe_interpolation_fir(DCAContext *s, const float *samples_in,
640 /* samples_in: An array holding decimated samples.
641 * Samples in current subframe starts from samples_in[0],
642 * while samples_in[-1], samples_in[-2], ..., stores samples
643 * from last subframe as history.
645 * samples_out: An array holding interpolated samples
649 const float *prCoeff;
652 /* Select decimation filter */
655 prCoeff = ff_dca_lfe_fir_128;
658 if (s->exss_ext_mask & DCA_EXT_EXSS_XLL)
659 prCoeff = ff_dca_lfe_xll_fir_64;
661 prCoeff = ff_dca_lfe_fir_64;
664 for (deciindex = 0; deciindex < 2 * s->lfe; deciindex++) {
665 s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
667 samples_out += 2 * 32 * (1 + idx);
671 /* downmixing routines */
672 #define MIX_REAR1(samples, s1, rs, coef) \
673 samples[0][i] += samples[s1][i] * coef[rs][0]; \
674 samples[1][i] += samples[s1][i] * coef[rs][1];
676 #define MIX_REAR2(samples, s1, s2, rs, coef) \
677 samples[0][i] += samples[s1][i] * coef[rs][0] + samples[s2][i] * coef[rs + 1][0]; \
678 samples[1][i] += samples[s1][i] * coef[rs][1] + samples[s2][i] * coef[rs + 1][1];
680 #define MIX_FRONT3(samples, coef) \
684 samples[0][i] = t * coef[0][0] + u * coef[1][0] + v * coef[2][0]; \
685 samples[1][i] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
687 #define DOWNMIX_TO_STEREO(op1, op2) \
688 for (i = 0; i < 256; i++) { \
693 static void dca_downmix(float **samples, int srcfmt, int lfe_present,
694 float coef[DCA_PRIM_CHANNELS_MAX + 1][2],
695 const int8_t *channel_mapping)
697 int c, l, r, sl, sr, s;
704 av_log(NULL, 0, "Not implemented!\n");
708 case DCA_STEREO_TOTAL:
709 case DCA_STEREO_SUMDIFF:
712 c = channel_mapping[0];
713 l = channel_mapping[1];
714 r = channel_mapping[2];
715 DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
718 s = channel_mapping[2];
719 DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );
722 c = channel_mapping[0];
723 l = channel_mapping[1];
724 r = channel_mapping[2];
725 s = channel_mapping[3];
726 DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
727 MIX_REAR1(samples, s, 3, coef));
730 sl = channel_mapping[2];
731 sr = channel_mapping[3];
732 DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );
735 c = channel_mapping[0];
736 l = channel_mapping[1];
737 r = channel_mapping[2];
738 sl = channel_mapping[3];
739 sr = channel_mapping[4];
740 DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
741 MIX_REAR2(samples, sl, sr, 3, coef));
745 int lf_buf = ff_dca_lfe_index[srcfmt];
746 int lf_idx = ff_dca_channels[srcfmt];
747 for (i = 0; i < 256; i++) {
748 samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];
749 samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];
754 #ifndef decode_blockcodes
755 /* Very compact version of the block code decoder that does not use table
756 * look-up but is slightly slower */
757 static int decode_blockcode(int code, int levels, int32_t *values)
760 int offset = (levels - 1) >> 1;
762 for (i = 0; i < 4; i++) {
763 int div = FASTDIV(code, levels);
764 values[i] = code - offset - div * levels;
771 static int decode_blockcodes(int code1, int code2, int levels, int32_t *values)
773 return decode_blockcode(code1, levels, values) |
774 decode_blockcode(code2, levels, values + 4);
778 static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
779 static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
781 static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
784 int subsubframe = s->current_subsubframe;
786 const float *quant_step_table;
789 float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
790 LOCAL_ALIGNED_16(int32_t, block, [8 * DCA_SUBBANDS]);
796 /* Select quantization step size table */
797 if (s->bit_rate_index == 0x1f)
798 quant_step_table = ff_dca_lossless_quant_d;
800 quant_step_table = ff_dca_lossy_quant_d;
802 for (k = base_channel; k < s->prim_channels; k++) {
803 float rscale[DCA_SUBBANDS];
805 if (get_bits_left(&s->gb) < 0)
806 return AVERROR_INVALIDDATA;
808 for (l = 0; l < s->vq_start_subband[k]; l++) {
811 /* Select the mid-tread linear quantizer */
812 int abits = s->bitalloc[k][l];
814 float quant_step_size = quant_step_table[abits];
817 * Determine quantization index code book and its type
820 /* Select quantization index code book */
821 int sel = s->quant_index_huffman[k][abits];
824 * Extract bits from the bit stream
828 memset(block + 8 * l, 0, 8 * sizeof(block[0]));
830 /* Deal with transients */
831 int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];
832 rscale[l] = quant_step_size * s->scale_factor[k][l][sfi] *
833 s->scalefactor_adj[k][sel];
835 if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
838 int block_code1, block_code2, size, levels, err;
840 size = abits_sizes[abits - 1];
841 levels = abits_levels[abits - 1];
843 block_code1 = get_bits(&s->gb, size);
844 block_code2 = get_bits(&s->gb, size);
845 err = decode_blockcodes(block_code1, block_code2,
846 levels, block + 8 * l);
848 av_log(s->avctx, AV_LOG_ERROR,
849 "ERROR: block code look-up failed\n");
850 return AVERROR_INVALIDDATA;
854 for (m = 0; m < 8; m++)
855 block[8 * l + m] = get_sbits(&s->gb, abits - 3);
859 for (m = 0; m < 8; m++)
860 block[8 * l + m] = get_bitalloc(&s->gb,
861 &dca_smpl_bitalloc[abits], sel);
866 s->fmt_conv.int32_to_float_fmul_array8(&s->fmt_conv, subband_samples[k][0],
867 block, rscale, 8 * s->vq_start_subband[k]);
869 for (l = 0; l < s->vq_start_subband[k]; l++) {
872 * Inverse ADPCM if in prediction mode
874 if (s->prediction_mode[k][l]) {
876 if (s->predictor_history)
877 subband_samples[k][l][0] += (ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
878 s->subband_samples_hist[k][l][3] +
879 ff_dca_adpcm_vb[s->prediction_vq[k][l]][1] *
880 s->subband_samples_hist[k][l][2] +
881 ff_dca_adpcm_vb[s->prediction_vq[k][l]][2] *
882 s->subband_samples_hist[k][l][1] +
883 ff_dca_adpcm_vb[s->prediction_vq[k][l]][3] *
884 s->subband_samples_hist[k][l][0]) *
886 for (m = 1; m < 8; m++) {
887 float sum = ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
888 subband_samples[k][l][m - 1];
889 for (n = 2; n <= 4; n++)
891 sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
892 subband_samples[k][l][m - n];
893 else if (s->predictor_history)
894 sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
895 s->subband_samples_hist[k][l][m - n + 4];
896 subband_samples[k][l][m] += sum * 1.0f / 8192;
902 * Decode VQ encoded high frequencies
904 if (s->subband_activity[k] > s->vq_start_subband[k]) {
905 if (!s->debug_flag & 0x01) {
906 av_log(s->avctx, AV_LOG_DEBUG,
907 "Stream with high frequencies VQ coding\n");
908 s->debug_flag |= 0x01;
910 s->dcadsp.decode_hf(subband_samples[k], s->high_freq_vq[k],
911 ff_dca_high_freq_vq, subsubframe * 8,
912 s->scale_factor[k], s->vq_start_subband[k],
913 s->subband_activity[k]);
917 /* Check for DSYNC after subsubframe */
918 if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
919 if (get_bits(&s->gb, 16) != 0xFFFF) {
920 av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
921 return AVERROR_INVALIDDATA;
925 /* Backup predictor history for adpcm */
926 for (k = base_channel; k < s->prim_channels; k++)
927 for (l = 0; l < s->vq_start_subband[k]; l++)
928 AV_COPY128(s->subband_samples_hist[k][l], &subband_samples[k][l][4]);
933 static int dca_filter_channels(DCAContext *s, int block_index, int upsample)
935 float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
939 if (!s->qmf64_table) {
940 s->qmf64_table = qmf64_precompute();
942 return AVERROR(ENOMEM);
945 /* 64 subbands QMF */
946 for (k = 0; k < s->prim_channels; k++) {
947 if (s->channel_order_tab[k] >= 0)
948 qmf_64_subbands(s, k, subband_samples[k],
949 s->samples_chanptr[s->channel_order_tab[k]],
950 /* Upsampling needs a factor 2 here. */
954 /* 32 subbands QMF */
955 for (k = 0; k < s->prim_channels; k++) {
956 if (s->channel_order_tab[k] >= 0)
957 qmf_32_subbands(s, k, subband_samples[k],
958 s->samples_chanptr[s->channel_order_tab[k]],
959 M_SQRT1_2 / 32768.0);
963 /* Generate LFE samples for this subsubframe FIXME!!! */
965 float *samples = s->samples_chanptr[ff_dca_lfe_index[s->amode]];
966 lfe_interpolation_fir(s,
967 s->lfe_data + 2 * s->lfe * (block_index + 4),
971 /* Should apply the filter in Table 6-11 when upsampling. For
972 * now, just duplicate. */
973 for (i = 511; i > 0; i--) {
975 samples[2 * i + 1] = samples[i];
977 samples[1] = samples[0];
981 /* FIXME: This downmixing is probably broken with upsample.
982 * Probably totally broken also with XLL in general. */
983 /* Downmixing to Stereo */
984 if (s->prim_channels + !!s->lfe > 2 &&
985 s->avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
986 dca_downmix(s->samples_chanptr, s->amode, !!s->lfe, s->downmix_coef,
987 s->channel_order_tab);
993 static int dca_subframe_footer(DCAContext *s, int base_channel)
995 int in, out, aux_data_count, aux_data_end, reserved;
999 * Unpack optional information
1002 /* presumably optional information only appears in the core? */
1003 if (!base_channel) {
1005 skip_bits_long(&s->gb, 32);
1008 aux_data_count = get_bits(&s->gb, 6);
1011 skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1013 aux_data_end = 8 * aux_data_count + get_bits_count(&s->gb);
1015 if ((nsyncaux = get_bits_long(&s->gb, 32)) != DCA_NSYNCAUX) {
1016 av_log(s->avctx, AV_LOG_ERROR, "nSYNCAUX mismatch %#"PRIx32"\n",
1018 return AVERROR_INVALIDDATA;
1021 if (get_bits1(&s->gb)) { // bAUXTimeStampFlag
1022 avpriv_request_sample(s->avctx,
1023 "Auxiliary Decode Time Stamp Flag");
1025 skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 4);
1026 // 44 bits: nMSByte (8), nMarker (4), nLSByte (28), nMarker (4)
1027 skip_bits_long(&s->gb, 44);
1030 if ((s->core_downmix = get_bits1(&s->gb))) {
1031 int am = get_bits(&s->gb, 3);
1034 s->core_downmix_amode = DCA_MONO;
1037 s->core_downmix_amode = DCA_STEREO;
1040 s->core_downmix_amode = DCA_STEREO_TOTAL;
1043 s->core_downmix_amode = DCA_3F;
1046 s->core_downmix_amode = DCA_2F1R;
1049 s->core_downmix_amode = DCA_2F2R;
1052 s->core_downmix_amode = DCA_3F1R;
1055 av_log(s->avctx, AV_LOG_ERROR,
1056 "Invalid mode %d for embedded downmix coefficients\n",
1058 return AVERROR_INVALIDDATA;
1060 for (out = 0; out < ff_dca_channels[s->core_downmix_amode]; out++) {
1061 for (in = 0; in < s->prim_channels + !!s->lfe; in++) {
1062 uint16_t tmp = get_bits(&s->gb, 9);
1063 if ((tmp & 0xFF) > 241) {
1064 av_log(s->avctx, AV_LOG_ERROR,
1065 "Invalid downmix coefficient code %"PRIu16"\n",
1067 return AVERROR_INVALIDDATA;
1069 s->core_downmix_codes[in][out] = tmp;
1074 align_get_bits(&s->gb); // byte align
1075 skip_bits(&s->gb, 16); // nAUXCRC16
1077 // additional data (reserved, cf. ETSI TS 102 114 V1.4.1)
1078 if ((reserved = (aux_data_end - get_bits_count(&s->gb))) < 0) {
1079 av_log(s->avctx, AV_LOG_ERROR,
1080 "Overread auxiliary data by %d bits\n", -reserved);
1081 return AVERROR_INVALIDDATA;
1082 } else if (reserved) {
1083 avpriv_request_sample(s->avctx,
1084 "Core auxiliary data reserved content");
1085 skip_bits_long(&s->gb, reserved);
1089 if (s->crc_present && s->dynrange)
1090 get_bits(&s->gb, 16);
1097 * Decode a dca frame block
1099 * @param s pointer to the DCAContext
1102 static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
1107 if (s->current_subframe >= s->subframes) {
1108 av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1109 s->current_subframe, s->subframes);
1110 return AVERROR_INVALIDDATA;
1113 if (!s->current_subsubframe) {
1114 /* Read subframe header */
1115 if ((ret = dca_subframe_header(s, base_channel, block_index)))
1119 /* Read subsubframe */
1120 if ((ret = dca_subsubframe(s, base_channel, block_index)))
1124 s->current_subsubframe++;
1125 if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
1126 s->current_subsubframe = 0;
1127 s->current_subframe++;
1129 if (s->current_subframe >= s->subframes) {
1130 /* Read subframe footer */
1131 if ((ret = dca_subframe_footer(s, base_channel)))
1138 static float dca_dmix_code(unsigned code)
1140 int sign = (code >> 8) - 1;
1142 return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1U << 15));
1146 * Main frame decoding function
1147 * FIXME add arguments
1149 static int dca_decode_frame(AVCodecContext *avctx, void *data,
1150 int *got_frame_ptr, AVPacket *avpkt)
1152 AVFrame *frame = data;
1153 const uint8_t *buf = avpkt->data;
1154 int buf_size = avpkt->size;
1157 int num_core_channels = 0;
1159 float **samples_flt;
1160 DCAContext *s = avctx->priv_data;
1161 int channels, full_channels;
1165 s->exss_ext_mask = 0;
1168 s->dca_buffer_size = ff_dca_convert_bitstream(buf, buf_size, s->dca_buffer,
1169 DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);
1170 if (s->dca_buffer_size == AVERROR_INVALIDDATA) {
1171 av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1172 return AVERROR_INVALIDDATA;
1175 if ((ret = dca_parse_frame_header(s)) < 0) {
1176 // seems like the frame is corrupt, try with the next one
1179 // set AVCodec values with parsed data
1180 avctx->sample_rate = s->sample_rate;
1181 avctx->bit_rate = s->bit_rate;
1183 s->profile = FF_PROFILE_DTS;
1185 for (i = 0; i < (s->sample_blocks / 8); i++) {
1186 if ((ret = dca_decode_block(s, 0, i))) {
1187 av_log(avctx, AV_LOG_ERROR, "error decoding block\n");
1192 /* record number of core channels incase less than max channels are requested */
1193 num_core_channels = s->prim_channels;
1196 s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];
1198 s->core_ext_mask = 0;
1200 core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
1202 /* only scan for extensions if ext_descr was unknown or indicated a
1203 * supported XCh extension */
1204 if (s->core_ext_mask < 0 || s->core_ext_mask & DCA_EXT_XCH) {
1205 /* if ext_descr was unknown, clear s->core_ext_mask so that the
1206 * extensions scan can fill it up */
1207 s->core_ext_mask = FFMAX(s->core_ext_mask, 0);
1209 /* extensions start at 32-bit boundaries into bitstream */
1210 skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1212 while (core_ss_end - get_bits_count(&s->gb) >= 32) {
1213 uint32_t bits = get_bits_long(&s->gb, 32);
1216 case DCA_SYNCWORD_XCH: {
1217 int ext_amode, xch_fsize;
1219 s->xch_base_channel = s->prim_channels;
1221 /* validate sync word using XCHFSIZE field */
1222 xch_fsize = show_bits(&s->gb, 10);
1223 if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
1224 (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
1227 /* skip length-to-end-of-frame field for the moment */
1228 skip_bits(&s->gb, 10);
1230 s->core_ext_mask |= DCA_EXT_XCH;
1232 /* extension amode(number of channels in extension) should be 1 */
1233 /* AFAIK XCh is not used for more channels */
1234 if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
1235 av_log(avctx, AV_LOG_ERROR,
1236 "XCh extension amode %d not supported!\n",
1241 /* much like core primary audio coding header */
1242 dca_parse_audio_coding_header(s, s->xch_base_channel);
1244 for (i = 0; i < (s->sample_blocks / 8); i++)
1245 if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
1246 av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
1253 case DCA_SYNCWORD_XXCH:
1254 /* XXCh: extended channels */
1255 /* usually found either in core or HD part in DTS-HD HRA streams,
1256 * but not in DTS-ES which contains XCh extensions instead */
1257 s->core_ext_mask |= DCA_EXT_XXCH;
1261 int fsize96 = show_bits(&s->gb, 12) + 1;
1262 if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
1265 av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",
1266 get_bits_count(&s->gb));
1267 skip_bits(&s->gb, 12);
1268 av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
1269 av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
1271 s->core_ext_mask |= DCA_EXT_X96;
1276 skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1279 /* no supported extensions, skip the rest of the core substream */
1280 skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
1283 if (s->core_ext_mask & DCA_EXT_X96)
1284 s->profile = FF_PROFILE_DTS_96_24;
1285 else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))
1286 s->profile = FF_PROFILE_DTS_ES;
1288 /* check for ExSS (HD part) */
1289 if (s->dca_buffer_size - s->frame_size > 32 &&
1290 get_bits_long(&s->gb, 32) == DCA_SYNCWORD_SUBSTREAM)
1291 ff_dca_exss_parse_header(s);
1293 avctx->profile = s->profile;
1295 full_channels = channels = s->prim_channels + !!s->lfe;
1297 if (s->amode < 16) {
1298 avctx->channel_layout = dca_core_channel_layout[s->amode];
1300 if (s->prim_channels + !!s->lfe > 2 &&
1301 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1303 * Neither the core's auxiliary data nor our default tables contain
1304 * downmix coefficients for the additional channel coded in the XCh
1305 * extension, so when we're doing a Stereo downmix, don't decode it.
1310 if (s->xch_present && !s->xch_disable) {
1311 avctx->channel_layout |= AV_CH_BACK_CENTER;
1313 avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1314 s->channel_order_tab = ff_dca_channel_reorder_lfe_xch[s->amode];
1316 s->channel_order_tab = ff_dca_channel_reorder_nolfe_xch[s->amode];
1319 channels = num_core_channels + !!s->lfe;
1320 s->xch_present = 0; /* disable further xch processing */
1322 avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1323 s->channel_order_tab = ff_dca_channel_reorder_lfe[s->amode];
1325 s->channel_order_tab = ff_dca_channel_reorder_nolfe[s->amode];
1328 if (channels > !!s->lfe &&
1329 s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
1330 return AVERROR_INVALIDDATA;
1332 if (num_core_channels + !!s->lfe > 2 &&
1333 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
1335 s->output = s->prim_channels == 2 ? s->amode : DCA_STEREO;
1336 avctx->channel_layout = AV_CH_LAYOUT_STEREO;
1338 /* Stereo downmix coefficients
1340 * The decoder can only downmix to 2-channel, so we need to ensure
1341 * embedded downmix coefficients are actually targeting 2-channel.
1343 if (s->core_downmix && (s->core_downmix_amode == DCA_STEREO ||
1344 s->core_downmix_amode == DCA_STEREO_TOTAL)) {
1345 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1346 /* Range checked earlier */
1347 s->downmix_coef[i][0] = dca_dmix_code(s->core_downmix_codes[i][0]);
1348 s->downmix_coef[i][1] = dca_dmix_code(s->core_downmix_codes[i][1]);
1350 s->output = s->core_downmix_amode;
1352 int am = s->amode & DCA_CHANNEL_MASK;
1353 if (am >= FF_ARRAY_ELEMS(ff_dca_default_coeffs)) {
1354 av_log(s->avctx, AV_LOG_ERROR,
1355 "Invalid channel mode %d\n", am);
1356 return AVERROR_INVALIDDATA;
1358 if (num_core_channels + !!s->lfe >
1359 FF_ARRAY_ELEMS(ff_dca_default_coeffs[0])) {
1360 avpriv_request_sample(s->avctx, "Downmixing %d channels",
1361 s->prim_channels + !!s->lfe);
1362 return AVERROR_PATCHWELCOME;
1364 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1365 s->downmix_coef[i][0] = ff_dca_default_coeffs[am][i][0];
1366 s->downmix_coef[i][1] = ff_dca_default_coeffs[am][i][1];
1369 ff_dlog(s->avctx, "Stereo downmix coeffs:\n");
1370 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1371 ff_dlog(s->avctx, "L, input channel %d = %f\n", i,
1372 s->downmix_coef[i][0]);
1373 ff_dlog(s->avctx, "R, input channel %d = %f\n", i,
1374 s->downmix_coef[i][1]);
1376 ff_dlog(s->avctx, "\n");
1379 av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n", s->amode);
1380 return AVERROR_INVALIDDATA;
1382 avctx->channels = channels;
1384 /* get output buffer */
1385 frame->nb_samples = 256 * (s->sample_blocks / 8);
1386 if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
1387 int xll_nb_samples = s->xll_segments * s->xll_smpl_in_seg;
1388 /* Check for invalid/unsupported conditions first */
1389 if (s->xll_residual_channels > channels) {
1390 av_log(s->avctx, AV_LOG_WARNING,
1391 "DCA: too many residual channels (%d, core channels %d). Disabling XLL\n",
1392 s->xll_residual_channels, channels);
1393 s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
1394 } else if (xll_nb_samples != frame->nb_samples &&
1395 2 * frame->nb_samples != xll_nb_samples) {
1396 av_log(s->avctx, AV_LOG_WARNING,
1397 "DCA: unsupported upsampling (%d XLL samples, %d core samples). Disabling XLL\n",
1398 xll_nb_samples, frame->nb_samples);
1399 s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
1401 if (2 * frame->nb_samples == xll_nb_samples) {
1402 av_log(s->avctx, AV_LOG_INFO,
1403 "XLL: upsampling core channels by a factor of 2\n");
1406 frame->nb_samples = xll_nb_samples;
1407 // FIXME: Is it good enough to copy from the first channel set?
1408 avctx->sample_rate = s->xll_chsets[0].sampling_frequency;
1410 /* If downmixing to stereo, don't decode additional channels.
1411 * FIXME: Using the xch_disable flag for this doesn't seem right. */
1412 if (!s->xch_disable)
1413 avctx->channels += s->xll_channels - s->xll_residual_channels;
1417 /* FIXME: This is an ugly hack, to just revert to the default
1418 * layout if we have additional channels. Need to convert the XLL
1419 * channel masks to libav channel_layout mask. */
1420 if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels)
1421 avctx->channel_layout = 0;
1423 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1424 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1427 samples_flt = (float **) frame->extended_data;
1429 /* allocate buffer for extra channels if downmixing */
1430 if (avctx->channels < full_channels) {
1431 ret = av_samples_get_buffer_size(NULL, full_channels - channels,
1433 avctx->sample_fmt, 0);
1437 av_fast_malloc(&s->extra_channels_buffer,
1438 &s->extra_channels_buffer_size, ret);
1439 if (!s->extra_channels_buffer)
1440 return AVERROR(ENOMEM);
1442 ret = av_samples_fill_arrays((uint8_t **) s->extra_channels, NULL,
1443 s->extra_channels_buffer,
1444 full_channels - channels,
1445 frame->nb_samples, avctx->sample_fmt, 0);
1450 /* filter to get final output */
1451 for (i = 0; i < (s->sample_blocks / 8); i++) {
1453 unsigned block = upsample ? 512 : 256;
1454 for (ch = 0; ch < channels; ch++)
1455 s->samples_chanptr[ch] = samples_flt[ch] + i * block;
1456 for (; ch < full_channels; ch++)
1457 s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * block;
1459 dca_filter_channels(s, i, upsample);
1461 /* If this was marked as a DTS-ES stream we need to subtract back- */
1462 /* channel from SL & SR to remove matrixed back-channel signal */
1463 if ((s->source_pcm_res & 1) && s->xch_present) {
1464 float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];
1465 float *lt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];
1466 float *rt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];
1467 s->fdsp.vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
1468 s->fdsp.vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
1472 /* update lfe history */
1473 lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);
1474 for (i = 0; i < 2 * s->lfe * 4; i++)
1475 s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1477 if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
1478 ret = ff_dca_xll_decode_audio(s, frame);
1484 * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */
1485 ret = ff_side_data_update_matrix_encoding(frame,
1486 (s->output & ~DCA_LFE) == DCA_STEREO_TOTAL ?
1487 AV_MATRIX_ENCODING_DOLBY : AV_MATRIX_ENCODING_NONE);
1497 * DCA initialization
1499 * @param avctx pointer to the AVCodecContext
1502 static av_cold int dca_decode_init(AVCodecContext *avctx)
1504 DCAContext *s = avctx->priv_data;
1509 avpriv_float_dsp_init(&s->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
1510 ff_mdct_init(&s->imdct, 6, 1, 1.0);
1511 ff_synth_filter_init(&s->synth);
1512 ff_dcadsp_init(&s->dcadsp);
1513 ff_fmt_convert_init(&s->fmt_conv, avctx);
1515 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1517 /* allow downmixing to stereo */
1518 if (avctx->channels > 2 &&
1519 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO)
1520 avctx->channels = 2;
1525 static av_cold int dca_decode_end(AVCodecContext *avctx)
1527 DCAContext *s = avctx->priv_data;
1528 ff_mdct_end(&s->imdct);
1529 av_freep(&s->extra_channels_buffer);
1530 av_freep(&s->xll_sample_buf);
1531 av_freep(&s->qmf64_table);
1535 static const AVProfile profiles[] = {
1536 { FF_PROFILE_DTS, "DTS" },
1537 { FF_PROFILE_DTS_ES, "DTS-ES" },
1538 { FF_PROFILE_DTS_96_24, "DTS 96/24" },
1539 { FF_PROFILE_DTS_HD_HRA, "DTS-HD HRA" },
1540 { FF_PROFILE_DTS_HD_MA, "DTS-HD MA" },
1541 { FF_PROFILE_UNKNOWN },
1544 static const AVOption options[] = {
1545 { "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 },
1546 { "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 },
1550 static const AVClass dca_decoder_class = {
1551 .class_name = "DCA decoder",
1552 .item_name = av_default_item_name,
1554 .version = LIBAVUTIL_VERSION_INT,
1557 AVCodec ff_dca_decoder = {
1559 .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1560 .type = AVMEDIA_TYPE_AUDIO,
1561 .id = AV_CODEC_ID_DTS,
1562 .priv_data_size = sizeof(DCAContext),
1563 .init = dca_decode_init,
1564 .decode = dca_decode_frame,
1565 .close = dca_decode_end,
1566 .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
1567 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1568 AV_SAMPLE_FMT_NONE },
1569 .profiles = NULL_IF_CONFIG_SMALL(profiles),
1570 .priv_class = &dca_decoder_class,