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.

1298 lines
46KB

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