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.

1162 lines
38KB

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