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