FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
mlpdec.c
Go to the documentation of this file.
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 /**
23  * @file
24  * MLP decoder
25  */
26 
27 #include <stdint.h>
28 
29 #include "avcodec.h"
30 #include "libavutil/intreadwrite.h"
32 #include "get_bits.h"
33 #include "internal.h"
34 #include "libavutil/crc.h"
35 #include "parser.h"
36 #include "mlp_parser.h"
37 #include "mlpdsp.h"
38 #include "mlp.h"
39 
40 /** number of bits used for VLC lookup - longest Huffman code is 9 */
41 #define VLC_BITS 9
42 
43 typedef struct SubStream {
44  /// Set if a valid restart header has been read. Otherwise the substream cannot be decoded.
46 
47  //@{
48  /** restart header data */
49  /// The type of noise to be used in the rematrix stage.
50  uint16_t noise_type;
51 
52  /// The index of the first channel coded in this substream.
54  /// The index of the last channel coded in this substream.
56  /// The number of channels input into the rematrix stage.
58  /// For each channel output by the matrix, the output channel to map it to
60  /// The channel layout for this substream
61  uint64_t ch_layout;
62 
63  /// Channel coding parameters for channels in the substream
65 
66  /// The left shift applied to random noise in 0x31ea substreams.
68  /// The current seed value for the pseudorandom noise generator(s).
69  uint32_t noisegen_seed;
70 
71  /// Set if the substream contains extra info to check the size of VLC blocks.
73 
74  /// Bitmask of which parameter sets are conveyed in a decoding parameter block.
76 #define PARAM_BLOCKSIZE (1 << 7)
77 #define PARAM_MATRIX (1 << 6)
78 #define PARAM_OUTSHIFT (1 << 5)
79 #define PARAM_QUANTSTEP (1 << 4)
80 #define PARAM_FIR (1 << 3)
81 #define PARAM_IIR (1 << 2)
82 #define PARAM_HUFFOFFSET (1 << 1)
83 #define PARAM_PRESENCE (1 << 0)
84  //@}
85 
86  //@{
87  /** matrix data */
88 
89  /// Number of matrices to be applied.
91 
92  /// matrix output channel
94 
95  /// Whether the LSBs of the matrix output are encoded in the bitstream.
97  /// Matrix coefficients, stored as 2.14 fixed point.
99  /// Left shift to apply to noise values in 0x31eb substreams.
101  //@}
102 
103  /// Left shift to apply to Huffman-decoded residuals.
105 
106  /// number of PCM samples in current audio block
107  uint16_t blocksize;
108  /// Number of PCM samples decoded so far in this frame.
109  uint16_t blockpos;
110 
111  /// Left shift to apply to decoded PCM values to get final 24-bit output.
113 
114  /// Running XOR of all output samples.
116 
117 } SubStream;
118 
119 typedef struct MLPDecodeContext {
122 
123  /// Current access unit being read has a major sync.
125 
126  /// Set if a valid major sync block has been read. Otherwise no decoding is possible.
128 
129  /// Number of substreams contained within this stream.
131 
132  /// Index of the last substream to decode - further substreams are skipped.
134 
135  /// Stream needs channel reordering to comply with FFmpeg's channel order
137 
138  /// number of PCM samples contained in each frame
140  /// next power of two above the number of samples in each frame
142 
144 
147 
151 
154 
155 static const uint64_t thd_channel_order[] = {
157  AV_CH_FRONT_CENTER, // C
158  AV_CH_LOW_FREQUENCY, // LFE
163  AV_CH_BACK_CENTER, // Cs
164  AV_CH_TOP_CENTER, // Ts
167  AV_CH_TOP_FRONT_CENTER, // Cvh
168  AV_CH_LOW_FREQUENCY_2, // LFE2
169 };
170 
171 static uint64_t thd_channel_layout_extract_channel(uint64_t channel_layout,
172  int index)
173 {
174  int i;
175 
176  if (av_get_channel_layout_nb_channels(channel_layout) <= index)
177  return 0;
178 
179  for (i = 0; i < FF_ARRAY_ELEMS(thd_channel_order); i++)
180  if (channel_layout & thd_channel_order[i] && !index--)
181  return thd_channel_order[i];
182  return 0;
183 }
184 
185 static VLC huff_vlc[3];
186 
187 /** Initialize static data, constant between all invocations of the codec. */
188 
189 static av_cold void init_static(void)
190 {
191  if (!huff_vlc[0].bits) {
192  INIT_VLC_STATIC(&huff_vlc[0], VLC_BITS, 18,
193  &ff_mlp_huffman_tables[0][0][1], 2, 1,
194  &ff_mlp_huffman_tables[0][0][0], 2, 1, 512);
195  INIT_VLC_STATIC(&huff_vlc[1], VLC_BITS, 16,
196  &ff_mlp_huffman_tables[1][0][1], 2, 1,
197  &ff_mlp_huffman_tables[1][0][0], 2, 1, 512);
198  INIT_VLC_STATIC(&huff_vlc[2], VLC_BITS, 15,
199  &ff_mlp_huffman_tables[2][0][1], 2, 1,
200  &ff_mlp_huffman_tables[2][0][0], 2, 1, 512);
201  }
202 
203  ff_mlp_init_crc();
204 }
205 
207  unsigned int substr, unsigned int ch)
208 {
209  SubStream *s = &m->substream[substr];
210  ChannelParams *cp = &s->channel_params[ch];
211  int lsb_bits = cp->huff_lsbs - s->quant_step_size[ch];
212  int sign_shift = lsb_bits + (cp->codebook ? 2 - cp->codebook : -1);
213  int32_t sign_huff_offset = cp->huff_offset;
214 
215  if (cp->codebook > 0)
216  sign_huff_offset -= 7 << lsb_bits;
217 
218  if (sign_shift >= 0)
219  sign_huff_offset -= 1 << sign_shift;
220 
221  return sign_huff_offset;
222 }
223 
224 /** Read a sample, consisting of either, both or neither of entropy-coded MSBs
225  * and plain LSBs. */
226 
228  unsigned int substr, unsigned int pos)
229 {
230  SubStream *s = &m->substream[substr];
231  unsigned int mat, channel;
232 
233  for (mat = 0; mat < s->num_primitive_matrices; mat++)
234  if (s->lsb_bypass[mat])
235  m->bypassed_lsbs[pos + s->blockpos][mat] = get_bits1(gbp);
236 
237  for (channel = s->min_channel; channel <= s->max_channel; channel++) {
238  ChannelParams *cp = &s->channel_params[channel];
239  int codebook = cp->codebook;
240  int quant_step_size = s->quant_step_size[channel];
241  int lsb_bits = cp->huff_lsbs - quant_step_size;
242  int result = 0;
243 
244  if (codebook > 0)
245  result = get_vlc2(gbp, huff_vlc[codebook-1].table,
246  VLC_BITS, (9 + VLC_BITS - 1) / VLC_BITS);
247 
248  if (result < 0)
249  return AVERROR_INVALIDDATA;
250 
251  if (lsb_bits > 0)
252  result = (result << lsb_bits) + get_bits(gbp, lsb_bits);
253 
254  result += cp->sign_huff_offset;
255  result <<= quant_step_size;
256 
257  m->sample_buffer[pos + s->blockpos][channel] = result;
258  }
259 
260  return 0;
261 }
262 
264 {
265  MLPDecodeContext *m = avctx->priv_data;
266  int substr;
267 
268  init_static();
269  m->avctx = avctx;
270  for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
271  m->substream[substr].lossless_check_data = 0xffffffff;
272  ff_mlpdsp_init(&m->dsp);
273 
275  avctx->coded_frame = &m->frame;
276 
277  return 0;
278 }
279 
280 /** Read a major sync info header - contains high level information about
281  * the stream - sample rate, channel arrangement etc. Most of this
282  * information is not actually necessary for decoding, only for playback.
283  */
284 
286 {
288  int substr, ret;
289 
290  if ((ret = ff_mlp_read_major_sync(m->avctx, &mh, gb)) != 0)
291  return ret;
292 
293  if (mh.group1_bits == 0) {
294  av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown bits per sample\n");
295  return AVERROR_INVALIDDATA;
296  }
297  if (mh.group2_bits > mh.group1_bits) {
299  "Channel group 2 cannot have more bits per sample than group 1.\n");
300  return AVERROR_INVALIDDATA;
301  }
302 
305  "Channel groups with differing sample rates are not currently supported.\n");
306  return AVERROR_INVALIDDATA;
307  }
308 
309  if (mh.group1_samplerate == 0) {
310  av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown sampling rate\n");
311  return AVERROR_INVALIDDATA;
312  }
315  "Sampling rate %d is greater than the supported maximum (%d).\n",
317  return AVERROR_INVALIDDATA;
318  }
319  if (mh.access_unit_size > MAX_BLOCKSIZE) {
321  "Block size %d is greater than the supported maximum (%d).\n",
323  return AVERROR_INVALIDDATA;
324  }
327  "Block size pow2 %d is greater than the supported maximum (%d).\n",
329  return AVERROR_INVALIDDATA;
330  }
331 
332  if (mh.num_substreams == 0)
333  return AVERROR_INVALIDDATA;
334  if (m->avctx->codec_id == AV_CODEC_ID_MLP && mh.num_substreams > 2) {
335  av_log(m->avctx, AV_LOG_ERROR, "MLP only supports up to 2 substreams.\n");
336  return AVERROR_INVALIDDATA;
337  }
338  if (mh.num_substreams > MAX_SUBSTREAMS) {
340  "Number of substreams %d is larger than the maximum supported "
341  "by the decoder.\n", mh.num_substreams);
342  return AVERROR_PATCHWELCOME;
343  }
344 
347 
350 
353 
355  if (mh.group1_bits > 16)
357  else
359 
360  m->params_valid = 1;
361  for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
362  m->substream[substr].restart_seen = 0;
363 
364  /* Set the layout for each substream. When there's more than one, the first
365  * substream is Stereo. Subsequent substreams' layouts are indicated in the
366  * major sync. */
367  if (m->avctx->codec_id == AV_CODEC_ID_MLP) {
368  if ((substr = (mh.num_substreams > 1)))
370  m->substream[substr].ch_layout = mh.channel_layout_mlp;
371  } else {
372  if ((substr = (mh.num_substreams > 1)))
374  if (mh.num_substreams > 2)
377  else
380 
381  if (m->avctx->channels<=2 && m->substream[substr].ch_layout == AV_CH_LAYOUT_MONO && m->max_decoded_substream == 1) {
382  av_log(m->avctx, AV_LOG_DEBUG, "Mono stream with 2 substreams, ignoring 2nd\n");
383  m->max_decoded_substream = 0;
384  if (m->avctx->channels==2)
386  }
387  }
388 
389  m->needs_reordering = mh.channel_arrangement >= 18 && mh.channel_arrangement <= 20;
390 
391  return 0;
392 }
393 
394 /** Read a restart header from a block in a substream. This contains parameters
395  * required to decode the audio that do not change very often. Generally
396  * (always) present only in blocks following a major sync. */
397 
399  const uint8_t *buf, unsigned int substr)
400 {
401  SubStream *s = &m->substream[substr];
402  unsigned int ch;
403  int sync_word, tmp;
404  uint8_t checksum;
405  uint8_t lossless_check;
406  int start_count = get_bits_count(gbp);
407  const int max_matrix_channel = m->avctx->codec_id == AV_CODEC_ID_MLP
410  int max_channel, min_channel, matrix_channel;
411 
412  sync_word = get_bits(gbp, 13);
413 
414  if (sync_word != 0x31ea >> 1) {
416  "restart header sync incorrect (got 0x%04x)\n", sync_word);
417  return AVERROR_INVALIDDATA;
418  }
419 
420  s->noise_type = get_bits1(gbp);
421 
422  if (m->avctx->codec_id == AV_CODEC_ID_MLP && s->noise_type) {
423  av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n");
424  return AVERROR_INVALIDDATA;
425  }
426 
427  skip_bits(gbp, 16); /* Output timestamp */
428 
429  min_channel = get_bits(gbp, 4);
430  max_channel = get_bits(gbp, 4);
431  matrix_channel = get_bits(gbp, 4);
432 
433  if (matrix_channel > max_matrix_channel) {
435  "Max matrix channel cannot be greater than %d.\n",
436  max_matrix_channel);
437  return AVERROR_INVALIDDATA;
438  }
439 
440  if (max_channel != matrix_channel) {
442  "Max channel must be equal max matrix channel.\n");
443  return AVERROR_INVALIDDATA;
444  }
445 
446  /* This should happen for TrueHD streams with >6 channels and MLP's noise
447  * type. It is not yet known if this is allowed. */
448  if (max_channel > MAX_MATRIX_CHANNEL_MLP && !s->noise_type) {
450  "Number of channels %d is larger than the maximum supported "
451  "by the decoder.\n", max_channel + 2);
452  return AVERROR_PATCHWELCOME;
453  }
454 
455  if (min_channel > max_channel) {
457  "Substream min channel cannot be greater than max channel.\n");
458  return AVERROR_INVALIDDATA;
459  }
460 
461  s->min_channel = min_channel;
462  s->max_channel = max_channel;
463  s->max_matrix_channel = matrix_channel;
464 
465  if (m->avctx->request_channels > 0
466  && s->max_channel + 1 >= m->avctx->request_channels
467  && substr < m->max_decoded_substream) {
469  "Extracting %d channel downmix from substream %d. "
470  "Further substreams will be skipped.\n",
471  s->max_channel + 1, substr);
472  m->max_decoded_substream = substr;
473  }
474 
475  s->noise_shift = get_bits(gbp, 4);
476  s->noisegen_seed = get_bits(gbp, 23);
477 
478  skip_bits(gbp, 19);
479 
480  s->data_check_present = get_bits1(gbp);
481  lossless_check = get_bits(gbp, 8);
482  if (substr == m->max_decoded_substream
483  && s->lossless_check_data != 0xffffffff) {
485  if (tmp != lossless_check)
487  "Lossless check failed - expected %02x, calculated %02x.\n",
488  lossless_check, tmp);
489  }
490 
491  skip_bits(gbp, 16);
492 
493  memset(s->ch_assign, 0, sizeof(s->ch_assign));
494 
495  for (ch = 0; ch <= s->max_matrix_channel; ch++) {
496  int ch_assign = get_bits(gbp, 6);
497  if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD) {
498  uint64_t channel = thd_channel_layout_extract_channel(s->ch_layout,
499  ch_assign);
501  channel);
502  }
503  if (ch_assign > s->max_matrix_channel) {
505  "Assignment of matrix channel %d to invalid output channel %d.\n",
506  ch, ch_assign);
507  return AVERROR_PATCHWELCOME;
508  }
509  s->ch_assign[ch_assign] = ch;
510  }
511 
512  if (m->avctx->codec_id == AV_CODEC_ID_MLP && m->needs_reordering) {
515  int i = s->ch_assign[4];
516  s->ch_assign[4] = s->ch_assign[3];
517  s->ch_assign[3] = s->ch_assign[2];
518  s->ch_assign[2] = i;
519  } else if (m->avctx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK) {
520  FFSWAP(int, s->ch_assign[2], s->ch_assign[4]);
521  FFSWAP(int, s->ch_assign[3], s->ch_assign[5]);
522  }
523  }
524 
525  checksum = ff_mlp_restart_checksum(buf, get_bits_count(gbp) - start_count);
526 
527  if (checksum != get_bits(gbp, 8))
528  av_log(m->avctx, AV_LOG_ERROR, "restart header checksum error\n");
529 
530  /* Set default decoding parameters. */
531  s->param_presence_flags = 0xff;
532  s->num_primitive_matrices = 0;
533  s->blocksize = 8;
534  s->lossless_check_data = 0;
535 
536  memset(s->output_shift , 0, sizeof(s->output_shift ));
537  memset(s->quant_step_size, 0, sizeof(s->quant_step_size));
538 
539  for (ch = s->min_channel; ch <= s->max_channel; ch++) {
540  ChannelParams *cp = &s->channel_params[ch];
541  cp->filter_params[FIR].order = 0;
542  cp->filter_params[IIR].order = 0;
543  cp->filter_params[FIR].shift = 0;
544  cp->filter_params[IIR].shift = 0;
545 
546  /* Default audio coding is 24-bit raw PCM. */
547  cp->huff_offset = 0;
548  cp->sign_huff_offset = (-1) << 23;
549  cp->codebook = 0;
550  cp->huff_lsbs = 24;
551  }
552 
553  if (substr == m->max_decoded_substream) {
554  m->avctx->channels = s->max_matrix_channel + 1;
555  m->avctx->channel_layout = s->ch_layout;
556  }
557 
558  return 0;
559 }
560 
561 /** Read parameters for one of the prediction filters. */
562 
564  unsigned int substr, unsigned int channel,
565  unsigned int filter)
566 {
567  SubStream *s = &m->substream[substr];
569  const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;
570  const char fchar = filter ? 'I' : 'F';
571  int i, order;
572 
573  // Filter is 0 for FIR, 1 for IIR.
574  av_assert0(filter < 2);
575 
576  if (m->filter_changed[channel][filter]++ > 1) {
577  av_log(m->avctx, AV_LOG_ERROR, "Filters may change only once per access unit.\n");
578  return AVERROR_INVALIDDATA;
579  }
580 
581  order = get_bits(gbp, 4);
582  if (order > max_order) {
584  "%cIR filter order %d is greater than maximum %d.\n",
585  fchar, order, max_order);
586  return AVERROR_INVALIDDATA;
587  }
588  fp->order = order;
589 
590  if (order > 0) {
591  int32_t *fcoeff = s->channel_params[channel].coeff[filter];
592  int coeff_bits, coeff_shift;
593 
594  fp->shift = get_bits(gbp, 4);
595 
596  coeff_bits = get_bits(gbp, 5);
597  coeff_shift = get_bits(gbp, 3);
598  if (coeff_bits < 1 || coeff_bits > 16) {
600  "%cIR filter coeff_bits must be between 1 and 16.\n",
601  fchar);
602  return AVERROR_INVALIDDATA;
603  }
604  if (coeff_bits + coeff_shift > 16) {
606  "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",
607  fchar);
608  return AVERROR_INVALIDDATA;
609  }
610 
611  for (i = 0; i < order; i++)
612  fcoeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift;
613 
614  if (get_bits1(gbp)) {
615  int state_bits, state_shift;
616 
617  if (filter == FIR) {
619  "FIR filter has state data specified.\n");
620  return AVERROR_INVALIDDATA;
621  }
622 
623  state_bits = get_bits(gbp, 4);
624  state_shift = get_bits(gbp, 4);
625 
626  /* TODO: Check validity of state data. */
627 
628  for (i = 0; i < order; i++)
629  fp->state[i] = get_sbits(gbp, state_bits) << state_shift;
630  }
631  }
632 
633  return 0;
634 }
635 
636 /** Read parameters for primitive matrices. */
637 
638 static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitContext *gbp)
639 {
640  SubStream *s = &m->substream[substr];
641  unsigned int mat, ch;
642  const int max_primitive_matrices = m->avctx->codec_id == AV_CODEC_ID_MLP
645 
646  if (m->matrix_changed++ > 1) {
647  av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");
648  return AVERROR_INVALIDDATA;
649  }
650 
651  s->num_primitive_matrices = get_bits(gbp, 4);
652 
653  if (s->num_primitive_matrices > max_primitive_matrices) {
655  "Number of primitive matrices cannot be greater than %d.\n",
656  max_primitive_matrices);
657  return AVERROR_INVALIDDATA;
658  }
659 
660  for (mat = 0; mat < s->num_primitive_matrices; mat++) {
661  int frac_bits, max_chan;
662  s->matrix_out_ch[mat] = get_bits(gbp, 4);
663  frac_bits = get_bits(gbp, 4);
664  s->lsb_bypass [mat] = get_bits1(gbp);
665 
666  if (s->matrix_out_ch[mat] > s->max_matrix_channel) {
668  "Invalid channel %d specified as output from matrix.\n",
669  s->matrix_out_ch[mat]);
670  return AVERROR_INVALIDDATA;
671  }
672  if (frac_bits > 14) {
674  "Too many fractional bits specified.\n");
675  return AVERROR_INVALIDDATA;
676  }
677 
678  max_chan = s->max_matrix_channel;
679  if (!s->noise_type)
680  max_chan+=2;
681 
682  for (ch = 0; ch <= max_chan; ch++) {
683  int coeff_val = 0;
684  if (get_bits1(gbp))
685  coeff_val = get_sbits(gbp, frac_bits + 2);
686 
687  s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
688  }
689 
690  if (s->noise_type)
691  s->matrix_noise_shift[mat] = get_bits(gbp, 4);
692  else
693  s->matrix_noise_shift[mat] = 0;
694  }
695 
696  return 0;
697 }
698 
699 /** Read channel parameters. */
700 
701 static int read_channel_params(MLPDecodeContext *m, unsigned int substr,
702  GetBitContext *gbp, unsigned int ch)
703 {
704  SubStream *s = &m->substream[substr];
705  ChannelParams *cp = &s->channel_params[ch];
706  FilterParams *fir = &cp->filter_params[FIR];
707  FilterParams *iir = &cp->filter_params[IIR];
708  int ret;
709 
711  if (get_bits1(gbp))
712  if ((ret = read_filter_params(m, gbp, substr, ch, FIR)) < 0)
713  return ret;
714 
716  if (get_bits1(gbp))
717  if ((ret = read_filter_params(m, gbp, substr, ch, IIR)) < 0)
718  return ret;
719 
720  if (fir->order + iir->order > 8) {
721  av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");
722  return AVERROR_INVALIDDATA;
723  }
724 
725  if (fir->order && iir->order &&
726  fir->shift != iir->shift) {
728  "FIR and IIR filters must use the same precision.\n");
729  return AVERROR_INVALIDDATA;
730  }
731  /* The FIR and IIR filters must have the same precision.
732  * To simplify the filtering code, only the precision of the
733  * FIR filter is considered. If only the IIR filter is employed,
734  * the FIR filter precision is set to that of the IIR filter, so
735  * that the filtering code can use it. */
736  if (!fir->order && iir->order)
737  fir->shift = iir->shift;
738 
740  if (get_bits1(gbp))
741  cp->huff_offset = get_sbits(gbp, 15);
742 
743  cp->codebook = get_bits(gbp, 2);
744  cp->huff_lsbs = get_bits(gbp, 5);
745 
746  if (cp->huff_lsbs > 24) {
747  av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");
748  cp->huff_lsbs = 0;
749  return AVERROR_INVALIDDATA;
750  }
751 
752  cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
753 
754  return 0;
755 }
756 
757 /** Read decoding parameters that change more often than those in the restart
758  * header. */
759 
761  unsigned int substr)
762 {
763  SubStream *s = &m->substream[substr];
764  unsigned int ch;
765  int ret;
766 
768  if (get_bits1(gbp))
769  s->param_presence_flags = get_bits(gbp, 8);
770 
772  if (get_bits1(gbp)) {
773  s->blocksize = get_bits(gbp, 9);
774  if (s->blocksize < 8 || s->blocksize > m->access_unit_size) {
775  av_log(m->avctx, AV_LOG_ERROR, "Invalid blocksize.\n");
776  s->blocksize = 0;
777  return AVERROR_INVALIDDATA;
778  }
779  }
780 
782  if (get_bits1(gbp))
783  if ((ret = read_matrix_params(m, substr, gbp)) < 0)
784  return ret;
785 
787  if (get_bits1(gbp))
788  for (ch = 0; ch <= s->max_matrix_channel; ch++)
789  s->output_shift[ch] = get_sbits(gbp, 4);
790 
792  if (get_bits1(gbp))
793  for (ch = 0; ch <= s->max_channel; ch++) {
794  ChannelParams *cp = &s->channel_params[ch];
795 
796  s->quant_step_size[ch] = get_bits(gbp, 4);
797 
798  cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
799  }
800 
801  for (ch = s->min_channel; ch <= s->max_channel; ch++)
802  if (get_bits1(gbp))
803  if ((ret = read_channel_params(m, substr, gbp, ch)) < 0)
804  return ret;
805 
806  return 0;
807 }
808 
809 #define MSB_MASK(bits) (-1u << bits)
810 
811 /** Generate PCM samples using the prediction filters and residual values
812  * read from the data stream, and update the filter state. */
813 
814 static void filter_channel(MLPDecodeContext *m, unsigned int substr,
815  unsigned int channel)
816 {
817  SubStream *s = &m->substream[substr];
818  const int32_t *fircoeff = s->channel_params[channel].coeff[FIR];
820  int32_t *firbuf = state_buffer[FIR] + MAX_BLOCKSIZE;
821  int32_t *iirbuf = state_buffer[IIR] + MAX_BLOCKSIZE;
822  FilterParams *fir = &s->channel_params[channel].filter_params[FIR];
823  FilterParams *iir = &s->channel_params[channel].filter_params[IIR];
824  unsigned int filter_shift = fir->shift;
825  int32_t mask = MSB_MASK(s->quant_step_size[channel]);
826 
827  memcpy(firbuf, fir->state, MAX_FIR_ORDER * sizeof(int32_t));
828  memcpy(iirbuf, iir->state, MAX_IIR_ORDER * sizeof(int32_t));
829 
830  m->dsp.mlp_filter_channel(firbuf, fircoeff,
831  fir->order, iir->order,
832  filter_shift, mask, s->blocksize,
833  &m->sample_buffer[s->blockpos][channel]);
834 
835  memcpy(fir->state, firbuf - s->blocksize, MAX_FIR_ORDER * sizeof(int32_t));
836  memcpy(iir->state, iirbuf - s->blocksize, MAX_IIR_ORDER * sizeof(int32_t));
837 }
838 
839 /** Read a block of PCM residual data (or actual if no filtering active). */
840 
842  unsigned int substr)
843 {
844  SubStream *s = &m->substream[substr];
845  unsigned int i, ch, expected_stream_pos = 0;
846  int ret;
847 
848  if (s->data_check_present) {
849  expected_stream_pos = get_bits_count(gbp);
850  expected_stream_pos += get_bits(gbp, 16);
851  av_log_ask_for_sample(m->avctx, "This file contains some features "
852  "we have not tested yet.\n");
853  }
854 
855  if (s->blockpos + s->blocksize > m->access_unit_size) {
856  av_log(m->avctx, AV_LOG_ERROR, "too many audio samples in frame\n");
857  return AVERROR_INVALIDDATA;
858  }
859 
860  memset(&m->bypassed_lsbs[s->blockpos][0], 0,
861  s->blocksize * sizeof(m->bypassed_lsbs[0]));
862 
863  for (i = 0; i < s->blocksize; i++)
864  if ((ret = read_huff_channels(m, gbp, substr, i)) < 0)
865  return ret;
866 
867  for (ch = s->min_channel; ch <= s->max_channel; ch++)
868  filter_channel(m, substr, ch);
869 
870  s->blockpos += s->blocksize;
871 
872  if (s->data_check_present) {
873  if (get_bits_count(gbp) != expected_stream_pos)
874  av_log(m->avctx, AV_LOG_ERROR, "block data length mismatch\n");
875  skip_bits(gbp, 8);
876  }
877 
878  return 0;
879 }
880 
881 /** Data table used for TrueHD noise generation function. */
882 
883 static const int8_t noise_table[256] = {
884  30, 51, 22, 54, 3, 7, -4, 38, 14, 55, 46, 81, 22, 58, -3, 2,
885  52, 31, -7, 51, 15, 44, 74, 30, 85, -17, 10, 33, 18, 80, 28, 62,
886  10, 32, 23, 69, 72, 26, 35, 17, 73, 60, 8, 56, 2, 6, -2, -5,
887  51, 4, 11, 50, 66, 76, 21, 44, 33, 47, 1, 26, 64, 48, 57, 40,
888  38, 16, -10, -28, 92, 22, -18, 29, -10, 5, -13, 49, 19, 24, 70, 34,
889  61, 48, 30, 14, -6, 25, 58, 33, 42, 60, 67, 17, 54, 17, 22, 30,
890  67, 44, -9, 50, -11, 43, 40, 32, 59, 82, 13, 49, -14, 55, 60, 36,
891  48, 49, 31, 47, 15, 12, 4, 65, 1, 23, 29, 39, 45, -2, 84, 69,
892  0, 72, 37, 57, 27, 41, -15, -16, 35, 31, 14, 61, 24, 0, 27, 24,
893  16, 41, 55, 34, 53, 9, 56, 12, 25, 29, 53, 5, 20, -20, -8, 20,
894  13, 28, -3, 78, 38, 16, 11, 62, 46, 29, 21, 24, 46, 65, 43, -23,
895  89, 18, 74, 21, 38, -12, 19, 12, -19, 8, 15, 33, 4, 57, 9, -8,
896  36, 35, 26, 28, 7, 83, 63, 79, 75, 11, 3, 87, 37, 47, 34, 40,
897  39, 19, 20, 42, 27, 34, 39, 77, 13, 42, 59, 64, 45, -1, 32, 37,
898  45, -5, 53, -6, 7, 36, 50, 23, 6, 32, 9, -21, 18, 71, 27, 52,
899  -25, 31, 35, 42, -1, 68, 63, 52, 26, 43, 66, 37, 41, 25, 40, 70,
900 };
901 
902 /** Noise generation functions.
903  * I'm not sure what these are for - they seem to be some kind of pseudorandom
904  * sequence generators, used to generate noise data which is used when the
905  * channels are rematrixed. I'm not sure if they provide a practical benefit
906  * to compression, or just obfuscate the decoder. Are they for some kind of
907  * dithering? */
908 
909 /** Generate two channels of noise, used in the matrix when
910  * restart sync word == 0x31ea. */
911 
912 static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr)
913 {
914  SubStream *s = &m->substream[substr];
915  unsigned int i;
916  uint32_t seed = s->noisegen_seed;
917  unsigned int maxchan = s->max_matrix_channel;
918 
919  for (i = 0; i < s->blockpos; i++) {
920  uint16_t seed_shr7 = seed >> 7;
921  m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift;
922  m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7) << s->noise_shift;
923 
924  seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);
925  }
926 
927  s->noisegen_seed = seed;
928 }
929 
930 /** Generate a block of noise, used when restart sync word == 0x31eb. */
931 
932 static void fill_noise_buffer(MLPDecodeContext *m, unsigned int substr)
933 {
934  SubStream *s = &m->substream[substr];
935  unsigned int i;
936  uint32_t seed = s->noisegen_seed;
937 
938  for (i = 0; i < m->access_unit_size_pow2; i++) {
939  uint8_t seed_shr15 = seed >> 15;
940  m->noise_buffer[i] = noise_table[seed_shr15];
941  seed = (seed << 8) ^ seed_shr15 ^ (seed_shr15 << 5);
942  }
943 
944  s->noisegen_seed = seed;
945 }
946 
947 
948 /** Apply the channel matrices in turn to reconstruct the original audio
949  * samples. */
950 
951 static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
952 {
953  SubStream *s = &m->substream[substr];
954  unsigned int mat, src_ch, i;
955  unsigned int maxchan;
956 
957  maxchan = s->max_matrix_channel;
958  if (!s->noise_type) {
959  generate_2_noise_channels(m, substr);
960  maxchan += 2;
961  } else {
962  fill_noise_buffer(m, substr);
963  }
964 
965  for (mat = 0; mat < s->num_primitive_matrices; mat++) {
966  int matrix_noise_shift = s->matrix_noise_shift[mat];
967  unsigned int dest_ch = s->matrix_out_ch[mat];
968  int32_t mask = MSB_MASK(s->quant_step_size[dest_ch]);
969  int32_t *coeffs = s->matrix_coeff[mat];
970  int index = s->num_primitive_matrices - mat;
971  int index2 = 2 * index + 1;
972 
973  /* TODO: DSPContext? */
974 
975  for (i = 0; i < s->blockpos; i++) {
976  int32_t bypassed_lsb = m->bypassed_lsbs[i][mat];
977  int32_t *samples = m->sample_buffer[i];
978  int64_t accum = 0;
979 
980  for (src_ch = 0; src_ch <= maxchan; src_ch++)
981  accum += (int64_t) samples[src_ch] * coeffs[src_ch];
982 
983  if (matrix_noise_shift) {
984  index &= m->access_unit_size_pow2 - 1;
985  accum += m->noise_buffer[index] << (matrix_noise_shift + 7);
986  index += index2;
987  }
988 
989  samples[dest_ch] = ((accum >> 14) & mask) + bypassed_lsb;
990  }
991  }
992 }
993 
994 /** Write the audio data into the output buffer. */
995 
996 static int output_data(MLPDecodeContext *m, unsigned int substr,
997  void *data, int *got_frame_ptr)
998 {
999  AVCodecContext *avctx = m->avctx;
1000  SubStream *s = &m->substream[substr];
1001  unsigned int i, out_ch = 0;
1002  int32_t *data_32;
1003  int16_t *data_16;
1004  int ret;
1005  int is32 = (m->avctx->sample_fmt == AV_SAMPLE_FMT_S32);
1006 
1007  if (m->avctx->channels != s->max_matrix_channel + 1) {
1008  av_log(m->avctx, AV_LOG_ERROR, "channel count mismatch\n");
1009  return AVERROR_INVALIDDATA;
1010  }
1011 
1012  if (!s->blockpos) {
1013  av_log(avctx, AV_LOG_ERROR, "No samples to output.\n");
1014  return AVERROR_INVALIDDATA;
1015  }
1016 
1017  /* get output buffer */
1018  m->frame.nb_samples = s->blockpos;
1019  if ((ret = ff_get_buffer(avctx, &m->frame)) < 0) {
1020  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1021  return ret;
1022  }
1023  data_32 = (int32_t *)m->frame.data[0];
1024  data_16 = (int16_t *)m->frame.data[0];
1025 
1026  for (i = 0; i < s->blockpos; i++) {
1027  for (out_ch = 0; out_ch <= s->max_matrix_channel; out_ch++) {
1028  int mat_ch = s->ch_assign[out_ch];
1029  int32_t sample = m->sample_buffer[i][mat_ch]
1030  << s->output_shift[mat_ch];
1031  s->lossless_check_data ^= (sample & 0xffffff) << mat_ch;
1032  if (is32) *data_32++ = sample << 8;
1033  else *data_16++ = sample >> 8;
1034  }
1035  }
1036 
1037  *got_frame_ptr = 1;
1038  *(AVFrame *)data = m->frame;
1039 
1040  return 0;
1041 }
1042 
1043 /** Read an access unit from the stream.
1044  * @return negative on error, 0 if not enough data is present in the input stream,
1045  * otherwise the number of bytes consumed. */
1046 
1047 static int read_access_unit(AVCodecContext *avctx, void* data,
1048  int *got_frame_ptr, AVPacket *avpkt)
1049 {
1050  const uint8_t *buf = avpkt->data;
1051  int buf_size = avpkt->size;
1052  MLPDecodeContext *m = avctx->priv_data;
1053  GetBitContext gb;
1054  unsigned int length, substr;
1055  unsigned int substream_start;
1056  unsigned int header_size = 4;
1057  unsigned int substr_header_size = 0;
1058  uint8_t substream_parity_present[MAX_SUBSTREAMS];
1059  uint16_t substream_data_len[MAX_SUBSTREAMS];
1060  uint8_t parity_bits;
1061  int ret;
1062 
1063  if (buf_size < 4)
1064  return 0;
1065 
1066  length = (AV_RB16(buf) & 0xfff) * 2;
1067 
1068  if (length < 4 || length > buf_size)
1069  return AVERROR_INVALIDDATA;
1070 
1071  init_get_bits(&gb, (buf + 4), (length - 4) * 8);
1072 
1073  m->is_major_sync_unit = 0;
1074  if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {
1075  if (read_major_sync(m, &gb) < 0)
1076  goto error;
1077  m->is_major_sync_unit = 1;
1078  header_size += 28;
1079  }
1080 
1081  if (!m->params_valid) {
1083  "Stream parameters not seen; skipping frame.\n");
1084  *got_frame_ptr = 0;
1085  return length;
1086  }
1087 
1088  substream_start = 0;
1089 
1090  for (substr = 0; substr < m->num_substreams; substr++) {
1091  int extraword_present, checkdata_present, end, nonrestart_substr;
1092 
1093  extraword_present = get_bits1(&gb);
1094  nonrestart_substr = get_bits1(&gb);
1095  checkdata_present = get_bits1(&gb);
1096  skip_bits1(&gb);
1097 
1098  end = get_bits(&gb, 12) * 2;
1099 
1100  substr_header_size += 2;
1101 
1102  if (extraword_present) {
1103  if (m->avctx->codec_id == AV_CODEC_ID_MLP) {
1104  av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
1105  goto error;
1106  }
1107  skip_bits(&gb, 16);
1108  substr_header_size += 2;
1109  }
1110 
1111  if (!(nonrestart_substr ^ m->is_major_sync_unit)) {
1112  av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");
1113  goto error;
1114  }
1115 
1116  if (end + header_size + substr_header_size > length) {
1118  "Indicated length of substream %d data goes off end of "
1119  "packet.\n", substr);
1120  end = length - header_size - substr_header_size;
1121  }
1122 
1123  if (end < substream_start) {
1124  av_log(avctx, AV_LOG_ERROR,
1125  "Indicated end offset of substream %d data "
1126  "is smaller than calculated start offset.\n",
1127  substr);
1128  goto error;
1129  }
1130 
1131  if (substr > m->max_decoded_substream)
1132  continue;
1133 
1134  substream_parity_present[substr] = checkdata_present;
1135  substream_data_len[substr] = end - substream_start;
1136  substream_start = end;
1137  }
1138 
1139  parity_bits = ff_mlp_calculate_parity(buf, 4);
1140  parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);
1141 
1142  if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {
1143  av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");
1144  goto error;
1145  }
1146 
1147  buf += header_size + substr_header_size;
1148 
1149  for (substr = 0; substr <= m->max_decoded_substream; substr++) {
1150  SubStream *s = &m->substream[substr];
1151  init_get_bits(&gb, buf, substream_data_len[substr] * 8);
1152 
1153  m->matrix_changed = 0;
1154  memset(m->filter_changed, 0, sizeof(m->filter_changed));
1155 
1156  s->blockpos = 0;
1157  do {
1158  if (get_bits1(&gb)) {
1159  if (get_bits1(&gb)) {
1160  /* A restart header should be present. */
1161  if (read_restart_header(m, &gb, buf, substr) < 0)
1162  goto next_substr;
1163  s->restart_seen = 1;
1164  }
1165 
1166  if (!s->restart_seen)
1167  goto next_substr;
1168  if (read_decoding_params(m, &gb, substr) < 0)
1169  goto next_substr;
1170  }
1171 
1172  if (!s->restart_seen)
1173  goto next_substr;
1174 
1175  if ((ret = read_block_data(m, &gb, substr)) < 0)
1176  return ret;
1177 
1178  if (get_bits_count(&gb) >= substream_data_len[substr] * 8)
1179  goto substream_length_mismatch;
1180 
1181  } while (!get_bits1(&gb));
1182 
1183  skip_bits(&gb, (-get_bits_count(&gb)) & 15);
1184 
1185  if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {
1186  int shorten_by;
1187 
1188  if (get_bits(&gb, 16) != 0xD234)
1189  return AVERROR_INVALIDDATA;
1190 
1191  shorten_by = get_bits(&gb, 16);
1192  if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD && shorten_by & 0x2000)
1193  s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
1194  else if (m->avctx->codec_id == AV_CODEC_ID_MLP && shorten_by != 0xD234)
1195  return AVERROR_INVALIDDATA;
1196 
1197  if (substr == m->max_decoded_substream)
1198  av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");
1199  }
1200 
1201  if (substream_parity_present[substr]) {
1202  uint8_t parity, checksum;
1203 
1204  if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)
1205  goto substream_length_mismatch;
1206 
1207  parity = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);
1208  checksum = ff_mlp_checksum8 (buf, substream_data_len[substr] - 2);
1209 
1210  if ((get_bits(&gb, 8) ^ parity) != 0xa9 )
1211  av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);
1212  if ( get_bits(&gb, 8) != checksum)
1213  av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n" , substr);
1214  }
1215 
1216  if (substream_data_len[substr] * 8 != get_bits_count(&gb))
1217  goto substream_length_mismatch;
1218 
1219 next_substr:
1220  if (!s->restart_seen)
1222  "No restart header present in substream %d.\n", substr);
1223 
1224  buf += substream_data_len[substr];
1225  }
1226 
1228 
1229  if ((ret = output_data(m, m->max_decoded_substream, data, got_frame_ptr)) < 0)
1230  return ret;
1231 
1232  return length;
1233 
1234 substream_length_mismatch:
1235  av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
1236  return AVERROR_INVALIDDATA;
1237 
1238 error:
1239  m->params_valid = 0;
1240  return AVERROR_INVALIDDATA;
1241 }
1242 
1243 #if CONFIG_MLP_DECODER
1244 AVCodec ff_mlp_decoder = {
1245  .name = "mlp",
1246  .type = AVMEDIA_TYPE_AUDIO,
1247  .id = AV_CODEC_ID_MLP,
1248  .priv_data_size = sizeof(MLPDecodeContext),
1249  .init = mlp_decode_init,
1251  .capabilities = CODEC_CAP_DR1,
1252  .long_name = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
1253 };
1254 #endif
1255 #if CONFIG_TRUEHD_DECODER
1256 AVCodec ff_truehd_decoder = {
1257  .name = "truehd",
1258  .type = AVMEDIA_TYPE_AUDIO,
1259  .id = AV_CODEC_ID_TRUEHD,
1260  .priv_data_size = sizeof(MLPDecodeContext),
1261  .init = mlp_decode_init,
1263  .capabilities = CODEC_CAP_DR1,
1264  .long_name = NULL_IF_CONFIG_SMALL("TrueHD"),
1265 };
1266 #endif /* CONFIG_TRUEHD_DECODER */