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.

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