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.

1356 lines
48KB

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