You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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