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.

1606 lines
59KB

  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 Libav.
  11. *
  12. * Libav is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * Libav is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with Libav; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  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 "put_bits.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. /* -1 are reserved or unknown */
  68. static const int dca_ext_audio_descr_mask[] = {
  69. DCA_EXT_XCH,
  70. -1,
  71. DCA_EXT_X96,
  72. DCA_EXT_XCH | DCA_EXT_X96,
  73. -1,
  74. -1,
  75. DCA_EXT_XXCH,
  76. -1,
  77. };
  78. /* Tables for mapping dts channel configurations to libavcodec multichannel api.
  79. * Some compromises have been made for special configurations. Most configurations
  80. * are never used so complete accuracy is not needed.
  81. *
  82. * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
  83. * S -> side, when both rear and back are configured move one of them to the side channel
  84. * OV -> center back
  85. * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
  86. */
  87. static const uint64_t dca_core_channel_layout[] = {
  88. AV_CH_FRONT_CENTER, ///< 1, A
  89. AV_CH_LAYOUT_STEREO, ///< 2, A + B (dual mono)
  90. AV_CH_LAYOUT_STEREO, ///< 2, L + R (stereo)
  91. AV_CH_LAYOUT_STEREO, ///< 2, (L + R) + (L - R) (sum-difference)
  92. AV_CH_LAYOUT_STEREO, ///< 2, LT + RT (left and right total)
  93. AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER, ///< 3, C + L + R
  94. AV_CH_LAYOUT_STEREO | AV_CH_BACK_CENTER, ///< 3, L + R + S
  95. AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER, ///< 4, C + L + R + S
  96. AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT, ///< 4, L + R + SL + SR
  97. AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT |
  98. AV_CH_SIDE_RIGHT, ///< 5, C + L + R + SL + SR
  99. AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
  100. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER, ///< 6, CL + CR + L + R + SL + SR
  101. AV_CH_LAYOUT_STEREO | AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT |
  102. AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER, ///< 6, C + L + R + LR + RR + OV
  103. AV_CH_FRONT_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
  104. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_BACK_CENTER |
  105. AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT, ///< 6, CF + CR + LF + RF + LR + RR
  106. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER |
  107. AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
  108. AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT, ///< 7, CL + C + CR + L + R + SL + SR
  109. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
  110. AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
  111. AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT, ///< 8, CL + CR + L + R + SL1 + SL2 + SR1 + SR2
  112. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER |
  113. AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
  114. AV_CH_SIDE_LEFT | AV_CH_BACK_CENTER | AV_CH_SIDE_RIGHT, ///< 8, CL + C + CR + L + R + SL + S + SR
  115. };
  116. #define DCA_DOLBY 101 /* FIXME */
  117. #define DCA_CHANNEL_BITS 6
  118. #define DCA_CHANNEL_MASK 0x3F
  119. #define DCA_LFE 0x80
  120. #define HEADER_SIZE 14
  121. #define DCA_NSYNCAUX 0x9A1105A0
  122. #define SAMPLES_PER_SUBBAND 8 // number of samples per subband per subsubframe
  123. /** Bit allocation */
  124. typedef struct BitAlloc {
  125. int offset; ///< code values offset
  126. int maxbits[8]; ///< max bits in VLC
  127. int wrap; ///< wrap for get_vlc2()
  128. VLC vlc[8]; ///< actual codes
  129. } BitAlloc;
  130. static BitAlloc dca_bitalloc_index; ///< indexes for samples VLC select
  131. static BitAlloc dca_tmode; ///< transition mode VLCs
  132. static BitAlloc dca_scalefactor; ///< scalefactor VLCs
  133. static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
  134. static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba,
  135. int idx)
  136. {
  137. return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) +
  138. ba->offset;
  139. }
  140. static av_cold void dca_init_vlcs(void)
  141. {
  142. static int vlcs_initialized = 0;
  143. int i, j, c = 14;
  144. static VLC_TYPE dca_table[23622][2];
  145. if (vlcs_initialized)
  146. return;
  147. dca_bitalloc_index.offset = 1;
  148. dca_bitalloc_index.wrap = 2;
  149. for (i = 0; i < 5; i++) {
  150. dca_bitalloc_index.vlc[i].table = &dca_table[ff_dca_vlc_offs[i]];
  151. dca_bitalloc_index.vlc[i].table_allocated = ff_dca_vlc_offs[i + 1] - ff_dca_vlc_offs[i];
  152. init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
  153. bitalloc_12_bits[i], 1, 1,
  154. bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
  155. }
  156. dca_scalefactor.offset = -64;
  157. dca_scalefactor.wrap = 2;
  158. for (i = 0; i < 5; i++) {
  159. dca_scalefactor.vlc[i].table = &dca_table[ff_dca_vlc_offs[i + 5]];
  160. dca_scalefactor.vlc[i].table_allocated = ff_dca_vlc_offs[i + 6] - ff_dca_vlc_offs[i + 5];
  161. init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
  162. scales_bits[i], 1, 1,
  163. scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
  164. }
  165. dca_tmode.offset = 0;
  166. dca_tmode.wrap = 1;
  167. for (i = 0; i < 4; i++) {
  168. dca_tmode.vlc[i].table = &dca_table[ff_dca_vlc_offs[i + 10]];
  169. dca_tmode.vlc[i].table_allocated = ff_dca_vlc_offs[i + 11] - ff_dca_vlc_offs[i + 10];
  170. init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
  171. tmode_bits[i], 1, 1,
  172. tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
  173. }
  174. for (i = 0; i < 10; i++)
  175. for (j = 0; j < 7; j++) {
  176. if (!bitalloc_codes[i][j])
  177. break;
  178. dca_smpl_bitalloc[i + 1].offset = bitalloc_offsets[i];
  179. dca_smpl_bitalloc[i + 1].wrap = 1 + (j > 4);
  180. dca_smpl_bitalloc[i + 1].vlc[j].table = &dca_table[ff_dca_vlc_offs[c]];
  181. dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = ff_dca_vlc_offs[c + 1] - ff_dca_vlc_offs[c];
  182. init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
  183. bitalloc_sizes[i],
  184. bitalloc_bits[i][j], 1, 1,
  185. bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
  186. c++;
  187. }
  188. vlcs_initialized = 1;
  189. }
  190. static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
  191. {
  192. while (len--)
  193. *dst++ = get_bits(gb, bits);
  194. }
  195. static int dca_parse_audio_coding_header(DCAContext *s, int base_channel)
  196. {
  197. int i, j;
  198. static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
  199. static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
  200. static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
  201. s->audio_header.total_channels = get_bits(&s->gb, 3) + 1 + base_channel;
  202. s->audio_header.prim_channels = s->audio_header.total_channels;
  203. if (s->audio_header.prim_channels > DCA_PRIM_CHANNELS_MAX)
  204. s->audio_header.prim_channels = DCA_PRIM_CHANNELS_MAX;
  205. for (i = base_channel; i < s->audio_header.prim_channels; i++) {
  206. s->audio_header.subband_activity[i] = get_bits(&s->gb, 5) + 2;
  207. if (s->audio_header.subband_activity[i] > DCA_SUBBANDS)
  208. s->audio_header.subband_activity[i] = DCA_SUBBANDS;
  209. }
  210. for (i = base_channel; i < s->audio_header.prim_channels; i++) {
  211. s->audio_header.vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
  212. if (s->audio_header.vq_start_subband[i] > DCA_SUBBANDS)
  213. s->audio_header.vq_start_subband[i] = DCA_SUBBANDS;
  214. }
  215. get_array(&s->gb, s->audio_header.joint_intensity + base_channel,
  216. s->audio_header.prim_channels - base_channel, 3);
  217. get_array(&s->gb, s->audio_header.transient_huffman + base_channel,
  218. s->audio_header.prim_channels - base_channel, 2);
  219. get_array(&s->gb, s->audio_header.scalefactor_huffman + base_channel,
  220. s->audio_header.prim_channels - base_channel, 3);
  221. get_array(&s->gb, s->audio_header.bitalloc_huffman + base_channel,
  222. s->audio_header.prim_channels - base_channel, 3);
  223. /* Get codebooks quantization indexes */
  224. if (!base_channel)
  225. memset(s->audio_header.quant_index_huffman, 0, sizeof(s->audio_header.quant_index_huffman));
  226. for (j = 1; j < 11; j++)
  227. for (i = base_channel; i < s->audio_header.prim_channels; i++)
  228. s->audio_header.quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
  229. /* Get scale factor adjustment */
  230. for (j = 0; j < 11; j++)
  231. for (i = base_channel; i < s->audio_header.prim_channels; i++)
  232. s->audio_header.scalefactor_adj[i][j] = 1;
  233. for (j = 1; j < 11; j++)
  234. for (i = base_channel; i < s->audio_header.prim_channels; i++)
  235. if (s->audio_header.quant_index_huffman[i][j] < thr[j])
  236. s->audio_header.scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
  237. if (s->crc_present) {
  238. /* Audio header CRC check */
  239. get_bits(&s->gb, 16);
  240. }
  241. s->current_subframe = 0;
  242. s->current_subsubframe = 0;
  243. return 0;
  244. }
  245. static int dca_parse_frame_header(DCAContext *s)
  246. {
  247. init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
  248. /* Sync code */
  249. skip_bits_long(&s->gb, 32);
  250. /* Frame header */
  251. s->frame_type = get_bits(&s->gb, 1);
  252. s->samples_deficit = get_bits(&s->gb, 5) + 1;
  253. s->crc_present = get_bits(&s->gb, 1);
  254. s->sample_blocks = get_bits(&s->gb, 7) + 1;
  255. s->frame_size = get_bits(&s->gb, 14) + 1;
  256. if (s->frame_size < 95)
  257. return AVERROR_INVALIDDATA;
  258. s->amode = get_bits(&s->gb, 6);
  259. s->sample_rate = avpriv_dca_sample_rates[get_bits(&s->gb, 4)];
  260. if (!s->sample_rate)
  261. return AVERROR_INVALIDDATA;
  262. s->bit_rate_index = get_bits(&s->gb, 5);
  263. s->bit_rate = ff_dca_bit_rates[s->bit_rate_index];
  264. if (!s->bit_rate)
  265. return AVERROR_INVALIDDATA;
  266. skip_bits1(&s->gb); // always 0 (reserved, cf. ETSI TS 102 114 V1.4.1)
  267. s->dynrange = get_bits(&s->gb, 1);
  268. s->timestamp = get_bits(&s->gb, 1);
  269. s->aux_data = get_bits(&s->gb, 1);
  270. s->hdcd = get_bits(&s->gb, 1);
  271. s->ext_descr = get_bits(&s->gb, 3);
  272. s->ext_coding = get_bits(&s->gb, 1);
  273. s->aspf = get_bits(&s->gb, 1);
  274. s->lfe = get_bits(&s->gb, 2);
  275. s->predictor_history = get_bits(&s->gb, 1);
  276. if (s->lfe > 2) {
  277. av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE value: %d\n", s->lfe);
  278. return AVERROR_INVALIDDATA;
  279. }
  280. /* TODO: check CRC */
  281. if (s->crc_present)
  282. s->header_crc = get_bits(&s->gb, 16);
  283. s->multirate_inter = get_bits(&s->gb, 1);
  284. s->version = get_bits(&s->gb, 4);
  285. s->copy_history = get_bits(&s->gb, 2);
  286. s->source_pcm_res = get_bits(&s->gb, 3);
  287. s->front_sum = get_bits(&s->gb, 1);
  288. s->surround_sum = get_bits(&s->gb, 1);
  289. s->dialog_norm = get_bits(&s->gb, 4);
  290. /* FIXME: channels mixing levels */
  291. s->output = s->amode;
  292. if (s->lfe)
  293. s->output |= DCA_LFE;
  294. /* Primary audio coding header */
  295. s->audio_header.subframes = get_bits(&s->gb, 4) + 1;
  296. return dca_parse_audio_coding_header(s, 0);
  297. }
  298. static inline int get_scale(GetBitContext *gb, int level, int value, int log2range)
  299. {
  300. if (level < 5) {
  301. /* huffman encoded */
  302. value += get_bitalloc(gb, &dca_scalefactor, level);
  303. value = av_clip(value, 0, (1 << log2range) - 1);
  304. } else if (level < 8) {
  305. if (level + 1 > log2range) {
  306. skip_bits(gb, level + 1 - log2range);
  307. value = get_bits(gb, log2range);
  308. } else {
  309. value = get_bits(gb, level + 1);
  310. }
  311. }
  312. return value;
  313. }
  314. static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)
  315. {
  316. /* Primary audio coding side information */
  317. int j, k;
  318. if (get_bits_left(&s->gb) < 0)
  319. return AVERROR_INVALIDDATA;
  320. if (!base_channel) {
  321. s->subsubframes[s->current_subframe] = get_bits(&s->gb, 2) + 1;
  322. s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
  323. }
  324. for (j = base_channel; j < s->audio_header.prim_channels; j++) {
  325. for (k = 0; k < s->audio_header.subband_activity[j]; k++)
  326. s->dca_chan[j].prediction_mode[k] = get_bits(&s->gb, 1);
  327. }
  328. /* Get prediction codebook */
  329. for (j = base_channel; j < s->audio_header.prim_channels; j++) {
  330. for (k = 0; k < s->audio_header.subband_activity[j]; k++) {
  331. if (s->dca_chan[j].prediction_mode[k] > 0) {
  332. /* (Prediction coefficient VQ address) */
  333. s->dca_chan[j].prediction_vq[k] = get_bits(&s->gb, 12);
  334. }
  335. }
  336. }
  337. /* Bit allocation index */
  338. for (j = base_channel; j < s->audio_header.prim_channels; j++) {
  339. for (k = 0; k < s->audio_header.vq_start_subband[j]; k++) {
  340. if (s->audio_header.bitalloc_huffman[j] == 6)
  341. s->dca_chan[j].bitalloc[k] = get_bits(&s->gb, 5);
  342. else if (s->audio_header.bitalloc_huffman[j] == 5)
  343. s->dca_chan[j].bitalloc[k] = get_bits(&s->gb, 4);
  344. else if (s->audio_header.bitalloc_huffman[j] == 7) {
  345. av_log(s->avctx, AV_LOG_ERROR,
  346. "Invalid bit allocation index\n");
  347. return AVERROR_INVALIDDATA;
  348. } else {
  349. s->dca_chan[j].bitalloc[k] =
  350. get_bitalloc(&s->gb, &dca_bitalloc_index, s->audio_header.bitalloc_huffman[j]);
  351. }
  352. if (s->dca_chan[j].bitalloc[k] > 26) {
  353. ff_dlog(s->avctx, "bitalloc index [%i][%i] too big (%i)\n",
  354. j, k, s->dca_chan[j].bitalloc[k]);
  355. return AVERROR_INVALIDDATA;
  356. }
  357. }
  358. }
  359. /* Transition mode */
  360. for (j = base_channel; j < s->audio_header.prim_channels; j++) {
  361. for (k = 0; k < s->audio_header.subband_activity[j]; k++) {
  362. s->dca_chan[j].transition_mode[k] = 0;
  363. if (s->subsubframes[s->current_subframe] > 1 &&
  364. k < s->audio_header.vq_start_subband[j] && s->dca_chan[j].bitalloc[k] > 0) {
  365. s->dca_chan[j].transition_mode[k] =
  366. get_bitalloc(&s->gb, &dca_tmode, s->audio_header.transient_huffman[j]);
  367. }
  368. }
  369. }
  370. if (get_bits_left(&s->gb) < 0)
  371. return AVERROR_INVALIDDATA;
  372. for (j = base_channel; j < s->audio_header.prim_channels; j++) {
  373. const uint32_t *scale_table;
  374. int scale_sum, log_size;
  375. memset(s->dca_chan[j].scale_factor, 0,
  376. s->audio_header.subband_activity[j] * sizeof(s->dca_chan[j].scale_factor[0][0]) * 2);
  377. if (s->audio_header.scalefactor_huffman[j] == 6) {
  378. scale_table = ff_dca_scale_factor_quant7;
  379. log_size = 7;
  380. } else {
  381. scale_table = ff_dca_scale_factor_quant6;
  382. log_size = 6;
  383. }
  384. /* When huffman coded, only the difference is encoded */
  385. scale_sum = 0;
  386. for (k = 0; k < s->audio_header.subband_activity[j]; k++) {
  387. if (k >= s->audio_header.vq_start_subband[j] || s->dca_chan[j].bitalloc[k] > 0) {
  388. scale_sum = get_scale(&s->gb, s->audio_header.scalefactor_huffman[j], scale_sum, log_size);
  389. s->dca_chan[j].scale_factor[k][0] = scale_table[scale_sum];
  390. }
  391. if (k < s->audio_header.vq_start_subband[j] && s->dca_chan[j].transition_mode[k]) {
  392. /* Get second scale factor */
  393. scale_sum = get_scale(&s->gb, s->audio_header.scalefactor_huffman[j], scale_sum, log_size);
  394. s->dca_chan[j].scale_factor[k][1] = scale_table[scale_sum];
  395. }
  396. }
  397. }
  398. /* Joint subband scale factor codebook select */
  399. for (j = base_channel; j < s->audio_header.prim_channels; j++) {
  400. /* Transmitted only if joint subband coding enabled */
  401. if (s->audio_header.joint_intensity[j] > 0)
  402. s->dca_chan[j].joint_huff = get_bits(&s->gb, 3);
  403. }
  404. if (get_bits_left(&s->gb) < 0)
  405. return AVERROR_INVALIDDATA;
  406. /* Scale factors for joint subband coding */
  407. for (j = base_channel; j < s->audio_header.prim_channels; j++) {
  408. int source_channel;
  409. /* Transmitted only if joint subband coding enabled */
  410. if (s->audio_header.joint_intensity[j] > 0) {
  411. int scale = 0;
  412. source_channel = s->audio_header.joint_intensity[j] - 1;
  413. /* When huffman coded, only the difference is encoded
  414. * (is this valid as well for joint scales ???) */
  415. for (k = s->audio_header.subband_activity[j];
  416. k < s->audio_header.subband_activity[source_channel]; k++) {
  417. scale = get_scale(&s->gb, s->dca_chan[j].joint_huff, 64 /* bias */, 7);
  418. s->dca_chan[j].joint_scale_factor[k] = scale; /*joint_scale_table[scale]; */
  419. }
  420. if (!(s->debug_flag & 0x02)) {
  421. av_log(s->avctx, AV_LOG_DEBUG,
  422. "Joint stereo coding not supported\n");
  423. s->debug_flag |= 0x02;
  424. }
  425. }
  426. }
  427. /* Dynamic range coefficient */
  428. if (!base_channel && s->dynrange)
  429. s->dynrange_coef = get_bits(&s->gb, 8);
  430. /* Side information CRC check word */
  431. if (s->crc_present) {
  432. get_bits(&s->gb, 16);
  433. }
  434. /*
  435. * Primary audio data arrays
  436. */
  437. /* VQ encoded high frequency subbands */
  438. for (j = base_channel; j < s->audio_header.prim_channels; j++)
  439. for (k = s->audio_header.vq_start_subband[j]; k < s->audio_header.subband_activity[j]; k++)
  440. /* 1 vector -> 32 samples */
  441. s->dca_chan[j].high_freq_vq[k] = get_bits(&s->gb, 10);
  442. /* Low frequency effect data */
  443. if (!base_channel && s->lfe) {
  444. /* LFE samples */
  445. int lfe_samples = 2 * s->lfe * (4 + block_index);
  446. int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
  447. float lfe_scale;
  448. for (j = lfe_samples; j < lfe_end_sample; j++) {
  449. /* Signed 8 bits int */
  450. s->lfe_data[j] = get_sbits(&s->gb, 8);
  451. }
  452. /* Scale factor index */
  453. skip_bits(&s->gb, 1);
  454. s->lfe_scale_factor = ff_dca_scale_factor_quant7[get_bits(&s->gb, 7)];
  455. /* Quantization step size * scale factor */
  456. lfe_scale = 0.035 * s->lfe_scale_factor;
  457. for (j = lfe_samples; j < lfe_end_sample; j++)
  458. s->lfe_data[j] *= lfe_scale;
  459. }
  460. return 0;
  461. }
  462. static void qmf_32_subbands(DCAContext *s, int chans,
  463. float samples_in[32][SAMPLES_PER_SUBBAND], float *samples_out,
  464. float scale)
  465. {
  466. const float *prCoeff;
  467. int sb_act = s->audio_header.subband_activity[chans];
  468. scale *= sqrt(1 / 8.0);
  469. /* Select filter */
  470. if (!s->multirate_inter) /* Non-perfect reconstruction */
  471. prCoeff = ff_dca_fir_32bands_nonperfect;
  472. else /* Perfect reconstruction */
  473. prCoeff = ff_dca_fir_32bands_perfect;
  474. s->dcadsp.qmf_32_subbands(samples_in, sb_act, &s->synth, &s->imdct,
  475. s->dca_chan[chans].subband_fir_hist,
  476. &s->dca_chan[chans].hist_index,
  477. s->dca_chan[chans].subband_fir_noidea, prCoeff,
  478. samples_out, s->raXin, scale);
  479. }
  480. static QMF64_table *qmf64_precompute(void)
  481. {
  482. unsigned i, j;
  483. QMF64_table *table = av_malloc(sizeof(*table));
  484. if (!table)
  485. return NULL;
  486. for (i = 0; i < 32; i++)
  487. for (j = 0; j < 32; j++)
  488. table->dct4_coeff[i][j] = cos((2 * i + 1) * (2 * j + 1) * M_PI / 128);
  489. for (i = 0; i < 32; i++)
  490. for (j = 0; j < 32; j++)
  491. table->dct2_coeff[i][j] = cos((2 * i + 1) * j * M_PI / 64);
  492. /* FIXME: Is the factor 0.125 = 1/8 right? */
  493. for (i = 0; i < 32; i++)
  494. table->rcos[i] = 0.125 / cos((2 * i + 1) * M_PI / 256);
  495. for (i = 0; i < 32; i++)
  496. table->rsin[i] = -0.125 / sin((2 * i + 1) * M_PI / 256);
  497. return table;
  498. }
  499. /* FIXME: Totally unoptimized. Based on the reference code and
  500. * http://multimedia.cx/mirror/dca-transform.pdf, with guessed tweaks
  501. * for doubling the size. */
  502. static void qmf_64_subbands(DCAContext *s, int chans, float samples_in[64][SAMPLES_PER_SUBBAND],
  503. float *samples_out, float scale)
  504. {
  505. float raXin[64];
  506. float A[32], B[32];
  507. float *raX = s->dca_chan[chans].subband_fir_hist;
  508. float *raZ = s->dca_chan[chans].subband_fir_noidea;
  509. unsigned i, j, k, subindex;
  510. for (i = s->audio_header.subband_activity[chans]; i < 64; i++)
  511. raXin[i] = 0.0;
  512. for (subindex = 0; subindex < SAMPLES_PER_SUBBAND; subindex++) {
  513. for (i = 0; i < s->audio_header.subband_activity[chans]; i++)
  514. raXin[i] = samples_in[i][subindex];
  515. for (k = 0; k < 32; k++) {
  516. A[k] = 0.0;
  517. for (i = 0; i < 32; i++)
  518. A[k] += (raXin[2 * i] + raXin[2 * i + 1]) * s->qmf64_table->dct4_coeff[k][i];
  519. }
  520. for (k = 0; k < 32; k++) {
  521. B[k] = raXin[0] * s->qmf64_table->dct2_coeff[k][0];
  522. for (i = 1; i < 32; i++)
  523. B[k] += (raXin[2 * i] + raXin[2 * i - 1]) * s->qmf64_table->dct2_coeff[k][i];
  524. }
  525. for (k = 0; k < 32; k++) {
  526. raX[k] = s->qmf64_table->rcos[k] * (A[k] + B[k]);
  527. raX[63 - k] = s->qmf64_table->rsin[k] * (A[k] - B[k]);
  528. }
  529. for (i = 0; i < 64; i++) {
  530. float out = raZ[i];
  531. for (j = 0; j < 1024; j += 128)
  532. out += ff_dca_fir_64bands[j + i] * (raX[j + i] - raX[j + 63 - i]);
  533. *samples_out++ = out * scale;
  534. }
  535. for (i = 0; i < 64; i++) {
  536. float hist = 0.0;
  537. for (j = 0; j < 1024; j += 128)
  538. hist += ff_dca_fir_64bands[64 + j + i] * (-raX[i + j] - raX[j + 63 - i]);
  539. raZ[i] = hist;
  540. }
  541. /* FIXME: Make buffer circular, to avoid this move. */
  542. memmove(raX + 64, raX, (1024 - 64) * sizeof(*raX));
  543. }
  544. }
  545. static void lfe_interpolation_fir(DCAContext *s, const float *samples_in,
  546. float *samples_out)
  547. {
  548. /* samples_in: An array holding decimated samples.
  549. * Samples in current subframe starts from samples_in[0],
  550. * while samples_in[-1], samples_in[-2], ..., stores samples
  551. * from last subframe as history.
  552. *
  553. * samples_out: An array holding interpolated samples
  554. */
  555. int idx;
  556. const float *prCoeff;
  557. int deciindex;
  558. /* Select decimation filter */
  559. if (s->lfe == 1) {
  560. idx = 1;
  561. prCoeff = ff_dca_lfe_fir_128;
  562. } else {
  563. idx = 0;
  564. if (s->exss_ext_mask & DCA_EXT_EXSS_XLL)
  565. prCoeff = ff_dca_lfe_xll_fir_64;
  566. else
  567. prCoeff = ff_dca_lfe_fir_64;
  568. }
  569. /* Interpolation */
  570. for (deciindex = 0; deciindex < 2 * s->lfe; deciindex++) {
  571. s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
  572. samples_in++;
  573. samples_out += 2 * 32 * (1 + idx);
  574. }
  575. }
  576. /* downmixing routines */
  577. #define MIX_REAR1(samples, s1, rs, coef) \
  578. samples[0][i] += samples[s1][i] * coef[rs][0]; \
  579. samples[1][i] += samples[s1][i] * coef[rs][1];
  580. #define MIX_REAR2(samples, s1, s2, rs, coef) \
  581. samples[0][i] += samples[s1][i] * coef[rs][0] + samples[s2][i] * coef[rs + 1][0]; \
  582. samples[1][i] += samples[s1][i] * coef[rs][1] + samples[s2][i] * coef[rs + 1][1];
  583. #define MIX_FRONT3(samples, coef) \
  584. t = samples[c][i]; \
  585. u = samples[l][i]; \
  586. v = samples[r][i]; \
  587. samples[0][i] = t * coef[0][0] + u * coef[1][0] + v * coef[2][0]; \
  588. samples[1][i] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
  589. #define DOWNMIX_TO_STEREO(op1, op2) \
  590. for (i = 0; i < 256; i++) { \
  591. op1 \
  592. op2 \
  593. }
  594. static void dca_downmix(float **samples, int srcfmt, int lfe_present,
  595. float coef[DCA_PRIM_CHANNELS_MAX + 1][2],
  596. const int8_t *channel_mapping)
  597. {
  598. int c, l, r, sl, sr, s;
  599. int i;
  600. float t, u, v;
  601. switch (srcfmt) {
  602. case DCA_MONO:
  603. case DCA_4F2R:
  604. av_log(NULL, 0, "Not implemented!\n");
  605. break;
  606. case DCA_CHANNEL:
  607. case DCA_STEREO:
  608. case DCA_STEREO_TOTAL:
  609. case DCA_STEREO_SUMDIFF:
  610. break;
  611. case DCA_3F:
  612. c = channel_mapping[0];
  613. l = channel_mapping[1];
  614. r = channel_mapping[2];
  615. DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
  616. break;
  617. case DCA_2F1R:
  618. s = channel_mapping[2];
  619. DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );
  620. break;
  621. case DCA_3F1R:
  622. c = channel_mapping[0];
  623. l = channel_mapping[1];
  624. r = channel_mapping[2];
  625. s = channel_mapping[3];
  626. DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
  627. MIX_REAR1(samples, s, 3, coef));
  628. break;
  629. case DCA_2F2R:
  630. sl = channel_mapping[2];
  631. sr = channel_mapping[3];
  632. DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );
  633. break;
  634. case DCA_3F2R:
  635. c = channel_mapping[0];
  636. l = channel_mapping[1];
  637. r = channel_mapping[2];
  638. sl = channel_mapping[3];
  639. sr = channel_mapping[4];
  640. DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
  641. MIX_REAR2(samples, sl, sr, 3, coef));
  642. break;
  643. }
  644. if (lfe_present) {
  645. int lf_buf = ff_dca_lfe_index[srcfmt];
  646. int lf_idx = ff_dca_channels[srcfmt];
  647. for (i = 0; i < 256; i++) {
  648. samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];
  649. samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];
  650. }
  651. }
  652. }
  653. #ifndef decode_blockcodes
  654. /* Very compact version of the block code decoder that does not use table
  655. * look-up but is slightly slower */
  656. static int decode_blockcode(int code, int levels, int32_t *values)
  657. {
  658. int i;
  659. int offset = (levels - 1) >> 1;
  660. for (i = 0; i < 4; i++) {
  661. int div = FASTDIV(code, levels);
  662. values[i] = code - offset - div * levels;
  663. code = div;
  664. }
  665. return code;
  666. }
  667. static int decode_blockcodes(int code1, int code2, int levels, int32_t *values)
  668. {
  669. return decode_blockcode(code1, levels, values) |
  670. decode_blockcode(code2, levels, values + 4);
  671. }
  672. #endif
  673. static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
  674. static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
  675. static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
  676. {
  677. int k, l;
  678. int subsubframe = s->current_subsubframe;
  679. const float *quant_step_table;
  680. LOCAL_ALIGNED_16(int32_t, block, [SAMPLES_PER_SUBBAND * DCA_SUBBANDS]);
  681. /*
  682. * Audio data
  683. */
  684. /* Select quantization step size table */
  685. if (s->bit_rate_index == 0x1f)
  686. quant_step_table = ff_dca_lossless_quant_d;
  687. else
  688. quant_step_table = ff_dca_lossy_quant_d;
  689. for (k = base_channel; k < s->audio_header.prim_channels; k++) {
  690. float (*subband_samples)[8] = s->dca_chan[k].subband_samples[block_index];
  691. float rscale[DCA_SUBBANDS];
  692. if (get_bits_left(&s->gb) < 0)
  693. return AVERROR_INVALIDDATA;
  694. for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
  695. int m;
  696. /* Select the mid-tread linear quantizer */
  697. int abits = s->dca_chan[k].bitalloc[l];
  698. float quant_step_size = quant_step_table[abits];
  699. /*
  700. * Determine quantization index code book and its type
  701. */
  702. /* Select quantization index code book */
  703. int sel = s->audio_header.quant_index_huffman[k][abits];
  704. /*
  705. * Extract bits from the bit stream
  706. */
  707. if (!abits) {
  708. rscale[l] = 0;
  709. memset(block + SAMPLES_PER_SUBBAND * l, 0, SAMPLES_PER_SUBBAND * sizeof(block[0]));
  710. } else {
  711. /* Deal with transients */
  712. int sfi = s->dca_chan[k].transition_mode[l] &&
  713. subsubframe >= s->dca_chan[k].transition_mode[l];
  714. rscale[l] = quant_step_size * s->dca_chan[k].scale_factor[l][sfi] *
  715. s->audio_header.scalefactor_adj[k][sel];
  716. if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
  717. if (abits <= 7) {
  718. /* Block code */
  719. int block_code1, block_code2, size, levels, err;
  720. size = abits_sizes[abits - 1];
  721. levels = abits_levels[abits - 1];
  722. block_code1 = get_bits(&s->gb, size);
  723. block_code2 = get_bits(&s->gb, size);
  724. err = decode_blockcodes(block_code1, block_code2,
  725. levels, block + SAMPLES_PER_SUBBAND * l);
  726. if (err) {
  727. av_log(s->avctx, AV_LOG_ERROR,
  728. "ERROR: block code look-up failed\n");
  729. return AVERROR_INVALIDDATA;
  730. }
  731. } else {
  732. /* no coding */
  733. for (m = 0; m < SAMPLES_PER_SUBBAND; m++)
  734. block[SAMPLES_PER_SUBBAND * l + m] = get_sbits(&s->gb, abits - 3);
  735. }
  736. } else {
  737. /* Huffman coded */
  738. for (m = 0; m < SAMPLES_PER_SUBBAND; m++)
  739. block[SAMPLES_PER_SUBBAND * l + m] = get_bitalloc(&s->gb,
  740. &dca_smpl_bitalloc[abits], sel);
  741. }
  742. }
  743. }
  744. s->fmt_conv.int32_to_float_fmul_array8(&s->fmt_conv, subband_samples[0],
  745. block, rscale, SAMPLES_PER_SUBBAND * s->audio_header.vq_start_subband[k]);
  746. for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
  747. int m;
  748. /*
  749. * Inverse ADPCM if in prediction mode
  750. */
  751. if (s->dca_chan[k].prediction_mode[l]) {
  752. int n;
  753. if (s->predictor_history)
  754. subband_samples[l][0] += (ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][0] *
  755. s->dca_chan[k].subband_samples_hist[l][3] +
  756. ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][1] *
  757. s->dca_chan[k].subband_samples_hist[l][2] +
  758. ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][2] *
  759. s->dca_chan[k].subband_samples_hist[l][1] +
  760. ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][3] *
  761. s->dca_chan[k].subband_samples_hist[l][0]) *
  762. (1.0f / 8192);
  763. for (m = 1; m < SAMPLES_PER_SUBBAND; m++) {
  764. float sum = ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][0] *
  765. subband_samples[l][m - 1];
  766. for (n = 2; n <= 4; n++)
  767. if (m >= n)
  768. sum += ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][n - 1] *
  769. subband_samples[l][m - n];
  770. else if (s->predictor_history)
  771. sum += ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][n - 1] *
  772. s->dca_chan[k].subband_samples_hist[l][m - n + 4];
  773. subband_samples[l][m] += sum * 1.0f / 8192;
  774. }
  775. }
  776. }
  777. /* Backup predictor history for adpcm */
  778. for (l = 0; l < DCA_SUBBANDS; l++)
  779. AV_COPY128(s->dca_chan[k].subband_samples_hist[l], &subband_samples[l][4]);
  780. /*
  781. * Decode VQ encoded high frequencies
  782. */
  783. if (s->audio_header.subband_activity[k] > s->audio_header.vq_start_subband[k]) {
  784. if (!s->debug_flag & 0x01) {
  785. av_log(s->avctx, AV_LOG_DEBUG,
  786. "Stream with high frequencies VQ coding\n");
  787. s->debug_flag |= 0x01;
  788. }
  789. s->dcadsp.decode_hf(subband_samples, s->dca_chan[k].high_freq_vq,
  790. ff_dca_high_freq_vq, subsubframe * SAMPLES_PER_SUBBAND,
  791. s->dca_chan[k].scale_factor,
  792. s->audio_header.vq_start_subband[k],
  793. s->audio_header.subband_activity[k]);
  794. }
  795. }
  796. /* Check for DSYNC after subsubframe */
  797. if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
  798. if (get_bits(&s->gb, 16) != 0xFFFF) {
  799. av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
  800. return AVERROR_INVALIDDATA;
  801. }
  802. }
  803. return 0;
  804. }
  805. static int dca_filter_channels(DCAContext *s, int block_index, int upsample)
  806. {
  807. int k;
  808. if (upsample) {
  809. if (!s->qmf64_table) {
  810. s->qmf64_table = qmf64_precompute();
  811. if (!s->qmf64_table)
  812. return AVERROR(ENOMEM);
  813. }
  814. /* 64 subbands QMF */
  815. for (k = 0; k < s->audio_header.prim_channels; k++) {
  816. float (*subband_samples)[SAMPLES_PER_SUBBAND] = s->dca_chan[k].subband_samples[block_index];
  817. if (s->channel_order_tab[k] >= 0)
  818. qmf_64_subbands(s, k, subband_samples,
  819. s->samples_chanptr[s->channel_order_tab[k]],
  820. /* Upsampling needs a factor 2 here. */
  821. M_SQRT2 / 32768.0);
  822. }
  823. } else {
  824. /* 32 subbands QMF */
  825. for (k = 0; k < s->audio_header.prim_channels; k++) {
  826. float (*subband_samples)[SAMPLES_PER_SUBBAND] = s->dca_chan[k].subband_samples[block_index];
  827. if (s->channel_order_tab[k] >= 0)
  828. qmf_32_subbands(s, k, subband_samples,
  829. s->samples_chanptr[s->channel_order_tab[k]],
  830. M_SQRT1_2 / 32768.0);
  831. }
  832. }
  833. /* Generate LFE samples for this subsubframe FIXME!!! */
  834. if (s->lfe) {
  835. float *samples = s->samples_chanptr[ff_dca_lfe_index[s->amode]];
  836. lfe_interpolation_fir(s,
  837. s->lfe_data + 2 * s->lfe * (block_index + 4),
  838. samples);
  839. if (upsample) {
  840. unsigned i;
  841. /* Should apply the filter in Table 6-11 when upsampling. For
  842. * now, just duplicate. */
  843. for (i = 511; i > 0; i--) {
  844. samples[2 * i] =
  845. samples[2 * i + 1] = samples[i];
  846. }
  847. samples[1] = samples[0];
  848. }
  849. }
  850. /* FIXME: This downmixing is probably broken with upsample.
  851. * Probably totally broken also with XLL in general. */
  852. /* Downmixing to Stereo */
  853. if (s->audio_header.prim_channels + !!s->lfe > 2 &&
  854. s->avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
  855. dca_downmix(s->samples_chanptr, s->amode, !!s->lfe, s->downmix_coef,
  856. s->channel_order_tab);
  857. }
  858. return 0;
  859. }
  860. static int dca_subframe_footer(DCAContext *s, int base_channel)
  861. {
  862. int in, out, aux_data_count, aux_data_end, reserved;
  863. uint32_t nsyncaux;
  864. /*
  865. * Unpack optional information
  866. */
  867. /* presumably optional information only appears in the core? */
  868. if (!base_channel) {
  869. if (s->timestamp)
  870. skip_bits_long(&s->gb, 32);
  871. if (s->aux_data) {
  872. aux_data_count = get_bits(&s->gb, 6);
  873. // align (32-bit)
  874. skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
  875. aux_data_end = 8 * aux_data_count + get_bits_count(&s->gb);
  876. if ((nsyncaux = get_bits_long(&s->gb, 32)) != DCA_NSYNCAUX) {
  877. av_log(s->avctx, AV_LOG_ERROR, "nSYNCAUX mismatch %#"PRIx32"\n",
  878. nsyncaux);
  879. return AVERROR_INVALIDDATA;
  880. }
  881. if (get_bits1(&s->gb)) { // bAUXTimeStampFlag
  882. avpriv_request_sample(s->avctx,
  883. "Auxiliary Decode Time Stamp Flag");
  884. // align (4-bit)
  885. skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 4);
  886. // 44 bits: nMSByte (8), nMarker (4), nLSByte (28), nMarker (4)
  887. skip_bits_long(&s->gb, 44);
  888. }
  889. if ((s->core_downmix = get_bits1(&s->gb))) {
  890. int am = get_bits(&s->gb, 3);
  891. switch (am) {
  892. case 0:
  893. s->core_downmix_amode = DCA_MONO;
  894. break;
  895. case 1:
  896. s->core_downmix_amode = DCA_STEREO;
  897. break;
  898. case 2:
  899. s->core_downmix_amode = DCA_STEREO_TOTAL;
  900. break;
  901. case 3:
  902. s->core_downmix_amode = DCA_3F;
  903. break;
  904. case 4:
  905. s->core_downmix_amode = DCA_2F1R;
  906. break;
  907. case 5:
  908. s->core_downmix_amode = DCA_2F2R;
  909. break;
  910. case 6:
  911. s->core_downmix_amode = DCA_3F1R;
  912. break;
  913. default:
  914. av_log(s->avctx, AV_LOG_ERROR,
  915. "Invalid mode %d for embedded downmix coefficients\n",
  916. am);
  917. return AVERROR_INVALIDDATA;
  918. }
  919. for (out = 0; out < ff_dca_channels[s->core_downmix_amode]; out++) {
  920. for (in = 0; in < s->audio_header.prim_channels + !!s->lfe; in++) {
  921. uint16_t tmp = get_bits(&s->gb, 9);
  922. if ((tmp & 0xFF) > 241) {
  923. av_log(s->avctx, AV_LOG_ERROR,
  924. "Invalid downmix coefficient code %"PRIu16"\n",
  925. tmp);
  926. return AVERROR_INVALIDDATA;
  927. }
  928. s->core_downmix_codes[in][out] = tmp;
  929. }
  930. }
  931. }
  932. align_get_bits(&s->gb); // byte align
  933. skip_bits(&s->gb, 16); // nAUXCRC16
  934. // additional data (reserved, cf. ETSI TS 102 114 V1.4.1)
  935. if ((reserved = (aux_data_end - get_bits_count(&s->gb))) < 0) {
  936. av_log(s->avctx, AV_LOG_ERROR,
  937. "Overread auxiliary data by %d bits\n", -reserved);
  938. return AVERROR_INVALIDDATA;
  939. } else if (reserved) {
  940. avpriv_request_sample(s->avctx,
  941. "Core auxiliary data reserved content");
  942. skip_bits_long(&s->gb, reserved);
  943. }
  944. }
  945. if (s->crc_present && s->dynrange)
  946. get_bits(&s->gb, 16);
  947. }
  948. return 0;
  949. }
  950. /**
  951. * Decode a dca frame block
  952. *
  953. * @param s pointer to the DCAContext
  954. */
  955. static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
  956. {
  957. int ret;
  958. /* Sanity check */
  959. if (s->current_subframe >= s->audio_header.subframes) {
  960. av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
  961. s->current_subframe, s->audio_header.subframes);
  962. return AVERROR_INVALIDDATA;
  963. }
  964. if (!s->current_subsubframe) {
  965. /* Read subframe header */
  966. if ((ret = dca_subframe_header(s, base_channel, block_index)))
  967. return ret;
  968. }
  969. /* Read subsubframe */
  970. if ((ret = dca_subsubframe(s, base_channel, block_index)))
  971. return ret;
  972. /* Update state */
  973. s->current_subsubframe++;
  974. if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
  975. s->current_subsubframe = 0;
  976. s->current_subframe++;
  977. }
  978. if (s->current_subframe >= s->audio_header.subframes) {
  979. /* Read subframe footer */
  980. if ((ret = dca_subframe_footer(s, base_channel)))
  981. return ret;
  982. }
  983. return 0;
  984. }
  985. static float dca_dmix_code(unsigned code)
  986. {
  987. int sign = (code >> 8) - 1;
  988. code &= 0xff;
  989. return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1U << 15));
  990. }
  991. static int scan_for_extensions(AVCodecContext *avctx)
  992. {
  993. DCAContext *s = avctx->priv_data;
  994. int core_ss_end, ret = 0;
  995. core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
  996. /* only scan for extensions if ext_descr was unknown or indicated a
  997. * supported XCh extension */
  998. if (s->core_ext_mask < 0 || s->core_ext_mask & DCA_EXT_XCH) {
  999. /* if ext_descr was unknown, clear s->core_ext_mask so that the
  1000. * extensions scan can fill it up */
  1001. s->core_ext_mask = FFMAX(s->core_ext_mask, 0);
  1002. /* extensions start at 32-bit boundaries into bitstream */
  1003. skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
  1004. while (core_ss_end - get_bits_count(&s->gb) >= 32) {
  1005. uint32_t bits = get_bits_long(&s->gb, 32);
  1006. int i;
  1007. switch (bits) {
  1008. case DCA_SYNCWORD_XCH: {
  1009. int ext_amode, xch_fsize;
  1010. s->xch_base_channel = s->audio_header.prim_channels;
  1011. /* validate sync word using XCHFSIZE field */
  1012. xch_fsize = show_bits(&s->gb, 10);
  1013. if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
  1014. (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
  1015. continue;
  1016. /* skip length-to-end-of-frame field for the moment */
  1017. skip_bits(&s->gb, 10);
  1018. s->core_ext_mask |= DCA_EXT_XCH;
  1019. /* extension amode(number of channels in extension) should be 1 */
  1020. /* AFAIK XCh is not used for more channels */
  1021. if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
  1022. av_log(avctx, AV_LOG_ERROR,
  1023. "XCh extension amode %d not supported!\n",
  1024. ext_amode);
  1025. continue;
  1026. }
  1027. /* much like core primary audio coding header */
  1028. dca_parse_audio_coding_header(s, s->xch_base_channel);
  1029. for (i = 0; i < (s->sample_blocks / 8); i++)
  1030. if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
  1031. av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
  1032. continue;
  1033. }
  1034. s->xch_present = 1;
  1035. break;
  1036. }
  1037. case DCA_SYNCWORD_XXCH:
  1038. /* XXCh: extended channels */
  1039. /* usually found either in core or HD part in DTS-HD HRA streams,
  1040. * but not in DTS-ES which contains XCh extensions instead */
  1041. s->core_ext_mask |= DCA_EXT_XXCH;
  1042. break;
  1043. case 0x1d95f262: {
  1044. int fsize96 = show_bits(&s->gb, 12) + 1;
  1045. if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
  1046. continue;
  1047. av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",
  1048. get_bits_count(&s->gb));
  1049. skip_bits(&s->gb, 12);
  1050. av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
  1051. av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
  1052. s->core_ext_mask |= DCA_EXT_X96;
  1053. break;
  1054. }
  1055. }
  1056. skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
  1057. }
  1058. } else {
  1059. /* no supported extensions, skip the rest of the core substream */
  1060. skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
  1061. }
  1062. if (s->core_ext_mask & DCA_EXT_X96)
  1063. s->profile = FF_PROFILE_DTS_96_24;
  1064. else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))
  1065. s->profile = FF_PROFILE_DTS_ES;
  1066. /* check for ExSS (HD part) */
  1067. if (s->dca_buffer_size - s->frame_size > 32 &&
  1068. get_bits_long(&s->gb, 32) == DCA_SYNCWORD_SUBSTREAM)
  1069. ff_dca_exss_parse_header(s);
  1070. return ret;
  1071. }
  1072. static int set_channel_layout(AVCodecContext *avctx, int channels, int num_core_channels)
  1073. {
  1074. DCAContext *s = avctx->priv_data;
  1075. int i;
  1076. if (s->amode < 16) {
  1077. avctx->channel_layout = dca_core_channel_layout[s->amode];
  1078. if (s->audio_header.prim_channels + !!s->lfe > 2 &&
  1079. avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
  1080. /*
  1081. * Neither the core's auxiliary data nor our default tables contain
  1082. * downmix coefficients for the additional channel coded in the XCh
  1083. * extension, so when we're doing a Stereo downmix, don't decode it.
  1084. */
  1085. s->xch_disable = 1;
  1086. }
  1087. if (s->xch_present && !s->xch_disable) {
  1088. avctx->channel_layout |= AV_CH_BACK_CENTER;
  1089. if (s->lfe) {
  1090. avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
  1091. s->channel_order_tab = ff_dca_channel_reorder_lfe_xch[s->amode];
  1092. } else {
  1093. s->channel_order_tab = ff_dca_channel_reorder_nolfe_xch[s->amode];
  1094. }
  1095. } else {
  1096. channels = num_core_channels + !!s->lfe;
  1097. s->xch_present = 0; /* disable further xch processing */
  1098. if (s->lfe) {
  1099. avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
  1100. s->channel_order_tab = ff_dca_channel_reorder_lfe[s->amode];
  1101. } else
  1102. s->channel_order_tab = ff_dca_channel_reorder_nolfe[s->amode];
  1103. }
  1104. if (channels > !!s->lfe &&
  1105. s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
  1106. return AVERROR_INVALIDDATA;
  1107. if (num_core_channels + !!s->lfe > 2 &&
  1108. avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
  1109. channels = 2;
  1110. s->output = s->audio_header.prim_channels == 2 ? s->amode : DCA_STEREO;
  1111. avctx->channel_layout = AV_CH_LAYOUT_STEREO;
  1112. /* Stereo downmix coefficients
  1113. *
  1114. * The decoder can only downmix to 2-channel, so we need to ensure
  1115. * embedded downmix coefficients are actually targeting 2-channel.
  1116. */
  1117. if (s->core_downmix && (s->core_downmix_amode == DCA_STEREO ||
  1118. s->core_downmix_amode == DCA_STEREO_TOTAL)) {
  1119. for (i = 0; i < num_core_channels + !!s->lfe; i++) {
  1120. /* Range checked earlier */
  1121. s->downmix_coef[i][0] = dca_dmix_code(s->core_downmix_codes[i][0]);
  1122. s->downmix_coef[i][1] = dca_dmix_code(s->core_downmix_codes[i][1]);
  1123. }
  1124. s->output = s->core_downmix_amode;
  1125. } else {
  1126. int am = s->amode & DCA_CHANNEL_MASK;
  1127. if (am >= FF_ARRAY_ELEMS(ff_dca_default_coeffs)) {
  1128. av_log(s->avctx, AV_LOG_ERROR,
  1129. "Invalid channel mode %d\n", am);
  1130. return AVERROR_INVALIDDATA;
  1131. }
  1132. if (num_core_channels + !!s->lfe >
  1133. FF_ARRAY_ELEMS(ff_dca_default_coeffs[0])) {
  1134. avpriv_request_sample(s->avctx, "Downmixing %d channels",
  1135. s->audio_header.prim_channels + !!s->lfe);
  1136. return AVERROR_PATCHWELCOME;
  1137. }
  1138. for (i = 0; i < num_core_channels + !!s->lfe; i++) {
  1139. s->downmix_coef[i][0] = ff_dca_default_coeffs[am][i][0];
  1140. s->downmix_coef[i][1] = ff_dca_default_coeffs[am][i][1];
  1141. }
  1142. }
  1143. ff_dlog(s->avctx, "Stereo downmix coeffs:\n");
  1144. for (i = 0; i < num_core_channels + !!s->lfe; i++) {
  1145. ff_dlog(s->avctx, "L, input channel %d = %f\n", i,
  1146. s->downmix_coef[i][0]);
  1147. ff_dlog(s->avctx, "R, input channel %d = %f\n", i,
  1148. s->downmix_coef[i][1]);
  1149. }
  1150. ff_dlog(s->avctx, "\n");
  1151. }
  1152. } else {
  1153. av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n", s->amode);
  1154. return AVERROR_INVALIDDATA;
  1155. }
  1156. return 0;
  1157. }
  1158. /**
  1159. * Main frame decoding function
  1160. * FIXME add arguments
  1161. */
  1162. static int dca_decode_frame(AVCodecContext *avctx, void *data,
  1163. int *got_frame_ptr, AVPacket *avpkt)
  1164. {
  1165. AVFrame *frame = data;
  1166. const uint8_t *buf = avpkt->data;
  1167. int buf_size = avpkt->size;
  1168. int lfe_samples;
  1169. int num_core_channels = 0;
  1170. int i, ret;
  1171. float **samples_flt;
  1172. DCAContext *s = avctx->priv_data;
  1173. int channels, full_channels;
  1174. int upsample = 0;
  1175. s->exss_ext_mask = 0;
  1176. s->xch_present = 0;
  1177. s->dca_buffer_size = ff_dca_convert_bitstream(buf, buf_size, s->dca_buffer,
  1178. DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);
  1179. if (s->dca_buffer_size == AVERROR_INVALIDDATA) {
  1180. av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
  1181. return AVERROR_INVALIDDATA;
  1182. }
  1183. if ((ret = dca_parse_frame_header(s)) < 0) {
  1184. // seems like the frame is corrupt, try with the next one
  1185. return ret;
  1186. }
  1187. // set AVCodec values with parsed data
  1188. avctx->sample_rate = s->sample_rate;
  1189. avctx->bit_rate = s->bit_rate;
  1190. s->profile = FF_PROFILE_DTS;
  1191. for (i = 0; i < (s->sample_blocks / SAMPLES_PER_SUBBAND); i++) {
  1192. if ((ret = dca_decode_block(s, 0, i))) {
  1193. av_log(avctx, AV_LOG_ERROR, "error decoding block\n");
  1194. return ret;
  1195. }
  1196. }
  1197. /* record number of core channels incase less than max channels are requested */
  1198. num_core_channels = s->audio_header.prim_channels;
  1199. if (s->ext_coding)
  1200. s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];
  1201. else
  1202. s->core_ext_mask = 0;
  1203. ret = scan_for_extensions(avctx);
  1204. avctx->profile = s->profile;
  1205. full_channels = channels = s->audio_header.prim_channels + !!s->lfe;
  1206. ret = set_channel_layout(avctx, channels, num_core_channels);
  1207. if (ret < 0)
  1208. return ret;
  1209. avctx->channels = channels;
  1210. /* get output buffer */
  1211. frame->nb_samples = 256 * (s->sample_blocks / SAMPLES_PER_SUBBAND);
  1212. if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
  1213. int xll_nb_samples = s->xll_segments * s->xll_smpl_in_seg;
  1214. /* Check for invalid/unsupported conditions first */
  1215. if (s->xll_residual_channels > channels) {
  1216. av_log(s->avctx, AV_LOG_WARNING,
  1217. "DCA: too many residual channels (%d, core channels %d). Disabling XLL\n",
  1218. s->xll_residual_channels, channels);
  1219. s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
  1220. } else if (xll_nb_samples != frame->nb_samples &&
  1221. 2 * frame->nb_samples != xll_nb_samples) {
  1222. av_log(s->avctx, AV_LOG_WARNING,
  1223. "DCA: unsupported upsampling (%d XLL samples, %d core samples). Disabling XLL\n",
  1224. xll_nb_samples, frame->nb_samples);
  1225. s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
  1226. } else {
  1227. if (2 * frame->nb_samples == xll_nb_samples) {
  1228. av_log(s->avctx, AV_LOG_INFO,
  1229. "XLL: upsampling core channels by a factor of 2\n");
  1230. upsample = 1;
  1231. frame->nb_samples = xll_nb_samples;
  1232. // FIXME: Is it good enough to copy from the first channel set?
  1233. avctx->sample_rate = s->xll_chsets[0].sampling_frequency;
  1234. }
  1235. /* If downmixing to stereo, don't decode additional channels.
  1236. * FIXME: Using the xch_disable flag for this doesn't seem right. */
  1237. if (!s->xch_disable)
  1238. avctx->channels += s->xll_channels - s->xll_residual_channels;
  1239. }
  1240. }
  1241. /* FIXME: This is an ugly hack, to just revert to the default
  1242. * layout if we have additional channels. Need to convert the XLL
  1243. * channel masks to libav channel_layout mask. */
  1244. if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels)
  1245. avctx->channel_layout = 0;
  1246. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
  1247. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1248. return ret;
  1249. }
  1250. samples_flt = (float **) frame->extended_data;
  1251. /* allocate buffer for extra channels if downmixing */
  1252. if (avctx->channels < full_channels) {
  1253. ret = av_samples_get_buffer_size(NULL, full_channels - channels,
  1254. frame->nb_samples,
  1255. avctx->sample_fmt, 0);
  1256. if (ret < 0)
  1257. return ret;
  1258. av_fast_malloc(&s->extra_channels_buffer,
  1259. &s->extra_channels_buffer_size, ret);
  1260. if (!s->extra_channels_buffer)
  1261. return AVERROR(ENOMEM);
  1262. ret = av_samples_fill_arrays((uint8_t **) s->extra_channels, NULL,
  1263. s->extra_channels_buffer,
  1264. full_channels - channels,
  1265. frame->nb_samples, avctx->sample_fmt, 0);
  1266. if (ret < 0)
  1267. return ret;
  1268. }
  1269. /* filter to get final output */
  1270. for (i = 0; i < (s->sample_blocks / SAMPLES_PER_SUBBAND); i++) {
  1271. int ch;
  1272. unsigned block = upsample ? 512 : 256;
  1273. for (ch = 0; ch < channels; ch++)
  1274. s->samples_chanptr[ch] = samples_flt[ch] + i * block;
  1275. for (; ch < full_channels; ch++)
  1276. s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * block;
  1277. dca_filter_channels(s, i, upsample);
  1278. /* If this was marked as a DTS-ES stream we need to subtract back- */
  1279. /* channel from SL & SR to remove matrixed back-channel signal */
  1280. if ((s->source_pcm_res & 1) && s->xch_present) {
  1281. float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];
  1282. float *lt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];
  1283. float *rt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];
  1284. s->fdsp.vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
  1285. s->fdsp.vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
  1286. }
  1287. }
  1288. /* update lfe history */
  1289. lfe_samples = 2 * s->lfe * (s->sample_blocks / SAMPLES_PER_SUBBAND);
  1290. for (i = 0; i < 2 * s->lfe * 4; i++)
  1291. s->lfe_data[i] = s->lfe_data[i + lfe_samples];
  1292. if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
  1293. ret = ff_dca_xll_decode_audio(s, frame);
  1294. if (ret < 0)
  1295. return ret;
  1296. }
  1297. /* AVMatrixEncoding
  1298. *
  1299. * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */
  1300. ret = ff_side_data_update_matrix_encoding(frame,
  1301. (s->output & ~DCA_LFE) == DCA_STEREO_TOTAL ?
  1302. AV_MATRIX_ENCODING_DOLBY : AV_MATRIX_ENCODING_NONE);
  1303. if (ret < 0)
  1304. return ret;
  1305. *got_frame_ptr = 1;
  1306. return buf_size;
  1307. }
  1308. /**
  1309. * DCA initialization
  1310. *
  1311. * @param avctx pointer to the AVCodecContext
  1312. */
  1313. static av_cold int dca_decode_init(AVCodecContext *avctx)
  1314. {
  1315. DCAContext *s = avctx->priv_data;
  1316. s->avctx = avctx;
  1317. dca_init_vlcs();
  1318. avpriv_float_dsp_init(&s->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
  1319. ff_mdct_init(&s->imdct, 6, 1, 1.0);
  1320. ff_synth_filter_init(&s->synth);
  1321. ff_dcadsp_init(&s->dcadsp);
  1322. ff_fmt_convert_init(&s->fmt_conv, avctx);
  1323. avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  1324. /* allow downmixing to stereo */
  1325. if (avctx->channels > 2 &&
  1326. avctx->request_channel_layout == AV_CH_LAYOUT_STEREO)
  1327. avctx->channels = 2;
  1328. return 0;
  1329. }
  1330. static av_cold int dca_decode_end(AVCodecContext *avctx)
  1331. {
  1332. DCAContext *s = avctx->priv_data;
  1333. ff_mdct_end(&s->imdct);
  1334. av_freep(&s->extra_channels_buffer);
  1335. av_freep(&s->xll_sample_buf);
  1336. av_freep(&s->qmf64_table);
  1337. return 0;
  1338. }
  1339. static const AVProfile profiles[] = {
  1340. { FF_PROFILE_DTS, "DTS" },
  1341. { FF_PROFILE_DTS_ES, "DTS-ES" },
  1342. { FF_PROFILE_DTS_96_24, "DTS 96/24" },
  1343. { FF_PROFILE_DTS_HD_HRA, "DTS-HD HRA" },
  1344. { FF_PROFILE_DTS_HD_MA, "DTS-HD MA" },
  1345. { FF_PROFILE_UNKNOWN },
  1346. };
  1347. static const AVOption options[] = {
  1348. { "disable_xch", "disable decoding of the XCh extension", offsetof(DCAContext, xch_disable), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM },
  1349. { "disable_xll", "disable decoding of the XLL extension", offsetof(DCAContext, xll_disable), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM },
  1350. { NULL },
  1351. };
  1352. static const AVClass dca_decoder_class = {
  1353. .class_name = "DCA decoder",
  1354. .item_name = av_default_item_name,
  1355. .option = options,
  1356. .version = LIBAVUTIL_VERSION_INT,
  1357. };
  1358. AVCodec ff_dca_decoder = {
  1359. .name = "dca",
  1360. .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
  1361. .type = AVMEDIA_TYPE_AUDIO,
  1362. .id = AV_CODEC_ID_DTS,
  1363. .priv_data_size = sizeof(DCAContext),
  1364. .init = dca_decode_init,
  1365. .decode = dca_decode_frame,
  1366. .close = dca_decode_end,
  1367. .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
  1368. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
  1369. AV_SAMPLE_FMT_NONE },
  1370. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1371. .priv_class = &dca_decoder_class,
  1372. };