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.

1143 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 "bitstream.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. }
  346. return 0;
  347. }
  348. /** Read parameters for one of the prediction filters. */
  349. static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp,
  350. unsigned int channel, unsigned int filter)
  351. {
  352. FilterParams *fp = &m->channel_params[channel].filter_params[filter];
  353. const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;
  354. const char fchar = filter ? 'I' : 'F';
  355. int i, order;
  356. // Filter is 0 for FIR, 1 for IIR.
  357. assert(filter < 2);
  358. m->filter_changed[channel][filter]++;
  359. order = get_bits(gbp, 4);
  360. if (order > max_order) {
  361. av_log(m->avctx, AV_LOG_ERROR,
  362. "%cIR filter order %d is greater than maximum %d.\n",
  363. fchar, order, max_order);
  364. return -1;
  365. }
  366. fp->order = order;
  367. if (order > 0) {
  368. int coeff_bits, coeff_shift;
  369. fp->shift = get_bits(gbp, 4);
  370. coeff_bits = get_bits(gbp, 5);
  371. coeff_shift = get_bits(gbp, 3);
  372. if (coeff_bits < 1 || coeff_bits > 16) {
  373. av_log(m->avctx, AV_LOG_ERROR,
  374. "%cIR filter coeff_bits must be between 1 and 16.\n",
  375. fchar);
  376. return -1;
  377. }
  378. if (coeff_bits + coeff_shift > 16) {
  379. av_log(m->avctx, AV_LOG_ERROR,
  380. "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",
  381. fchar);
  382. return -1;
  383. }
  384. for (i = 0; i < order; i++)
  385. fp->coeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift;
  386. if (get_bits1(gbp)) {
  387. int state_bits, state_shift;
  388. if (filter == FIR) {
  389. av_log(m->avctx, AV_LOG_ERROR,
  390. "FIR filter has state data specified.\n");
  391. return -1;
  392. }
  393. state_bits = get_bits(gbp, 4);
  394. state_shift = get_bits(gbp, 4);
  395. /* TODO: Check validity of state data. */
  396. for (i = 0; i < order; i++)
  397. fp->state[i] = get_sbits(gbp, state_bits) << state_shift;
  398. }
  399. }
  400. return 0;
  401. }
  402. /** Read parameters for primitive matrices. */
  403. static int read_matrix_params(MLPDecodeContext *m, SubStream *s, GetBitContext *gbp)
  404. {
  405. unsigned int mat, ch;
  406. s->num_primitive_matrices = get_bits(gbp, 4);
  407. m->matrix_changed++;
  408. for (mat = 0; mat < s->num_primitive_matrices; mat++) {
  409. int frac_bits, max_chan;
  410. s->matrix_out_ch[mat] = get_bits(gbp, 4);
  411. frac_bits = get_bits(gbp, 4);
  412. s->lsb_bypass [mat] = get_bits1(gbp);
  413. if (s->matrix_out_ch[mat] > s->max_matrix_channel) {
  414. av_log(m->avctx, AV_LOG_ERROR,
  415. "Invalid channel %d specified as output from matrix.\n",
  416. s->matrix_out_ch[mat]);
  417. return -1;
  418. }
  419. if (frac_bits > 14) {
  420. av_log(m->avctx, AV_LOG_ERROR,
  421. "Too many fractional bits specified.\n");
  422. return -1;
  423. }
  424. max_chan = s->max_matrix_channel;
  425. if (!s->noise_type)
  426. max_chan+=2;
  427. for (ch = 0; ch <= max_chan; ch++) {
  428. int coeff_val = 0;
  429. if (get_bits1(gbp))
  430. coeff_val = get_sbits(gbp, frac_bits + 2);
  431. s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
  432. }
  433. if (s->noise_type)
  434. s->matrix_noise_shift[mat] = get_bits(gbp, 4);
  435. else
  436. s->matrix_noise_shift[mat] = 0;
  437. }
  438. return 0;
  439. }
  440. /** Read channel parameters. */
  441. static int read_channel_params(MLPDecodeContext *m, unsigned int substr,
  442. GetBitContext *gbp, unsigned int ch)
  443. {
  444. ChannelParams *cp = &m->channel_params[ch];
  445. FilterParams *fir = &cp->filter_params[FIR];
  446. FilterParams *iir = &cp->filter_params[IIR];
  447. SubStream *s = &m->substream[substr];
  448. if (s->param_presence_flags & PARAM_FIR)
  449. if (get_bits1(gbp))
  450. if (read_filter_params(m, gbp, ch, FIR) < 0)
  451. return -1;
  452. if (s->param_presence_flags & PARAM_IIR)
  453. if (get_bits1(gbp))
  454. if (read_filter_params(m, gbp, ch, IIR) < 0)
  455. return -1;
  456. if (fir->order + iir->order > 8) {
  457. av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");
  458. return -1;
  459. }
  460. if (fir->order && iir->order &&
  461. fir->shift != iir->shift) {
  462. av_log(m->avctx, AV_LOG_ERROR,
  463. "FIR and IIR filters must use the same precision.\n");
  464. return -1;
  465. }
  466. /* The FIR and IIR filters must have the same precision.
  467. * To simplify the filtering code, only the precision of the
  468. * FIR filter is considered. If only the IIR filter is employed,
  469. * the FIR filter precision is set to that of the IIR filter, so
  470. * that the filtering code can use it. */
  471. if (!fir->order && iir->order)
  472. fir->shift = iir->shift;
  473. if (s->param_presence_flags & PARAM_HUFFOFFSET)
  474. if (get_bits1(gbp))
  475. cp->huff_offset = get_sbits(gbp, 15);
  476. cp->codebook = get_bits(gbp, 2);
  477. cp->huff_lsbs = get_bits(gbp, 5);
  478. if (cp->huff_lsbs > 24) {
  479. av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");
  480. return -1;
  481. }
  482. cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
  483. return 0;
  484. }
  485. /** Read decoding parameters that change more often than those in the restart
  486. * header. */
  487. static int read_decoding_params(MLPDecodeContext *m, GetBitContext *gbp,
  488. unsigned int substr)
  489. {
  490. SubStream *s = &m->substream[substr];
  491. unsigned int ch;
  492. if (s->param_presence_flags & PARAM_PRESENCE)
  493. if (get_bits1(gbp))
  494. s->param_presence_flags = get_bits(gbp, 8);
  495. if (s->param_presence_flags & PARAM_BLOCKSIZE)
  496. if (get_bits1(gbp)) {
  497. s->blocksize = get_bits(gbp, 9);
  498. if (s->blocksize < 8 || s->blocksize > m->access_unit_size) {
  499. av_log(m->avctx, AV_LOG_ERROR, "Invalid blocksize.");
  500. s->blocksize = 0;
  501. return -1;
  502. }
  503. }
  504. if (s->param_presence_flags & PARAM_MATRIX)
  505. if (get_bits1(gbp)) {
  506. if (read_matrix_params(m, s, gbp) < 0)
  507. return -1;
  508. }
  509. if (s->param_presence_flags & PARAM_OUTSHIFT)
  510. if (get_bits1(gbp))
  511. for (ch = 0; ch <= s->max_matrix_channel; ch++) {
  512. s->output_shift[ch] = get_sbits(gbp, 4);
  513. }
  514. if (s->param_presence_flags & PARAM_QUANTSTEP)
  515. if (get_bits1(gbp))
  516. for (ch = 0; ch <= s->max_channel; ch++) {
  517. ChannelParams *cp = &m->channel_params[ch];
  518. s->quant_step_size[ch] = get_bits(gbp, 4);
  519. cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
  520. }
  521. for (ch = s->min_channel; ch <= s->max_channel; ch++)
  522. if (get_bits1(gbp)) {
  523. if (read_channel_params(m, substr, gbp, ch) < 0)
  524. return -1;
  525. }
  526. return 0;
  527. }
  528. #define MSB_MASK(bits) (-1u << bits)
  529. /** Generate PCM samples using the prediction filters and residual values
  530. * read from the data stream, and update the filter state. */
  531. static void filter_channel(MLPDecodeContext *m, unsigned int substr,
  532. unsigned int channel)
  533. {
  534. SubStream *s = &m->substream[substr];
  535. int32_t firbuf[MAX_BLOCKSIZE + MAX_FIR_ORDER];
  536. int32_t iirbuf[MAX_BLOCKSIZE + MAX_IIR_ORDER];
  537. FilterParams *fir = &m->channel_params[channel].filter_params[FIR];
  538. FilterParams *iir = &m->channel_params[channel].filter_params[IIR];
  539. unsigned int filter_shift = fir->shift;
  540. int32_t mask = MSB_MASK(s->quant_step_size[channel]);
  541. int index = MAX_BLOCKSIZE;
  542. int i;
  543. memcpy(&firbuf[index], fir->state, MAX_FIR_ORDER * sizeof(int32_t));
  544. memcpy(&iirbuf[index], iir->state, MAX_IIR_ORDER * sizeof(int32_t));
  545. for (i = 0; i < s->blocksize; i++) {
  546. int32_t residual = m->sample_buffer[i + s->blockpos][channel];
  547. unsigned int order;
  548. int64_t accum = 0;
  549. int32_t result;
  550. /* TODO: Move this code to DSPContext? */
  551. for (order = 0; order < fir->order; order++)
  552. accum += (int64_t) firbuf[index + order] * fir->coeff[order];
  553. for (order = 0; order < iir->order; order++)
  554. accum += (int64_t) iirbuf[index + order] * iir->coeff[order];
  555. accum = accum >> filter_shift;
  556. result = (accum + residual) & mask;
  557. --index;
  558. firbuf[index] = result;
  559. iirbuf[index] = result - accum;
  560. m->sample_buffer[i + s->blockpos][channel] = result;
  561. }
  562. memcpy(fir->state, &firbuf[index], MAX_FIR_ORDER * sizeof(int32_t));
  563. memcpy(iir->state, &iirbuf[index], MAX_IIR_ORDER * sizeof(int32_t));
  564. }
  565. /** Read a block of PCM residual data (or actual if no filtering active). */
  566. static int read_block_data(MLPDecodeContext *m, GetBitContext *gbp,
  567. unsigned int substr)
  568. {
  569. SubStream *s = &m->substream[substr];
  570. unsigned int i, ch, expected_stream_pos = 0;
  571. if (s->data_check_present) {
  572. expected_stream_pos = get_bits_count(gbp);
  573. expected_stream_pos += get_bits(gbp, 16);
  574. av_log(m->avctx, AV_LOG_WARNING, "This file contains some features "
  575. "we have not tested yet. %s\n", sample_message);
  576. }
  577. if (s->blockpos + s->blocksize > m->access_unit_size) {
  578. av_log(m->avctx, AV_LOG_ERROR, "too many audio samples in frame\n");
  579. return -1;
  580. }
  581. memset(&m->bypassed_lsbs[s->blockpos][0], 0,
  582. s->blocksize * sizeof(m->bypassed_lsbs[0]));
  583. for (i = 0; i < s->blocksize; i++) {
  584. if (read_huff_channels(m, gbp, substr, i) < 0)
  585. return -1;
  586. }
  587. for (ch = s->min_channel; ch <= s->max_channel; ch++) {
  588. filter_channel(m, substr, ch);
  589. }
  590. s->blockpos += s->blocksize;
  591. if (s->data_check_present) {
  592. if (get_bits_count(gbp) != expected_stream_pos)
  593. av_log(m->avctx, AV_LOG_ERROR, "block data length mismatch\n");
  594. skip_bits(gbp, 8);
  595. }
  596. return 0;
  597. }
  598. /** Data table used for TrueHD noise generation function. */
  599. static const int8_t noise_table[256] = {
  600. 30, 51, 22, 54, 3, 7, -4, 38, 14, 55, 46, 81, 22, 58, -3, 2,
  601. 52, 31, -7, 51, 15, 44, 74, 30, 85, -17, 10, 33, 18, 80, 28, 62,
  602. 10, 32, 23, 69, 72, 26, 35, 17, 73, 60, 8, 56, 2, 6, -2, -5,
  603. 51, 4, 11, 50, 66, 76, 21, 44, 33, 47, 1, 26, 64, 48, 57, 40,
  604. 38, 16, -10, -28, 92, 22, -18, 29, -10, 5, -13, 49, 19, 24, 70, 34,
  605. 61, 48, 30, 14, -6, 25, 58, 33, 42, 60, 67, 17, 54, 17, 22, 30,
  606. 67, 44, -9, 50, -11, 43, 40, 32, 59, 82, 13, 49, -14, 55, 60, 36,
  607. 48, 49, 31, 47, 15, 12, 4, 65, 1, 23, 29, 39, 45, -2, 84, 69,
  608. 0, 72, 37, 57, 27, 41, -15, -16, 35, 31, 14, 61, 24, 0, 27, 24,
  609. 16, 41, 55, 34, 53, 9, 56, 12, 25, 29, 53, 5, 20, -20, -8, 20,
  610. 13, 28, -3, 78, 38, 16, 11, 62, 46, 29, 21, 24, 46, 65, 43, -23,
  611. 89, 18, 74, 21, 38, -12, 19, 12, -19, 8, 15, 33, 4, 57, 9, -8,
  612. 36, 35, 26, 28, 7, 83, 63, 79, 75, 11, 3, 87, 37, 47, 34, 40,
  613. 39, 19, 20, 42, 27, 34, 39, 77, 13, 42, 59, 64, 45, -1, 32, 37,
  614. 45, -5, 53, -6, 7, 36, 50, 23, 6, 32, 9, -21, 18, 71, 27, 52,
  615. -25, 31, 35, 42, -1, 68, 63, 52, 26, 43, 66, 37, 41, 25, 40, 70,
  616. };
  617. /** Noise generation functions.
  618. * I'm not sure what these are for - they seem to be some kind of pseudorandom
  619. * sequence generators, used to generate noise data which is used when the
  620. * channels are rematrixed. I'm not sure if they provide a practical benefit
  621. * to compression, or just obfuscate the decoder. Are they for some kind of
  622. * dithering? */
  623. /** Generate two channels of noise, used in the matrix when
  624. * restart sync word == 0x31ea. */
  625. static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr)
  626. {
  627. SubStream *s = &m->substream[substr];
  628. unsigned int i;
  629. uint32_t seed = s->noisegen_seed;
  630. unsigned int maxchan = s->max_matrix_channel;
  631. for (i = 0; i < s->blockpos; i++) {
  632. uint16_t seed_shr7 = seed >> 7;
  633. m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift;
  634. m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7) << s->noise_shift;
  635. seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);
  636. }
  637. s->noisegen_seed = seed;
  638. }
  639. /** Generate a block of noise, used when restart sync word == 0x31eb. */
  640. static void fill_noise_buffer(MLPDecodeContext *m, unsigned int substr)
  641. {
  642. SubStream *s = &m->substream[substr];
  643. unsigned int i;
  644. uint32_t seed = s->noisegen_seed;
  645. for (i = 0; i < m->access_unit_size_pow2; i++) {
  646. uint8_t seed_shr15 = seed >> 15;
  647. m->noise_buffer[i] = noise_table[seed_shr15];
  648. seed = (seed << 8) ^ seed_shr15 ^ (seed_shr15 << 5);
  649. }
  650. s->noisegen_seed = seed;
  651. }
  652. /** Apply the channel matrices in turn to reconstruct the original audio
  653. * samples. */
  654. static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
  655. {
  656. SubStream *s = &m->substream[substr];
  657. unsigned int mat, src_ch, i;
  658. unsigned int maxchan;
  659. maxchan = s->max_matrix_channel;
  660. if (!s->noise_type) {
  661. generate_2_noise_channels(m, substr);
  662. maxchan += 2;
  663. } else {
  664. fill_noise_buffer(m, substr);
  665. }
  666. for (mat = 0; mat < s->num_primitive_matrices; mat++) {
  667. int matrix_noise_shift = s->matrix_noise_shift[mat];
  668. unsigned int dest_ch = s->matrix_out_ch[mat];
  669. int32_t mask = MSB_MASK(s->quant_step_size[dest_ch]);
  670. /* TODO: DSPContext? */
  671. for (i = 0; i < s->blockpos; i++) {
  672. int64_t accum = 0;
  673. for (src_ch = 0; src_ch <= maxchan; src_ch++) {
  674. accum += (int64_t)m->sample_buffer[i][src_ch]
  675. * s->matrix_coeff[mat][src_ch];
  676. }
  677. if (matrix_noise_shift) {
  678. uint32_t index = s->num_primitive_matrices - mat;
  679. index = (i * (index * 2 + 1) + index) & (m->access_unit_size_pow2 - 1);
  680. accum += m->noise_buffer[index] << (matrix_noise_shift + 7);
  681. }
  682. m->sample_buffer[i][dest_ch] = ((accum >> 14) & mask)
  683. + m->bypassed_lsbs[i][mat];
  684. }
  685. }
  686. }
  687. /** Write the audio data into the output buffer. */
  688. static int output_data_internal(MLPDecodeContext *m, unsigned int substr,
  689. uint8_t *data, unsigned int *data_size, int is32)
  690. {
  691. SubStream *s = &m->substream[substr];
  692. unsigned int i, out_ch = 0;
  693. int32_t *data_32 = (int32_t*) data;
  694. int16_t *data_16 = (int16_t*) data;
  695. if (*data_size < (s->max_channel + 1) * s->blockpos * (is32 ? 4 : 2))
  696. return -1;
  697. for (i = 0; i < s->blockpos; i++) {
  698. for (out_ch = 0; out_ch <= s->max_matrix_channel; out_ch++) {
  699. int mat_ch = s->ch_assign[out_ch];
  700. int32_t sample = m->sample_buffer[i][mat_ch]
  701. << s->output_shift[mat_ch];
  702. s->lossless_check_data ^= (sample & 0xffffff) << mat_ch;
  703. if (is32) *data_32++ = sample << 8;
  704. else *data_16++ = sample >> 8;
  705. }
  706. }
  707. *data_size = i * out_ch * (is32 ? 4 : 2);
  708. return 0;
  709. }
  710. static int output_data(MLPDecodeContext *m, unsigned int substr,
  711. uint8_t *data, unsigned int *data_size)
  712. {
  713. if (m->avctx->sample_fmt == SAMPLE_FMT_S32)
  714. return output_data_internal(m, substr, data, data_size, 1);
  715. else
  716. return output_data_internal(m, substr, data, data_size, 0);
  717. }
  718. /** Read an access unit from the stream.
  719. * Returns < 0 on error, 0 if not enough data is present in the input stream
  720. * otherwise returns the number of bytes consumed. */
  721. static int read_access_unit(AVCodecContext *avctx, void* data, int *data_size,
  722. AVPacket *avpkt)
  723. {
  724. const uint8_t *buf = avpkt->data;
  725. int buf_size = avpkt->size;
  726. MLPDecodeContext *m = avctx->priv_data;
  727. GetBitContext gb;
  728. unsigned int length, substr;
  729. unsigned int substream_start;
  730. unsigned int header_size = 4;
  731. unsigned int substr_header_size = 0;
  732. uint8_t substream_parity_present[MAX_SUBSTREAMS];
  733. uint16_t substream_data_len[MAX_SUBSTREAMS];
  734. uint8_t parity_bits;
  735. if (buf_size < 4)
  736. return 0;
  737. length = (AV_RB16(buf) & 0xfff) * 2;
  738. if (length > buf_size)
  739. return -1;
  740. init_get_bits(&gb, (buf + 4), (length - 4) * 8);
  741. m->is_major_sync_unit = 0;
  742. if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {
  743. if (read_major_sync(m, &gb) < 0)
  744. goto error;
  745. m->is_major_sync_unit = 1;
  746. header_size += 28;
  747. }
  748. if (!m->params_valid) {
  749. av_log(m->avctx, AV_LOG_WARNING,
  750. "Stream parameters not seen; skipping frame.\n");
  751. *data_size = 0;
  752. return length;
  753. }
  754. substream_start = 0;
  755. for (substr = 0; substr < m->num_substreams; substr++) {
  756. int extraword_present, checkdata_present, end, nonrestart_substr;
  757. extraword_present = get_bits1(&gb);
  758. nonrestart_substr = get_bits1(&gb);
  759. checkdata_present = get_bits1(&gb);
  760. skip_bits1(&gb);
  761. end = get_bits(&gb, 12) * 2;
  762. substr_header_size += 2;
  763. if (extraword_present) {
  764. if (m->avctx->codec_id == CODEC_ID_MLP) {
  765. av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
  766. goto error;
  767. }
  768. skip_bits(&gb, 16);
  769. substr_header_size += 2;
  770. }
  771. if (!(nonrestart_substr ^ m->is_major_sync_unit)) {
  772. av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");
  773. goto error;
  774. }
  775. if (end + header_size + substr_header_size > length) {
  776. av_log(m->avctx, AV_LOG_ERROR,
  777. "Indicated length of substream %d data goes off end of "
  778. "packet.\n", substr);
  779. end = length - header_size - substr_header_size;
  780. }
  781. if (end < substream_start) {
  782. av_log(avctx, AV_LOG_ERROR,
  783. "Indicated end offset of substream %d data "
  784. "is smaller than calculated start offset.\n",
  785. substr);
  786. goto error;
  787. }
  788. if (substr > m->max_decoded_substream)
  789. continue;
  790. substream_parity_present[substr] = checkdata_present;
  791. substream_data_len[substr] = end - substream_start;
  792. substream_start = end;
  793. }
  794. parity_bits = ff_mlp_calculate_parity(buf, 4);
  795. parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);
  796. if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {
  797. av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");
  798. goto error;
  799. }
  800. buf += header_size + substr_header_size;
  801. for (substr = 0; substr <= m->max_decoded_substream; substr++) {
  802. SubStream *s = &m->substream[substr];
  803. init_get_bits(&gb, buf, substream_data_len[substr] * 8);
  804. m->matrix_changed = 0;
  805. memset(m->filter_changed, 0, sizeof(m->filter_changed));
  806. s->blockpos = 0;
  807. do {
  808. unsigned int ch;
  809. if (get_bits1(&gb)) {
  810. if (get_bits1(&gb)) {
  811. /* A restart header should be present. */
  812. if (read_restart_header(m, &gb, buf, substr) < 0)
  813. goto next_substr;
  814. s->restart_seen = 1;
  815. }
  816. if (!s->restart_seen) {
  817. goto next_substr;
  818. }
  819. if (read_decoding_params(m, &gb, substr) < 0)
  820. goto next_substr;
  821. }
  822. if (m->matrix_changed > 1) {
  823. av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");
  824. goto next_substr;
  825. }
  826. for (ch = 0; ch < s->max_channel; ch++)
  827. if (m->filter_changed[ch][FIR] > 1 ||
  828. m->filter_changed[ch][IIR] > 1) {
  829. av_log(m->avctx, AV_LOG_ERROR, "Filters may change only once per access unit.\n");
  830. goto next_substr;
  831. }
  832. if (!s->restart_seen) {
  833. goto next_substr;
  834. }
  835. if (read_block_data(m, &gb, substr) < 0)
  836. return -1;
  837. if (get_bits_count(&gb) >= substream_data_len[substr] * 8)
  838. goto substream_length_mismatch;
  839. } while (!get_bits1(&gb));
  840. skip_bits(&gb, (-get_bits_count(&gb)) & 15);
  841. if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {
  842. int shorten_by;
  843. if (get_bits(&gb, 16) != 0xD234)
  844. return -1;
  845. shorten_by = get_bits(&gb, 16);
  846. if (m->avctx->codec_id == CODEC_ID_TRUEHD && shorten_by & 0x2000)
  847. s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
  848. else if (m->avctx->codec_id == CODEC_ID_MLP && shorten_by != 0xD234)
  849. return -1;
  850. if (substr == m->max_decoded_substream)
  851. av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");
  852. }
  853. if (substream_parity_present[substr]) {
  854. uint8_t parity, checksum;
  855. if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)
  856. goto substream_length_mismatch;
  857. parity = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);
  858. checksum = ff_mlp_checksum8 (buf, substream_data_len[substr] - 2);
  859. if ((get_bits(&gb, 8) ^ parity) != 0xa9 )
  860. av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);
  861. if ( get_bits(&gb, 8) != checksum)
  862. av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n" , substr);
  863. }
  864. if (substream_data_len[substr] * 8 != get_bits_count(&gb)) {
  865. goto substream_length_mismatch;
  866. }
  867. next_substr:
  868. if (!s->restart_seen) {
  869. av_log(m->avctx, AV_LOG_ERROR,
  870. "No restart header present in substream %d.\n", substr);
  871. }
  872. buf += substream_data_len[substr];
  873. }
  874. rematrix_channels(m, m->max_decoded_substream);
  875. if (output_data(m, m->max_decoded_substream, data, data_size) < 0)
  876. return -1;
  877. return length;
  878. substream_length_mismatch:
  879. av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
  880. return -1;
  881. error:
  882. m->params_valid = 0;
  883. return -1;
  884. }
  885. #if CONFIG_MLP_DECODER
  886. AVCodec mlp_decoder = {
  887. "mlp",
  888. CODEC_TYPE_AUDIO,
  889. CODEC_ID_MLP,
  890. sizeof(MLPDecodeContext),
  891. mlp_decode_init,
  892. NULL,
  893. NULL,
  894. read_access_unit,
  895. .long_name = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
  896. };
  897. #endif /* CONFIG_MLP_DECODER */
  898. #if CONFIG_TRUEHD_DECODER
  899. AVCodec truehd_decoder = {
  900. "truehd",
  901. CODEC_TYPE_AUDIO,
  902. CODEC_ID_TRUEHD,
  903. sizeof(MLPDecodeContext),
  904. mlp_decode_init,
  905. NULL,
  906. NULL,
  907. read_access_unit,
  908. .long_name = NULL_IF_CONFIG_SMALL("TrueHD"),
  909. };
  910. #endif /* CONFIG_TRUEHD_DECODER */