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.

1596 lines
58KB

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