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
46KB

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