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.

1296 lines
45KB

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