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