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.

1586 lines
57KB

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