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.

1105 lines
36KB

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