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