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.

1607 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 "profiles.h"
  50. #include "put_bits.h"
  51. #include "synth_filter.h"
  52. #if ARCH_ARM
  53. # include "arm/dca.h"
  54. #endif
  55. enum DCAMode {
  56. DCA_MONO = 0,
  57. DCA_CHANNEL,
  58. DCA_STEREO,
  59. DCA_STEREO_SUMDIFF,
  60. DCA_STEREO_TOTAL,
  61. DCA_3F,
  62. DCA_2F1R,
  63. DCA_3F1R,
  64. DCA_2F2R,
  65. DCA_3F2R,
  66. DCA_4F2R
  67. };
  68. /* -1 are reserved or unknown */
  69. static const int dca_ext_audio_descr_mask[] = {
  70. DCA_EXT_XCH,
  71. -1,
  72. DCA_EXT_X96,
  73. DCA_EXT_XCH | DCA_EXT_X96,
  74. -1,
  75. -1,
  76. DCA_EXT_XXCH,
  77. -1,
  78. };
  79. /* Tables for mapping dts channel configurations to libavcodec multichannel api.
  80. * Some compromises have been made for special configurations. Most configurations
  81. * are never used so complete accuracy is not needed.
  82. *
  83. * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
  84. * S -> side, when both rear and back are configured move one of them to the side channel
  85. * OV -> center back
  86. * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
  87. */
  88. static const uint64_t dca_core_channel_layout[] = {
  89. AV_CH_FRONT_CENTER, ///< 1, A
  90. AV_CH_LAYOUT_STEREO, ///< 2, A + B (dual mono)
  91. AV_CH_LAYOUT_STEREO, ///< 2, L + R (stereo)
  92. AV_CH_LAYOUT_STEREO, ///< 2, (L + R) + (L - R) (sum-difference)
  93. AV_CH_LAYOUT_STEREO, ///< 2, LT + RT (left and right total)
  94. AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER, ///< 3, C + L + R
  95. AV_CH_LAYOUT_STEREO | AV_CH_BACK_CENTER, ///< 3, L + R + S
  96. AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER, ///< 4, C + L + R + S
  97. AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT, ///< 4, L + R + SL + SR
  98. AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT |
  99. AV_CH_SIDE_RIGHT, ///< 5, C + L + R + SL + SR
  100. AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
  101. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER, ///< 6, CL + CR + L + R + SL + SR
  102. AV_CH_LAYOUT_STEREO | AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT |
  103. AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER, ///< 6, C + L + R + LR + RR + OV
  104. AV_CH_FRONT_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
  105. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_BACK_CENTER |
  106. AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT, ///< 6, CF + CR + LF + RF + LR + RR
  107. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER |
  108. AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
  109. AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT, ///< 7, CL + C + CR + L + R + SL + SR
  110. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
  111. AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
  112. AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT, ///< 8, CL + CR + L + R + SL1 + SL2 + SR1 + SR2
  113. AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER |
  114. AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
  115. AV_CH_SIDE_LEFT | AV_CH_BACK_CENTER | AV_CH_SIDE_RIGHT, ///< 8, CL + C + CR + L + R + SL + S + SR
  116. };
  117. #define DCA_DOLBY 101 /* FIXME */
  118. #define DCA_CHANNEL_BITS 6
  119. #define DCA_CHANNEL_MASK 0x3F
  120. #define DCA_LFE 0x80
  121. #define HEADER_SIZE 14
  122. #define DCA_NSYNCAUX 0x9A1105A0
  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 uint8_t adj_table[4] = { 16, 18, 20, 23 };
  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] = 16;
  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[DCA_SUBBANDS][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,
  503. float samples_in[DCA_SUBBANDS_X96K][SAMPLES_PER_SUBBAND],
  504. float *samples_out, float scale)
  505. {
  506. float raXin[64];
  507. float A[32], B[32];
  508. float *raX = s->dca_chan[chans].subband_fir_hist;
  509. float *raZ = s->dca_chan[chans].subband_fir_noidea;
  510. unsigned i, j, k, subindex;
  511. for (i = s->audio_header.subband_activity[chans]; i < DCA_SUBBANDS_X96K; i++)
  512. raXin[i] = 0.0;
  513. for (subindex = 0; subindex < SAMPLES_PER_SUBBAND; subindex++) {
  514. for (i = 0; i < s->audio_header.subband_activity[chans]; i++)
  515. raXin[i] = samples_in[i][subindex];
  516. for (k = 0; k < 32; k++) {
  517. A[k] = 0.0;
  518. for (i = 0; i < 32; i++)
  519. A[k] += (raXin[2 * i] + raXin[2 * i + 1]) * s->qmf64_table->dct4_coeff[k][i];
  520. }
  521. for (k = 0; k < 32; k++) {
  522. B[k] = raXin[0] * s->qmf64_table->dct2_coeff[k][0];
  523. for (i = 1; i < 32; i++)
  524. B[k] += (raXin[2 * i] + raXin[2 * i - 1]) * s->qmf64_table->dct2_coeff[k][i];
  525. }
  526. for (k = 0; k < 32; k++) {
  527. raX[k] = s->qmf64_table->rcos[k] * (A[k] + B[k]);
  528. raX[63 - k] = s->qmf64_table->rsin[k] * (A[k] - B[k]);
  529. }
  530. for (i = 0; i < DCA_SUBBANDS_X96K; i++) {
  531. float out = raZ[i];
  532. for (j = 0; j < 1024; j += 128)
  533. out += ff_dca_fir_64bands[j + i] * (raX[j + i] - raX[j + 63 - i]);
  534. *samples_out++ = out * scale;
  535. }
  536. for (i = 0; i < DCA_SUBBANDS_X96K; i++) {
  537. float hist = 0.0;
  538. for (j = 0; j < 1024; j += 128)
  539. hist += ff_dca_fir_64bands[64 + j + i] * (-raX[i + j] - raX[j + 63 - i]);
  540. raZ[i] = hist;
  541. }
  542. /* FIXME: Make buffer circular, to avoid this move. */
  543. memmove(raX + 64, raX, (1024 - 64) * sizeof(*raX));
  544. }
  545. }
  546. static void lfe_interpolation_fir(DCAContext *s, const float *samples_in,
  547. float *samples_out)
  548. {
  549. /* samples_in: An array holding decimated samples.
  550. * Samples in current subframe starts from samples_in[0],
  551. * while samples_in[-1], samples_in[-2], ..., stores samples
  552. * from last subframe as history.
  553. *
  554. * samples_out: An array holding interpolated samples
  555. */
  556. int idx;
  557. const float *prCoeff;
  558. int deciindex;
  559. /* Select decimation filter */
  560. if (s->lfe == 1) {
  561. idx = 1;
  562. prCoeff = ff_dca_lfe_fir_128;
  563. } else {
  564. idx = 0;
  565. if (s->exss_ext_mask & DCA_EXT_EXSS_XLL)
  566. prCoeff = ff_dca_lfe_xll_fir_64;
  567. else
  568. prCoeff = ff_dca_lfe_fir_64;
  569. }
  570. /* Interpolation */
  571. for (deciindex = 0; deciindex < 2 * s->lfe; deciindex++) {
  572. s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
  573. samples_in++;
  574. samples_out += 2 * 32 * (1 + idx);
  575. }
  576. }
  577. /* downmixing routines */
  578. #define MIX_REAR1(samples, s1, rs, coef) \
  579. samples[0][i] += samples[s1][i] * coef[rs][0]; \
  580. samples[1][i] += samples[s1][i] * coef[rs][1];
  581. #define MIX_REAR2(samples, s1, s2, rs, coef) \
  582. samples[0][i] += samples[s1][i] * coef[rs][0] + samples[s2][i] * coef[rs + 1][0]; \
  583. samples[1][i] += samples[s1][i] * coef[rs][1] + samples[s2][i] * coef[rs + 1][1];
  584. #define MIX_FRONT3(samples, coef) \
  585. t = samples[c][i]; \
  586. u = samples[l][i]; \
  587. v = samples[r][i]; \
  588. samples[0][i] = t * coef[0][0] + u * coef[1][0] + v * coef[2][0]; \
  589. samples[1][i] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
  590. #define DOWNMIX_TO_STEREO(op1, op2) \
  591. for (i = 0; i < 256; i++) { \
  592. op1 \
  593. op2 \
  594. }
  595. static void dca_downmix(float **samples, int srcfmt, int lfe_present,
  596. float coef[DCA_PRIM_CHANNELS_MAX + 1][2],
  597. const int8_t *channel_mapping)
  598. {
  599. int c, l, r, sl, sr, s;
  600. int i;
  601. float t, u, v;
  602. switch (srcfmt) {
  603. case DCA_MONO:
  604. case DCA_4F2R:
  605. av_log(NULL, 0, "Not implemented!\n");
  606. break;
  607. case DCA_CHANNEL:
  608. case DCA_STEREO:
  609. case DCA_STEREO_TOTAL:
  610. case DCA_STEREO_SUMDIFF:
  611. break;
  612. case DCA_3F:
  613. c = channel_mapping[0];
  614. l = channel_mapping[1];
  615. r = channel_mapping[2];
  616. DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
  617. break;
  618. case DCA_2F1R:
  619. s = channel_mapping[2];
  620. DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );
  621. break;
  622. case DCA_3F1R:
  623. c = channel_mapping[0];
  624. l = channel_mapping[1];
  625. r = channel_mapping[2];
  626. s = channel_mapping[3];
  627. DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
  628. MIX_REAR1(samples, s, 3, coef));
  629. break;
  630. case DCA_2F2R:
  631. sl = channel_mapping[2];
  632. sr = channel_mapping[3];
  633. DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );
  634. break;
  635. case DCA_3F2R:
  636. c = channel_mapping[0];
  637. l = channel_mapping[1];
  638. r = channel_mapping[2];
  639. sl = channel_mapping[3];
  640. sr = channel_mapping[4];
  641. DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
  642. MIX_REAR2(samples, sl, sr, 3, coef));
  643. break;
  644. }
  645. if (lfe_present) {
  646. int lf_buf = ff_dca_lfe_index[srcfmt];
  647. int lf_idx = ff_dca_channels[srcfmt];
  648. for (i = 0; i < 256; i++) {
  649. samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];
  650. samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];
  651. }
  652. }
  653. }
  654. #ifndef decode_blockcodes
  655. /* Very compact version of the block code decoder that does not use table
  656. * look-up but is slightly slower */
  657. static int decode_blockcode(int code, int levels, int32_t *values)
  658. {
  659. int i;
  660. int offset = (levels - 1) >> 1;
  661. for (i = 0; i < 4; i++) {
  662. int div = FASTDIV(code, levels);
  663. values[i] = code - offset - div * levels;
  664. code = div;
  665. }
  666. return code;
  667. }
  668. static int decode_blockcodes(int code1, int code2, int levels, int32_t *values)
  669. {
  670. return decode_blockcode(code1, levels, values) |
  671. decode_blockcode(code2, levels, values + 4);
  672. }
  673. #endif
  674. static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
  675. static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
  676. static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
  677. {
  678. int k, l;
  679. int subsubframe = s->current_subsubframe;
  680. const uint32_t *quant_step_table;
  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;
  687. else
  688. quant_step_table = ff_dca_lossy_quant;
  689. for (k = base_channel; k < s->audio_header.prim_channels; k++) {
  690. int32_t (*subband_samples)[8] = s->dca_chan[k].subband_samples[block_index];
  691. if (get_bits_left(&s->gb) < 0)
  692. return AVERROR_INVALIDDATA;
  693. for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
  694. int m;
  695. /* Select the mid-tread linear quantizer */
  696. int abits = s->dca_chan[k].bitalloc[l];
  697. uint32_t quant_step_size = quant_step_table[abits];
  698. /*
  699. * Extract bits from the bit stream
  700. */
  701. if (!abits)
  702. memset(subband_samples[l], 0, SAMPLES_PER_SUBBAND *
  703. sizeof(subband_samples[l][0]));
  704. else {
  705. uint32_t rscale;
  706. /* Deal with transients */
  707. int sfi = s->dca_chan[k].transition_mode[l] &&
  708. subsubframe >= s->dca_chan[k].transition_mode[l];
  709. /* Determine quantization index code book and its type.
  710. Select quantization index code book */
  711. int sel = s->audio_header.quant_index_huffman[k][abits];
  712. rscale = (s->dca_chan[k].scale_factor[l][sfi] *
  713. s->audio_header.scalefactor_adj[k][sel] + 8) >> 4;
  714. if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
  715. if (abits <= 7) {
  716. /* Block code */
  717. int block_code1, block_code2, size, levels, err;
  718. size = abits_sizes[abits - 1];
  719. levels = abits_levels[abits - 1];
  720. block_code1 = get_bits(&s->gb, size);
  721. block_code2 = get_bits(&s->gb, size);
  722. err = decode_blockcodes(block_code1, block_code2,
  723. levels, subband_samples[l]);
  724. if (err) {
  725. av_log(s->avctx, AV_LOG_ERROR,
  726. "ERROR: block code look-up failed\n");
  727. return AVERROR_INVALIDDATA;
  728. }
  729. } else {
  730. /* no coding */
  731. for (m = 0; m < SAMPLES_PER_SUBBAND; m++)
  732. subband_samples[l][m] = get_sbits(&s->gb, abits - 3);
  733. }
  734. } else {
  735. /* Huffman coded */
  736. for (m = 0; m < SAMPLES_PER_SUBBAND; m++)
  737. subband_samples[l][m] = get_bitalloc(&s->gb,
  738. &dca_smpl_bitalloc[abits], sel);
  739. }
  740. s->dcadsp.dequantize(subband_samples[l], quant_step_size, rscale);
  741. }
  742. }
  743. for (l = 0; l < s->audio_header.vq_start_subband[k]; l++) {
  744. int m;
  745. /*
  746. * Inverse ADPCM if in prediction mode
  747. */
  748. if (s->dca_chan[k].prediction_mode[l]) {
  749. int n;
  750. if (s->predictor_history)
  751. subband_samples[l][0] += (ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][0] *
  752. (int64_t)s->dca_chan[k].subband_samples_hist[l][3] +
  753. ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][1] *
  754. (int64_t)s->dca_chan[k].subband_samples_hist[l][2] +
  755. ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][2] *
  756. (int64_t)s->dca_chan[k].subband_samples_hist[l][1] +
  757. ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][3] *
  758. (int64_t)s->dca_chan[k].subband_samples_hist[l][0]) +
  759. (1 << 12) >> 13;
  760. for (m = 1; m < SAMPLES_PER_SUBBAND; m++) {
  761. int64_t sum = ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][0] *
  762. (int64_t)subband_samples[l][m - 1];
  763. for (n = 2; n <= 4; n++)
  764. if (m >= n)
  765. sum += ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][n - 1] *
  766. (int64_t)subband_samples[l][m - n];
  767. else if (s->predictor_history)
  768. sum += ff_dca_adpcm_vb[s->dca_chan[k].prediction_vq[l]][n - 1] *
  769. (int64_t)s->dca_chan[k].subband_samples_hist[l][m - n + 4];
  770. subband_samples[l][m] += (int32_t)(sum + (1 << 12) >> 13);
  771. }
  772. }
  773. }
  774. /* Backup predictor history for adpcm */
  775. for (l = 0; l < DCA_SUBBANDS; l++)
  776. AV_COPY128(s->dca_chan[k].subband_samples_hist[l], &subband_samples[l][4]);
  777. /*
  778. * Decode VQ encoded high frequencies
  779. */
  780. if (s->audio_header.subband_activity[k] > s->audio_header.vq_start_subband[k]) {
  781. if (!s->debug_flag & 0x01) {
  782. av_log(s->avctx, AV_LOG_DEBUG,
  783. "Stream with high frequencies VQ coding\n");
  784. s->debug_flag |= 0x01;
  785. }
  786. s->dcadsp.decode_hf(subband_samples, s->dca_chan[k].high_freq_vq,
  787. ff_dca_high_freq_vq,
  788. subsubframe * SAMPLES_PER_SUBBAND,
  789. s->dca_chan[k].scale_factor,
  790. s->audio_header.vq_start_subband[k],
  791. s->audio_header.subband_activity[k]);
  792. }
  793. }
  794. /* Check for DSYNC after subsubframe */
  795. if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
  796. if (get_bits(&s->gb, 16) != 0xFFFF) {
  797. av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
  798. return AVERROR_INVALIDDATA;
  799. }
  800. }
  801. return 0;
  802. }
  803. static int dca_filter_channels(DCAContext *s, int block_index, int upsample, int downmix)
  804. {
  805. int k;
  806. if (upsample) {
  807. LOCAL_ALIGNED(32, float, samples, [DCA_SUBBANDS_X96K], [SAMPLES_PER_SUBBAND]);
  808. if (!s->qmf64_table) {
  809. s->qmf64_table = qmf64_precompute();
  810. if (!s->qmf64_table)
  811. return AVERROR(ENOMEM);
  812. }
  813. /* 64 subbands QMF */
  814. for (k = 0; k < s->audio_header.prim_channels; k++) {
  815. int channel = s->channel_order_tab[k];
  816. int32_t (*subband_samples)[SAMPLES_PER_SUBBAND] =
  817. s->dca_chan[k].subband_samples[block_index];
  818. s->fmt_conv.int32_to_float(samples[0], subband_samples[0],
  819. DCA_SUBBANDS_X96K * SAMPLES_PER_SUBBAND);
  820. if (channel >= 0)
  821. qmf_64_subbands(s, k, samples,
  822. s->samples_chanptr[channel],
  823. /* Upsampling needs a factor 2 here. */
  824. M_SQRT2 / 32768.0);
  825. }
  826. } else {
  827. /* 32 subbands QMF */
  828. LOCAL_ALIGNED(32, float, samples, [DCA_SUBBANDS], [SAMPLES_PER_SUBBAND]);
  829. for (k = 0; k < s->audio_header.prim_channels; k++) {
  830. int channel = s->channel_order_tab[k];
  831. int32_t (*subband_samples)[SAMPLES_PER_SUBBAND] =
  832. s->dca_chan[k].subband_samples[block_index];
  833. s->fmt_conv.int32_to_float(samples[0], subband_samples[0],
  834. DCA_SUBBANDS * SAMPLES_PER_SUBBAND);
  835. if (channel >= 0)
  836. qmf_32_subbands(s, k, samples,
  837. s->samples_chanptr[channel],
  838. M_SQRT1_2 / 32768.0);
  839. }
  840. }
  841. /* Generate LFE samples for this subsubframe FIXME!!! */
  842. if (s->lfe) {
  843. float *samples = s->samples_chanptr[ff_dca_lfe_index[s->amode]];
  844. lfe_interpolation_fir(s,
  845. s->lfe_data + 2 * s->lfe * (block_index + 4),
  846. samples);
  847. if (upsample) {
  848. unsigned i;
  849. /* Should apply the filter in Table 6-11 when upsampling. For
  850. * now, just duplicate. */
  851. for (i = 511; i > 0; i--) {
  852. samples[2 * i] =
  853. samples[2 * i + 1] = samples[i];
  854. }
  855. samples[1] = samples[0];
  856. }
  857. }
  858. /* FIXME: This downmixing is probably broken with upsample.
  859. * Probably totally broken also with XLL in general. */
  860. /* Downmixing to Stereo */
  861. if (downmix) {
  862. dca_downmix(s->samples_chanptr, s->amode, !!s->lfe, s->downmix_coef,
  863. s->channel_order_tab);
  864. }
  865. return 0;
  866. }
  867. static int dca_subframe_footer(DCAContext *s, int base_channel)
  868. {
  869. int in, out, aux_data_count, aux_data_end, reserved;
  870. uint32_t nsyncaux;
  871. /*
  872. * Unpack optional information
  873. */
  874. /* presumably optional information only appears in the core? */
  875. if (!base_channel) {
  876. if (s->timestamp)
  877. skip_bits_long(&s->gb, 32);
  878. if (s->aux_data) {
  879. aux_data_count = get_bits(&s->gb, 6);
  880. // align (32-bit)
  881. skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
  882. aux_data_end = 8 * aux_data_count + get_bits_count(&s->gb);
  883. if ((nsyncaux = get_bits_long(&s->gb, 32)) != DCA_NSYNCAUX) {
  884. av_log(s->avctx, AV_LOG_ERROR, "nSYNCAUX mismatch %#"PRIx32"\n",
  885. nsyncaux);
  886. return AVERROR_INVALIDDATA;
  887. }
  888. if (get_bits1(&s->gb)) { // bAUXTimeStampFlag
  889. avpriv_request_sample(s->avctx,
  890. "Auxiliary Decode Time Stamp Flag");
  891. // align (4-bit)
  892. skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 4);
  893. // 44 bits: nMSByte (8), nMarker (4), nLSByte (28), nMarker (4)
  894. skip_bits_long(&s->gb, 44);
  895. }
  896. if ((s->core_downmix = get_bits1(&s->gb))) {
  897. int am = get_bits(&s->gb, 3);
  898. switch (am) {
  899. case 0:
  900. s->core_downmix_amode = DCA_MONO;
  901. break;
  902. case 1:
  903. s->core_downmix_amode = DCA_STEREO;
  904. break;
  905. case 2:
  906. s->core_downmix_amode = DCA_STEREO_TOTAL;
  907. break;
  908. case 3:
  909. s->core_downmix_amode = DCA_3F;
  910. break;
  911. case 4:
  912. s->core_downmix_amode = DCA_2F1R;
  913. break;
  914. case 5:
  915. s->core_downmix_amode = DCA_2F2R;
  916. break;
  917. case 6:
  918. s->core_downmix_amode = DCA_3F1R;
  919. break;
  920. default:
  921. av_log(s->avctx, AV_LOG_ERROR,
  922. "Invalid mode %d for embedded downmix coefficients\n",
  923. am);
  924. return AVERROR_INVALIDDATA;
  925. }
  926. for (out = 0; out < ff_dca_channels[s->core_downmix_amode]; out++) {
  927. for (in = 0; in < s->audio_header.prim_channels + !!s->lfe; in++) {
  928. uint16_t tmp = get_bits(&s->gb, 9);
  929. if ((tmp & 0xFF) > 241) {
  930. av_log(s->avctx, AV_LOG_ERROR,
  931. "Invalid downmix coefficient code %"PRIu16"\n",
  932. tmp);
  933. return AVERROR_INVALIDDATA;
  934. }
  935. s->core_downmix_codes[in][out] = tmp;
  936. }
  937. }
  938. }
  939. align_get_bits(&s->gb); // byte align
  940. skip_bits(&s->gb, 16); // nAUXCRC16
  941. /*
  942. * additional data (reserved, cf. ETSI TS 102 114 V1.4.1)
  943. *
  944. * Note: don't check for overreads, aux_data_count can't be trusted.
  945. */
  946. if ((reserved = (aux_data_end - get_bits_count(&s->gb))) > 0) {
  947. avpriv_request_sample(s->avctx,
  948. "Core auxiliary data reserved content");
  949. skip_bits_long(&s->gb, reserved);
  950. }
  951. }
  952. if (s->crc_present && s->dynrange)
  953. get_bits(&s->gb, 16);
  954. }
  955. return 0;
  956. }
  957. /**
  958. * Decode a dca frame block
  959. *
  960. * @param s pointer to the DCAContext
  961. */
  962. static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
  963. {
  964. int ret;
  965. /* Sanity check */
  966. if (s->current_subframe >= s->audio_header.subframes) {
  967. av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
  968. s->current_subframe, s->audio_header.subframes);
  969. return AVERROR_INVALIDDATA;
  970. }
  971. if (!s->current_subsubframe) {
  972. /* Read subframe header */
  973. if ((ret = dca_subframe_header(s, base_channel, block_index)))
  974. return ret;
  975. }
  976. /* Read subsubframe */
  977. if ((ret = dca_subsubframe(s, base_channel, block_index)))
  978. return ret;
  979. /* Update state */
  980. s->current_subsubframe++;
  981. if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
  982. s->current_subsubframe = 0;
  983. s->current_subframe++;
  984. }
  985. if (s->current_subframe >= s->audio_header.subframes) {
  986. /* Read subframe footer */
  987. if ((ret = dca_subframe_footer(s, base_channel)))
  988. return ret;
  989. }
  990. return 0;
  991. }
  992. static float dca_dmix_code(unsigned code)
  993. {
  994. int sign = (code >> 8) - 1;
  995. code &= 0xff;
  996. return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1U << 15));
  997. }
  998. static int scan_for_extensions(AVCodecContext *avctx)
  999. {
  1000. DCAContext *s = avctx->priv_data;
  1001. int core_ss_end, ret = 0;
  1002. core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
  1003. /* only scan for extensions if ext_descr was unknown or indicated a
  1004. * supported XCh extension */
  1005. if (s->core_ext_mask < 0 || s->core_ext_mask & DCA_EXT_XCH) {
  1006. /* if ext_descr was unknown, clear s->core_ext_mask so that the
  1007. * extensions scan can fill it up */
  1008. s->core_ext_mask = FFMAX(s->core_ext_mask, 0);
  1009. /* extensions start at 32-bit boundaries into bitstream */
  1010. skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
  1011. while (core_ss_end - get_bits_count(&s->gb) >= 32) {
  1012. uint32_t bits = get_bits_long(&s->gb, 32);
  1013. int i;
  1014. switch (bits) {
  1015. case DCA_SYNCWORD_XCH: {
  1016. int ext_amode, xch_fsize;
  1017. s->xch_base_channel = s->audio_header.prim_channels;
  1018. /* validate sync word using XCHFSIZE field */
  1019. xch_fsize = show_bits(&s->gb, 10);
  1020. if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
  1021. (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
  1022. continue;
  1023. /* skip length-to-end-of-frame field for the moment */
  1024. skip_bits(&s->gb, 10);
  1025. s->core_ext_mask |= DCA_EXT_XCH;
  1026. /* extension amode(number of channels in extension) should be 1 */
  1027. /* AFAIK XCh is not used for more channels */
  1028. if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
  1029. av_log(avctx, AV_LOG_ERROR,
  1030. "XCh extension amode %d not supported!\n",
  1031. ext_amode);
  1032. continue;
  1033. }
  1034. /* much like core primary audio coding header */
  1035. dca_parse_audio_coding_header(s, s->xch_base_channel);
  1036. for (i = 0; i < (s->sample_blocks / 8); i++)
  1037. if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
  1038. av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
  1039. continue;
  1040. }
  1041. s->xch_present = 1;
  1042. break;
  1043. }
  1044. case DCA_SYNCWORD_XXCH:
  1045. /* XXCh: extended channels */
  1046. /* usually found either in core or HD part in DTS-HD HRA streams,
  1047. * but not in DTS-ES which contains XCh extensions instead */
  1048. s->core_ext_mask |= DCA_EXT_XXCH;
  1049. break;
  1050. case 0x1d95f262: {
  1051. int fsize96 = show_bits(&s->gb, 12) + 1;
  1052. if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
  1053. continue;
  1054. av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",
  1055. get_bits_count(&s->gb));
  1056. skip_bits(&s->gb, 12);
  1057. av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
  1058. av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
  1059. s->core_ext_mask |= DCA_EXT_X96;
  1060. break;
  1061. }
  1062. }
  1063. skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
  1064. }
  1065. } else {
  1066. /* no supported extensions, skip the rest of the core substream */
  1067. skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
  1068. }
  1069. if (s->core_ext_mask & DCA_EXT_X96)
  1070. s->profile = FF_PROFILE_DTS_96_24;
  1071. else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))
  1072. s->profile = FF_PROFILE_DTS_ES;
  1073. /* check for ExSS (HD part) */
  1074. if (s->dca_buffer_size - s->frame_size > 32 &&
  1075. get_bits_long(&s->gb, 32) == DCA_SYNCWORD_SUBSTREAM)
  1076. ff_dca_exss_parse_header(s);
  1077. return ret;
  1078. }
  1079. static int set_channel_layout(AVCodecContext *avctx, int channels)
  1080. {
  1081. DCAContext *s = avctx->priv_data;
  1082. int num_core_channels = s->audio_header.prim_channels;
  1083. int i;
  1084. if (s->amode < 16) {
  1085. avctx->channel_layout = dca_core_channel_layout[s->amode];
  1086. if (s->audio_header.prim_channels + !!s->lfe > 2 &&
  1087. avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
  1088. /*
  1089. * Neither the core's auxiliary data nor our default tables contain
  1090. * downmix coefficients for the additional channel coded in the XCh
  1091. * extension, so when we're doing a Stereo downmix, don't decode it.
  1092. */
  1093. s->xch_disable = 1;
  1094. }
  1095. if (s->xch_present && !s->xch_disable) {
  1096. avctx->channel_layout |= AV_CH_BACK_CENTER;
  1097. if (s->lfe) {
  1098. avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
  1099. s->channel_order_tab = ff_dca_channel_reorder_lfe_xch[s->amode];
  1100. } else {
  1101. s->channel_order_tab = ff_dca_channel_reorder_nolfe_xch[s->amode];
  1102. }
  1103. } else {
  1104. channels = num_core_channels + !!s->lfe;
  1105. s->xch_present = 0; /* disable further xch processing */
  1106. if (s->lfe) {
  1107. avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
  1108. s->channel_order_tab = ff_dca_channel_reorder_lfe[s->amode];
  1109. } else
  1110. s->channel_order_tab = ff_dca_channel_reorder_nolfe[s->amode];
  1111. }
  1112. if (channels < ff_dca_channels[s->amode] + !!s->lfe)
  1113. return AVERROR_INVALIDDATA;
  1114. if (channels > !!s->lfe &&
  1115. s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
  1116. return AVERROR_INVALIDDATA;
  1117. if (num_core_channels + !!s->lfe > 2 &&
  1118. avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
  1119. channels = 2;
  1120. s->output = s->audio_header.prim_channels == 2 ? s->amode : DCA_STEREO;
  1121. avctx->channel_layout = AV_CH_LAYOUT_STEREO;
  1122. /* Stereo downmix coefficients
  1123. *
  1124. * The decoder can only downmix to 2-channel, so we need to ensure
  1125. * embedded downmix coefficients are actually targeting 2-channel.
  1126. */
  1127. if (s->core_downmix && (s->core_downmix_amode == DCA_STEREO ||
  1128. s->core_downmix_amode == DCA_STEREO_TOTAL)) {
  1129. for (i = 0; i < num_core_channels + !!s->lfe; i++) {
  1130. /* Range checked earlier */
  1131. s->downmix_coef[i][0] = dca_dmix_code(s->core_downmix_codes[i][0]);
  1132. s->downmix_coef[i][1] = dca_dmix_code(s->core_downmix_codes[i][1]);
  1133. }
  1134. s->output = s->core_downmix_amode;
  1135. } else {
  1136. int am = s->amode & DCA_CHANNEL_MASK;
  1137. if (am >= FF_ARRAY_ELEMS(ff_dca_default_coeffs)) {
  1138. av_log(s->avctx, AV_LOG_ERROR,
  1139. "Invalid channel mode %d\n", am);
  1140. return AVERROR_INVALIDDATA;
  1141. }
  1142. if (num_core_channels + !!s->lfe >
  1143. FF_ARRAY_ELEMS(ff_dca_default_coeffs[0])) {
  1144. avpriv_request_sample(s->avctx, "Downmixing %d channels",
  1145. s->audio_header.prim_channels + !!s->lfe);
  1146. return AVERROR_PATCHWELCOME;
  1147. }
  1148. for (i = 0; i < num_core_channels + !!s->lfe; i++) {
  1149. s->downmix_coef[i][0] = ff_dca_default_coeffs[am][i][0];
  1150. s->downmix_coef[i][1] = ff_dca_default_coeffs[am][i][1];
  1151. }
  1152. }
  1153. ff_dlog(s->avctx, "Stereo downmix coeffs:\n");
  1154. for (i = 0; i < num_core_channels + !!s->lfe; i++) {
  1155. ff_dlog(s->avctx, "L, input channel %d = %f\n", i,
  1156. s->downmix_coef[i][0]);
  1157. ff_dlog(s->avctx, "R, input channel %d = %f\n", i,
  1158. s->downmix_coef[i][1]);
  1159. }
  1160. ff_dlog(s->avctx, "\n");
  1161. }
  1162. } else {
  1163. av_log(avctx, AV_LOG_ERROR, "Nonstandard configuration %d !\n", s->amode);
  1164. return AVERROR_INVALIDDATA;
  1165. }
  1166. return 0;
  1167. }
  1168. /**
  1169. * Main frame decoding function
  1170. * FIXME add arguments
  1171. */
  1172. static int dca_decode_frame(AVCodecContext *avctx, void *data,
  1173. int *got_frame_ptr, AVPacket *avpkt)
  1174. {
  1175. AVFrame *frame = data;
  1176. const uint8_t *buf = avpkt->data;
  1177. int buf_size = avpkt->size;
  1178. int lfe_samples;
  1179. int i, ret;
  1180. float **samples_flt;
  1181. DCAContext *s = avctx->priv_data;
  1182. int channels, full_channels;
  1183. int upsample = 0;
  1184. int downmix;
  1185. s->exss_ext_mask = 0;
  1186. s->xch_present = 0;
  1187. s->dca_buffer_size = ff_dca_convert_bitstream(buf, buf_size, s->dca_buffer,
  1188. DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);
  1189. if (s->dca_buffer_size == AVERROR_INVALIDDATA) {
  1190. av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
  1191. return AVERROR_INVALIDDATA;
  1192. }
  1193. if ((ret = dca_parse_frame_header(s)) < 0) {
  1194. // seems like the frame is corrupt, try with the next one
  1195. return ret;
  1196. }
  1197. // set AVCodec values with parsed data
  1198. avctx->sample_rate = s->sample_rate;
  1199. avctx->bit_rate = s->bit_rate;
  1200. s->profile = FF_PROFILE_DTS;
  1201. for (i = 0; i < (s->sample_blocks / SAMPLES_PER_SUBBAND); i++) {
  1202. if ((ret = dca_decode_block(s, 0, i))) {
  1203. av_log(avctx, AV_LOG_ERROR, "error decoding block\n");
  1204. return ret;
  1205. }
  1206. }
  1207. if (s->ext_coding)
  1208. s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];
  1209. else
  1210. s->core_ext_mask = 0;
  1211. ret = scan_for_extensions(avctx);
  1212. avctx->profile = s->profile;
  1213. full_channels = channels = s->audio_header.prim_channels + !!s->lfe;
  1214. ret = set_channel_layout(avctx, channels);
  1215. if (ret < 0)
  1216. return ret;
  1217. avctx->channels = channels;
  1218. /* get output buffer */
  1219. frame->nb_samples = 256 * (s->sample_blocks / SAMPLES_PER_SUBBAND);
  1220. if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
  1221. int xll_nb_samples = s->xll_segments * s->xll_smpl_in_seg;
  1222. /* Check for invalid/unsupported conditions first */
  1223. if (s->xll_residual_channels > channels) {
  1224. av_log(s->avctx, AV_LOG_WARNING,
  1225. "DCA: too many residual channels (%d, core channels %d). Disabling XLL\n",
  1226. s->xll_residual_channels, channels);
  1227. s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
  1228. } else if (xll_nb_samples != frame->nb_samples &&
  1229. 2 * frame->nb_samples != xll_nb_samples) {
  1230. av_log(s->avctx, AV_LOG_WARNING,
  1231. "DCA: unsupported upsampling (%d XLL samples, %d core samples). Disabling XLL\n",
  1232. xll_nb_samples, frame->nb_samples);
  1233. s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
  1234. } else {
  1235. if (2 * frame->nb_samples == xll_nb_samples) {
  1236. av_log(s->avctx, AV_LOG_INFO,
  1237. "XLL: upsampling core channels by a factor of 2\n");
  1238. upsample = 1;
  1239. frame->nb_samples = xll_nb_samples;
  1240. // FIXME: Is it good enough to copy from the first channel set?
  1241. avctx->sample_rate = s->xll_chsets[0].sampling_frequency;
  1242. }
  1243. /* If downmixing to stereo, don't decode additional channels.
  1244. * FIXME: Using the xch_disable flag for this doesn't seem right. */
  1245. if (!s->xch_disable)
  1246. avctx->channels += s->xll_channels - s->xll_residual_channels;
  1247. }
  1248. }
  1249. /* FIXME: This is an ugly hack, to just revert to the default
  1250. * layout if we have additional channels. Need to convert the XLL
  1251. * channel masks to libav channel_layout mask. */
  1252. if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels)
  1253. avctx->channel_layout = 0;
  1254. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
  1255. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1256. return ret;
  1257. }
  1258. samples_flt = (float **) frame->extended_data;
  1259. /* allocate buffer for extra channels if downmixing */
  1260. if (avctx->channels < full_channels) {
  1261. ret = av_samples_get_buffer_size(NULL, full_channels - channels,
  1262. frame->nb_samples,
  1263. avctx->sample_fmt, 0);
  1264. if (ret < 0)
  1265. return ret;
  1266. av_fast_malloc(&s->extra_channels_buffer,
  1267. &s->extra_channels_buffer_size, ret);
  1268. if (!s->extra_channels_buffer)
  1269. return AVERROR(ENOMEM);
  1270. ret = av_samples_fill_arrays((uint8_t **) s->extra_channels, NULL,
  1271. s->extra_channels_buffer,
  1272. full_channels - channels,
  1273. frame->nb_samples, avctx->sample_fmt, 0);
  1274. if (ret < 0)
  1275. return ret;
  1276. }
  1277. downmix = s->audio_header.prim_channels > 2 &&
  1278. avctx->request_channel_layout == AV_CH_LAYOUT_STEREO;
  1279. /* filter to get final output */
  1280. for (i = 0; i < (s->sample_blocks / SAMPLES_PER_SUBBAND); i++) {
  1281. int ch;
  1282. unsigned block = upsample ? 512 : 256;
  1283. for (ch = 0; ch < channels; ch++)
  1284. s->samples_chanptr[ch] = samples_flt[ch] + i * block;
  1285. for (; ch < full_channels; ch++)
  1286. s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * block;
  1287. dca_filter_channels(s, i, upsample, downmix);
  1288. /* If this was marked as a DTS-ES stream we need to subtract back- */
  1289. /* channel from SL & SR to remove matrixed back-channel signal */
  1290. if ((s->source_pcm_res & 1) && s->xch_present) {
  1291. float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];
  1292. float *lt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];
  1293. float *rt_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];
  1294. s->fdsp.vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
  1295. s->fdsp.vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
  1296. }
  1297. }
  1298. /* update lfe history */
  1299. lfe_samples = 2 * s->lfe * (s->sample_blocks / SAMPLES_PER_SUBBAND);
  1300. for (i = 0; i < 2 * s->lfe * 4; i++)
  1301. s->lfe_data[i] = s->lfe_data[i + lfe_samples];
  1302. if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
  1303. ret = ff_dca_xll_decode_audio(s, frame);
  1304. if (ret < 0)
  1305. return ret;
  1306. }
  1307. /* AVMatrixEncoding
  1308. *
  1309. * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */
  1310. ret = ff_side_data_update_matrix_encoding(frame,
  1311. (s->output & ~DCA_LFE) == DCA_STEREO_TOTAL ?
  1312. AV_MATRIX_ENCODING_DOLBY : AV_MATRIX_ENCODING_NONE);
  1313. if (ret < 0)
  1314. return ret;
  1315. *got_frame_ptr = 1;
  1316. return buf_size;
  1317. }
  1318. /**
  1319. * DCA initialization
  1320. *
  1321. * @param avctx pointer to the AVCodecContext
  1322. */
  1323. static av_cold int dca_decode_init(AVCodecContext *avctx)
  1324. {
  1325. DCAContext *s = avctx->priv_data;
  1326. s->avctx = avctx;
  1327. dca_init_vlcs();
  1328. avpriv_float_dsp_init(&s->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
  1329. ff_mdct_init(&s->imdct, 6, 1, 1.0);
  1330. ff_synth_filter_init(&s->synth);
  1331. ff_dcadsp_init(&s->dcadsp);
  1332. ff_fmt_convert_init(&s->fmt_conv, avctx);
  1333. avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  1334. /* allow downmixing to stereo */
  1335. if (avctx->channels > 2 &&
  1336. avctx->request_channel_layout == AV_CH_LAYOUT_STEREO)
  1337. avctx->channels = 2;
  1338. return 0;
  1339. }
  1340. static av_cold int dca_decode_end(AVCodecContext *avctx)
  1341. {
  1342. DCAContext *s = avctx->priv_data;
  1343. ff_mdct_end(&s->imdct);
  1344. av_freep(&s->extra_channels_buffer);
  1345. av_freep(&s->xll_sample_buf);
  1346. av_freep(&s->qmf64_table);
  1347. return 0;
  1348. }
  1349. static const AVOption options[] = {
  1350. { "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 },
  1351. { "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 },
  1352. { NULL },
  1353. };
  1354. static const AVClass dca_decoder_class = {
  1355. .class_name = "DCA decoder",
  1356. .item_name = av_default_item_name,
  1357. .option = options,
  1358. .version = LIBAVUTIL_VERSION_INT,
  1359. };
  1360. AVCodec ff_dca_decoder = {
  1361. .name = "dca",
  1362. .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
  1363. .type = AVMEDIA_TYPE_AUDIO,
  1364. .id = AV_CODEC_ID_DTS,
  1365. .priv_data_size = sizeof(DCAContext),
  1366. .init = dca_decode_init,
  1367. .decode = dca_decode_frame,
  1368. .close = dca_decode_end,
  1369. .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
  1370. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
  1371. AV_SAMPLE_FMT_NONE },
  1372. .profiles = NULL_IF_CONFIG_SMALL(ff_dca_profiles),
  1373. .priv_class = &dca_decoder_class,
  1374. };