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.

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