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