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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
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 
41 #define VLC_BITS 9
42 
43 typedef struct SubStream {
46 
48 
49  uint16_t noise_type;
51 
61  uint64_t ch_layout;
62 
65 
69  uint32_t noisegen_seed;
70 
73 
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 
87 
91 
94 
102 
105 
107  uint16_t blocksize;
109  uint16_t blockpos;
110 
113 
116 
117 } SubStream;
118 
119 typedef struct MLPDecodeContext {
122 
125 
128 
131 
134 
139 
141 
144 
148 
151 
152 static const uint64_t thd_channel_order[] = {
154  AV_CH_FRONT_CENTER, // C
155  AV_CH_LOW_FREQUENCY, // LFE
160  AV_CH_BACK_CENTER, // Cs
161  AV_CH_TOP_CENTER, // Ts
164  AV_CH_TOP_FRONT_CENTER, // Cvh
165  AV_CH_LOW_FREQUENCY_2, // LFE2
166 };
167 
168 static uint64_t thd_channel_layout_extract_channel(uint64_t channel_layout,
169  int index)
170 {
171  int i;
172 
173  if (av_get_channel_layout_nb_channels(channel_layout) <= index)
174  return 0;
175 
176  for (i = 0; i < FF_ARRAY_ELEMS(thd_channel_order); i++)
177  if (channel_layout & thd_channel_order[i] && !index--)
178  return thd_channel_order[i];
179  return 0;
180 }
181 
182 static VLC huff_vlc[3];
183 
186 static av_cold void init_static(void)
187 {
188  if (!huff_vlc[0].bits) {
189  INIT_VLC_STATIC(&huff_vlc[0], VLC_BITS, 18,
190  &ff_mlp_huffman_tables[0][0][1], 2, 1,
191  &ff_mlp_huffman_tables[0][0][0], 2, 1, 512);
192  INIT_VLC_STATIC(&huff_vlc[1], VLC_BITS, 16,
193  &ff_mlp_huffman_tables[1][0][1], 2, 1,
194  &ff_mlp_huffman_tables[1][0][0], 2, 1, 512);
195  INIT_VLC_STATIC(&huff_vlc[2], VLC_BITS, 15,
196  &ff_mlp_huffman_tables[2][0][1], 2, 1,
197  &ff_mlp_huffman_tables[2][0][0], 2, 1, 512);
198  }
199 
200  ff_mlp_init_crc();
201 }
202 
204  unsigned int substr, unsigned int ch)
205 {
206  SubStream *s = &m->substream[substr];
207  ChannelParams *cp = &s->channel_params[ch];
208  int lsb_bits = cp->huff_lsbs - s->quant_step_size[ch];
209  int sign_shift = lsb_bits + (cp->codebook ? 2 - cp->codebook : -1);
210  int32_t sign_huff_offset = cp->huff_offset;
211 
212  if (cp->codebook > 0)
213  sign_huff_offset -= 7 << lsb_bits;
214 
215  if (sign_shift >= 0)
216  sign_huff_offset -= 1 << sign_shift;
217 
218  return sign_huff_offset;
219 }
220 
225  unsigned int substr, unsigned int pos)
226 {
227  SubStream *s = &m->substream[substr];
228  unsigned int mat, channel;
229 
230  for (mat = 0; mat < s->num_primitive_matrices; mat++)
231  if (s->lsb_bypass[mat])
232  m->bypassed_lsbs[pos + s->blockpos][mat] = get_bits1(gbp);
233 
234  for (channel = s->min_channel; channel <= s->max_channel; channel++) {
235  ChannelParams *cp = &s->channel_params[channel];
236  int codebook = cp->codebook;
237  int quant_step_size = s->quant_step_size[channel];
238  int lsb_bits = cp->huff_lsbs - quant_step_size;
239  int result = 0;
240 
241  if (codebook > 0)
242  result = get_vlc2(gbp, huff_vlc[codebook-1].table,
243  VLC_BITS, (9 + VLC_BITS - 1) / VLC_BITS);
244 
245  if (result < 0)
246  return AVERROR_INVALIDDATA;
247 
248  if (lsb_bits > 0)
249  result = (result << lsb_bits) + get_bits(gbp, lsb_bits);
250 
251  result += cp->sign_huff_offset;
252  result <<= quant_step_size;
253 
254  m->sample_buffer[pos + s->blockpos][channel] = result;
255  }
256 
257  return 0;
258 }
259 
261 {
262  MLPDecodeContext *m = avctx->priv_data;
263  int substr;
264 
265  init_static();
266  m->avctx = avctx;
267  for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
268  m->substream[substr].lossless_check_data = 0xffffffff;
269  ff_mlpdsp_init(&m->dsp);
270 
272  avctx->coded_frame = &m->frame;
273 
274  return 0;
275 }
276 
283 {
284  MLPHeaderInfo mh;
285  int substr, ret;
286 
287  if ((ret = ff_mlp_read_major_sync(m->avctx, &mh, gb)) != 0)
288  return ret;
289 
290  if (mh.group1_bits == 0) {
291  av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown bits per sample\n");
292  return AVERROR_INVALIDDATA;
293  }
294  if (mh.group2_bits > mh.group1_bits) {
296  "Channel group 2 cannot have more bits per sample than group 1.\n");
297  return AVERROR_INVALIDDATA;
298  }
299 
302  "Channel groups with differing sample rates are not currently supported.\n");
303  return AVERROR_INVALIDDATA;
304  }
305 
306  if (mh.group1_samplerate == 0) {
307  av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown sampling rate\n");
308  return AVERROR_INVALIDDATA;
309  }
312  "Sampling rate %d is greater than the supported maximum (%d).\n",
314  return AVERROR_INVALIDDATA;
315  }
316  if (mh.access_unit_size > MAX_BLOCKSIZE) {
318  "Block size %d is greater than the supported maximum (%d).\n",
320  return AVERROR_INVALIDDATA;
321  }
324  "Block size pow2 %d is greater than the supported maximum (%d).\n",
326  return AVERROR_INVALIDDATA;
327  }
328 
329  if (mh.num_substreams == 0)
330  return AVERROR_INVALIDDATA;
331  if (m->avctx->codec_id == AV_CODEC_ID_MLP && mh.num_substreams > 2) {
332  av_log(m->avctx, AV_LOG_ERROR, "MLP only supports up to 2 substreams.\n");
333  return AVERROR_INVALIDDATA;
334  }
335  if (mh.num_substreams > MAX_SUBSTREAMS) {
337  "Number of substreams %d is larger than the maximum supported "
338  "by the decoder.\n", mh.num_substreams);
339  return AVERROR_PATCHWELCOME;
340  }
341 
344 
347 
350 
352  if (mh.group1_bits > 16)
354  else
356 
357  m->params_valid = 1;
358  for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
359  m->substream[substr].restart_seen = 0;
360 
361  /* Set the layout for each substream. When there's more than one, the first
362  * substream is Stereo. Subsequent substreams' layouts are indicated in the
363  * major sync. */
364  if (m->avctx->codec_id == AV_CODEC_ID_MLP) {
365  if ((substr = (mh.num_substreams > 1)))
367  m->substream[substr].ch_layout = mh.channel_layout_mlp;
368  } else {
369  if ((substr = (mh.num_substreams > 1)))
371  if (mh.num_substreams > 2)
374  else
377  }
378 
379  return 0;
380 }
381 
387  const uint8_t *buf, unsigned int substr)
388 {
389  SubStream *s = &m->substream[substr];
390  unsigned int ch;
391  int sync_word, tmp;
392  uint8_t checksum;
393  uint8_t lossless_check;
394  int start_count = get_bits_count(gbp);
395  const int max_matrix_channel = m->avctx->codec_id == AV_CODEC_ID_MLP
398 
399  sync_word = get_bits(gbp, 13);
400 
401  if (sync_word != 0x31ea >> 1) {
403  "restart header sync incorrect (got 0x%04x)\n", sync_word);
404  return AVERROR_INVALIDDATA;
405  }
406 
407  s->noise_type = get_bits1(gbp);
408 
409  if (m->avctx->codec_id == AV_CODEC_ID_MLP && s->noise_type) {
410  av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n");
411  return AVERROR_INVALIDDATA;
412  }
413 
414  skip_bits(gbp, 16); /* Output timestamp */
415 
416  s->min_channel = get_bits(gbp, 4);
417  s->max_channel = get_bits(gbp, 4);
418  s->max_matrix_channel = get_bits(gbp, 4);
419 
420  if (s->max_matrix_channel > max_matrix_channel) {
422  "Max matrix channel cannot be greater than %d.\n",
423  max_matrix_channel);
424  return AVERROR_INVALIDDATA;
425  }
426 
427  if (s->max_channel != s->max_matrix_channel) {
429  "Max channel must be equal max matrix channel.\n");
430  return AVERROR_INVALIDDATA;
431  }
432 
433  /* This should happen for TrueHD streams with >6 channels and MLP's noise
434  * type. It is not yet known if this is allowed. */
437  "Number of channels %d is larger than the maximum supported "
438  "by the decoder.\n", s->max_channel + 2);
439  return AVERROR_PATCHWELCOME;
440  }
441 
442  if (s->min_channel > s->max_channel) {
444  "Substream min channel cannot be greater than max channel.\n");
445  return AVERROR_INVALIDDATA;
446  }
447 
448  if (m->avctx->request_channels > 0
449  && s->max_channel + 1 >= m->avctx->request_channels
450  && substr < m->max_decoded_substream) {
452  "Extracting %d channel downmix from substream %d. "
453  "Further substreams will be skipped.\n",
454  s->max_channel + 1, substr);
455  m->max_decoded_substream = substr;
456  }
457 
458  s->noise_shift = get_bits(gbp, 4);
459  s->noisegen_seed = get_bits(gbp, 23);
460 
461  skip_bits(gbp, 19);
462 
463  s->data_check_present = get_bits1(gbp);
464  lossless_check = get_bits(gbp, 8);
465  if (substr == m->max_decoded_substream
466  && s->lossless_check_data != 0xffffffff) {
468  if (tmp != lossless_check)
470  "Lossless check failed - expected %02x, calculated %02x.\n",
471  lossless_check, tmp);
472  }
473 
474  skip_bits(gbp, 16);
475 
476  memset(s->ch_assign, 0, sizeof(s->ch_assign));
477 
478  for (ch = 0; ch <= s->max_matrix_channel; ch++) {
479  int ch_assign = get_bits(gbp, 6);
480  if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD) {
481  uint64_t channel = thd_channel_layout_extract_channel(s->ch_layout,
482  ch_assign);
484  channel);
485  }
486  if (ch_assign > s->max_matrix_channel) {
488  "Assignment of matrix channel %d to invalid output channel %d.\n",
489  ch, ch_assign);
490  return AVERROR_PATCHWELCOME;
491  }
492  s->ch_assign[ch_assign] = ch;
493  }
494 
495  checksum = ff_mlp_restart_checksum(buf, get_bits_count(gbp) - start_count);
496 
497  if (checksum != get_bits(gbp, 8))
498  av_log(m->avctx, AV_LOG_ERROR, "restart header checksum error\n");
499 
500  /* Set default decoding parameters. */
501  s->param_presence_flags = 0xff;
502  s->num_primitive_matrices = 0;
503  s->blocksize = 8;
504  s->lossless_check_data = 0;
505 
506  memset(s->output_shift , 0, sizeof(s->output_shift ));
507  memset(s->quant_step_size, 0, sizeof(s->quant_step_size));
508 
509  for (ch = s->min_channel; ch <= s->max_channel; ch++) {
510  ChannelParams *cp = &s->channel_params[ch];
511  cp->filter_params[FIR].order = 0;
512  cp->filter_params[IIR].order = 0;
513  cp->filter_params[FIR].shift = 0;
514  cp->filter_params[IIR].shift = 0;
515 
516  /* Default audio coding is 24-bit raw PCM. */
517  cp->huff_offset = 0;
518  cp->sign_huff_offset = (-1) << 23;
519  cp->codebook = 0;
520  cp->huff_lsbs = 24;
521  }
522 
523  if (substr == m->max_decoded_substream) {
524  m->avctx->channels = s->max_matrix_channel + 1;
525  m->avctx->channel_layout = s->ch_layout;
526  }
527 
528  return 0;
529 }
530 
534  unsigned int substr, unsigned int channel,
535  unsigned int filter)
536 {
537  SubStream *s = &m->substream[substr];
539  const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;
540  const char fchar = filter ? 'I' : 'F';
541  int i, order;
542 
543  // Filter is 0 for FIR, 1 for IIR.
544  assert(filter < 2);
545 
546  if (m->filter_changed[channel][filter]++ > 1) {
547  av_log(m->avctx, AV_LOG_ERROR, "Filters may change only once per access unit.\n");
548  return AVERROR_INVALIDDATA;
549  }
550 
551  order = get_bits(gbp, 4);
552  if (order > max_order) {
554  "%cIR filter order %d is greater than maximum %d.\n",
555  fchar, order, max_order);
556  return AVERROR_INVALIDDATA;
557  }
558  fp->order = order;
559 
560  if (order > 0) {
561  int32_t *fcoeff = s->channel_params[channel].coeff[filter];
562  int coeff_bits, coeff_shift;
563 
564  fp->shift = get_bits(gbp, 4);
565 
566  coeff_bits = get_bits(gbp, 5);
567  coeff_shift = get_bits(gbp, 3);
568  if (coeff_bits < 1 || coeff_bits > 16) {
570  "%cIR filter coeff_bits must be between 1 and 16.\n",
571  fchar);
572  return AVERROR_INVALIDDATA;
573  }
574  if (coeff_bits + coeff_shift > 16) {
576  "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",
577  fchar);
578  return AVERROR_INVALIDDATA;
579  }
580 
581  for (i = 0; i < order; i++)
582  fcoeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift;
583 
584  if (get_bits1(gbp)) {
585  int state_bits, state_shift;
586 
587  if (filter == FIR) {
589  "FIR filter has state data specified.\n");
590  return AVERROR_INVALIDDATA;
591  }
592 
593  state_bits = get_bits(gbp, 4);
594  state_shift = get_bits(gbp, 4);
595 
596  /* TODO: Check validity of state data. */
597 
598  for (i = 0; i < order; i++)
599  fp->state[i] = get_sbits(gbp, state_bits) << state_shift;
600  }
601  }
602 
603  return 0;
604 }
605 
608 static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitContext *gbp)
609 {
610  SubStream *s = &m->substream[substr];
611  unsigned int mat, ch;
612  const int max_primitive_matrices = m->avctx->codec_id == AV_CODEC_ID_MLP
615 
616  if (m->matrix_changed++ > 1) {
617  av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");
618  return AVERROR_INVALIDDATA;
619  }
620 
621  s->num_primitive_matrices = get_bits(gbp, 4);
622 
623  if (s->num_primitive_matrices > max_primitive_matrices) {
625  "Number of primitive matrices cannot be greater than %d.\n",
626  max_primitive_matrices);
627  return AVERROR_INVALIDDATA;
628  }
629 
630  for (mat = 0; mat < s->num_primitive_matrices; mat++) {
631  int frac_bits, max_chan;
632  s->matrix_out_ch[mat] = get_bits(gbp, 4);
633  frac_bits = get_bits(gbp, 4);
634  s->lsb_bypass [mat] = get_bits1(gbp);
635 
636  if (s->matrix_out_ch[mat] > s->max_matrix_channel) {
638  "Invalid channel %d specified as output from matrix.\n",
639  s->matrix_out_ch[mat]);
640  return AVERROR_INVALIDDATA;
641  }
642  if (frac_bits > 14) {
644  "Too many fractional bits specified.\n");
645  return AVERROR_INVALIDDATA;
646  }
647 
648  max_chan = s->max_matrix_channel;
649  if (!s->noise_type)
650  max_chan+=2;
651 
652  for (ch = 0; ch <= max_chan; ch++) {
653  int coeff_val = 0;
654  if (get_bits1(gbp))
655  coeff_val = get_sbits(gbp, frac_bits + 2);
656 
657  s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
658  }
659 
660  if (s->noise_type)
661  s->matrix_noise_shift[mat] = get_bits(gbp, 4);
662  else
663  s->matrix_noise_shift[mat] = 0;
664  }
665 
666  return 0;
667 }
668 
671 static int read_channel_params(MLPDecodeContext *m, unsigned int substr,
672  GetBitContext *gbp, unsigned int ch)
673 {
674  SubStream *s = &m->substream[substr];
675  ChannelParams *cp = &s->channel_params[ch];
676  FilterParams *fir = &cp->filter_params[FIR];
677  FilterParams *iir = &cp->filter_params[IIR];
678  int ret;
679 
681  if (get_bits1(gbp))
682  if ((ret = read_filter_params(m, gbp, substr, ch, FIR)) < 0)
683  return ret;
684 
686  if (get_bits1(gbp))
687  if ((ret = read_filter_params(m, gbp, substr, ch, IIR)) < 0)
688  return ret;
689 
690  if (fir->order + iir->order > 8) {
691  av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");
692  return AVERROR_INVALIDDATA;
693  }
694 
695  if (fir->order && iir->order &&
696  fir->shift != iir->shift) {
698  "FIR and IIR filters must use the same precision.\n");
699  return AVERROR_INVALIDDATA;
700  }
701  /* The FIR and IIR filters must have the same precision.
702  * To simplify the filtering code, only the precision of the
703  * FIR filter is considered. If only the IIR filter is employed,
704  * the FIR filter precision is set to that of the IIR filter, so
705  * that the filtering code can use it. */
706  if (!fir->order && iir->order)
707  fir->shift = iir->shift;
708 
710  if (get_bits1(gbp))
711  cp->huff_offset = get_sbits(gbp, 15);
712 
713  cp->codebook = get_bits(gbp, 2);
714  cp->huff_lsbs = get_bits(gbp, 5);
715 
716  if (cp->huff_lsbs > 24) {
717  av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");
718  return AVERROR_INVALIDDATA;
719  }
720 
721  cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
722 
723  return 0;
724 }
725 
730  unsigned int substr)
731 {
732  SubStream *s = &m->substream[substr];
733  unsigned int ch;
734  int ret;
735 
737  if (get_bits1(gbp))
738  s->param_presence_flags = get_bits(gbp, 8);
739 
741  if (get_bits1(gbp)) {
742  s->blocksize = get_bits(gbp, 9);
743  if (s->blocksize < 8 || s->blocksize > m->access_unit_size) {
744  av_log(m->avctx, AV_LOG_ERROR, "Invalid blocksize.");
745  s->blocksize = 0;
746  return AVERROR_INVALIDDATA;
747  }
748  }
749 
751  if (get_bits1(gbp))
752  if ((ret = read_matrix_params(m, substr, gbp)) < 0)
753  return ret;
754 
756  if (get_bits1(gbp))
757  for (ch = 0; ch <= s->max_matrix_channel; ch++)
758  s->output_shift[ch] = get_sbits(gbp, 4);
759 
761  if (get_bits1(gbp))
762  for (ch = 0; ch <= s->max_channel; ch++) {
763  ChannelParams *cp = &s->channel_params[ch];
764 
765  s->quant_step_size[ch] = get_bits(gbp, 4);
766 
767  cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
768  }
769 
770  for (ch = s->min_channel; ch <= s->max_channel; ch++)
771  if (get_bits1(gbp))
772  if ((ret = read_channel_params(m, substr, gbp, ch)) < 0)
773  return ret;
774 
775  return 0;
776 }
777 
778 #define MSB_MASK(bits) (-1u << bits)
779 
783 static void filter_channel(MLPDecodeContext *m, unsigned int substr,
784  unsigned int channel)
785 {
786  SubStream *s = &m->substream[substr];
787  const int32_t *fircoeff = s->channel_params[channel].coeff[FIR];
789  int32_t *firbuf = state_buffer[FIR] + MAX_BLOCKSIZE;
790  int32_t *iirbuf = state_buffer[IIR] + MAX_BLOCKSIZE;
791  FilterParams *fir = &s->channel_params[channel].filter_params[FIR];
792  FilterParams *iir = &s->channel_params[channel].filter_params[IIR];
793  unsigned int filter_shift = fir->shift;
794  int32_t mask = MSB_MASK(s->quant_step_size[channel]);
795 
796  memcpy(firbuf, fir->state, MAX_FIR_ORDER * sizeof(int32_t));
797  memcpy(iirbuf, iir->state, MAX_IIR_ORDER * sizeof(int32_t));
798 
799  m->dsp.mlp_filter_channel(firbuf, fircoeff,
800  fir->order, iir->order,
801  filter_shift, mask, s->blocksize,
802  &m->sample_buffer[s->blockpos][channel]);
803 
804  memcpy(fir->state, firbuf - s->blocksize, MAX_FIR_ORDER * sizeof(int32_t));
805  memcpy(iir->state, iirbuf - s->blocksize, MAX_IIR_ORDER * sizeof(int32_t));
806 }
807 
811  unsigned int substr)
812 {
813  SubStream *s = &m->substream[substr];
814  unsigned int i, ch, expected_stream_pos = 0;
815  int ret;
816 
817  if (s->data_check_present) {
818  expected_stream_pos = get_bits_count(gbp);
819  expected_stream_pos += get_bits(gbp, 16);
820  av_log_ask_for_sample(m->avctx, "This file contains some features "
821  "we have not tested yet.\n");
822  }
823 
824  if (s->blockpos + s->blocksize > m->access_unit_size) {
825  av_log(m->avctx, AV_LOG_ERROR, "too many audio samples in frame\n");
826  return AVERROR_INVALIDDATA;
827  }
828 
829  memset(&m->bypassed_lsbs[s->blockpos][0], 0,
830  s->blocksize * sizeof(m->bypassed_lsbs[0]));
831 
832  for (i = 0; i < s->blocksize; i++)
833  if ((ret = read_huff_channels(m, gbp, substr, i)) < 0)
834  return ret;
835 
836  for (ch = s->min_channel; ch <= s->max_channel; ch++)
837  filter_channel(m, substr, ch);
838 
839  s->blockpos += s->blocksize;
840 
841  if (s->data_check_present) {
842  if (get_bits_count(gbp) != expected_stream_pos)
843  av_log(m->avctx, AV_LOG_ERROR, "block data length mismatch\n");
844  skip_bits(gbp, 8);
845  }
846 
847  return 0;
848 }
849 
852 static const int8_t noise_table[256] = {
853  30, 51, 22, 54, 3, 7, -4, 38, 14, 55, 46, 81, 22, 58, -3, 2,
854  52, 31, -7, 51, 15, 44, 74, 30, 85, -17, 10, 33, 18, 80, 28, 62,
855  10, 32, 23, 69, 72, 26, 35, 17, 73, 60, 8, 56, 2, 6, -2, -5,
856  51, 4, 11, 50, 66, 76, 21, 44, 33, 47, 1, 26, 64, 48, 57, 40,
857  38, 16, -10, -28, 92, 22, -18, 29, -10, 5, -13, 49, 19, 24, 70, 34,
858  61, 48, 30, 14, -6, 25, 58, 33, 42, 60, 67, 17, 54, 17, 22, 30,
859  67, 44, -9, 50, -11, 43, 40, 32, 59, 82, 13, 49, -14, 55, 60, 36,
860  48, 49, 31, 47, 15, 12, 4, 65, 1, 23, 29, 39, 45, -2, 84, 69,
861  0, 72, 37, 57, 27, 41, -15, -16, 35, 31, 14, 61, 24, 0, 27, 24,
862  16, 41, 55, 34, 53, 9, 56, 12, 25, 29, 53, 5, 20, -20, -8, 20,
863  13, 28, -3, 78, 38, 16, 11, 62, 46, 29, 21, 24, 46, 65, 43, -23,
864  89, 18, 74, 21, 38, -12, 19, 12, -19, 8, 15, 33, 4, 57, 9, -8,
865  36, 35, 26, 28, 7, 83, 63, 79, 75, 11, 3, 87, 37, 47, 34, 40,
866  39, 19, 20, 42, 27, 34, 39, 77, 13, 42, 59, 64, 45, -1, 32, 37,
867  45, -5, 53, -6, 7, 36, 50, 23, 6, 32, 9, -21, 18, 71, 27, 52,
868  -25, 31, 35, 42, -1, 68, 63, 52, 26, 43, 66, 37, 41, 25, 40, 70,
869 };
870 
881 static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr)
882 {
883  SubStream *s = &m->substream[substr];
884  unsigned int i;
885  uint32_t seed = s->noisegen_seed;
886  unsigned int maxchan = s->max_matrix_channel;
887 
888  for (i = 0; i < s->blockpos; i++) {
889  uint16_t seed_shr7 = seed >> 7;
890  m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift;
891  m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7) << s->noise_shift;
892 
893  seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);
894  }
895 
896  s->noisegen_seed = seed;
897 }
898 
901 static void fill_noise_buffer(MLPDecodeContext *m, unsigned int substr)
902 {
903  SubStream *s = &m->substream[substr];
904  unsigned int i;
905  uint32_t seed = s->noisegen_seed;
906 
907  for (i = 0; i < m->access_unit_size_pow2; i++) {
908  uint8_t seed_shr15 = seed >> 15;
909  m->noise_buffer[i] = noise_table[seed_shr15];
910  seed = (seed << 8) ^ seed_shr15 ^ (seed_shr15 << 5);
911  }
912 
913  s->noisegen_seed = seed;
914 }
915 
916 
920 static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
921 {
922  SubStream *s = &m->substream[substr];
923  unsigned int mat, src_ch, i;
924  unsigned int maxchan;
925 
926  maxchan = s->max_matrix_channel;
927  if (!s->noise_type) {
928  generate_2_noise_channels(m, substr);
929  maxchan += 2;
930  } else {
931  fill_noise_buffer(m, substr);
932  }
933 
934  for (mat = 0; mat < s->num_primitive_matrices; mat++) {
935  int matrix_noise_shift = s->matrix_noise_shift[mat];
936  unsigned int dest_ch = s->matrix_out_ch[mat];
937  int32_t mask = MSB_MASK(s->quant_step_size[dest_ch]);
938  int32_t *coeffs = s->matrix_coeff[mat];
939  int index = s->num_primitive_matrices - mat;
940  int index2 = 2 * index + 1;
941 
942  /* TODO: DSPContext? */
943 
944  for (i = 0; i < s->blockpos; i++) {
945  int32_t bypassed_lsb = m->bypassed_lsbs[i][mat];
946  int32_t *samples = m->sample_buffer[i];
947  int64_t accum = 0;
948 
949  for (src_ch = 0; src_ch <= maxchan; src_ch++)
950  accum += (int64_t) samples[src_ch] * coeffs[src_ch];
951 
952  if (matrix_noise_shift) {
953  index &= m->access_unit_size_pow2 - 1;
954  accum += m->noise_buffer[index] << (matrix_noise_shift + 7);
955  index += index2;
956  }
957 
958  samples[dest_ch] = ((accum >> 14) & mask) + bypassed_lsb;
959  }
960  }
961 }
962 
965 static int output_data(MLPDecodeContext *m, unsigned int substr,
966  void *data, int *got_frame_ptr)
967 {
968  AVCodecContext *avctx = m->avctx;
969  SubStream *s = &m->substream[substr];
970  unsigned int i, out_ch = 0;
971  int32_t *data_32;
972  int16_t *data_16;
973  int ret;
974  int is32 = (m->avctx->sample_fmt == AV_SAMPLE_FMT_S32);
975 
976  if (m->avctx->channels != s->max_matrix_channel + 1) {
977  av_log(m->avctx, AV_LOG_ERROR, "channel count mismatch\n");
978  return AVERROR_INVALIDDATA;
979  }
980 
981  if (!s->blockpos) {
982  av_log(avctx, AV_LOG_ERROR, "No samples to output.\n");
983  return AVERROR_INVALIDDATA;
984  }
985 
986  /* get output buffer */
987  m->frame.nb_samples = s->blockpos;
988  if ((ret = ff_get_buffer(avctx, &m->frame)) < 0) {
989  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
990  return ret;
991  }
992  data_32 = (int32_t *)m->frame.data[0];
993  data_16 = (int16_t *)m->frame.data[0];
994 
995  for (i = 0; i < s->blockpos; i++) {
996  for (out_ch = 0; out_ch <= s->max_matrix_channel; out_ch++) {
997  int mat_ch = s->ch_assign[out_ch];
998  int32_t sample = m->sample_buffer[i][mat_ch]
999  << s->output_shift[mat_ch];
1000  s->lossless_check_data ^= (sample & 0xffffff) << mat_ch;
1001  if (is32) *data_32++ = sample << 8;
1002  else *data_16++ = sample >> 8;
1003  }
1004  }
1005 
1006  *got_frame_ptr = 1;
1007  *(AVFrame *)data = m->frame;
1008 
1009  return 0;
1010 }
1011 
1016 static int read_access_unit(AVCodecContext *avctx, void* data,
1017  int *got_frame_ptr, AVPacket *avpkt)
1018 {
1019  const uint8_t *buf = avpkt->data;
1020  int buf_size = avpkt->size;
1021  MLPDecodeContext *m = avctx->priv_data;
1022  GetBitContext gb;
1023  unsigned int length, substr;
1024  unsigned int substream_start;
1025  unsigned int header_size = 4;
1026  unsigned int substr_header_size = 0;
1027  uint8_t substream_parity_present[MAX_SUBSTREAMS];
1028  uint16_t substream_data_len[MAX_SUBSTREAMS];
1029  uint8_t parity_bits;
1030  int ret;
1031 
1032  if (buf_size < 4)
1033  return 0;
1034 
1035  length = (AV_RB16(buf) & 0xfff) * 2;
1036 
1037  if (length < 4 || length > buf_size)
1038  return AVERROR_INVALIDDATA;
1039 
1040  init_get_bits(&gb, (buf + 4), (length - 4) * 8);
1041 
1042  m->is_major_sync_unit = 0;
1043  if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {
1044  if (read_major_sync(m, &gb) < 0)
1045  goto error;
1046  m->is_major_sync_unit = 1;
1047  header_size += 28;
1048  }
1049 
1050  if (!m->params_valid) {
1052  "Stream parameters not seen; skipping frame.\n");
1053  *got_frame_ptr = 0;
1054  return length;
1055  }
1056 
1057  substream_start = 0;
1058 
1059  for (substr = 0; substr < m->num_substreams; substr++) {
1060  int extraword_present, checkdata_present, end, nonrestart_substr;
1061 
1062  extraword_present = get_bits1(&gb);
1063  nonrestart_substr = get_bits1(&gb);
1064  checkdata_present = get_bits1(&gb);
1065  skip_bits1(&gb);
1066 
1067  end = get_bits(&gb, 12) * 2;
1068 
1069  substr_header_size += 2;
1070 
1071  if (extraword_present) {
1072  if (m->avctx->codec_id == AV_CODEC_ID_MLP) {
1073  av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
1074  goto error;
1075  }
1076  skip_bits(&gb, 16);
1077  substr_header_size += 2;
1078  }
1079 
1080  if (!(nonrestart_substr ^ m->is_major_sync_unit)) {
1081  av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");
1082  goto error;
1083  }
1084 
1085  if (end + header_size + substr_header_size > length) {
1087  "Indicated length of substream %d data goes off end of "
1088  "packet.\n", substr);
1089  end = length - header_size - substr_header_size;
1090  }
1091 
1092  if (end < substream_start) {
1093  av_log(avctx, AV_LOG_ERROR,
1094  "Indicated end offset of substream %d data "
1095  "is smaller than calculated start offset.\n",
1096  substr);
1097  goto error;
1098  }
1099 
1100  if (substr > m->max_decoded_substream)
1101  continue;
1102 
1103  substream_parity_present[substr] = checkdata_present;
1104  substream_data_len[substr] = end - substream_start;
1105  substream_start = end;
1106  }
1107 
1108  parity_bits = ff_mlp_calculate_parity(buf, 4);
1109  parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);
1110 
1111  if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {
1112  av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");
1113  goto error;
1114  }
1115 
1116  buf += header_size + substr_header_size;
1117 
1118  for (substr = 0; substr <= m->max_decoded_substream; substr++) {
1119  SubStream *s = &m->substream[substr];
1120  init_get_bits(&gb, buf, substream_data_len[substr] * 8);
1121 
1122  m->matrix_changed = 0;
1123  memset(m->filter_changed, 0, sizeof(m->filter_changed));
1124 
1125  s->blockpos = 0;
1126  do {
1127  if (get_bits1(&gb)) {
1128  if (get_bits1(&gb)) {
1129  /* A restart header should be present. */
1130  if (read_restart_header(m, &gb, buf, substr) < 0)
1131  goto next_substr;
1132  s->restart_seen = 1;
1133  }
1134 
1135  if (!s->restart_seen)
1136  goto next_substr;
1137  if (read_decoding_params(m, &gb, substr) < 0)
1138  goto next_substr;
1139  }
1140 
1141  if (!s->restart_seen)
1142  goto next_substr;
1143 
1144  if ((ret = read_block_data(m, &gb, substr)) < 0)
1145  return ret;
1146 
1147  if (get_bits_count(&gb) >= substream_data_len[substr] * 8)
1148  goto substream_length_mismatch;
1149 
1150  } while (!get_bits1(&gb));
1151 
1152  skip_bits(&gb, (-get_bits_count(&gb)) & 15);
1153 
1154  if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {
1155  int shorten_by;
1156 
1157  if (get_bits(&gb, 16) != 0xD234)
1158  return AVERROR_INVALIDDATA;
1159 
1160  shorten_by = get_bits(&gb, 16);
1161  if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD && shorten_by & 0x2000)
1162  s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
1163  else if (m->avctx->codec_id == AV_CODEC_ID_MLP && shorten_by != 0xD234)
1164  return AVERROR_INVALIDDATA;
1165 
1166  if (substr == m->max_decoded_substream)
1167  av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");
1168  }
1169 
1170  if (substream_parity_present[substr]) {
1171  uint8_t parity, checksum;
1172 
1173  if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)
1174  goto substream_length_mismatch;
1175 
1176  parity = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);
1177  checksum = ff_mlp_checksum8 (buf, substream_data_len[substr] - 2);
1178 
1179  if ((get_bits(&gb, 8) ^ parity) != 0xa9 )
1180  av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);
1181  if ( get_bits(&gb, 8) != checksum)
1182  av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n" , substr);
1183  }
1184 
1185  if (substream_data_len[substr] * 8 != get_bits_count(&gb))
1186  goto substream_length_mismatch;
1187 
1188 next_substr:
1189  if (!s->restart_seen)
1191  "No restart header present in substream %d.\n", substr);
1192 
1193  buf += substream_data_len[substr];
1194  }
1195 
1197 
1198  if ((ret = output_data(m, m->max_decoded_substream, data, got_frame_ptr)) < 0)
1199  return ret;
1200 
1201  return length;
1202 
1203 substream_length_mismatch:
1204  av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
1205  return AVERROR_INVALIDDATA;
1206 
1207 error:
1208  m->params_valid = 0;
1209  return AVERROR_INVALIDDATA;
1210 }
1211 
1213  .name = "mlp",
1214  .type = AVMEDIA_TYPE_AUDIO,
1215  .id = AV_CODEC_ID_MLP,
1216  .priv_data_size = sizeof(MLPDecodeContext),
1217  .init = mlp_decode_init,
1219  .capabilities = CODEC_CAP_DR1,
1220  .long_name = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
1221 };
1222 
1223 #if CONFIG_TRUEHD_DECODER
1224 AVCodec ff_truehd_decoder = {
1225  .name = "truehd",
1226  .type = AVMEDIA_TYPE_AUDIO,
1227  .id = AV_CODEC_ID_TRUEHD,
1228  .priv_data_size = sizeof(MLPDecodeContext),
1229  .init = mlp_decode_init,
1231  .capabilities = CODEC_CAP_DR1,
1232  .long_name = NULL_IF_CONFIG_SMALL("TrueHD"),
1233 };
1234 #endif /* CONFIG_TRUEHD_DECODER */