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.

1202 lines
40KB

  1. /*
  2. * MLP decoder
  3. * Copyright (c) 2007-2008 Ian Caulfield
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * MLP decoder
  24. */
  25. #include <stdint.h>
  26. #include "avcodec.h"
  27. #include "dsputil.h"
  28. #include "libavutil/intreadwrite.h"
  29. #include "get_bits.h"
  30. #include "libavutil/crc.h"
  31. #include "parser.h"
  32. #include "mlp_parser.h"
  33. #include "mlp.h"
  34. /** number of bits used for VLC lookup - longest Huffman code is 9 */
  35. #define VLC_BITS 9
  36. static const char* sample_message =
  37. "Please file a bug report following the instructions at "
  38. "http://ffmpeg.org/bugreports.html and include "
  39. "a sample of this file.";
  40. typedef struct SubStream {
  41. //! Set if a valid restart header has been read. Otherwise the substream cannot be decoded.
  42. uint8_t restart_seen;
  43. //@{
  44. /** restart header data */
  45. //! The type of noise to be used in the rematrix stage.
  46. uint16_t noise_type;
  47. //! The index of the first channel coded in this substream.
  48. uint8_t min_channel;
  49. //! The index of the last channel coded in this substream.
  50. uint8_t max_channel;
  51. //! The number of channels input into the rematrix stage.
  52. uint8_t max_matrix_channel;
  53. //! For each channel output by the matrix, the output channel to map it to
  54. uint8_t ch_assign[MAX_CHANNELS];
  55. //! Channel coding parameters for channels in the substream
  56. ChannelParams channel_params[MAX_CHANNELS];
  57. //! The left shift applied to random noise in 0x31ea substreams.
  58. uint8_t noise_shift;
  59. //! The current seed value for the pseudorandom noise generator(s).
  60. uint32_t noisegen_seed;
  61. //! Set if the substream contains extra info to check the size of VLC blocks.
  62. uint8_t data_check_present;
  63. //! Bitmask of which parameter sets are conveyed in a decoding parameter block.
  64. uint8_t param_presence_flags;
  65. #define PARAM_BLOCKSIZE (1 << 7)
  66. #define PARAM_MATRIX (1 << 6)
  67. #define PARAM_OUTSHIFT (1 << 5)
  68. #define PARAM_QUANTSTEP (1 << 4)
  69. #define PARAM_FIR (1 << 3)
  70. #define PARAM_IIR (1 << 2)
  71. #define PARAM_HUFFOFFSET (1 << 1)
  72. #define PARAM_PRESENCE (1 << 0)
  73. //@}
  74. //@{
  75. /** matrix data */
  76. //! Number of matrices to be applied.
  77. uint8_t num_primitive_matrices;
  78. //! matrix output channel
  79. uint8_t matrix_out_ch[MAX_MATRICES];
  80. //! Whether the LSBs of the matrix output are encoded in the bitstream.
  81. uint8_t lsb_bypass[MAX_MATRICES];
  82. //! Matrix coefficients, stored as 2.14 fixed point.
  83. int32_t matrix_coeff[MAX_MATRICES][MAX_CHANNELS];
  84. //! Left shift to apply to noise values in 0x31eb substreams.
  85. uint8_t matrix_noise_shift[MAX_MATRICES];
  86. //@}
  87. //! Left shift to apply to Huffman-decoded residuals.
  88. uint8_t quant_step_size[MAX_CHANNELS];
  89. //! number of PCM samples in current audio block
  90. uint16_t blocksize;
  91. //! Number of PCM samples decoded so far in this frame.
  92. uint16_t blockpos;
  93. //! Left shift to apply to decoded PCM values to get final 24-bit output.
  94. int8_t output_shift[MAX_CHANNELS];
  95. //! Running XOR of all output samples.
  96. int32_t lossless_check_data;
  97. } SubStream;
  98. typedef struct MLPDecodeContext {
  99. AVCodecContext *avctx;
  100. //! Current access unit being read has a major sync.
  101. int is_major_sync_unit;
  102. //! Set if a valid major sync block has been read. Otherwise no decoding is possible.
  103. uint8_t params_valid;
  104. //! Number of substreams contained within this stream.
  105. uint8_t num_substreams;
  106. //! Index of the last substream to decode - further substreams are skipped.
  107. uint8_t max_decoded_substream;
  108. //! Stream needs channel reordering to comply with FFmpeg's channel order
  109. uint8_t needs_reordering;
  110. //! number of PCM samples contained in each frame
  111. int access_unit_size;
  112. //! next power of two above the number of samples in each frame
  113. int access_unit_size_pow2;
  114. SubStream substream[MAX_SUBSTREAMS];
  115. int matrix_changed;
  116. int filter_changed[MAX_CHANNELS][NUM_FILTERS];
  117. int8_t noise_buffer[MAX_BLOCKSIZE_POW2];
  118. int8_t bypassed_lsbs[MAX_BLOCKSIZE][MAX_CHANNELS];
  119. int32_t sample_buffer[MAX_BLOCKSIZE][MAX_CHANNELS];
  120. DSPContext dsp;
  121. } MLPDecodeContext;
  122. static VLC huff_vlc[3];
  123. /** Initialize static data, constant between all invocations of the codec. */
  124. static av_cold void init_static(void)
  125. {
  126. if (!huff_vlc[0].bits) {
  127. INIT_VLC_STATIC(&huff_vlc[0], VLC_BITS, 18,
  128. &ff_mlp_huffman_tables[0][0][1], 2, 1,
  129. &ff_mlp_huffman_tables[0][0][0], 2, 1, 512);
  130. INIT_VLC_STATIC(&huff_vlc[1], VLC_BITS, 16,
  131. &ff_mlp_huffman_tables[1][0][1], 2, 1,
  132. &ff_mlp_huffman_tables[1][0][0], 2, 1, 512);
  133. INIT_VLC_STATIC(&huff_vlc[2], VLC_BITS, 15,
  134. &ff_mlp_huffman_tables[2][0][1], 2, 1,
  135. &ff_mlp_huffman_tables[2][0][0], 2, 1, 512);
  136. }
  137. ff_mlp_init_crc();
  138. }
  139. static inline int32_t calculate_sign_huff(MLPDecodeContext *m,
  140. unsigned int substr, unsigned int ch)
  141. {
  142. SubStream *s = &m->substream[substr];
  143. ChannelParams *cp = &s->channel_params[ch];
  144. int lsb_bits = cp->huff_lsbs - s->quant_step_size[ch];
  145. int sign_shift = lsb_bits + (cp->codebook ? 2 - cp->codebook : -1);
  146. int32_t sign_huff_offset = cp->huff_offset;
  147. if (cp->codebook > 0)
  148. sign_huff_offset -= 7 << lsb_bits;
  149. if (sign_shift >= 0)
  150. sign_huff_offset -= 1 << sign_shift;
  151. return sign_huff_offset;
  152. }
  153. /** Read a sample, consisting of either, both or neither of entropy-coded MSBs
  154. * and plain LSBs. */
  155. static inline int read_huff_channels(MLPDecodeContext *m, GetBitContext *gbp,
  156. unsigned int substr, unsigned int pos)
  157. {
  158. SubStream *s = &m->substream[substr];
  159. unsigned int mat, channel;
  160. for (mat = 0; mat < s->num_primitive_matrices; mat++)
  161. if (s->lsb_bypass[mat])
  162. m->bypassed_lsbs[pos + s->blockpos][mat] = get_bits1(gbp);
  163. for (channel = s->min_channel; channel <= s->max_channel; channel++) {
  164. ChannelParams *cp = &s->channel_params[channel];
  165. int codebook = cp->codebook;
  166. int quant_step_size = s->quant_step_size[channel];
  167. int lsb_bits = cp->huff_lsbs - quant_step_size;
  168. int result = 0;
  169. if (codebook > 0)
  170. result = get_vlc2(gbp, huff_vlc[codebook-1].table,
  171. VLC_BITS, (9 + VLC_BITS - 1) / VLC_BITS);
  172. if (result < 0)
  173. return -1;
  174. if (lsb_bits > 0)
  175. result = (result << lsb_bits) + get_bits(gbp, lsb_bits);
  176. result += cp->sign_huff_offset;
  177. result <<= quant_step_size;
  178. m->sample_buffer[pos + s->blockpos][channel] = result;
  179. }
  180. return 0;
  181. }
  182. static av_cold int mlp_decode_init(AVCodecContext *avctx)
  183. {
  184. MLPDecodeContext *m = avctx->priv_data;
  185. int substr;
  186. init_static();
  187. m->avctx = avctx;
  188. for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
  189. m->substream[substr].lossless_check_data = 0xffffffff;
  190. dsputil_init(&m->dsp, avctx);
  191. return 0;
  192. }
  193. /** Read a major sync info header - contains high level information about
  194. * the stream - sample rate, channel arrangement etc. Most of this
  195. * information is not actually necessary for decoding, only for playback.
  196. */
  197. static int read_major_sync(MLPDecodeContext *m, GetBitContext *gb)
  198. {
  199. MLPHeaderInfo mh;
  200. int substr;
  201. if (ff_mlp_read_major_sync(m->avctx, &mh, gb) != 0)
  202. return -1;
  203. if (mh.group1_bits == 0) {
  204. av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown bits per sample\n");
  205. return -1;
  206. }
  207. if (mh.group2_bits > mh.group1_bits) {
  208. av_log(m->avctx, AV_LOG_ERROR,
  209. "Channel group 2 cannot have more bits per sample than group 1.\n");
  210. return -1;
  211. }
  212. if (mh.group2_samplerate && mh.group2_samplerate != mh.group1_samplerate) {
  213. av_log(m->avctx, AV_LOG_ERROR,
  214. "Channel groups with differing sample rates are not currently supported.\n");
  215. return -1;
  216. }
  217. if (mh.group1_samplerate == 0) {
  218. av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown sampling rate\n");
  219. return -1;
  220. }
  221. if (mh.group1_samplerate > MAX_SAMPLERATE) {
  222. av_log(m->avctx, AV_LOG_ERROR,
  223. "Sampling rate %d is greater than the supported maximum (%d).\n",
  224. mh.group1_samplerate, MAX_SAMPLERATE);
  225. return -1;
  226. }
  227. if (mh.access_unit_size > MAX_BLOCKSIZE) {
  228. av_log(m->avctx, AV_LOG_ERROR,
  229. "Block size %d is greater than the supported maximum (%d).\n",
  230. mh.access_unit_size, MAX_BLOCKSIZE);
  231. return -1;
  232. }
  233. if (mh.access_unit_size_pow2 > MAX_BLOCKSIZE_POW2) {
  234. av_log(m->avctx, AV_LOG_ERROR,
  235. "Block size pow2 %d is greater than the supported maximum (%d).\n",
  236. mh.access_unit_size_pow2, MAX_BLOCKSIZE_POW2);
  237. return -1;
  238. }
  239. if (mh.num_substreams == 0)
  240. return -1;
  241. if (m->avctx->codec_id == CODEC_ID_MLP && mh.num_substreams > 2) {
  242. av_log(m->avctx, AV_LOG_ERROR, "MLP only supports up to 2 substreams.\n");
  243. return -1;
  244. }
  245. if (mh.num_substreams > MAX_SUBSTREAMS) {
  246. av_log(m->avctx, AV_LOG_ERROR,
  247. "Number of substreams %d is larger than the maximum supported "
  248. "by the decoder. %s\n", mh.num_substreams, sample_message);
  249. return -1;
  250. }
  251. m->access_unit_size = mh.access_unit_size;
  252. m->access_unit_size_pow2 = mh.access_unit_size_pow2;
  253. m->num_substreams = mh.num_substreams;
  254. m->max_decoded_substream = m->num_substreams - 1;
  255. m->avctx->sample_rate = mh.group1_samplerate;
  256. m->avctx->frame_size = mh.access_unit_size;
  257. m->avctx->bits_per_raw_sample = mh.group1_bits;
  258. if (mh.group1_bits > 16)
  259. m->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  260. else
  261. m->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  262. m->params_valid = 1;
  263. for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
  264. m->substream[substr].restart_seen = 0;
  265. if (mh.stream_type == 0xbb) {
  266. /* MLP stream */
  267. m->avctx->channel_layout = ff_mlp_layout[mh.channels_mlp];
  268. } else { /* mh.stream_type == 0xba */
  269. /* TrueHD stream */
  270. if (mh.channels_thd_stream2) {
  271. m->avctx->channel_layout = ff_truehd_layout(mh.channels_thd_stream2);
  272. } else {
  273. m->avctx->channel_layout = ff_truehd_layout(mh.channels_thd_stream1);
  274. }
  275. if (m->avctx->channels &&
  276. !m->avctx->request_channels && !m->avctx->request_channel_layout &&
  277. av_get_channel_layout_nb_channels(m->avctx->channel_layout) != m->avctx->channels) {
  278. m->avctx->channel_layout = 0;
  279. av_log_ask_for_sample(m->avctx, "Unknown channel layout.");
  280. }
  281. }
  282. m->needs_reordering = mh.channels_mlp >= 18 && mh.channels_mlp <= 20;
  283. return 0;
  284. }
  285. /** Read a restart header from a block in a substream. This contains parameters
  286. * required to decode the audio that do not change very often. Generally
  287. * (always) present only in blocks following a major sync. */
  288. static int read_restart_header(MLPDecodeContext *m, GetBitContext *gbp,
  289. const uint8_t *buf, unsigned int substr)
  290. {
  291. SubStream *s = &m->substream[substr];
  292. unsigned int ch;
  293. int sync_word, tmp;
  294. uint8_t checksum;
  295. uint8_t lossless_check;
  296. int start_count = get_bits_count(gbp);
  297. const int max_matrix_channel = m->avctx->codec_id == CODEC_ID_MLP
  298. ? MAX_MATRIX_CHANNEL_MLP
  299. : MAX_MATRIX_CHANNEL_TRUEHD;
  300. sync_word = get_bits(gbp, 13);
  301. if (sync_word != 0x31ea >> 1) {
  302. av_log(m->avctx, AV_LOG_ERROR,
  303. "restart header sync incorrect (got 0x%04x)\n", sync_word);
  304. return -1;
  305. }
  306. s->noise_type = get_bits1(gbp);
  307. if (m->avctx->codec_id == CODEC_ID_MLP && s->noise_type) {
  308. av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n");
  309. return -1;
  310. }
  311. skip_bits(gbp, 16); /* Output timestamp */
  312. s->min_channel = get_bits(gbp, 4);
  313. s->max_channel = get_bits(gbp, 4);
  314. s->max_matrix_channel = get_bits(gbp, 4);
  315. if (s->max_matrix_channel > max_matrix_channel) {
  316. av_log(m->avctx, AV_LOG_ERROR,
  317. "Max matrix channel cannot be greater than %d.\n",
  318. max_matrix_channel);
  319. return -1;
  320. }
  321. if (s->max_channel != s->max_matrix_channel) {
  322. av_log(m->avctx, AV_LOG_ERROR,
  323. "Max channel must be equal max matrix channel.\n");
  324. return -1;
  325. }
  326. /* This should happen for TrueHD streams with >6 channels and MLP's noise
  327. * type. It is not yet known if this is allowed. */
  328. if (s->max_channel > MAX_MATRIX_CHANNEL_MLP && !s->noise_type) {
  329. av_log(m->avctx, AV_LOG_ERROR,
  330. "Number of channels %d is larger than the maximum supported "
  331. "by the decoder. %s\n", s->max_channel+2, sample_message);
  332. return -1;
  333. }
  334. if (s->min_channel > s->max_channel) {
  335. av_log(m->avctx, AV_LOG_ERROR,
  336. "Substream min channel cannot be greater than max channel.\n");
  337. return -1;
  338. }
  339. if (m->avctx->request_channels > 0
  340. && s->max_channel + 1 >= m->avctx->request_channels
  341. && substr < m->max_decoded_substream) {
  342. av_log(m->avctx, AV_LOG_DEBUG,
  343. "Extracting %d channel downmix from substream %d. "
  344. "Further substreams will be skipped.\n",
  345. s->max_channel + 1, substr);
  346. m->max_decoded_substream = substr;
  347. }
  348. s->noise_shift = get_bits(gbp, 4);
  349. s->noisegen_seed = get_bits(gbp, 23);
  350. skip_bits(gbp, 19);
  351. s->data_check_present = get_bits1(gbp);
  352. lossless_check = get_bits(gbp, 8);
  353. if (substr == m->max_decoded_substream
  354. && s->lossless_check_data != 0xffffffff) {
  355. tmp = xor_32_to_8(s->lossless_check_data);
  356. if (tmp != lossless_check)
  357. av_log(m->avctx, AV_LOG_WARNING,
  358. "Lossless check failed - expected %02x, calculated %02x.\n",
  359. lossless_check, tmp);
  360. }
  361. skip_bits(gbp, 16);
  362. memset(s->ch_assign, 0, sizeof(s->ch_assign));
  363. for (ch = 0; ch <= s->max_matrix_channel; ch++) {
  364. int ch_assign = get_bits(gbp, 6);
  365. if (ch_assign > s->max_matrix_channel) {
  366. av_log(m->avctx, AV_LOG_ERROR,
  367. "Assignment of matrix channel %d to invalid output channel %d. %s\n",
  368. ch, ch_assign, sample_message);
  369. return -1;
  370. }
  371. s->ch_assign[ch_assign] = ch;
  372. }
  373. if (m->avctx->codec_id == CODEC_ID_MLP && m->needs_reordering) {
  374. if (m->avctx->channel_layout == (AV_CH_LAYOUT_QUAD|AV_CH_LOW_FREQUENCY) ||
  375. m->avctx->channel_layout == AV_CH_LAYOUT_5POINT0_BACK) {
  376. int i = s->ch_assign[4];
  377. s->ch_assign[4] = s->ch_assign[3];
  378. s->ch_assign[3] = s->ch_assign[2];
  379. s->ch_assign[2] = i;
  380. } else if (m->avctx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK) {
  381. FFSWAP(int, s->ch_assign[2], s->ch_assign[4]);
  382. FFSWAP(int, s->ch_assign[3], s->ch_assign[5]);
  383. }
  384. }
  385. if (m->avctx->codec_id == CODEC_ID_TRUEHD &&
  386. m->avctx->channel_layout == AV_CH_LAYOUT_7POINT1) {
  387. FFSWAP(int, s->ch_assign[4], s->ch_assign[6]);
  388. FFSWAP(int, s->ch_assign[5], s->ch_assign[7]);
  389. }
  390. checksum = ff_mlp_restart_checksum(buf, get_bits_count(gbp) - start_count);
  391. if (checksum != get_bits(gbp, 8))
  392. av_log(m->avctx, AV_LOG_ERROR, "restart header checksum error\n");
  393. /* Set default decoding parameters. */
  394. s->param_presence_flags = 0xff;
  395. s->num_primitive_matrices = 0;
  396. s->blocksize = 8;
  397. s->lossless_check_data = 0;
  398. memset(s->output_shift , 0, sizeof(s->output_shift ));
  399. memset(s->quant_step_size, 0, sizeof(s->quant_step_size));
  400. for (ch = s->min_channel; ch <= s->max_channel; ch++) {
  401. ChannelParams *cp = &s->channel_params[ch];
  402. cp->filter_params[FIR].order = 0;
  403. cp->filter_params[IIR].order = 0;
  404. cp->filter_params[FIR].shift = 0;
  405. cp->filter_params[IIR].shift = 0;
  406. /* Default audio coding is 24-bit raw PCM. */
  407. cp->huff_offset = 0;
  408. cp->sign_huff_offset = (-1) << 23;
  409. cp->codebook = 0;
  410. cp->huff_lsbs = 24;
  411. }
  412. if (substr == m->max_decoded_substream)
  413. m->avctx->channels = s->max_matrix_channel + 1;
  414. return 0;
  415. }
  416. /** Read parameters for one of the prediction filters. */
  417. static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp,
  418. unsigned int substr, unsigned int channel,
  419. unsigned int filter)
  420. {
  421. SubStream *s = &m->substream[substr];
  422. FilterParams *fp = &s->channel_params[channel].filter_params[filter];
  423. const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;
  424. const char fchar = filter ? 'I' : 'F';
  425. int i, order;
  426. // Filter is 0 for FIR, 1 for IIR.
  427. assert(filter < 2);
  428. if (m->filter_changed[channel][filter]++ > 1) {
  429. av_log(m->avctx, AV_LOG_ERROR, "Filters may change only once per access unit.\n");
  430. return -1;
  431. }
  432. order = get_bits(gbp, 4);
  433. if (order > max_order) {
  434. av_log(m->avctx, AV_LOG_ERROR,
  435. "%cIR filter order %d is greater than maximum %d.\n",
  436. fchar, order, max_order);
  437. return -1;
  438. }
  439. fp->order = order;
  440. if (order > 0) {
  441. int32_t *fcoeff = s->channel_params[channel].coeff[filter];
  442. int coeff_bits, coeff_shift;
  443. fp->shift = get_bits(gbp, 4);
  444. coeff_bits = get_bits(gbp, 5);
  445. coeff_shift = get_bits(gbp, 3);
  446. if (coeff_bits < 1 || coeff_bits > 16) {
  447. av_log(m->avctx, AV_LOG_ERROR,
  448. "%cIR filter coeff_bits must be between 1 and 16.\n",
  449. fchar);
  450. return -1;
  451. }
  452. if (coeff_bits + coeff_shift > 16) {
  453. av_log(m->avctx, AV_LOG_ERROR,
  454. "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",
  455. fchar);
  456. return -1;
  457. }
  458. for (i = 0; i < order; i++)
  459. fcoeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift;
  460. if (get_bits1(gbp)) {
  461. int state_bits, state_shift;
  462. if (filter == FIR) {
  463. av_log(m->avctx, AV_LOG_ERROR,
  464. "FIR filter has state data specified.\n");
  465. return -1;
  466. }
  467. state_bits = get_bits(gbp, 4);
  468. state_shift = get_bits(gbp, 4);
  469. /* TODO: Check validity of state data. */
  470. for (i = 0; i < order; i++)
  471. fp->state[i] = get_sbits(gbp, state_bits) << state_shift;
  472. }
  473. }
  474. return 0;
  475. }
  476. /** Read parameters for primitive matrices. */
  477. static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitContext *gbp)
  478. {
  479. SubStream *s = &m->substream[substr];
  480. unsigned int mat, ch;
  481. const int max_primitive_matrices = m->avctx->codec_id == CODEC_ID_MLP
  482. ? MAX_MATRICES_MLP
  483. : MAX_MATRICES_TRUEHD;
  484. if (m->matrix_changed++ > 1) {
  485. av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");
  486. return -1;
  487. }
  488. s->num_primitive_matrices = get_bits(gbp, 4);
  489. if (s->num_primitive_matrices > max_primitive_matrices) {
  490. av_log(m->avctx, AV_LOG_ERROR,
  491. "Number of primitive matrices cannot be greater than %d.\n",
  492. max_primitive_matrices);
  493. return -1;
  494. }
  495. for (mat = 0; mat < s->num_primitive_matrices; mat++) {
  496. int frac_bits, max_chan;
  497. s->matrix_out_ch[mat] = get_bits(gbp, 4);
  498. frac_bits = get_bits(gbp, 4);
  499. s->lsb_bypass [mat] = get_bits1(gbp);
  500. if (s->matrix_out_ch[mat] > s->max_matrix_channel) {
  501. av_log(m->avctx, AV_LOG_ERROR,
  502. "Invalid channel %d specified as output from matrix.\n",
  503. s->matrix_out_ch[mat]);
  504. return -1;
  505. }
  506. if (frac_bits > 14) {
  507. av_log(m->avctx, AV_LOG_ERROR,
  508. "Too many fractional bits specified.\n");
  509. return -1;
  510. }
  511. max_chan = s->max_matrix_channel;
  512. if (!s->noise_type)
  513. max_chan+=2;
  514. for (ch = 0; ch <= max_chan; ch++) {
  515. int coeff_val = 0;
  516. if (get_bits1(gbp))
  517. coeff_val = get_sbits(gbp, frac_bits + 2);
  518. s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
  519. }
  520. if (s->noise_type)
  521. s->matrix_noise_shift[mat] = get_bits(gbp, 4);
  522. else
  523. s->matrix_noise_shift[mat] = 0;
  524. }
  525. return 0;
  526. }
  527. /** Read channel parameters. */
  528. static int read_channel_params(MLPDecodeContext *m, unsigned int substr,
  529. GetBitContext *gbp, unsigned int ch)
  530. {
  531. SubStream *s = &m->substream[substr];
  532. ChannelParams *cp = &s->channel_params[ch];
  533. FilterParams *fir = &cp->filter_params[FIR];
  534. FilterParams *iir = &cp->filter_params[IIR];
  535. if (s->param_presence_flags & PARAM_FIR)
  536. if (get_bits1(gbp))
  537. if (read_filter_params(m, gbp, substr, ch, FIR) < 0)
  538. return -1;
  539. if (s->param_presence_flags & PARAM_IIR)
  540. if (get_bits1(gbp))
  541. if (read_filter_params(m, gbp, substr, ch, IIR) < 0)
  542. return -1;
  543. if (fir->order + iir->order > 8) {
  544. av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");
  545. return -1;
  546. }
  547. if (fir->order && iir->order &&
  548. fir->shift != iir->shift) {
  549. av_log(m->avctx, AV_LOG_ERROR,
  550. "FIR and IIR filters must use the same precision.\n");
  551. return -1;
  552. }
  553. /* The FIR and IIR filters must have the same precision.
  554. * To simplify the filtering code, only the precision of the
  555. * FIR filter is considered. If only the IIR filter is employed,
  556. * the FIR filter precision is set to that of the IIR filter, so
  557. * that the filtering code can use it. */
  558. if (!fir->order && iir->order)
  559. fir->shift = iir->shift;
  560. if (s->param_presence_flags & PARAM_HUFFOFFSET)
  561. if (get_bits1(gbp))
  562. cp->huff_offset = get_sbits(gbp, 15);
  563. cp->codebook = get_bits(gbp, 2);
  564. cp->huff_lsbs = get_bits(gbp, 5);
  565. if (cp->huff_lsbs > 24) {
  566. av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");
  567. return -1;
  568. }
  569. cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
  570. return 0;
  571. }
  572. /** Read decoding parameters that change more often than those in the restart
  573. * header. */
  574. static int read_decoding_params(MLPDecodeContext *m, GetBitContext *gbp,
  575. unsigned int substr)
  576. {
  577. SubStream *s = &m->substream[substr];
  578. unsigned int ch;
  579. if (s->param_presence_flags & PARAM_PRESENCE)
  580. if (get_bits1(gbp))
  581. s->param_presence_flags = get_bits(gbp, 8);
  582. if (s->param_presence_flags & PARAM_BLOCKSIZE)
  583. if (get_bits1(gbp)) {
  584. s->blocksize = get_bits(gbp, 9);
  585. if (s->blocksize < 8 || s->blocksize > m->access_unit_size) {
  586. av_log(m->avctx, AV_LOG_ERROR, "Invalid blocksize.");
  587. s->blocksize = 0;
  588. return -1;
  589. }
  590. }
  591. if (s->param_presence_flags & PARAM_MATRIX)
  592. if (get_bits1(gbp))
  593. if (read_matrix_params(m, substr, gbp) < 0)
  594. return -1;
  595. if (s->param_presence_flags & PARAM_OUTSHIFT)
  596. if (get_bits1(gbp))
  597. for (ch = 0; ch <= s->max_matrix_channel; ch++)
  598. s->output_shift[ch] = get_sbits(gbp, 4);
  599. if (s->param_presence_flags & PARAM_QUANTSTEP)
  600. if (get_bits1(gbp))
  601. for (ch = 0; ch <= s->max_channel; ch++) {
  602. ChannelParams *cp = &s->channel_params[ch];
  603. s->quant_step_size[ch] = get_bits(gbp, 4);
  604. cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
  605. }
  606. for (ch = s->min_channel; ch <= s->max_channel; ch++)
  607. if (get_bits1(gbp))
  608. if (read_channel_params(m, substr, gbp, ch) < 0)
  609. return -1;
  610. return 0;
  611. }
  612. #define MSB_MASK(bits) (-1u << bits)
  613. /** Generate PCM samples using the prediction filters and residual values
  614. * read from the data stream, and update the filter state. */
  615. static void filter_channel(MLPDecodeContext *m, unsigned int substr,
  616. unsigned int channel)
  617. {
  618. SubStream *s = &m->substream[substr];
  619. const int32_t *fircoeff = s->channel_params[channel].coeff[FIR];
  620. int32_t state_buffer[NUM_FILTERS][MAX_BLOCKSIZE + MAX_FIR_ORDER];
  621. int32_t *firbuf = state_buffer[FIR] + MAX_BLOCKSIZE;
  622. int32_t *iirbuf = state_buffer[IIR] + MAX_BLOCKSIZE;
  623. FilterParams *fir = &s->channel_params[channel].filter_params[FIR];
  624. FilterParams *iir = &s->channel_params[channel].filter_params[IIR];
  625. unsigned int filter_shift = fir->shift;
  626. int32_t mask = MSB_MASK(s->quant_step_size[channel]);
  627. memcpy(firbuf, fir->state, MAX_FIR_ORDER * sizeof(int32_t));
  628. memcpy(iirbuf, iir->state, MAX_IIR_ORDER * sizeof(int32_t));
  629. m->dsp.mlp_filter_channel(firbuf, fircoeff,
  630. fir->order, iir->order,
  631. filter_shift, mask, s->blocksize,
  632. &m->sample_buffer[s->blockpos][channel]);
  633. memcpy(fir->state, firbuf - s->blocksize, MAX_FIR_ORDER * sizeof(int32_t));
  634. memcpy(iir->state, iirbuf - s->blocksize, MAX_IIR_ORDER * sizeof(int32_t));
  635. }
  636. /** Read a block of PCM residual data (or actual if no filtering active). */
  637. static int read_block_data(MLPDecodeContext *m, GetBitContext *gbp,
  638. unsigned int substr)
  639. {
  640. SubStream *s = &m->substream[substr];
  641. unsigned int i, ch, expected_stream_pos = 0;
  642. if (s->data_check_present) {
  643. expected_stream_pos = get_bits_count(gbp);
  644. expected_stream_pos += get_bits(gbp, 16);
  645. av_log(m->avctx, AV_LOG_WARNING, "This file contains some features "
  646. "we have not tested yet. %s\n", sample_message);
  647. }
  648. if (s->blockpos + s->blocksize > m->access_unit_size) {
  649. av_log(m->avctx, AV_LOG_ERROR, "too many audio samples in frame\n");
  650. return -1;
  651. }
  652. memset(&m->bypassed_lsbs[s->blockpos][0], 0,
  653. s->blocksize * sizeof(m->bypassed_lsbs[0]));
  654. for (i = 0; i < s->blocksize; i++)
  655. if (read_huff_channels(m, gbp, substr, i) < 0)
  656. return -1;
  657. for (ch = s->min_channel; ch <= s->max_channel; ch++)
  658. filter_channel(m, substr, ch);
  659. s->blockpos += s->blocksize;
  660. if (s->data_check_present) {
  661. if (get_bits_count(gbp) != expected_stream_pos)
  662. av_log(m->avctx, AV_LOG_ERROR, "block data length mismatch\n");
  663. skip_bits(gbp, 8);
  664. }
  665. return 0;
  666. }
  667. /** Data table used for TrueHD noise generation function. */
  668. static const int8_t noise_table[256] = {
  669. 30, 51, 22, 54, 3, 7, -4, 38, 14, 55, 46, 81, 22, 58, -3, 2,
  670. 52, 31, -7, 51, 15, 44, 74, 30, 85, -17, 10, 33, 18, 80, 28, 62,
  671. 10, 32, 23, 69, 72, 26, 35, 17, 73, 60, 8, 56, 2, 6, -2, -5,
  672. 51, 4, 11, 50, 66, 76, 21, 44, 33, 47, 1, 26, 64, 48, 57, 40,
  673. 38, 16, -10, -28, 92, 22, -18, 29, -10, 5, -13, 49, 19, 24, 70, 34,
  674. 61, 48, 30, 14, -6, 25, 58, 33, 42, 60, 67, 17, 54, 17, 22, 30,
  675. 67, 44, -9, 50, -11, 43, 40, 32, 59, 82, 13, 49, -14, 55, 60, 36,
  676. 48, 49, 31, 47, 15, 12, 4, 65, 1, 23, 29, 39, 45, -2, 84, 69,
  677. 0, 72, 37, 57, 27, 41, -15, -16, 35, 31, 14, 61, 24, 0, 27, 24,
  678. 16, 41, 55, 34, 53, 9, 56, 12, 25, 29, 53, 5, 20, -20, -8, 20,
  679. 13, 28, -3, 78, 38, 16, 11, 62, 46, 29, 21, 24, 46, 65, 43, -23,
  680. 89, 18, 74, 21, 38, -12, 19, 12, -19, 8, 15, 33, 4, 57, 9, -8,
  681. 36, 35, 26, 28, 7, 83, 63, 79, 75, 11, 3, 87, 37, 47, 34, 40,
  682. 39, 19, 20, 42, 27, 34, 39, 77, 13, 42, 59, 64, 45, -1, 32, 37,
  683. 45, -5, 53, -6, 7, 36, 50, 23, 6, 32, 9, -21, 18, 71, 27, 52,
  684. -25, 31, 35, 42, -1, 68, 63, 52, 26, 43, 66, 37, 41, 25, 40, 70,
  685. };
  686. /** Noise generation functions.
  687. * I'm not sure what these are for - they seem to be some kind of pseudorandom
  688. * sequence generators, used to generate noise data which is used when the
  689. * channels are rematrixed. I'm not sure if they provide a practical benefit
  690. * to compression, or just obfuscate the decoder. Are they for some kind of
  691. * dithering? */
  692. /** Generate two channels of noise, used in the matrix when
  693. * restart sync word == 0x31ea. */
  694. static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr)
  695. {
  696. SubStream *s = &m->substream[substr];
  697. unsigned int i;
  698. uint32_t seed = s->noisegen_seed;
  699. unsigned int maxchan = s->max_matrix_channel;
  700. for (i = 0; i < s->blockpos; i++) {
  701. uint16_t seed_shr7 = seed >> 7;
  702. m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift;
  703. m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7) << s->noise_shift;
  704. seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);
  705. }
  706. s->noisegen_seed = seed;
  707. }
  708. /** Generate a block of noise, used when restart sync word == 0x31eb. */
  709. static void fill_noise_buffer(MLPDecodeContext *m, unsigned int substr)
  710. {
  711. SubStream *s = &m->substream[substr];
  712. unsigned int i;
  713. uint32_t seed = s->noisegen_seed;
  714. for (i = 0; i < m->access_unit_size_pow2; i++) {
  715. uint8_t seed_shr15 = seed >> 15;
  716. m->noise_buffer[i] = noise_table[seed_shr15];
  717. seed = (seed << 8) ^ seed_shr15 ^ (seed_shr15 << 5);
  718. }
  719. s->noisegen_seed = seed;
  720. }
  721. /** Apply the channel matrices in turn to reconstruct the original audio
  722. * samples. */
  723. static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
  724. {
  725. SubStream *s = &m->substream[substr];
  726. unsigned int mat, src_ch, i;
  727. unsigned int maxchan;
  728. maxchan = s->max_matrix_channel;
  729. if (!s->noise_type) {
  730. generate_2_noise_channels(m, substr);
  731. maxchan += 2;
  732. } else {
  733. fill_noise_buffer(m, substr);
  734. }
  735. for (mat = 0; mat < s->num_primitive_matrices; mat++) {
  736. int matrix_noise_shift = s->matrix_noise_shift[mat];
  737. unsigned int dest_ch = s->matrix_out_ch[mat];
  738. int32_t mask = MSB_MASK(s->quant_step_size[dest_ch]);
  739. int32_t *coeffs = s->matrix_coeff[mat];
  740. int index = s->num_primitive_matrices - mat;
  741. int index2 = 2 * index + 1;
  742. /* TODO: DSPContext? */
  743. for (i = 0; i < s->blockpos; i++) {
  744. int32_t bypassed_lsb = m->bypassed_lsbs[i][mat];
  745. int32_t *samples = m->sample_buffer[i];
  746. int64_t accum = 0;
  747. for (src_ch = 0; src_ch <= maxchan; src_ch++)
  748. accum += (int64_t) samples[src_ch] * coeffs[src_ch];
  749. if (matrix_noise_shift) {
  750. index &= m->access_unit_size_pow2 - 1;
  751. accum += m->noise_buffer[index] << (matrix_noise_shift + 7);
  752. index += index2;
  753. }
  754. samples[dest_ch] = ((accum >> 14) & mask) + bypassed_lsb;
  755. }
  756. }
  757. }
  758. /** Write the audio data into the output buffer. */
  759. static int output_data_internal(MLPDecodeContext *m, unsigned int substr,
  760. uint8_t *data, unsigned int *data_size, int is32)
  761. {
  762. SubStream *s = &m->substream[substr];
  763. unsigned int i, out_ch = 0;
  764. int32_t *data_32 = (int32_t*) data;
  765. int16_t *data_16 = (int16_t*) data;
  766. if (*data_size < (s->max_channel + 1) * s->blockpos * (is32 ? 4 : 2))
  767. return -1;
  768. for (i = 0; i < s->blockpos; i++) {
  769. for (out_ch = 0; out_ch <= s->max_matrix_channel; out_ch++) {
  770. int mat_ch = s->ch_assign[out_ch];
  771. int32_t sample = m->sample_buffer[i][mat_ch]
  772. << s->output_shift[mat_ch];
  773. s->lossless_check_data ^= (sample & 0xffffff) << mat_ch;
  774. if (is32) *data_32++ = sample << 8;
  775. else *data_16++ = sample >> 8;
  776. }
  777. }
  778. *data_size = i * out_ch * (is32 ? 4 : 2);
  779. return 0;
  780. }
  781. static int output_data(MLPDecodeContext *m, unsigned int substr,
  782. uint8_t *data, unsigned int *data_size)
  783. {
  784. if (m->avctx->sample_fmt == AV_SAMPLE_FMT_S32)
  785. return output_data_internal(m, substr, data, data_size, 1);
  786. else
  787. return output_data_internal(m, substr, data, data_size, 0);
  788. }
  789. /** Read an access unit from the stream.
  790. * @return negative on error, 0 if not enough data is present in the input stream,
  791. * otherwise the number of bytes consumed. */
  792. static int read_access_unit(AVCodecContext *avctx, void* data, int *data_size,
  793. AVPacket *avpkt)
  794. {
  795. const uint8_t *buf = avpkt->data;
  796. int buf_size = avpkt->size;
  797. MLPDecodeContext *m = avctx->priv_data;
  798. GetBitContext gb;
  799. unsigned int length, substr;
  800. unsigned int substream_start;
  801. unsigned int header_size = 4;
  802. unsigned int substr_header_size = 0;
  803. uint8_t substream_parity_present[MAX_SUBSTREAMS];
  804. uint16_t substream_data_len[MAX_SUBSTREAMS];
  805. uint8_t parity_bits;
  806. if (buf_size < 4)
  807. return 0;
  808. length = (AV_RB16(buf) & 0xfff) * 2;
  809. if (length < 4 || length > buf_size)
  810. return -1;
  811. init_get_bits(&gb, (buf + 4), (length - 4) * 8);
  812. m->is_major_sync_unit = 0;
  813. if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {
  814. if (read_major_sync(m, &gb) < 0)
  815. goto error;
  816. m->is_major_sync_unit = 1;
  817. header_size += 28;
  818. }
  819. if (!m->params_valid) {
  820. av_log(m->avctx, AV_LOG_WARNING,
  821. "Stream parameters not seen; skipping frame.\n");
  822. *data_size = 0;
  823. return length;
  824. }
  825. substream_start = 0;
  826. for (substr = 0; substr < m->num_substreams; substr++) {
  827. int extraword_present, checkdata_present, end, nonrestart_substr;
  828. extraword_present = get_bits1(&gb);
  829. nonrestart_substr = get_bits1(&gb);
  830. checkdata_present = get_bits1(&gb);
  831. skip_bits1(&gb);
  832. end = get_bits(&gb, 12) * 2;
  833. substr_header_size += 2;
  834. if (extraword_present) {
  835. if (m->avctx->codec_id == CODEC_ID_MLP) {
  836. av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
  837. goto error;
  838. }
  839. skip_bits(&gb, 16);
  840. substr_header_size += 2;
  841. }
  842. if (!(nonrestart_substr ^ m->is_major_sync_unit)) {
  843. av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");
  844. goto error;
  845. }
  846. if (end + header_size + substr_header_size > length) {
  847. av_log(m->avctx, AV_LOG_ERROR,
  848. "Indicated length of substream %d data goes off end of "
  849. "packet.\n", substr);
  850. end = length - header_size - substr_header_size;
  851. }
  852. if (end < substream_start) {
  853. av_log(avctx, AV_LOG_ERROR,
  854. "Indicated end offset of substream %d data "
  855. "is smaller than calculated start offset.\n",
  856. substr);
  857. goto error;
  858. }
  859. if (substr > m->max_decoded_substream)
  860. continue;
  861. substream_parity_present[substr] = checkdata_present;
  862. substream_data_len[substr] = end - substream_start;
  863. substream_start = end;
  864. }
  865. parity_bits = ff_mlp_calculate_parity(buf, 4);
  866. parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);
  867. if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {
  868. av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");
  869. goto error;
  870. }
  871. buf += header_size + substr_header_size;
  872. for (substr = 0; substr <= m->max_decoded_substream; substr++) {
  873. SubStream *s = &m->substream[substr];
  874. init_get_bits(&gb, buf, substream_data_len[substr] * 8);
  875. m->matrix_changed = 0;
  876. memset(m->filter_changed, 0, sizeof(m->filter_changed));
  877. s->blockpos = 0;
  878. do {
  879. if (get_bits1(&gb)) {
  880. if (get_bits1(&gb)) {
  881. /* A restart header should be present. */
  882. if (read_restart_header(m, &gb, buf, substr) < 0)
  883. goto next_substr;
  884. s->restart_seen = 1;
  885. }
  886. if (!s->restart_seen)
  887. goto next_substr;
  888. if (read_decoding_params(m, &gb, substr) < 0)
  889. goto next_substr;
  890. }
  891. if (!s->restart_seen)
  892. goto next_substr;
  893. if (read_block_data(m, &gb, substr) < 0)
  894. return -1;
  895. if (get_bits_count(&gb) >= substream_data_len[substr] * 8)
  896. goto substream_length_mismatch;
  897. } while (!get_bits1(&gb));
  898. skip_bits(&gb, (-get_bits_count(&gb)) & 15);
  899. if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {
  900. int shorten_by;
  901. if (get_bits(&gb, 16) != 0xD234)
  902. return -1;
  903. shorten_by = get_bits(&gb, 16);
  904. if (m->avctx->codec_id == CODEC_ID_TRUEHD && shorten_by & 0x2000)
  905. s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
  906. else if (m->avctx->codec_id == CODEC_ID_MLP && shorten_by != 0xD234)
  907. return -1;
  908. if (substr == m->max_decoded_substream)
  909. av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");
  910. }
  911. if (substream_parity_present[substr]) {
  912. uint8_t parity, checksum;
  913. if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)
  914. goto substream_length_mismatch;
  915. parity = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);
  916. checksum = ff_mlp_checksum8 (buf, substream_data_len[substr] - 2);
  917. if ((get_bits(&gb, 8) ^ parity) != 0xa9 )
  918. av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);
  919. if ( get_bits(&gb, 8) != checksum)
  920. av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n" , substr);
  921. }
  922. if (substream_data_len[substr] * 8 != get_bits_count(&gb))
  923. goto substream_length_mismatch;
  924. next_substr:
  925. if (!s->restart_seen)
  926. av_log(m->avctx, AV_LOG_ERROR,
  927. "No restart header present in substream %d.\n", substr);
  928. buf += substream_data_len[substr];
  929. }
  930. rematrix_channels(m, m->max_decoded_substream);
  931. if (output_data(m, m->max_decoded_substream, data, data_size) < 0)
  932. return -1;
  933. return length;
  934. substream_length_mismatch:
  935. av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
  936. return -1;
  937. error:
  938. m->params_valid = 0;
  939. return -1;
  940. }
  941. AVCodec ff_mlp_decoder = {
  942. .name = "mlp",
  943. .type = AVMEDIA_TYPE_AUDIO,
  944. .id = CODEC_ID_MLP,
  945. .priv_data_size = sizeof(MLPDecodeContext),
  946. .init = mlp_decode_init,
  947. .decode = read_access_unit,
  948. .long_name = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
  949. };
  950. #if CONFIG_TRUEHD_DECODER
  951. AVCodec ff_truehd_decoder = {
  952. .name = "truehd",
  953. .type = AVMEDIA_TYPE_AUDIO,
  954. .id = CODEC_ID_TRUEHD,
  955. .priv_data_size = sizeof(MLPDecodeContext),
  956. .init = mlp_decode_init,
  957. .decode = read_access_unit,
  958. .long_name = NULL_IF_CONFIG_SMALL("TrueHD"),
  959. };
  960. #endif /* CONFIG_TRUEHD_DECODER */