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.

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