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.

1181 lines
39KB

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