FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
dcadec.c
Go to the documentation of this file.
1 /*
2  * DCA compatible decoder
3  * Copyright (C) 2004 Gildas Bazin
4  * Copyright (C) 2004 Benjamin Zores
5  * Copyright (C) 2006 Benjamin Larsson
6  * Copyright (C) 2007 Konstantin Shishkov
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24 
25 #include <math.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 
30 #include "libavutil/common.h"
31 #include "libavutil/float_dsp.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/samplefmt.h"
37 
38 #include "avcodec.h"
39 #include "dca.h"
40 #include "dca_syncwords.h"
41 #include "dcadata.h"
42 #include "dcadsp.h"
43 #include "dcahuff.h"
44 #include "fft.h"
45 #include "fmtconvert.h"
46 #include "get_bits.h"
47 #include "internal.h"
48 #include "mathops.h"
49 #include "synth_filter.h"
50 
51 #if ARCH_ARM
52 # include "arm/dca.h"
53 #endif
54 
55 enum DCAMode {
56  DCA_MONO = 0,
67 };
68 
69 
71  DCA_XXCH_FRONT_CENTER = 0x0000001,
72  DCA_XXCH_FRONT_LEFT = 0x0000002,
73  DCA_XXCH_FRONT_RIGHT = 0x0000004,
76  DCA_XXCH_LFE1 = 0x0000020,
77  DCA_XXCH_REAR_CENTER = 0x0000040,
87  DCA_XXCH_LFE2 = 0x0010000,
90  DCA_XXCH_OVERHEAD = 0x0080000,
99 };
100 
101 #define DCA_DOLBY 101 /* FIXME */
102 
103 #define DCA_CHANNEL_BITS 6
104 #define DCA_CHANNEL_MASK 0x3F
105 
106 #define DCA_LFE 0x80
107 
108 #define HEADER_SIZE 14
109 
110 #define DCA_NSYNCAUX 0x9A1105A0
111 
112 
113 /** Bit allocation */
114 typedef struct BitAlloc {
115  int offset; ///< code values offset
116  int maxbits[8]; ///< max bits in VLC
117  int wrap; ///< wrap for get_vlc2()
118  VLC vlc[8]; ///< actual codes
119 } BitAlloc;
120 
121 static BitAlloc dca_bitalloc_index; ///< indexes for samples VLC select
122 static BitAlloc dca_tmode; ///< transition mode VLCs
123 static BitAlloc dca_scalefactor; ///< scalefactor VLCs
124 static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
125 
127  int idx)
128 {
129  return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) +
130  ba->offset;
131 }
132 
133 static float dca_dmix_code(unsigned code);
134 
135 static av_cold void dca_init_vlcs(void)
136 {
137  static int vlcs_initialized = 0;
138  int i, j, c = 14;
139  static VLC_TYPE dca_table[23622][2];
140 
141  if (vlcs_initialized)
142  return;
143 
144  dca_bitalloc_index.offset = 1;
145  dca_bitalloc_index.wrap = 2;
146  for (i = 0; i < 5; i++) {
147  dca_bitalloc_index.vlc[i].table = &dca_table[ff_dca_vlc_offs[i]];
148  dca_bitalloc_index.vlc[i].table_allocated = ff_dca_vlc_offs[i + 1] - ff_dca_vlc_offs[i];
149  init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
150  bitalloc_12_bits[i], 1, 1,
152  }
153  dca_scalefactor.offset = -64;
154  dca_scalefactor.wrap = 2;
155  for (i = 0; i < 5; i++) {
156  dca_scalefactor.vlc[i].table = &dca_table[ff_dca_vlc_offs[i + 5]];
157  dca_scalefactor.vlc[i].table_allocated = ff_dca_vlc_offs[i + 6] - ff_dca_vlc_offs[i + 5];
158  init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
159  scales_bits[i], 1, 1,
161  }
162  dca_tmode.offset = 0;
163  dca_tmode.wrap = 1;
164  for (i = 0; i < 4; i++) {
165  dca_tmode.vlc[i].table = &dca_table[ff_dca_vlc_offs[i + 10]];
166  dca_tmode.vlc[i].table_allocated = ff_dca_vlc_offs[i + 11] - ff_dca_vlc_offs[i + 10];
167  init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
168  tmode_bits[i], 1, 1,
170  }
171 
172  for (i = 0; i < 10; i++)
173  for (j = 0; j < 7; j++) {
174  if (!bitalloc_codes[i][j])
175  break;
176  dca_smpl_bitalloc[i + 1].offset = bitalloc_offsets[i];
177  dca_smpl_bitalloc[i + 1].wrap = 1 + (j > 4);
178  dca_smpl_bitalloc[i + 1].vlc[j].table = &dca_table[ff_dca_vlc_offs[c]];
179  dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = ff_dca_vlc_offs[c + 1] - ff_dca_vlc_offs[c];
180 
181  init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
182  bitalloc_sizes[i],
183  bitalloc_bits[i][j], 1, 1,
185  c++;
186  }
187  vlcs_initialized = 1;
188 }
189 
190 static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
191 {
192  while (len--)
193  *dst++ = get_bits(gb, bits);
194 }
195 
196 static inline int dca_xxch2index(DCAContext *s, int xxch_ch)
197 {
198  int i, base, mask;
199 
200  /* locate channel set containing the channel */
201  for (i = -1, base = 0, mask = (s->xxch_core_spkmask & ~DCA_XXCH_LFE1);
202  i <= s->xxch_chset && !(mask & xxch_ch); mask = s->xxch_spk_masks[++i])
203  base += av_popcount(mask);
204 
205  return base + av_popcount(mask & (xxch_ch - 1));
206 }
207 
208 static int dca_parse_audio_coding_header(DCAContext *s, int base_channel,
209  int xxch)
210 {
211  int i, j;
212  static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
213  static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
214  static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
215  int hdr_pos = 0, hdr_size = 0;
216  float scale_factor;
217  int this_chans, acc_mask;
218  int embedded_downmix;
219  int nchans, mask[8];
220  int coeff, ichan;
221 
222  /* xxch has arbitrary sized audio coding headers */
223  if (xxch) {
224  hdr_pos = get_bits_count(&s->gb);
225  hdr_size = get_bits(&s->gb, 7) + 1;
226  }
227 
228  nchans = get_bits(&s->gb, 3) + 1;
229  s->total_channels = nchans + base_channel;
231 
232  /* obtain speaker layout mask & downmix coefficients for XXCH */
233  if (xxch) {
234  acc_mask = s->xxch_core_spkmask;
235 
236  this_chans = get_bits(&s->gb, s->xxch_nbits_spk_mask - 6) << 6;
237  s->xxch_spk_masks[s->xxch_chset] = this_chans;
238  s->xxch_chset_nch[s->xxch_chset] = nchans;
239 
240  for (i = 0; i <= s->xxch_chset; i++)
241  acc_mask |= s->xxch_spk_masks[i];
242 
243  /* check for downmixing information */
244  if (get_bits1(&s->gb)) {
245  embedded_downmix = get_bits1(&s->gb);
246  coeff = get_bits(&s->gb, 6);
247 
248  if (coeff<1 || coeff>61) {
249  av_log(s->avctx, AV_LOG_ERROR, "6bit coeff %d is out of range\n", coeff);
250  return AVERROR_INVALIDDATA;
251  }
252 
253  scale_factor = -1.0f / dca_dmix_code((coeff<<2)-3);
254 
255  s->xxch_dmix_sf[s->xxch_chset] = scale_factor;
256 
257  for (i = base_channel; i < s->prim_channels; i++) {
258  mask[i] = get_bits(&s->gb, s->xxch_nbits_spk_mask);
259  }
260 
261  for (j = base_channel; j < s->prim_channels; j++) {
262  memset(s->xxch_dmix_coeff[j], 0, sizeof(s->xxch_dmix_coeff[0]));
263  s->xxch_dmix_embedded |= (embedded_downmix << j);
264  for (i = 0; i < s->xxch_nbits_spk_mask; i++) {
265  if (mask[j] & (1 << i)) {
266  if ((1 << i) == DCA_XXCH_LFE1) {
268  "DCA-XXCH: dmix to LFE1 not supported.\n");
269  continue;
270  }
271 
272  coeff = get_bits(&s->gb, 7);
273  ichan = dca_xxch2index(s, 1 << i);
274  if ((coeff&63)<1 || (coeff&63)>61) {
275  av_log(s->avctx, AV_LOG_ERROR, "7bit coeff %d is out of range\n", coeff);
276  return AVERROR_INVALIDDATA;
277  }
278  s->xxch_dmix_coeff[j][ichan] = dca_dmix_code((coeff<<2)-3);
279  }
280  }
281  }
282  }
283  }
284 
287 
288  for (i = base_channel; i < s->prim_channels; i++) {
289  s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
290  if (s->subband_activity[i] > DCA_SUBBANDS)
292  }
293  for (i = base_channel; i < s->prim_channels; i++) {
294  s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
295  if (s->vq_start_subband[i] > DCA_SUBBANDS)
297  }
298  get_array(&s->gb, s->joint_intensity + base_channel, s->prim_channels - base_channel, 3);
299  get_array(&s->gb, s->transient_huffman + base_channel, s->prim_channels - base_channel, 2);
300  get_array(&s->gb, s->scalefactor_huffman + base_channel, s->prim_channels - base_channel, 3);
301  get_array(&s->gb, s->bitalloc_huffman + base_channel, s->prim_channels - base_channel, 3);
302 
303  /* Get codebooks quantization indexes */
304  if (!base_channel)
305  memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
306  for (j = 1; j < 11; j++)
307  for (i = base_channel; i < s->prim_channels; i++)
308  s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
309 
310  /* Get scale factor adjustment */
311  for (j = 0; j < 11; j++)
312  for (i = base_channel; i < s->prim_channels; i++)
313  s->scalefactor_adj[i][j] = 1;
314 
315  for (j = 1; j < 11; j++)
316  for (i = base_channel; i < s->prim_channels; i++)
317  if (s->quant_index_huffman[i][j] < thr[j])
318  s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
319 
320  if (!xxch) {
321  if (s->crc_present) {
322  /* Audio header CRC check */
323  get_bits(&s->gb, 16);
324  }
325  } else {
326  /* Skip to the end of the header, also ignore CRC if present */
327  i = get_bits_count(&s->gb);
328  if (hdr_pos + 8 * hdr_size > i)
329  skip_bits_long(&s->gb, hdr_pos + 8 * hdr_size - i);
330  }
331 
332  s->current_subframe = 0;
333  s->current_subsubframe = 0;
334 
335  return 0;
336 }
337 
339 {
340  init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
341 
342  /* Sync code */
343  skip_bits_long(&s->gb, 32);
344 
345  /* Frame header */
346  s->frame_type = get_bits(&s->gb, 1);
347  s->samples_deficit = get_bits(&s->gb, 5) + 1;
348  s->crc_present = get_bits(&s->gb, 1);
349  s->sample_blocks = get_bits(&s->gb, 7) + 1;
350  s->frame_size = get_bits(&s->gb, 14) + 1;
351  if (s->frame_size < 95)
352  return AVERROR_INVALIDDATA;
353  s->amode = get_bits(&s->gb, 6);
355  if (!s->sample_rate)
356  return AVERROR_INVALIDDATA;
357  s->bit_rate_index = get_bits(&s->gb, 5);
359  if (!s->bit_rate)
360  return AVERROR_INVALIDDATA;
361 
362  skip_bits1(&s->gb); // always 0 (reserved, cf. ETSI TS 102 114 V1.4.1)
363  s->dynrange = get_bits(&s->gb, 1);
364  s->timestamp = get_bits(&s->gb, 1);
365  s->aux_data = get_bits(&s->gb, 1);
366  s->hdcd = get_bits(&s->gb, 1);
367  s->ext_descr = get_bits(&s->gb, 3);
368  s->ext_coding = get_bits(&s->gb, 1);
369  s->aspf = get_bits(&s->gb, 1);
370  s->lfe = get_bits(&s->gb, 2);
371  s->predictor_history = get_bits(&s->gb, 1);
372 
373  if (s->lfe > 2) {
374  s->lfe = 0;
375  av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE value: %d\n", s->lfe);
376  return AVERROR_INVALIDDATA;
377  }
378 
379  /* TODO: check CRC */
380  if (s->crc_present)
381  s->header_crc = get_bits(&s->gb, 16);
382 
383  s->multirate_inter = get_bits(&s->gb, 1);
384  s->version = get_bits(&s->gb, 4);
385  s->copy_history = get_bits(&s->gb, 2);
386  s->source_pcm_res = get_bits(&s->gb, 3);
387  s->front_sum = get_bits(&s->gb, 1);
388  s->surround_sum = get_bits(&s->gb, 1);
389  s->dialog_norm = get_bits(&s->gb, 4);
390 
391  /* FIXME: channels mixing levels */
392  s->output = s->amode;
393  if (s->lfe)
394  s->output |= DCA_LFE;
395 
396  /* Primary audio coding header */
397  s->subframes = get_bits(&s->gb, 4) + 1;
398 
399  return dca_parse_audio_coding_header(s, 0, 0);
400 }
401 
402 static inline int get_scale(GetBitContext *gb, int level, int value, int log2range)
403 {
404  if (level < 5) {
405  /* huffman encoded */
406  value += get_bitalloc(gb, &dca_scalefactor, level);
407  value = av_clip(value, 0, (1 << log2range) - 1);
408  } else if (level < 8) {
409  if (level + 1 > log2range) {
410  skip_bits(gb, level + 1 - log2range);
411  value = get_bits(gb, log2range);
412  } else {
413  value = get_bits(gb, level + 1);
414  }
415  }
416  return value;
417 }
418 
419 static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)
420 {
421  /* Primary audio coding side information */
422  int j, k;
423 
424  if (get_bits_left(&s->gb) < 0)
425  return AVERROR_INVALIDDATA;
426 
427  if (!base_channel) {
428  s->subsubframes[s->current_subframe] = get_bits(&s->gb, 2) + 1;
429  s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
430  }
431 
432  for (j = base_channel; j < s->prim_channels; j++) {
433  for (k = 0; k < s->subband_activity[j]; k++)
434  s->prediction_mode[j][k] = get_bits(&s->gb, 1);
435  }
436 
437  /* Get prediction codebook */
438  for (j = base_channel; j < s->prim_channels; j++) {
439  for (k = 0; k < s->subband_activity[j]; k++) {
440  if (s->prediction_mode[j][k] > 0) {
441  /* (Prediction coefficient VQ address) */
442  s->prediction_vq[j][k] = get_bits(&s->gb, 12);
443  }
444  }
445  }
446 
447  /* Bit allocation index */
448  for (j = base_channel; j < s->prim_channels; j++) {
449  for (k = 0; k < s->vq_start_subband[j]; k++) {
450  if (s->bitalloc_huffman[j] == 6)
451  s->bitalloc[j][k] = get_bits(&s->gb, 5);
452  else if (s->bitalloc_huffman[j] == 5)
453  s->bitalloc[j][k] = get_bits(&s->gb, 4);
454  else if (s->bitalloc_huffman[j] == 7) {
456  "Invalid bit allocation index\n");
457  return AVERROR_INVALIDDATA;
458  } else {
459  s->bitalloc[j][k] =
460  get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
461  }
462 
463  if (s->bitalloc[j][k] > 26) {
464  av_dlog(s->avctx, "bitalloc index [%i][%i] too big (%i)\n",
465  j, k, s->bitalloc[j][k]);
466  return AVERROR_INVALIDDATA;
467  }
468  }
469  }
470 
471  /* Transition mode */
472  for (j = base_channel; j < s->prim_channels; j++) {
473  for (k = 0; k < s->subband_activity[j]; k++) {
474  s->transition_mode[j][k] = 0;
475  if (s->subsubframes[s->current_subframe] > 1 &&
476  k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
477  s->transition_mode[j][k] =
478  get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
479  }
480  }
481  }
482 
483  if (get_bits_left(&s->gb) < 0)
484  return AVERROR_INVALIDDATA;
485 
486  for (j = base_channel; j < s->prim_channels; j++) {
487  const uint32_t *scale_table;
488  int scale_sum, log_size;
489 
490  memset(s->scale_factor[j], 0,
491  s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
492 
493  if (s->scalefactor_huffman[j] == 6) {
494  scale_table = ff_dca_scale_factor_quant7;
495  log_size = 7;
496  } else {
497  scale_table = ff_dca_scale_factor_quant6;
498  log_size = 6;
499  }
500 
501  /* When huffman coded, only the difference is encoded */
502  scale_sum = 0;
503 
504  for (k = 0; k < s->subband_activity[j]; k++) {
505  if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
506  scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);
507  s->scale_factor[j][k][0] = scale_table[scale_sum];
508  }
509 
510  if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
511  /* Get second scale factor */
512  scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);
513  s->scale_factor[j][k][1] = scale_table[scale_sum];
514  }
515  }
516  }
517 
518  /* Joint subband scale factor codebook select */
519  for (j = base_channel; j < s->prim_channels; j++) {
520  /* Transmitted only if joint subband coding enabled */
521  if (s->joint_intensity[j] > 0)
522  s->joint_huff[j] = get_bits(&s->gb, 3);
523  }
524 
525  if (get_bits_left(&s->gb) < 0)
526  return AVERROR_INVALIDDATA;
527 
528  /* Scale factors for joint subband coding */
529  for (j = base_channel; j < s->prim_channels; j++) {
530  int source_channel;
531 
532  /* Transmitted only if joint subband coding enabled */
533  if (s->joint_intensity[j] > 0) {
534  int scale = 0;
535  source_channel = s->joint_intensity[j] - 1;
536 
537  /* When huffman coded, only the difference is encoded
538  * (is this valid as well for joint scales ???) */
539 
540  for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
541  scale = get_scale(&s->gb, s->joint_huff[j], 64 /* bias */, 7);
542  s->joint_scale_factor[j][k] = scale; /*joint_scale_table[scale]; */
543  }
544 
545  if (!(s->debug_flag & 0x02)) {
547  "Joint stereo coding not supported\n");
548  s->debug_flag |= 0x02;
549  }
550  }
551  }
552 
553  /* Dynamic range coefficient */
554  if (!base_channel && s->dynrange)
555  s->dynrange_coef = get_bits(&s->gb, 8);
556 
557  /* Side information CRC check word */
558  if (s->crc_present) {
559  get_bits(&s->gb, 16);
560  }
561 
562  /*
563  * Primary audio data arrays
564  */
565 
566  /* VQ encoded high frequency subbands */
567  for (j = base_channel; j < s->prim_channels; j++)
568  for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
569  /* 1 vector -> 32 samples */
570  s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
571 
572  /* Low frequency effect data */
573  if (!base_channel && s->lfe) {
574  int quant7;
575  /* LFE samples */
576  int lfe_samples = 2 * s->lfe * (4 + block_index);
577  int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
578  float lfe_scale;
579 
580  for (j = lfe_samples; j < lfe_end_sample; j++) {
581  /* Signed 8 bits int */
582  s->lfe_data[j] = get_sbits(&s->gb, 8);
583  }
584 
585  /* Scale factor index */
586  quant7 = get_bits(&s->gb, 8);
587  if (quant7 > 127) {
588  avpriv_request_sample(s->avctx, "LFEScaleIndex larger than 127");
589  return AVERROR_INVALIDDATA;
590  }
592 
593  /* Quantization step size * scale factor */
594  lfe_scale = 0.035 * s->lfe_scale_factor;
595 
596  for (j = lfe_samples; j < lfe_end_sample; j++)
597  s->lfe_data[j] *= lfe_scale;
598  }
599 
600  return 0;
601 }
602 
603 static void qmf_32_subbands(DCAContext *s, int chans,
604  float samples_in[32][8], float *samples_out,
605  float scale)
606 {
607  const float *prCoeff;
608 
609  int sb_act = s->subband_activity[chans];
610 
611  scale *= sqrt(1 / 8.0);
612 
613  /* Select filter */
614  if (!s->multirate_inter) /* Non-perfect reconstruction */
616  else /* Perfect reconstruction */
617  prCoeff = ff_dca_fir_32bands_perfect;
618 
619  s->dcadsp.qmf_32_subbands(samples_in, sb_act, &s->synth, &s->imdct,
620  s->subband_fir_hist[chans],
621  &s->hist_index[chans],
622  s->subband_fir_noidea[chans], prCoeff,
623  samples_out, s->raXin, scale);
624 }
625 
626 static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
627  int num_deci_sample, float *samples_in,
628  float *samples_out)
629 {
630  /* samples_in: An array holding decimated samples.
631  * Samples in current subframe starts from samples_in[0],
632  * while samples_in[-1], samples_in[-2], ..., stores samples
633  * from last subframe as history.
634  *
635  * samples_out: An array holding interpolated samples
636  */
637 
638  int idx;
639  const float *prCoeff;
640  int deciindex;
641 
642  /* Select decimation filter */
643  if (decimation_select == 1) {
644  idx = 1;
645  prCoeff = ff_dca_lfe_fir_128;
646  } else {
647  idx = 0;
648  prCoeff = ff_dca_lfe_fir_64;
649  }
650  /* Interpolation */
651  for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
652  s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
653  samples_in++;
654  samples_out += 2 * 32 * (1 + idx);
655  }
656 }
657 
658 /* downmixing routines */
659 #define MIX_REAR1(samples, s1, rs, coef) \
660  samples[0][i] += samples[s1][i] * coef[rs][0]; \
661  samples[1][i] += samples[s1][i] * coef[rs][1];
662 
663 #define MIX_REAR2(samples, s1, s2, rs, coef) \
664  samples[0][i] += samples[s1][i] * coef[rs][0] + samples[s2][i] * coef[rs + 1][0]; \
665  samples[1][i] += samples[s1][i] * coef[rs][1] + samples[s2][i] * coef[rs + 1][1];
666 
667 #define MIX_FRONT3(samples, coef) \
668  t = samples[c][i]; \
669  u = samples[l][i]; \
670  v = samples[r][i]; \
671  samples[0][i] = t * coef[0][0] + u * coef[1][0] + v * coef[2][0]; \
672  samples[1][i] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
673 
674 #define DOWNMIX_TO_STEREO(op1, op2) \
675  for (i = 0; i < 256; i++) { \
676  op1 \
677  op2 \
678  }
679 
680 static void dca_downmix(float **samples, int srcfmt, int lfe_present,
681  float coef[DCA_PRIM_CHANNELS_MAX + 1][2],
682  const int8_t *channel_mapping)
683 {
684  int c, l, r, sl, sr, s;
685  int i;
686  float t, u, v;
687 
688  switch (srcfmt) {
689  case DCA_MONO:
690  case DCA_4F2R:
691  av_log(NULL, AV_LOG_ERROR, "Not implemented!\n");
692  break;
693  case DCA_CHANNEL:
694  case DCA_STEREO:
695  case DCA_STEREO_TOTAL:
696  case DCA_STEREO_SUMDIFF:
697  break;
698  case DCA_3F:
699  c = channel_mapping[0];
700  l = channel_mapping[1];
701  r = channel_mapping[2];
702  DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
703  break;
704  case DCA_2F1R:
705  s = channel_mapping[2];
706  DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );
707  break;
708  case DCA_3F1R:
709  c = channel_mapping[0];
710  l = channel_mapping[1];
711  r = channel_mapping[2];
712  s = channel_mapping[3];
713  DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
714  MIX_REAR1(samples, s, 3, coef));
715  break;
716  case DCA_2F2R:
717  sl = channel_mapping[2];
718  sr = channel_mapping[3];
719  DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );
720  break;
721  case DCA_3F2R:
722  c = channel_mapping[0];
723  l = channel_mapping[1];
724  r = channel_mapping[2];
725  sl = channel_mapping[3];
726  sr = channel_mapping[4];
727  DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
728  MIX_REAR2(samples, sl, sr, 3, coef));
729  break;
730  }
731  if (lfe_present) {
732  int lf_buf = ff_dca_lfe_index[srcfmt];
733  int lf_idx = ff_dca_channels[srcfmt];
734  for (i = 0; i < 256; i++) {
735  samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];
736  samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];
737  }
738  }
739 }
740 
741 #ifndef decode_blockcodes
742 /* Very compact version of the block code decoder that does not use table
743  * look-up but is slightly slower */
744 static int decode_blockcode(int code, int levels, int32_t *values)
745 {
746  int i;
747  int offset = (levels - 1) >> 1;
748 
749  for (i = 0; i < 4; i++) {
750  int div = FASTDIV(code, levels);
751  values[i] = code - offset - div * levels;
752  code = div;
753  }
754 
755  return code;
756 }
757 
758 static int decode_blockcodes(int code1, int code2, int levels, int32_t *values)
759 {
760  return decode_blockcode(code1, levels, values) |
761  decode_blockcode(code2, levels, values + 4);
762 }
763 #endif
764 
765 static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
766 static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
767 
768 static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
769 {
770  int k, l;
771  int subsubframe = s->current_subsubframe;
772 
773  const float *quant_step_table;
774 
775  /* FIXME */
776  float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
778 
779  /*
780  * Audio data
781  */
782 
783  /* Select quantization step size table */
784  if (s->bit_rate_index == 0x1f)
785  quant_step_table = ff_dca_lossless_quant_d;
786  else
787  quant_step_table = ff_dca_lossy_quant_d;
788 
789  for (k = base_channel; k < s->prim_channels; k++) {
790  float rscale[DCA_SUBBANDS];
791 
792  if (get_bits_left(&s->gb) < 0)
793  return AVERROR_INVALIDDATA;
794 
795  for (l = 0; l < s->vq_start_subband[k]; l++) {
796  int m;
797 
798  /* Select the mid-tread linear quantizer */
799  int abits = s->bitalloc[k][l];
800 
801  float quant_step_size = quant_step_table[abits];
802 
803  /*
804  * Determine quantization index code book and its type
805  */
806 
807  /* Select quantization index code book */
808  int sel = s->quant_index_huffman[k][abits];
809 
810  /*
811  * Extract bits from the bit stream
812  */
813  if (!abits) {
814  rscale[l] = 0;
815  memset(block + 8 * l, 0, 8 * sizeof(block[0]));
816  } else {
817  /* Deal with transients */
818  int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];
819  rscale[l] = quant_step_size * s->scale_factor[k][l][sfi] *
820  s->scalefactor_adj[k][sel];
821 
822  if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
823  if (abits <= 7) {
824  /* Block code */
825  int block_code1, block_code2, size, levels, err;
826 
827  size = abits_sizes[abits - 1];
828  levels = abits_levels[abits - 1];
829 
830  block_code1 = get_bits(&s->gb, size);
831  block_code2 = get_bits(&s->gb, size);
832  err = decode_blockcodes(block_code1, block_code2,
833  levels, block + 8 * l);
834  if (err) {
836  "ERROR: block code look-up failed\n");
837  return AVERROR_INVALIDDATA;
838  }
839  } else {
840  /* no coding */
841  for (m = 0; m < 8; m++)
842  block[8 * l + m] = get_sbits(&s->gb, abits - 3);
843  }
844  } else {
845  /* Huffman coded */
846  for (m = 0; m < 8; m++)
847  block[8 * l + m] = get_bitalloc(&s->gb,
848  &dca_smpl_bitalloc[abits], sel);
849  }
850  }
851  }
852 
853  s->fmt_conv.int32_to_float_fmul_array8(&s->fmt_conv, subband_samples[k][0],
854  block, rscale, 8 * s->vq_start_subband[k]);
855 
856  for (l = 0; l < s->vq_start_subband[k]; l++) {
857  int m;
858  /*
859  * Inverse ADPCM if in prediction mode
860  */
861  if (s->prediction_mode[k][l]) {
862  int n;
863  if (s->predictor_history)
864  subband_samples[k][l][0] += (ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
865  s->subband_samples_hist[k][l][3] +
866  ff_dca_adpcm_vb[s->prediction_vq[k][l]][1] *
867  s->subband_samples_hist[k][l][2] +
868  ff_dca_adpcm_vb[s->prediction_vq[k][l]][2] *
869  s->subband_samples_hist[k][l][1] +
870  ff_dca_adpcm_vb[s->prediction_vq[k][l]][3] *
871  s->subband_samples_hist[k][l][0]) *
872  (1.0f / 8192);
873  for (m = 1; m < 8; m++) {
874  float sum = ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
875  subband_samples[k][l][m - 1];
876  for (n = 2; n <= 4; n++)
877  if (m >= n)
878  sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
879  subband_samples[k][l][m - n];
880  else if (s->predictor_history)
881  sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
882  s->subband_samples_hist[k][l][m - n + 4];
883  subband_samples[k][l][m] += sum * (1.0f / 8192);
884  }
885  }
886  }
887 
888  /*
889  * Decode VQ encoded high frequencies
890  */
891  if (s->subband_activity[k] > s->vq_start_subband[k]) {
892  if (!(s->debug_flag & 0x01)) {
894  "Stream with high frequencies VQ coding\n");
895  s->debug_flag |= 0x01;
896  }
897  s->dcadsp.decode_hf(subband_samples[k], s->high_freq_vq[k],
898  ff_dca_high_freq_vq, subsubframe * 8,
899  s->scale_factor[k], s->vq_start_subband[k],
900  s->subband_activity[k]);
901  }
902  }
903 
904  /* Check for DSYNC after subsubframe */
905  if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
906  if (get_bits(&s->gb, 16) != 0xFFFF) {
907  av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
908  return AVERROR_INVALIDDATA;
909  }
910  }
911 
912  /* Backup predictor history for adpcm */
913  for (k = base_channel; k < s->prim_channels; k++)
914  for (l = 0; l < s->vq_start_subband[k]; l++)
915  AV_COPY128(s->subband_samples_hist[k][l], &subband_samples[k][l][4]);
916 
917  return 0;
918 }
919 
920 static int dca_filter_channels(DCAContext *s, int block_index)
921 {
922  float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
923  int k;
924 
925  /* 32 subbands QMF */
926  for (k = 0; k < s->prim_channels; k++) {
927  if (s->channel_order_tab[k] >= 0)
928  qmf_32_subbands(s, k, subband_samples[k],
930  M_SQRT1_2 / 32768.0);
931  }
932 
933  /* Generate LFE samples for this subsubframe FIXME!!! */
934  if (s->lfe) {
935  lfe_interpolation_fir(s, s->lfe, 2 * s->lfe,
936  s->lfe_data + 2 * s->lfe * (block_index + 4),
937  s->samples_chanptr[s->lfe_index]);
938  /* Outputs 20bits pcm samples */
939  }
940 
941  /* Downmixing to Stereo */
942  if (s->prim_channels + !!s->lfe > 2 &&
945  s->channel_order_tab);
946  }
947 
948  return 0;
949 }
950 
951 static int dca_subframe_footer(DCAContext *s, int base_channel)
952 {
953  int in, out, aux_data_count, aux_data_end, reserved;
954  uint32_t nsyncaux;
955 
956  /*
957  * Unpack optional information
958  */
959 
960  /* presumably optional information only appears in the core? */
961  if (!base_channel) {
962  if (s->timestamp)
963  skip_bits_long(&s->gb, 32);
964 
965  if (s->aux_data) {
966  aux_data_count = get_bits(&s->gb, 6);
967 
968  // align (32-bit)
969  skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
970 
971  aux_data_end = 8 * aux_data_count + get_bits_count(&s->gb);
972 
973  if ((nsyncaux = get_bits_long(&s->gb, 32)) != DCA_NSYNCAUX) {
974  av_log(s->avctx, AV_LOG_ERROR, "nSYNCAUX mismatch %#"PRIx32"\n",
975  nsyncaux);
976  return AVERROR_INVALIDDATA;
977  }
978 
979  if (get_bits1(&s->gb)) { // bAUXTimeStampFlag
981  "Auxiliary Decode Time Stamp Flag");
982  // align (4-bit)
983  skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 4);
984  // 44 bits: nMSByte (8), nMarker (4), nLSByte (28), nMarker (4)
985  skip_bits_long(&s->gb, 44);
986  }
987 
988  if ((s->core_downmix = get_bits1(&s->gb))) {
989  int am = get_bits(&s->gb, 3);
990  switch (am) {
991  case 0:
993  break;
994  case 1:
996  break;
997  case 2:
999  break;
1000  case 3:
1002  break;
1003  case 4:
1005  break;
1006  case 5:
1008  break;
1009  case 6:
1011  break;
1012  default:
1014  "Invalid mode %d for embedded downmix coefficients\n",
1015  am);
1016  return AVERROR_INVALIDDATA;
1017  }
1018  for (out = 0; out < ff_dca_channels[s->core_downmix_amode]; out++) {
1019  for (in = 0; in < s->prim_channels + !!s->lfe; in++) {
1020  uint16_t tmp = get_bits(&s->gb, 9);
1021  if ((tmp & 0xFF) > 241) {
1023  "Invalid downmix coefficient code %"PRIu16"\n",
1024  tmp);
1025  return AVERROR_INVALIDDATA;
1026  }
1027  s->core_downmix_codes[in][out] = tmp;
1028  }
1029  }
1030  }
1031 
1032  align_get_bits(&s->gb); // byte align
1033  skip_bits(&s->gb, 16); // nAUXCRC16
1034 
1035  // additional data (reserved, cf. ETSI TS 102 114 V1.4.1)
1036  if ((reserved = (aux_data_end - get_bits_count(&s->gb))) < 0) {
1038  "Overread auxiliary data by %d bits\n", -reserved);
1039  return AVERROR_INVALIDDATA;
1040  } else if (reserved) {
1042  "Core auxiliary data reserved content");
1043  skip_bits_long(&s->gb, reserved);
1044  }
1045  }
1046 
1047  if (s->crc_present && s->dynrange)
1048  get_bits(&s->gb, 16);
1049  }
1050 
1051  return 0;
1052 }
1053 
1054 /**
1055  * Decode a dca frame block
1056  *
1057  * @param s pointer to the DCAContext
1058  */
1059 
1060 static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
1061 {
1062  int ret;
1063 
1064  /* Sanity check */
1065  if (s->current_subframe >= s->subframes) {
1066  av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1067  s->current_subframe, s->subframes);
1068  return AVERROR_INVALIDDATA;
1069  }
1070 
1071  if (!s->current_subsubframe) {
1072  /* Read subframe header */
1073  if ((ret = dca_subframe_header(s, base_channel, block_index)))
1074  return ret;
1075  }
1076 
1077  /* Read subsubframe */
1078  if ((ret = dca_subsubframe(s, base_channel, block_index)))
1079  return ret;
1080 
1081  /* Update state */
1082  s->current_subsubframe++;
1084  s->current_subsubframe = 0;
1085  s->current_subframe++;
1086  }
1087  if (s->current_subframe >= s->subframes) {
1088  /* Read subframe footer */
1089  if ((ret = dca_subframe_footer(s, base_channel)))
1090  return ret;
1091  }
1092 
1093  return 0;
1094 }
1095 
1097 {
1098  int scale_table_high[DCA_CHSET_CHANS_MAX][DCA_SUBBANDS][2];
1099  int active_bands[DCA_CHSETS_MAX][DCA_CHSET_CHANS_MAX];
1100  int abits_high[DCA_CHSET_CHANS_MAX][DCA_SUBBANDS];
1101  int anctemp[DCA_CHSET_CHANS_MAX];
1102  int chset_fsize[DCA_CHSETS_MAX];
1103  int n_xbr_ch[DCA_CHSETS_MAX];
1104  int hdr_size, num_chsets, xbr_tmode, hdr_pos;
1105  int i, j, k, l, chset, chan_base;
1106 
1107  av_log(s->avctx, AV_LOG_DEBUG, "DTS-XBR: decoding XBR extension\n");
1108 
1109  /* get bit position of sync header */
1110  hdr_pos = get_bits_count(&s->gb) - 32;
1111 
1112  hdr_size = get_bits(&s->gb, 6) + 1;
1113  num_chsets = get_bits(&s->gb, 2) + 1;
1114 
1115  for(i = 0; i < num_chsets; i++)
1116  chset_fsize[i] = get_bits(&s->gb, 14) + 1;
1117 
1118  xbr_tmode = get_bits1(&s->gb);
1119 
1120  for(i = 0; i < num_chsets; i++) {
1121  n_xbr_ch[i] = get_bits(&s->gb, 3) + 1;
1122  k = get_bits(&s->gb, 2) + 5;
1123  for(j = 0; j < n_xbr_ch[i]; j++)
1124  active_bands[i][j] = get_bits(&s->gb, k) + 1;
1125  }
1126 
1127  /* skip to the end of the header */
1128  i = get_bits_count(&s->gb);
1129  if(hdr_pos + hdr_size * 8 > i)
1130  skip_bits_long(&s->gb, hdr_pos + hdr_size * 8 - i);
1131 
1132  /* loop over the channel data sets */
1133  /* only decode as many channels as we've decoded base data for */
1134  for(chset = 0, chan_base = 0;
1135  chset < num_chsets && chan_base + n_xbr_ch[chset] <= s->prim_channels;
1136  chan_base += n_xbr_ch[chset++]) {
1137  int start_posn = get_bits_count(&s->gb);
1138  int subsubframe = 0;
1139  int subframe = 0;
1140 
1141  /* loop over subframes */
1142  for (k = 0; k < (s->sample_blocks / 8); k++) {
1143  /* parse header if we're on first subsubframe of a block */
1144  if(subsubframe == 0) {
1145  /* Parse subframe header */
1146  for(i = 0; i < n_xbr_ch[chset]; i++) {
1147  anctemp[i] = get_bits(&s->gb, 2) + 2;
1148  }
1149 
1150  for(i = 0; i < n_xbr_ch[chset]; i++) {
1151  get_array(&s->gb, abits_high[i], active_bands[chset][i], anctemp[i]);
1152  }
1153 
1154  for(i = 0; i < n_xbr_ch[chset]; i++) {
1155  anctemp[i] = get_bits(&s->gb, 3);
1156  if(anctemp[i] < 1) {
1157  av_log(s->avctx, AV_LOG_ERROR, "DTS-XBR: SYNC ERROR\n");
1158  return AVERROR_INVALIDDATA;
1159  }
1160  }
1161 
1162  /* generate scale factors */
1163  for(i = 0; i < n_xbr_ch[chset]; i++) {
1164  const uint32_t *scale_table;
1165  int nbits;
1166 
1167  if (s->scalefactor_huffman[chan_base+i] == 6) {
1168  scale_table = ff_dca_scale_factor_quant7;
1169  } else {
1170  scale_table = ff_dca_scale_factor_quant6;
1171  }
1172 
1173  nbits = anctemp[i];
1174 
1175  for(j = 0; j < active_bands[chset][i]; j++) {
1176  if(abits_high[i][j] > 0) {
1177  scale_table_high[i][j][0] =
1178  scale_table[get_bits(&s->gb, nbits)];
1179 
1180  if(xbr_tmode && s->transition_mode[i][j]) {
1181  scale_table_high[i][j][1] =
1182  scale_table[get_bits(&s->gb, nbits)];
1183  }
1184  }
1185  }
1186  }
1187  }
1188 
1189  /* decode audio array for this block */
1190  for(i = 0; i < n_xbr_ch[chset]; i++) {
1191  for(j = 0; j < active_bands[chset][i]; j++) {
1192  const int xbr_abits = abits_high[i][j];
1193  const float quant_step_size = ff_dca_lossless_quant_d[xbr_abits];
1194  const int sfi = xbr_tmode && s->transition_mode[i][j] && subsubframe >= s->transition_mode[i][j];
1195  const float rscale = quant_step_size * scale_table_high[i][j][sfi];
1196  float *subband_samples = s->subband_samples[k][chan_base+i][j];
1197  int block[8];
1198 
1199  if(xbr_abits <= 0)
1200  continue;
1201 
1202  if(xbr_abits > 7) {
1203  get_array(&s->gb, block, 8, xbr_abits - 3);
1204  } else {
1205  int block_code1, block_code2, size, levels, err;
1206 
1207  size = abits_sizes[xbr_abits - 1];
1208  levels = abits_levels[xbr_abits - 1];
1209 
1210  block_code1 = get_bits(&s->gb, size);
1211  block_code2 = get_bits(&s->gb, size);
1212  err = decode_blockcodes(block_code1, block_code2,
1213  levels, block);
1214  if (err) {
1216  "ERROR: DTS-XBR: block code look-up failed\n");
1217  return AVERROR_INVALIDDATA;
1218  }
1219  }
1220 
1221  /* scale & sum into subband */
1222  for(l = 0; l < 8; l++)
1223  subband_samples[l] += (float)block[l] * rscale;
1224  }
1225  }
1226 
1227  /* check DSYNC marker */
1228  if(s->aspf || subsubframe == s->subsubframes[subframe] - 1) {
1229  if(get_bits(&s->gb, 16) != 0xffff) {
1230  av_log(s->avctx, AV_LOG_ERROR, "DTS-XBR: Didn't get subframe DSYNC\n");
1231  return AVERROR_INVALIDDATA;
1232  }
1233  }
1234 
1235  /* advance sub-sub-frame index */
1236  if(++subsubframe >= s->subsubframes[subframe]) {
1237  subsubframe = 0;
1238  subframe++;
1239  }
1240  }
1241 
1242  /* skip to next channel set */
1243  i = get_bits_count(&s->gb);
1244  if(start_posn + chset_fsize[chset] * 8 != i) {
1245  j = start_posn + chset_fsize[chset] * 8 - i;
1246  if(j < 0 || j >= 8)
1247  av_log(s->avctx, AV_LOG_ERROR, "DTS-XBR: end of channel set,"
1248  " skipping further than expected (%d bits)\n", j);
1249  skip_bits_long(&s->gb, j);
1250  }
1251  }
1252 
1253  return 0;
1254 }
1255 
1256 
1257 /* parse initial header for XXCH and dump details */
1259 {
1260  int hdr_size, spkmsk_bits, num_chsets, core_spk, hdr_pos;
1261  int i, chset, base_channel, chstart, fsize[8];
1262 
1263  /* assume header word has already been parsed */
1264  hdr_pos = get_bits_count(&s->gb) - 32;
1265  hdr_size = get_bits(&s->gb, 6) + 1;
1266  /*chhdr_crc =*/ skip_bits1(&s->gb);
1267  spkmsk_bits = get_bits(&s->gb, 5) + 1;
1268  num_chsets = get_bits(&s->gb, 2) + 1;
1269 
1270  for (i = 0; i < num_chsets; i++)
1271  fsize[i] = get_bits(&s->gb, 14) + 1;
1272 
1273  core_spk = get_bits(&s->gb, spkmsk_bits);
1274  s->xxch_core_spkmask = core_spk;
1275  s->xxch_nbits_spk_mask = spkmsk_bits;
1276  s->xxch_dmix_embedded = 0;
1277 
1278  /* skip to the end of the header */
1279  i = get_bits_count(&s->gb);
1280  if (hdr_pos + hdr_size * 8 > i)
1281  skip_bits_long(&s->gb, hdr_pos + hdr_size * 8 - i);
1282 
1283  for (chset = 0; chset < num_chsets; chset++) {
1284  chstart = get_bits_count(&s->gb);
1285  base_channel = s->prim_channels;
1286  s->xxch_chset = chset;
1287 
1288  /* XXCH and Core headers differ, see 6.4.2 "XXCH Channel Set Header" vs.
1289  5.3.2 "Primary Audio Coding Header", DTS Spec 1.3.1 */
1290  dca_parse_audio_coding_header(s, base_channel, 1);
1291 
1292  /* decode channel data */
1293  for (i = 0; i < (s->sample_blocks / 8); i++) {
1294  if (dca_decode_block(s, base_channel, i)) {
1296  "Error decoding DTS-XXCH extension\n");
1297  continue;
1298  }
1299  }
1300 
1301  /* skip to end of this section */
1302  i = get_bits_count(&s->gb);
1303  if (chstart + fsize[chset] * 8 > i)
1304  skip_bits_long(&s->gb, chstart + fsize[chset] * 8 - i);
1305  }
1306  s->xxch_chset = num_chsets;
1307 
1308  return 0;
1309 }
1310 
1311 static float dca_dmix_code(unsigned code)
1312 {
1313  int sign = (code >> 8) - 1;
1314  code &= 0xff;
1315  return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1 << 15));
1316 }
1317 
1318 /**
1319  * Main frame decoding function
1320  * FIXME add arguments
1321  */
1322 static int dca_decode_frame(AVCodecContext *avctx, void *data,
1323  int *got_frame_ptr, AVPacket *avpkt)
1324 {
1325  AVFrame *frame = data;
1326  const uint8_t *buf = avpkt->data;
1327  int buf_size = avpkt->size;
1328  int channel_mask;
1329  int channel_layout;
1330  int lfe_samples;
1331  int num_core_channels = 0;
1332  int i, ret;
1333  float **samples_flt;
1334  float *src_chan;
1335  float *dst_chan;
1336  DCAContext *s = avctx->priv_data;
1337  int core_ss_end;
1338  int channels, full_channels;
1339  float scale;
1340  int achan;
1341  int chset;
1342  int mask;
1343  int lavc;
1344  int posn;
1345  int j, k;
1346  int endch;
1347 
1348  s->xch_present = 0;
1349 
1353  av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1354  return AVERROR_INVALIDDATA;
1355  }
1356 
1357  if ((ret = dca_parse_frame_header(s)) < 0) {
1358  // seems like the frame is corrupt, try with the next one
1359  return ret;
1360  }
1361  // set AVCodec values with parsed data
1362  avctx->sample_rate = s->sample_rate;
1363  avctx->bit_rate = s->bit_rate;
1364 
1365  s->profile = FF_PROFILE_DTS;
1366 
1367  for (i = 0; i < (s->sample_blocks / 8); i++) {
1368  if ((ret = dca_decode_block(s, 0, i))) {
1369  av_log(avctx, AV_LOG_ERROR, "error decoding block\n");
1370  return ret;
1371  }
1372  }
1373 
1374  /* record number of core channels incase less than max channels are requested */
1375  num_core_channels = s->prim_channels;
1376 
1377  if (s->prim_channels + !!s->lfe > 2 &&
1379  /* Stereo downmix coefficients
1380  *
1381  * The decoder can only downmix to 2-channel, so we need to ensure
1382  * embedded downmix coefficients are actually targeting 2-channel.
1383  */
1384  if (s->core_downmix && (s->core_downmix_amode == DCA_STEREO ||
1386  for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1387  /* Range checked earlier */
1388  s->downmix_coef[i][0] = dca_dmix_code(s->core_downmix_codes[i][0]);
1389  s->downmix_coef[i][1] = dca_dmix_code(s->core_downmix_codes[i][1]);
1390  }
1391  s->output = s->core_downmix_amode;
1392  } else {
1393  int am = s->amode & DCA_CHANNEL_MASK;
1396  "Invalid channel mode %d\n", am);
1397  return AVERROR_INVALIDDATA;
1398  }
1399  if (num_core_channels + !!s->lfe >
1401  avpriv_request_sample(s->avctx, "Downmixing %d channels",
1402  s->prim_channels + !!s->lfe);
1403  return AVERROR_PATCHWELCOME;
1404  }
1405  for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1406  s->downmix_coef[i][0] = ff_dca_default_coeffs[am][i][0];
1407  s->downmix_coef[i][1] = ff_dca_default_coeffs[am][i][1];
1408  }
1409  }
1410  av_dlog(s->avctx, "Stereo downmix coeffs:\n");
1411  for (i = 0; i < num_core_channels + !!s->lfe; i++) {
1412  av_dlog(s->avctx, "L, input channel %d = %f\n", i,
1413  s->downmix_coef[i][0]);
1414  av_dlog(s->avctx, "R, input channel %d = %f\n", i,
1415  s->downmix_coef[i][1]);
1416  }
1417  av_dlog(s->avctx, "\n");
1418  }
1419 
1420  if (s->ext_coding)
1422  else
1423  s->core_ext_mask = 0;
1424 
1425  core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
1426 
1427  /* only scan for extensions if ext_descr was unknown or indicated a
1428  * supported XCh extension */
1429  if (s->core_ext_mask < 0 || s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH)) {
1430  /* if ext_descr was unknown, clear s->core_ext_mask so that the
1431  * extensions scan can fill it up */
1432  s->core_ext_mask = FFMAX(s->core_ext_mask, 0);
1433 
1434  /* extensions start at 32-bit boundaries into bitstream */
1435  skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1436 
1437  while (core_ss_end - get_bits_count(&s->gb) >= 32) {
1438  uint32_t bits = get_bits_long(&s->gb, 32);
1439 
1440  switch (bits) {
1441  case DCA_SYNCWORD_XCH: {
1442  int ext_amode, xch_fsize;
1443 
1445 
1446  /* validate sync word using XCHFSIZE field */
1447  xch_fsize = show_bits(&s->gb, 10);
1448  if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
1449  (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
1450  continue;
1451 
1452  /* skip length-to-end-of-frame field for the moment */
1453  skip_bits(&s->gb, 10);
1454 
1455  s->core_ext_mask |= DCA_EXT_XCH;
1456 
1457  /* extension amode(number of channels in extension) should be 1 */
1458  /* AFAIK XCh is not used for more channels */
1459  if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
1460  av_log(avctx, AV_LOG_ERROR,
1461  "XCh extension amode %d not supported!\n",
1462  ext_amode);
1463  continue;
1464  }
1465 
1466  if (s->xch_base_channel < 2) {
1467  avpriv_request_sample(avctx, "XCh with fewer than 2 base channels");
1468  continue;
1469  }
1470 
1471  /* much like core primary audio coding header */
1473 
1474  for (i = 0; i < (s->sample_blocks / 8); i++)
1475  if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
1476  av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
1477  continue;
1478  }
1479 
1480  s->xch_present = 1;
1481  break;
1482  }
1483  case DCA_SYNCWORD_XXCH:
1484  /* XXCh: extended channels */
1485  /* usually found either in core or HD part in DTS-HD HRA streams,
1486  * but not in DTS-ES which contains XCh extensions instead */
1489  break;
1490 
1491  case 0x1d95f262: {
1492  int fsize96 = show_bits(&s->gb, 12) + 1;
1493  if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
1494  continue;
1495 
1496  av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",
1497  get_bits_count(&s->gb));
1498  skip_bits(&s->gb, 12);
1499  av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
1500  av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
1501 
1502  s->core_ext_mask |= DCA_EXT_X96;
1503  break;
1504  }
1505  }
1506 
1507  skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
1508  }
1509  } else {
1510  /* no supported extensions, skip the rest of the core substream */
1511  skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
1512  }
1513 
1514  if (s->core_ext_mask & DCA_EXT_X96)
1516  else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))
1518 
1519  /* check for ExSS (HD part) */
1520  if (s->dca_buffer_size - s->frame_size > 32 &&
1523 
1524  avctx->profile = s->profile;
1525 
1526  full_channels = channels = s->prim_channels + !!s->lfe;
1527 
1528  /* If we have XXCH then the channel layout is managed differently */
1529  /* note that XLL will also have another way to do things */
1530  if (!(s->core_ext_mask & DCA_EXT_XXCH)
1531  || (s->core_ext_mask & DCA_EXT_XXCH && avctx->request_channels > 0
1532  && avctx->request_channels
1533  < num_core_channels + !!s->lfe + s->xxch_chset_nch[0]))
1534  { /* xxx should also do MA extensions */
1535  if (s->amode < 16) {
1537 
1538  if (s->prim_channels + !!s->lfe > 2 &&
1540  /*
1541  * Neither the core's auxiliary data nor our default tables contain
1542  * downmix coefficients for the additional channel coded in the XCh
1543  * extension, so when we're doing a Stereo downmix, don't decode it.
1544  */
1545  s->xch_disable = 1;
1546  }
1547 
1548 #if FF_API_REQUEST_CHANNELS
1550  if (s->xch_present && !s->xch_disable &&
1551  (!avctx->request_channels ||
1552  avctx->request_channels > num_core_channels + !!s->lfe)) {
1554 #else
1555  if (s->xch_present && !s->xch_disable) {
1556 #endif
1557  if (avctx->channel_layout & AV_CH_BACK_CENTER) {
1558  avpriv_request_sample(avctx, "XCh with Back center channel");
1559  return AVERROR_INVALIDDATA;
1560  }
1562  if (s->lfe) {
1565  } else {
1567  }
1568  if (s->channel_order_tab[s->xch_base_channel] < 0)
1569  return AVERROR_INVALIDDATA;
1570  } else {
1571  channels = num_core_channels + !!s->lfe;
1572  s->xch_present = 0; /* disable further xch processing */
1573  if (s->lfe) {
1576  } else
1578  }
1579 
1580  if (channels > !!s->lfe &&
1581  s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
1582  return AVERROR_INVALIDDATA;
1583 
1584  if (av_get_channel_layout_nb_channels(avctx->channel_layout) != channels) {
1585  av_log(avctx, AV_LOG_ERROR, "Number of channels %d mismatches layout %d\n", channels, av_get_channel_layout_nb_channels(avctx->channel_layout));
1586  return AVERROR_INVALIDDATA;
1587  }
1588 
1589  if (num_core_channels + !!s->lfe > 2 &&
1591  channels = 2;
1592  s->output = s->prim_channels == 2 ? s->amode : DCA_STEREO;
1594  }
1595  else if (avctx->request_channel_layout & AV_CH_LAYOUT_NATIVE) {
1596  static const int8_t dca_channel_order_native[9] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
1597  s->channel_order_tab = dca_channel_order_native;
1598  }
1599  s->lfe_index = ff_dca_lfe_index[s->amode];
1600  } else {
1601  av_log(avctx, AV_LOG_ERROR,
1602  "Non standard configuration %d !\n", s->amode);
1603  return AVERROR_INVALIDDATA;
1604  }
1605 
1606  s->xxch_dmix_embedded = 0;
1607  } else {
1608  /* we only get here if an XXCH channel set can be added to the mix */
1609  channel_mask = s->xxch_core_spkmask;
1610 
1611  if (avctx->request_channels > 0
1612  && avctx->request_channels < s->prim_channels) {
1613  channels = num_core_channels + !!s->lfe;
1614  for (i = 0; i < s->xxch_chset && channels + s->xxch_chset_nch[i]
1615  <= avctx->request_channels; i++) {
1616  channels += s->xxch_chset_nch[i];
1617  channel_mask |= s->xxch_spk_masks[i];
1618  }
1619  } else {
1620  channels = s->prim_channels + !!s->lfe;
1621  for (i = 0; i < s->xxch_chset; i++) {
1622  channel_mask |= s->xxch_spk_masks[i];
1623  }
1624  }
1625 
1626  /* Given the DTS spec'ed channel mask, generate an avcodec version */
1627  channel_layout = 0;
1628  for (i = 0; i < s->xxch_nbits_spk_mask; ++i) {
1629  if (channel_mask & (1 << i)) {
1630  channel_layout |= ff_dca_map_xxch_to_native[i];
1631  }
1632  }
1633 
1634  /* make sure that we have managed to get equivalent dts/avcodec channel
1635  * masks in some sense -- unfortunately some channels could overlap */
1636  if (av_popcount(channel_mask) != av_popcount(channel_layout)) {
1637  av_log(avctx, AV_LOG_DEBUG,
1638  "DTS-XXCH: Inconsistent avcodec/dts channel layouts\n");
1639  return AVERROR_INVALIDDATA;
1640  }
1641 
1642  avctx->channel_layout = channel_layout;
1643 
1644  if (!(avctx->request_channel_layout & AV_CH_LAYOUT_NATIVE)) {
1645  /* Estimate DTS --> avcodec ordering table */
1646  for (chset = -1, j = 0; chset < s->xxch_chset; ++chset) {
1647  mask = chset >= 0 ? s->xxch_spk_masks[chset]
1648  : s->xxch_core_spkmask;
1649  for (i = 0; i < s->xxch_nbits_spk_mask; i++) {
1650  if (mask & ~(DCA_XXCH_LFE1 | DCA_XXCH_LFE2) & (1 << i)) {
1651  lavc = ff_dca_map_xxch_to_native[i];
1652  posn = av_popcount(channel_layout & (lavc - 1));
1653  s->xxch_order_tab[j++] = posn;
1654  }
1655  }
1656 
1657  }
1658 
1659  s->lfe_index = av_popcount(channel_layout & (AV_CH_LOW_FREQUENCY-1));
1660  } else { /* native ordering */
1661  for (i = 0; i < channels; i++)
1662  s->xxch_order_tab[i] = i;
1663 
1664  s->lfe_index = channels - 1;
1665  }
1666 
1668  }
1669 
1670  if (avctx->channels != channels) {
1671  if (avctx->channels)
1672  av_log(avctx, AV_LOG_INFO, "Number of channels changed in DCA decoder (%d -> %d)\n", avctx->channels, channels);
1673  avctx->channels = channels;
1674  }
1675 
1676  /* get output buffer */
1677  frame->nb_samples = 256 * (s->sample_blocks / 8);
1678  if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1679  return ret;
1680  samples_flt = (float **) frame->extended_data;
1681 
1682  /* allocate buffer for extra channels if downmixing */
1683  if (avctx->channels < full_channels) {
1684  ret = av_samples_get_buffer_size(NULL, full_channels - channels,
1685  frame->nb_samples,
1686  avctx->sample_fmt, 0);
1687  if (ret < 0)
1688  return ret;
1689 
1691  &s->extra_channels_buffer_size, ret);
1692  if (!s->extra_channels_buffer)
1693  return AVERROR(ENOMEM);
1694 
1697  full_channels - channels,
1698  frame->nb_samples, avctx->sample_fmt, 0);
1699  if (ret < 0)
1700  return ret;
1701  }
1702 
1703  /* filter to get final output */
1704  for (i = 0; i < (s->sample_blocks / 8); i++) {
1705  int ch;
1706 
1707  for (ch = 0; ch < channels; ch++)
1708  s->samples_chanptr[ch] = samples_flt[ch] + i * 256;
1709  for (; ch < full_channels; ch++)
1710  s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * 256;
1711 
1712  dca_filter_channels(s, i);
1713 
1714  /* If this was marked as a DTS-ES stream we need to subtract back- */
1715  /* channel from SL & SR to remove matrixed back-channel signal */
1716  if ((s->source_pcm_res & 1) && s->xch_present) {
1717  float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];
1718  float *lt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];
1719  float *rt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];
1720  s->fdsp->vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
1721  s->fdsp->vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
1722  }
1723 
1724  /* If stream contains XXCH, we might need to undo an embedded downmix */
1725  if (s->xxch_dmix_embedded) {
1726  /* Loop over channel sets in turn */
1727  ch = num_core_channels;
1728  for (chset = 0; chset < s->xxch_chset; chset++) {
1729  endch = ch + s->xxch_chset_nch[chset];
1730  mask = s->xxch_dmix_embedded;
1731 
1732  /* undo downmix */
1733  for (j = ch; j < endch; j++) {
1734  if (mask & (1 << j)) { /* this channel has been mixed-out */
1735  src_chan = s->samples_chanptr[s->channel_order_tab[j]];
1736  for (k = 0; k < endch; k++) {
1737  achan = s->channel_order_tab[k];
1738  scale = s->xxch_dmix_coeff[j][k];
1739  if (scale != 0.0) {
1740  dst_chan = s->samples_chanptr[achan];
1741  s->fdsp->vector_fmac_scalar(dst_chan, src_chan,
1742  -scale, 256);
1743  }
1744  }
1745  }
1746  }
1747 
1748  /* if a downmix has been embedded then undo the pre-scaling */
1749  if ((mask & (1 << ch)) && s->xxch_dmix_sf[chset] != 1.0f) {
1750  scale = s->xxch_dmix_sf[chset];
1751 
1752  for (j = 0; j < ch; j++) {
1753  src_chan = s->samples_chanptr[s->channel_order_tab[j]];
1754  for (k = 0; k < 256; k++)
1755  src_chan[k] *= scale;
1756  }
1757 
1758  /* LFE channel is always part of core, scale if it exists */
1759  if (s->lfe) {
1760  src_chan = s->samples_chanptr[s->lfe_index];
1761  for (k = 0; k < 256; k++)
1762  src_chan[k] *= scale;
1763  }
1764  }
1765 
1766  ch = endch;
1767  }
1768 
1769  }
1770  }
1771 
1772  /* update lfe history */
1773  lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);
1774  for (i = 0; i < 2 * s->lfe * 4; i++)
1775  s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1776 
1777  /* AVMatrixEncoding
1778  *
1779  * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */
1781  (s->output & ~DCA_LFE) == DCA_STEREO_TOTAL ?
1783  if (ret < 0)
1784  return ret;
1785 
1786  *got_frame_ptr = 1;
1787 
1788  return buf_size;
1789 }
1790 
1791 /**
1792  * DCA initialization
1793  *
1794  * @param avctx pointer to the AVCodecContext
1795  */
1796 
1798 {
1799  DCAContext *s = avctx->priv_data;
1800 
1801  s->avctx = avctx;
1802  dca_init_vlcs();
1803 
1805  if (!s->fdsp)
1806  return AVERROR(ENOMEM);
1807 
1808  ff_mdct_init(&s->imdct, 6, 1, 1.0);
1810  ff_dcadsp_init(&s->dcadsp);
1811  ff_fmt_convert_init(&s->fmt_conv, avctx);
1812 
1813  avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1814 
1815  /* allow downmixing to stereo */
1816 #if FF_API_REQUEST_CHANNELS
1818  if (avctx->request_channels == 2)
1821 #endif
1822  if (avctx->channels > 2 &&
1824  avctx->channels = 2;
1825 
1826  return 0;
1827 }
1828 
1830 {
1831  DCAContext *s = avctx->priv_data;
1832  ff_mdct_end(&s->imdct);
1834  av_freep(&s->fdsp);
1835  return 0;
1836 }
1837 
1838 static const AVProfile profiles[] = {
1839  { FF_PROFILE_DTS, "DTS" },
1840  { FF_PROFILE_DTS_ES, "DTS-ES" },
1841  { FF_PROFILE_DTS_96_24, "DTS 96/24" },
1842  { FF_PROFILE_DTS_HD_HRA, "DTS-HD HRA" },
1843  { FF_PROFILE_DTS_HD_MA, "DTS-HD MA" },
1844  { FF_PROFILE_UNKNOWN },
1845 };
1846 
1847 static const AVOption options[] = {
1848  { "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 },
1849  { NULL },
1850 };
1851 
1852 static const AVClass dca_decoder_class = {
1853  .class_name = "DCA decoder",
1854  .item_name = av_default_item_name,
1855  .option = options,
1856  .version = LIBAVUTIL_VERSION_INT,
1857  .category = AV_CLASS_CATEGORY_DECODER,
1858 };
1859 
1861  .name = "dca",
1862  .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1863  .type = AVMEDIA_TYPE_AUDIO,
1864  .id = AV_CODEC_ID_DTS,
1865  .priv_data_size = sizeof(DCAContext),
1866  .init = dca_decode_init,
1868  .close = dca_decode_end,
1869  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
1870  .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1872  .profiles = NULL_IF_CONFIG_SMALL(profiles),
1873  .priv_class = &dca_decoder_class,
1874 };