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.

1334 lines
47KB

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