mlpdec.c 35 KB

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