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.

1054 lines
35KB

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