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.

1135 lines
37KB

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