You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2071 lines
77KB

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