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.

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