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.

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