vlc: Add header #include when the types are used
[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
7950e519 29#include "libavutil/internal.h"
b517af05 30#include "libavutil/intreadwrite.h"
99ccd2ba 31#include "libavutil/channel_layout.h"
b517af05 32#include "libavutil/crc.h"
00c72a1e
AH
33
34#include "avcodec.h"
35#include "bitstream.h"
36#include "internal.h"
b517af05
RP
37#include "parser.h"
38#include "mlp_parser.h"
2d6caade 39#include "mlpdsp.h"
ce15710f 40#include "mlp.h"
fcf5fc44 41#include "config.h"
73fc82f3 42#include "vlc.h"
b517af05 43
9906a2be 44/** number of bits used for VLC lookup - longest Huffman code is 9 */
fcf5fc44
BA
45#if ARCH_ARM
46#define VLC_BITS 5
47#define VLC_STATIC_SIZE 64
48#else
b517af05 49#define VLC_BITS 9
fcf5fc44
BA
50#define VLC_STATIC_SIZE 512
51#endif
b517af05 52
b517af05 53typedef struct SubStream {
c68fafe0 54 /// Set if a valid restart header has been read. Otherwise the substream cannot be decoded.
b517af05
RP
55 uint8_t restart_seen;
56
57 //@{
58 /** restart header data */
c68fafe0 59 /// The type of noise to be used in the rematrix stage.
b517af05
RP
60 uint16_t noise_type;
61
c68fafe0 62 /// The index of the first channel coded in this substream.
b517af05 63 uint8_t min_channel;
c68fafe0 64 /// The index of the last channel coded in this substream.
b517af05 65 uint8_t max_channel;
c68fafe0 66 /// The number of channels input into the rematrix stage.
b517af05 67 uint8_t max_matrix_channel;
c68fafe0 68 /// For each channel output by the matrix, the output channel to map it to
9731e7f1 69 uint8_t ch_assign[MAX_CHANNELS];
99ccd2ba 70 /// The channel layout for this substream
1f6e5dd4 71 uint64_t mask;
4b7f1a7c
TW
72 /// The matrix encoding mode for this substream
73 enum AVMatrixEncoding matrix_encoding;
b517af05 74
c68fafe0 75 /// Channel coding parameters for channels in the substream
22fb814c
NB
76 ChannelParams channel_params[MAX_CHANNELS];
77
c68fafe0 78 /// The left shift applied to random noise in 0x31ea substreams.
b517af05 79 uint8_t noise_shift;
c68fafe0 80 /// The current seed value for the pseudorandom noise generator(s).
b517af05
RP
81 uint32_t noisegen_seed;
82
c68fafe0 83 /// Set if the substream contains extra info to check the size of VLC blocks.
b517af05
RP
84 uint8_t data_check_present;
85
c68fafe0 86 /// Bitmask of which parameter sets are conveyed in a decoding parameter block.
b517af05
RP
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)
cbf3cf19 95#define PARAM_PRESENCE (1 << 0)
b517af05
RP
96 //@}
97
98 //@{
99 /** matrix data */
100
c68fafe0 101 /// Number of matrices to be applied.
b517af05
RP
102 uint8_t num_primitive_matrices;
103
c68fafe0 104 /// matrix output channel
b517af05
RP
105 uint8_t matrix_out_ch[MAX_MATRICES];
106
c68fafe0 107 /// Whether the LSBs of the matrix output are encoded in the bitstream.
b517af05 108 uint8_t lsb_bypass[MAX_MATRICES];
c68fafe0 109 /// Matrix coefficients, stored as 2.14 fixed point.
420df930 110 int32_t matrix_coeff[MAX_MATRICES][MAX_CHANNELS];
c68fafe0 111 /// Left shift to apply to noise values in 0x31eb substreams.
b517af05
RP
112 uint8_t matrix_noise_shift[MAX_MATRICES];
113 //@}
114
c68fafe0 115 /// Left shift to apply to Huffman-decoded residuals.
b517af05
RP
116 uint8_t quant_step_size[MAX_CHANNELS];
117
c68fafe0 118 /// number of PCM samples in current audio block
b517af05 119 uint16_t blocksize;
c68fafe0 120 /// Number of PCM samples decoded so far in this frame.
b517af05
RP
121 uint16_t blockpos;
122
c68fafe0 123 /// Left shift to apply to decoded PCM values to get final 24-bit output.
b517af05
RP
124 int8_t output_shift[MAX_CHANNELS];
125
c68fafe0 126 /// Running XOR of all output samples.
b517af05
RP
127 int32_t lossless_check_data;
128
129} SubStream;
130
131typedef struct MLPDecodeContext {
132 AVCodecContext *avctx;
133
c68fafe0 134 /// Current access unit being read has a major sync.
cc9c5126
RP
135 int is_major_sync_unit;
136
f36f6a60
HL
137 /// Size of the major sync unit, in bytes
138 int major_sync_header_size;
139
c68fafe0 140 /// Set if a valid major sync block has been read. Otherwise no decoding is possible.
b517af05
RP
141 uint8_t params_valid;
142
c68fafe0 143 /// Number of substreams contained within this stream.
b517af05
RP
144 uint8_t num_substreams;
145
c68fafe0 146 /// Index of the last substream to decode - further substreams are skipped.
b517af05
RP
147 uint8_t max_decoded_substream;
148
c68fafe0 149 /// number of PCM samples contained in each frame
b517af05 150 int access_unit_size;
c68fafe0 151 /// next power of two above the number of samples in each frame
b517af05
RP
152 int access_unit_size_pow2;
153
154 SubStream substream[MAX_SUBSTREAMS];
155
75428fa4
RP
156 int matrix_changed;
157 int filter_changed[MAX_CHANNELS][NUM_FILTERS];
158
b517af05
RP
159 int8_t noise_buffer[MAX_BLOCKSIZE_POW2];
160 int8_t bypassed_lsbs[MAX_BLOCKSIZE][MAX_CHANNELS];
420df930 161 int32_t sample_buffer[MAX_BLOCKSIZE][MAX_CHANNELS];
bf4f19dc 162
2d6caade 163 MLPDSPContext dsp;
b517af05
RP
164} MLPDecodeContext;
165
3ffcccb4
TW
166static 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
970c76f3
VG
182static int mlp_channel_layout_subset(uint64_t channel_layout, uint64_t mask)
183{
184 return channel_layout && ((channel_layout & mask) == channel_layout);
185}
186
3ffcccb4
TW
187static 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
b517af05
RP
201static VLC huff_vlc[3];
202
b517af05
RP
203/** Initialize static data, constant between all invocations of the codec. */
204
dc8a7c93 205static av_cold void init_static(void)
b517af05 206{
7fd88069 207 if (!huff_vlc[0].bits) {
52ae1e86
RP
208 INIT_VLC_STATIC(&huff_vlc[0], VLC_BITS, 18,
209 &ff_mlp_huffman_tables[0][0][1], 2, 1,
fcf5fc44 210 &ff_mlp_huffman_tables[0][0][0], 2, 1, VLC_STATIC_SIZE);
52ae1e86
RP
211 INIT_VLC_STATIC(&huff_vlc[1], VLC_BITS, 16,
212 &ff_mlp_huffman_tables[1][0][1], 2, 1,
fcf5fc44 213 &ff_mlp_huffman_tables[1][0][0], 2, 1, VLC_STATIC_SIZE);
52ae1e86
RP
214 INIT_VLC_STATIC(&huff_vlc[2], VLC_BITS, 15,
215 &ff_mlp_huffman_tables[2][0][1], 2, 1,
fcf5fc44 216 &ff_mlp_huffman_tables[2][0][0], 2, 1, VLC_STATIC_SIZE);
7fd88069 217 }
b517af05 218
ce15710f 219 ff_mlp_init_crc();
b517af05
RP
220}
221
222static inline int32_t calculate_sign_huff(MLPDecodeContext *m,
223 unsigned int substr, unsigned int ch)
224{
225 SubStream *s = &m->substream[substr];
22fb814c 226 ChannelParams *cp = &s->channel_params[ch];
f53acb7b
RP
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;
b517af05 230
f53acb7b 231 if (cp->codebook > 0)
b517af05
RP
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
00c72a1e 243static inline int read_huff_channels(MLPDecodeContext *m, BitstreamContext *bc,
b517af05
RP
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])
00c72a1e 251 m->bypassed_lsbs[pos + s->blockpos][mat] = bitstream_read_bit(bc);
b517af05
RP
252
253 for (channel = s->min_channel; channel <= s->max_channel; channel++) {
22fb814c 254 ChannelParams *cp = &s->channel_params[channel];
f53acb7b 255 int codebook = cp->codebook;
b517af05 256 int quant_step_size = s->quant_step_size[channel];
f53acb7b 257 int lsb_bits = cp->huff_lsbs - quant_step_size;
b517af05
RP
258 int result = 0;
259
260 if (codebook > 0)
00c72a1e
AH
261 result = bitstream_read_vlc(bc, huff_vlc[codebook-1].table,
262 VLC_BITS,
263 (9 + VLC_BITS - 1) / VLC_BITS);
b517af05
RP
264
265 if (result < 0)
82be06bb 266 return AVERROR_INVALIDDATA;
b517af05
RP
267
268 if (lsb_bits > 0)
00c72a1e 269 result = (result << lsb_bits) + bitstream_read(bc, lsb_bits);
b517af05 270
f53acb7b 271 result += cp->sign_huff_offset;
b517af05
RP
272 result <<= quant_step_size;
273
274 m->sample_buffer[pos + s->blockpos][channel] = result;
275 }
276
277 return 0;
278}
279
280static 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;
2d6caade 289 ff_mlpdsp_init(&m->dsp);
ee1a8f62 290
b517af05
RP
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
00c72a1e 299static int read_major_sync(MLPDecodeContext *m, BitstreamContext *bc)
b517af05
RP
300{
301 MLPHeaderInfo mh;
82be06bb 302 int substr, ret;
b517af05 303
00c72a1e 304 if ((ret = ff_mlp_read_major_sync(m->avctx, &mh, bc)) != 0)
82be06bb 305 return ret;
b517af05
RP
306
307 if (mh.group1_bits == 0) {
9906a2be 308 av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown bits per sample\n");
82be06bb 309 return AVERROR_INVALIDDATA;
b517af05
RP
310 }
311 if (mh.group2_bits > mh.group1_bits) {
312 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 313 "Channel group 2 cannot have more bits per sample than group 1.\n");
82be06bb 314 return AVERROR_INVALIDDATA;
b517af05
RP
315 }
316
317 if (mh.group2_samplerate && mh.group2_samplerate != mh.group1_samplerate) {
318 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 319 "Channel groups with differing sample rates are not currently supported.\n");
82be06bb 320 return AVERROR_INVALIDDATA;
b517af05
RP
321 }
322
323 if (mh.group1_samplerate == 0) {
9906a2be 324 av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown sampling rate\n");
82be06bb 325 return AVERROR_INVALIDDATA;
b517af05
RP
326 }
327 if (mh.group1_samplerate > MAX_SAMPLERATE) {
328 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 329 "Sampling rate %d is greater than the supported maximum (%d).\n",
b517af05 330 mh.group1_samplerate, MAX_SAMPLERATE);
82be06bb 331 return AVERROR_INVALIDDATA;
b517af05
RP
332 }
333 if (mh.access_unit_size > MAX_BLOCKSIZE) {
334 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 335 "Block size %d is greater than the supported maximum (%d).\n",
b517af05 336 mh.access_unit_size, MAX_BLOCKSIZE);
82be06bb 337 return AVERROR_INVALIDDATA;
b517af05
RP
338 }
339 if (mh.access_unit_size_pow2 > MAX_BLOCKSIZE_POW2) {
340 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 341 "Block size pow2 %d is greater than the supported maximum (%d).\n",
b517af05 342 mh.access_unit_size_pow2, MAX_BLOCKSIZE_POW2);
82be06bb 343 return AVERROR_INVALIDDATA;
b517af05
RP
344 }
345
346 if (mh.num_substreams == 0)
82be06bb 347 return AVERROR_INVALIDDATA;
36ef5369 348 if (m->avctx->codec_id == AV_CODEC_ID_MLP && mh.num_substreams > 2) {
932cee5d 349 av_log(m->avctx, AV_LOG_ERROR, "MLP only supports up to 2 substreams.\n");
82be06bb 350 return AVERROR_INVALIDDATA;
932cee5d 351 }
b517af05 352 if (mh.num_substreams > MAX_SUBSTREAMS) {
6d97484d
DB
353 avpriv_request_sample(m->avctx,
354 "%d substreams (more than the "
355 "maximum supported by the decoder)",
356 mh.num_substreams);
ca085e66 357 return AVERROR_PATCHWELCOME;
b517af05
RP
358 }
359
f36f6a60
HL
360 m->major_sync_header_size = mh.header_size;
361
b517af05
RP
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;
dc2d0e06
HL
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);
b517af05
RP
369
370 m->avctx->sample_rate = mh.group1_samplerate;
371 m->avctx->frame_size = mh.access_unit_size;
372
97679e6e 373 m->avctx->bits_per_raw_sample = mh.group1_bits;
c687643c 374 if (mh.group1_bits > 16)
5d6e4c16 375 m->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
ee1a8f62 376 else
5d6e4c16 377 m->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
b9eb0341
BA
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);
b517af05
RP
382
383 m->params_valid = 1;
384 for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
385 m->substream[substr].restart_seen = 0;
386
99ccd2ba
TW
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)))
1f6e5dd4
VG
392 m->substream[0].mask = AV_CH_LAYOUT_STEREO;
393 m->substream[substr].mask = mh.channel_layout_mlp;
99ccd2ba
TW
394 } else {
395 if ((substr = (mh.num_substreams > 1)))
1f6e5dd4 396 m->substream[0].mask = AV_CH_LAYOUT_STEREO;
99ccd2ba
TW
397 if (mh.num_substreams > 2)
398 if (mh.channel_layout_thd_stream2)
1f6e5dd4 399 m->substream[2].mask = mh.channel_layout_thd_stream2;
99ccd2ba 400 else
1f6e5dd4
VG
401 m->substream[2].mask = mh.channel_layout_thd_stream1;
402 m->substream[substr].mask = mh.channel_layout_thd_stream1;
99ccd2ba
TW
403 }
404
4b7f1a7c
TW
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
b517af05
RP
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
00c72a1e 452static int read_restart_header(MLPDecodeContext *m, BitstreamContext *bc,
b517af05
RP
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;
00c72a1e 460 int start_count = bitstream_tell(bc);
e9d394f3
LB
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;
b517af05 465
00c72a1e 466 sync_word = bitstream_read(bc, 13);
b517af05 467
e8d341ce 468 if (sync_word != 0x31ea >> 1) {
b517af05 469 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 470 "restart header sync incorrect (got 0x%04x)\n", sync_word);
82be06bb 471 return AVERROR_INVALIDDATA;
b517af05 472 }
b517af05 473
00c72a1e 474 s->noise_type = bitstream_read_bit(bc);
e8d341ce 475
36ef5369 476 if (m->avctx->codec_id == AV_CODEC_ID_MLP && s->noise_type) {
e8d341ce 477 av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n");
82be06bb 478 return AVERROR_INVALIDDATA;
e8d341ce
RP
479 }
480
00c72a1e 481 bitstream_skip(bc, 16); /* Output timestamp */
b517af05 482
00c72a1e
AH
483 min_channel = bitstream_read(bc, 4);
484 max_channel = bitstream_read(bc, 4);
485 max_matrix_channel = bitstream_read(bc, 4);
b517af05 486
e9d394f3 487 if (max_matrix_channel > std_max_matrix_channel) {
868170c4
RP
488 av_log(m->avctx, AV_LOG_ERROR,
489 "Max matrix channel cannot be greater than %d.\n",
490 max_matrix_channel);
82be06bb 491 return AVERROR_INVALIDDATA;
868170c4
RP
492 }
493
e9d394f3 494 if (max_channel != max_matrix_channel) {
868170c4
RP
495 av_log(m->avctx, AV_LOG_ERROR,
496 "Max channel must be equal max matrix channel.\n");
82be06bb 497 return AVERROR_INVALIDDATA;
868170c4
RP
498 }
499
e2822726
RP
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) {
6d97484d
DB
503 avpriv_request_sample(m->avctx,
504 "%d channels (more than the "
505 "maximum supported by the decoder)",
506 s->max_channel + 2);
ca085e66 507 return AVERROR_PATCHWELCOME;
e2822726
RP
508 }
509
e9d394f3 510 if (min_channel > max_channel) {
b517af05
RP
511 av_log(m->avctx, AV_LOG_ERROR,
512 "Substream min channel cannot be greater than max channel.\n");
82be06bb 513 return AVERROR_INVALIDDATA;
b517af05
RP
514 }
515
e9d394f3
LB
516 s->min_channel = min_channel;
517 s->max_channel = max_channel;
518 s->max_matrix_channel = max_matrix_channel;
519
970c76f3 520 if (mlp_channel_layout_subset(m->avctx->request_channel_layout, s->mask) &&
94c54d97 521 m->max_decoded_substream > substr) {
ed1b0113
TW
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",
1f6e5dd4 525 s->max_channel + 1, s->mask, substr);
ed1b0113 526 m->max_decoded_substream = substr;
b517af05
RP
527 }
528
00c72a1e
AH
529 s->noise_shift = bitstream_read(bc, 4);
530 s->noisegen_seed = bitstream_read(bc, 23);
b517af05 531
00c72a1e 532 bitstream_skip(bc, 19);
b517af05 533
00c72a1e
AH
534 s->data_check_present = bitstream_read_bit(bc);
535 lossless_check = bitstream_read(bc, 8);
b517af05
RP
536 if (substr == m->max_decoded_substream
537 && s->lossless_check_data != 0xffffffff) {
a7cc783d 538 tmp = xor_32_to_8(s->lossless_check_data);
b517af05
RP
539 if (tmp != lossless_check)
540 av_log(m->avctx, AV_LOG_WARNING,
9906a2be 541 "Lossless check failed - expected %02x, calculated %02x.\n",
b517af05 542 lossless_check, tmp);
b517af05
RP
543 }
544
00c72a1e 545 bitstream_skip(bc, 16);
b517af05 546
9731e7f1
RP
547 memset(s->ch_assign, 0, sizeof(s->ch_assign));
548
b517af05 549 for (ch = 0; ch <= s->max_matrix_channel; ch++) {
00c72a1e 550 int ch_assign = bitstream_read(bc, 6);
3ffcccb4 551 if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD) {
1f6e5dd4 552 uint64_t channel = thd_channel_layout_extract_channel(s->mask,
3ffcccb4 553 ch_assign);
1f6e5dd4 554 ch_assign = av_get_channel_layout_channel_index(s->mask,
3ffcccb4
TW
555 channel);
556 }
2ffb0598 557 if (ch_assign < 0 || ch_assign > s->max_matrix_channel) {
6d97484d
DB
558 avpriv_request_sample(m->avctx,
559 "Assignment of matrix channel %d to invalid output channel %d",
560 ch, ch_assign);
ca085e66 561 return AVERROR_PATCHWELCOME;
b517af05 562 }
9731e7f1 563 s->ch_assign[ch_assign] = ch;
b517af05
RP
564 }
565
00c72a1e 566 checksum = ff_mlp_restart_checksum(buf, bitstream_tell(bc) - start_count);
b517af05 567
00c72a1e 568 if (checksum != bitstream_read(bc, 8))
9906a2be 569 av_log(m->avctx, AV_LOG_ERROR, "restart header checksum error\n");
b517af05 570
9906a2be 571 /* Set default decoding parameters. */
b517af05
RP
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++) {
22fb814c 581 ChannelParams *cp = &s->channel_params[ch];
f53acb7b
RP
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;
b517af05 586
9906a2be 587 /* Default audio coding is 24-bit raw PCM. */
f53acb7b 588 cp->huff_offset = 0;
977f41e2 589 cp->sign_huff_offset = -(1 << 23);
f53acb7b
RP
590 cp->codebook = 0;
591 cp->huff_lsbs = 24;
b517af05
RP
592 }
593
1fd2deed
TW
594 if (substr == m->max_decoded_substream) {
595 m->avctx->channels = s->max_matrix_channel + 1;
1f6e5dd4 596 m->avctx->channel_layout = s->mask;
b9eb0341
BA
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);
1fd2deed 601 }
b517af05
RP
602
603 return 0;
604}
605
606/** Read parameters for one of the prediction filters. */
607
00c72a1e 608static int read_filter_params(MLPDecodeContext *m, BitstreamContext *bc,
22fb814c
NB
609 unsigned int substr, unsigned int channel,
610 unsigned int filter)
b517af05 611{
22fb814c
NB
612 SubStream *s = &m->substream[substr];
613 FilterParams *fp = &s->channel_params[channel].filter_params[filter];
0c5670a0 614 const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;
b517af05
RP
615 const char fchar = filter ? 'I' : 'F';
616 int i, order;
617
9906a2be 618 // Filter is 0 for FIR, 1 for IIR.
b517af05
RP
619 assert(filter < 2);
620
5d9e4eaa
RP
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");
82be06bb 623 return AVERROR_INVALIDDATA;
5d9e4eaa 624 }
75428fa4 625
00c72a1e 626 order = bitstream_read(bc, 4);
0c5670a0 627 if (order > max_order) {
b517af05 628 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 629 "%cIR filter order %d is greater than maximum %d.\n",
0c5670a0 630 fchar, order, max_order);
82be06bb 631 return AVERROR_INVALIDDATA;
b517af05 632 }
d6aa052d 633 fp->order = order;
b517af05
RP
634
635 if (order > 0) {
22fb814c 636 int32_t *fcoeff = s->channel_params[channel].coeff[filter];
b517af05
RP
637 int coeff_bits, coeff_shift;
638
00c72a1e 639 fp->shift = bitstream_read(bc, 4);
b517af05 640
00c72a1e
AH
641 coeff_bits = bitstream_read(bc, 5);
642 coeff_shift = bitstream_read(bc, 3);
b517af05
RP
643 if (coeff_bits < 1 || coeff_bits > 16) {
644 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 645 "%cIR filter coeff_bits must be between 1 and 16.\n",
b517af05 646 fchar);
82be06bb 647 return AVERROR_INVALIDDATA;
b517af05
RP
648 }
649 if (coeff_bits + coeff_shift > 16) {
650 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 651 "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",
b517af05 652 fchar);
82be06bb 653 return AVERROR_INVALIDDATA;
b517af05
RP
654 }
655
656 for (i = 0; i < order; i++)
00c72a1e 657 fcoeff[i] = bitstream_read_signed(bc, coeff_bits) << coeff_shift;
b517af05 658
00c72a1e 659 if (bitstream_read_bit(bc)) {
b517af05
RP
660 int state_bits, state_shift;
661
662 if (filter == FIR) {
663 av_log(m->avctx, AV_LOG_ERROR,
9906a2be 664 "FIR filter has state data specified.\n");
82be06bb 665 return AVERROR_INVALIDDATA;
b517af05
RP
666 }
667
00c72a1e
AH
668 state_bits = bitstream_read(bc, 4);
669 state_shift = bitstream_read(bc, 4);
b517af05 670
9906a2be 671 /* TODO: Check validity of state data. */
b517af05
RP
672
673 for (i = 0; i < order; i++)
00c72a1e 674 fp->state[i] = bitstream_read_signed(bc, state_bits) << state_shift;
b517af05
RP
675 }
676 }
677
678 return 0;
679}
680
f8e6293b
RP
681/** Read parameters for primitive matrices. */
682
00c72a1e
AH
683static int read_matrix_params(MLPDecodeContext *m, unsigned int substr,
684 BitstreamContext *bc)
f8e6293b 685{
95c14b1e 686 SubStream *s = &m->substream[substr];
f8e6293b 687 unsigned int mat, ch;
36ef5369 688 const int max_primitive_matrices = m->avctx->codec_id == AV_CODEC_ID_MLP
309616b2
RP
689 ? MAX_MATRICES_MLP
690 : MAX_MATRICES_TRUEHD;
f8e6293b 691
5d9e4eaa
RP
692 if (m->matrix_changed++ > 1) {
693 av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");
82be06bb 694 return AVERROR_INVALIDDATA;
5d9e4eaa
RP
695 }
696
00c72a1e 697 s->num_primitive_matrices = bitstream_read(bc, 4);
f8e6293b 698
309616b2
RP
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);
82be06bb 703 return AVERROR_INVALIDDATA;
309616b2
RP
704 }
705
f8e6293b
RP
706 for (mat = 0; mat < s->num_primitive_matrices; mat++) {
707 int frac_bits, max_chan;
00c72a1e
AH
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);
f8e6293b 711
0091d8a1 712 if (s->matrix_out_ch[mat] > s->max_matrix_channel) {
f8e6293b
RP
713 av_log(m->avctx, AV_LOG_ERROR,
714 "Invalid channel %d specified as output from matrix.\n",
715 s->matrix_out_ch[mat]);
82be06bb 716 return AVERROR_INVALIDDATA;
f8e6293b
RP
717 }
718 if (frac_bits > 14) {
719 av_log(m->avctx, AV_LOG_ERROR,
720 "Too many fractional bits specified.\n");
82be06bb 721 return AVERROR_INVALIDDATA;
f8e6293b
RP
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;
00c72a1e
AH
730 if (bitstream_read_bit(bc))
731 coeff_val = bitstream_read_signed(bc, frac_bits + 2);
f8e6293b
RP
732
733 s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
734 }
735
736 if (s->noise_type)
00c72a1e 737 s->matrix_noise_shift[mat] = bitstream_read(bc, 4);
f8e6293b
RP
738 else
739 s->matrix_noise_shift[mat] = 0;
740 }
741
742 return 0;
743}
744
43ee5fe0
RP
745/** Read channel parameters. */
746
747static int read_channel_params(MLPDecodeContext *m, unsigned int substr,
00c72a1e 748 BitstreamContext *bc, unsigned int ch)
43ee5fe0 749{
22fb814c
NB
750 SubStream *s = &m->substream[substr];
751 ChannelParams *cp = &s->channel_params[ch];
43ee5fe0
RP
752 FilterParams *fir = &cp->filter_params[FIR];
753 FilterParams *iir = &cp->filter_params[IIR];
82be06bb 754 int ret;
43ee5fe0
RP
755
756 if (s->param_presence_flags & PARAM_FIR)
00c72a1e
AH
757 if (bitstream_read_bit(bc))
758 if ((ret = read_filter_params(m, bc, substr, ch, FIR)) < 0)
82be06bb 759 return ret;
43ee5fe0
RP
760
761 if (s->param_presence_flags & PARAM_IIR)
00c72a1e
AH
762 if (bitstream_read_bit(bc))
763 if ((ret = read_filter_params(m, bc, substr, ch, IIR)) < 0)
82be06bb 764 return ret;
43ee5fe0 765
125cf771
RP
766 if (fir->order + iir->order > 8) {
767 av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");
82be06bb 768 return AVERROR_INVALIDDATA;
125cf771
RP
769 }
770
43ee5fe0
RP
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");
82be06bb 775 return AVERROR_INVALIDDATA;
43ee5fe0
RP
776 }
777 /* The FIR and IIR filters must have the same precision.
aff42ee0
RP
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. */
43ee5fe0
RP
782 if (!fir->order && iir->order)
783 fir->shift = iir->shift;
784
785 if (s->param_presence_flags & PARAM_HUFFOFFSET)
00c72a1e
AH
786 if (bitstream_read_bit(bc))
787 cp->huff_offset = bitstream_read_signed(bc, 15);
43ee5fe0 788
00c72a1e
AH
789 cp->codebook = bitstream_read(bc, 2);
790 cp->huff_lsbs = bitstream_read(bc, 5);
43ee5fe0 791
125cf771
RP
792 if (cp->huff_lsbs > 24) {
793 av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");
82be06bb 794 return AVERROR_INVALIDDATA;
125cf771 795 }
43ee5fe0 796
125cf771 797 cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
43ee5fe0
RP
798
799 return 0;
800}
801
b517af05
RP
802/** Read decoding parameters that change more often than those in the restart
803 * header. */
804
00c72a1e 805static int read_decoding_params(MLPDecodeContext *m, BitstreamContext *bc,
b517af05
RP
806 unsigned int substr)
807{
808 SubStream *s = &m->substream[substr];
f8e6293b 809 unsigned int ch;
82be06bb 810 int ret;
b517af05 811
cbf3cf19 812 if (s->param_presence_flags & PARAM_PRESENCE)
00c72a1e
AH
813 if (bitstream_read_bit(bc))
814 s->param_presence_flags = bitstream_read(bc, 8);
b517af05
RP
815
816 if (s->param_presence_flags & PARAM_BLOCKSIZE)
00c72a1e
AH
817 if (bitstream_read_bit(bc)) {
818 s->blocksize = bitstream_read(bc, 9);
b864098c
RP
819 if (s->blocksize < 8 || s->blocksize > m->access_unit_size) {
820 av_log(m->avctx, AV_LOG_ERROR, "Invalid blocksize.");
b517af05 821 s->blocksize = 0;
82be06bb 822 return AVERROR_INVALIDDATA;
b517af05
RP
823 }
824 }
825
826 if (s->param_presence_flags & PARAM_MATRIX)
00c72a1e
AH
827 if (bitstream_read_bit(bc))
828 if ((ret = read_matrix_params(m, substr, bc)) < 0)
82be06bb 829 return ret;
b517af05
RP
830
831 if (s->param_presence_flags & PARAM_OUTSHIFT)
00c72a1e 832 if (bitstream_read_bit(bc)) {
f95f6ab9 833 for (ch = 0; ch <= s->max_matrix_channel; ch++)
00c72a1e 834 s->output_shift[ch] = bitstream_read_signed(bc, 4);
b9eb0341
BA
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 }
b517af05
RP
841
842 if (s->param_presence_flags & PARAM_QUANTSTEP)
00c72a1e 843 if (bitstream_read_bit(bc))
b517af05 844 for (ch = 0; ch <= s->max_channel; ch++) {
22fb814c 845 ChannelParams *cp = &s->channel_params[ch];
f53acb7b 846
00c72a1e 847 s->quant_step_size[ch] = bitstream_read(bc, 4);
b517af05 848
f53acb7b 849 cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
b517af05
RP
850 }
851
852 for (ch = s->min_channel; ch <= s->max_channel; ch++)
00c72a1e
AH
853 if (bitstream_read_bit(bc))
854 if ((ret = read_channel_params(m, substr, bc, ch)) < 0)
82be06bb 855 return ret;
b517af05
RP
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
865static void filter_channel(MLPDecodeContext *m, unsigned int substr,
866 unsigned int channel)
867{
868 SubStream *s = &m->substream[substr];
22fb814c 869 const int32_t *fircoeff = s->channel_params[channel].coeff[FIR];
13bd2044
RP
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;
22fb814c
NB
873 FilterParams *fir = &s->channel_params[channel].filter_params[FIR];
874 FilterParams *iir = &s->channel_params[channel].filter_params[IIR];
e71365f4 875 unsigned int filter_shift = fir->shift;
b517af05 876 int32_t mask = MSB_MASK(s->quant_step_size[channel]);
b517af05 877
77b12f80
RP
878 memcpy(firbuf, fir->state, MAX_FIR_ORDER * sizeof(int32_t));
879 memcpy(iirbuf, iir->state, MAX_IIR_ORDER * sizeof(int32_t));
b517af05 880
13bd2044
RP
881 m->dsp.mlp_filter_channel(firbuf, fircoeff,
882 fir->order, iir->order,
bf4f19dc
RP
883 filter_shift, mask, s->blocksize,
884 &m->sample_buffer[s->blockpos][channel]);
b517af05 885
bf4f19dc
RP
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));
b517af05
RP
888}
889
890/** Read a block of PCM residual data (or actual if no filtering active). */
891
00c72a1e 892static int read_block_data(MLPDecodeContext *m, BitstreamContext *bc,
b517af05
RP
893 unsigned int substr)
894{
895 SubStream *s = &m->substream[substr];
896 unsigned int i, ch, expected_stream_pos = 0;
82be06bb 897 int ret;
b517af05
RP
898
899 if (s->data_check_present) {
00c72a1e
AH
900 expected_stream_pos = bitstream_tell(bc);
901 expected_stream_pos += bitstream_read(bc, 16);
6d97484d
DB
902 avpriv_request_sample(m->avctx,
903 "Substreams with VLC block size check info");
b517af05
RP
904 }
905
906 if (s->blockpos + s->blocksize > m->access_unit_size) {
9906a2be 907 av_log(m->avctx, AV_LOG_ERROR, "too many audio samples in frame\n");
82be06bb 908 return AVERROR_INVALIDDATA;
b517af05
RP
909 }
910
911 memset(&m->bypassed_lsbs[s->blockpos][0], 0,
912 s->blocksize * sizeof(m->bypassed_lsbs[0]));
913
f95f6ab9 914 for (i = 0; i < s->blocksize; i++)
00c72a1e 915 if ((ret = read_huff_channels(m, bc, substr, i)) < 0)
82be06bb 916 return ret;
b517af05 917
f95f6ab9 918 for (ch = s->min_channel; ch <= s->max_channel; ch++)
b517af05 919 filter_channel(m, substr, ch);
b517af05
RP
920
921 s->blockpos += s->blocksize;
922
923 if (s->data_check_present) {
00c72a1e 924 if (bitstream_tell(bc) != expected_stream_pos)
9906a2be 925 av_log(m->avctx, AV_LOG_ERROR, "block data length mismatch\n");
00c72a1e 926 bitstream_skip(bc, 8);
b517af05
RP
927 }
928
929 return 0;
930}
931
9906a2be 932/** Data table used for TrueHD noise generation function. */
b517af05
RP
933
934static 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
963static 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
983static 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
1002static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
1003{
1004 SubStream *s = &m->substream[substr];
4e5aa080 1005 unsigned int mat;
b517af05
RP
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++) {
b517af05 1017 unsigned int dest_ch = s->matrix_out_ch[mat];
4e5aa080
BA
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]));
b517af05
RP
1029 }
1030}
1031
1032/** Write the audio data into the output buffer. */
1033
e1b8d88d 1034static int output_data(MLPDecodeContext *m, unsigned int substr,
dc33fbbf 1035 AVFrame *frame, int *got_frame_ptr)
b517af05 1036{
0eea2129 1037 AVCodecContext *avctx = m->avctx;
b517af05 1038 SubStream *s = &m->substream[substr];
0eea2129 1039 int ret;
e1b8d88d 1040 int is32 = (m->avctx->sample_fmt == AV_SAMPLE_FMT_S32);
b517af05 1041
caa84585
JR
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 }
0dff40bf
AK
1046
1047 if (!s->blockpos) {
1048 av_log(avctx, AV_LOG_ERROR, "No samples to output.\n");
1049 return AVERROR_INVALIDDATA;
1050 }
caa84585 1051
0eea2129 1052 /* get output buffer */
dc33fbbf 1053 frame->nb_samples = s->blockpos;
759001c5 1054 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
0eea2129
JR
1055 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1056 return ret;
1057 }
b9eb0341
BA
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);
b517af05 1066
e9212309
TW
1067 /* Update matrix encoding side data */
1068 if ((ret = ff_side_data_update_matrix_encoding(frame, s->matrix_encoding)) < 0)
1069 return ret;
1070
dc33fbbf 1071 *got_frame_ptr = 1;
b517af05
RP
1072
1073 return 0;
1074}
1075
b517af05 1076/** Read an access unit from the stream.
49bd8e4b
MR
1077 * @return negative on error, 0 if not enough data is present in the input stream,
1078 * otherwise the number of bytes consumed. */
b517af05 1079
0eea2129
JR
1080static int read_access_unit(AVCodecContext *avctx, void* data,
1081 int *got_frame_ptr, AVPacket *avpkt)
b517af05 1082{
7a00bbad
TB
1083 const uint8_t *buf = avpkt->data;
1084 int buf_size = avpkt->size;
b517af05 1085 MLPDecodeContext *m = avctx->priv_data;
00c72a1e 1086 BitstreamContext bc;
b517af05
RP
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;
82be06bb 1094 int ret;
b517af05
RP
1095
1096 if (buf_size < 4)
1097 return 0;
1098
1099 length = (AV_RB16(buf) & 0xfff) * 2;
1100
0b882b40 1101 if (length < 4 || length > buf_size)
82be06bb 1102 return AVERROR_INVALIDDATA;
b517af05 1103
a25dac97 1104 bitstream_init8(&bc, buf + 4, length - 4);
b517af05 1105
cc9c5126 1106 m->is_major_sync_unit = 0;
00c72a1e
AH
1107 if (bitstream_peek(&bc, 31) == (0xf8726fba >> 1)) {
1108 if (read_major_sync(m, &bc) < 0)
b517af05 1109 goto error;
cc9c5126 1110 m->is_major_sync_unit = 1;
f36f6a60 1111 header_size += m->major_sync_header_size;
b517af05
RP
1112 }
1113
1114 if (!m->params_valid) {
1115 av_log(m->avctx, AV_LOG_WARNING,
9906a2be 1116 "Stream parameters not seen; skipping frame.\n");
0eea2129 1117 *got_frame_ptr = 0;
b517af05
RP
1118 return length;
1119 }
1120
1121 substream_start = 0;
1122
1123 for (substr = 0; substr < m->num_substreams; substr++) {
cc9c5126 1124 int extraword_present, checkdata_present, end, nonrestart_substr;
b517af05 1125
00c72a1e
AH
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);
b517af05 1130
00c72a1e 1131 end = bitstream_read(&bc, 12) * 2;
b517af05
RP
1132
1133 substr_header_size += 2;
1134
1135 if (extraword_present) {
36ef5369 1136 if (m->avctx->codec_id == AV_CODEC_ID_MLP) {
89e39be3
RP
1137 av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
1138 goto error;
1139 }
00c72a1e 1140 bitstream_skip(&bc, 16);
b517af05
RP
1141 substr_header_size += 2;
1142 }
1143
cc9c5126
RP
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
b517af05
RP
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
ce15710f
RP
1172 parity_bits = ff_mlp_calculate_parity(buf, 4);
1173 parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);
b517af05
RP
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];
a25dac97 1184 bitstream_init8(&bc, buf, substream_data_len[substr]);
b517af05 1185
75428fa4
RP
1186 m->matrix_changed = 0;
1187 memset(m->filter_changed, 0, sizeof(m->filter_changed));
1188
b517af05
RP
1189 s->blockpos = 0;
1190 do {
00c72a1e
AH
1191 if (bitstream_read_bit(&bc)) {
1192 if (bitstream_read_bit(&bc)) {
9906a2be 1193 /* A restart header should be present. */
00c72a1e 1194 if (read_restart_header(m, &bc, buf, substr) < 0)
b517af05
RP
1195 goto next_substr;
1196 s->restart_seen = 1;
1197 }
1198
f95f6ab9 1199 if (!s->restart_seen)
b517af05 1200 goto next_substr;
00c72a1e 1201 if (read_decoding_params(m, &bc, substr) < 0)
b517af05
RP
1202 goto next_substr;
1203 }
1204
f95f6ab9 1205 if (!s->restart_seen)
b517af05 1206 goto next_substr;
b517af05 1207
00c72a1e 1208 if ((ret = read_block_data(m, &bc, substr)) < 0)
82be06bb 1209 return ret;
b517af05 1210
00c72a1e 1211 if (bitstream_tell(&bc) >= substream_data_len[substr] * 8)
d7952be3
RP
1212 goto substream_length_mismatch;
1213
00c72a1e 1214 } while (!bitstream_read_bit(&bc));
b517af05 1215
00c72a1e 1216 bitstream_skip(&bc, (-bitstream_tell(&bc)) & 15);
f95f6ab9 1217
00c72a1e 1218 if (substream_data_len[substr] * 8 - bitstream_tell(&bc) >= 32) {
7b18e13a
RP
1219 int shorten_by;
1220
00c72a1e 1221 if (bitstream_read(&bc, 16) != 0xD234)
82be06bb 1222 return AVERROR_INVALIDDATA;
7b18e13a 1223
00c72a1e 1224 shorten_by = bitstream_read(&bc, 16);
36ef5369 1225 if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD && shorten_by & 0x2000)
7b18e13a 1226 s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
36ef5369 1227 else if (m->avctx->codec_id == AV_CODEC_ID_MLP && shorten_by != 0xD234)
82be06bb 1228 return AVERROR_INVALIDDATA;
7b18e13a 1229
b517af05 1230 if (substr == m->max_decoded_substream)
9906a2be 1231 av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");
b517af05 1232 }
f95f6ab9 1233
ab79fa44 1234 if (substream_parity_present[substr]) {
b517af05
RP
1235 uint8_t parity, checksum;
1236
00c72a1e 1237 if (substream_data_len[substr] * 8 - bitstream_tell(&bc) != 16)
ab79fa44
RP
1238 goto substream_length_mismatch;
1239
d544dcdf
RP
1240 parity = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);
1241 checksum = ff_mlp_checksum8 (buf, substream_data_len[substr] - 2);
b517af05 1242
00c72a1e 1243 if ((bitstream_read(&bc, 8) ^ parity) != 0xa9)
d544dcdf 1244 av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);
00c72a1e 1245 if (bitstream_read(&bc, 8) != checksum)
d544dcdf 1246 av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n" , substr);
b517af05 1247 }
f95f6ab9 1248
00c72a1e 1249 if (substream_data_len[substr] * 8 != bitstream_tell(&bc))
d7952be3 1250 goto substream_length_mismatch;
b517af05
RP
1251
1252next_substr:
f95f6ab9 1253 if (!s->restart_seen)
01aaf092
RP
1254 av_log(m->avctx, AV_LOG_ERROR,
1255 "No restart header present in substream %d.\n", substr);
01aaf092 1256
b517af05
RP
1257 buf += substream_data_len[substr];
1258 }
1259
1260 rematrix_channels(m, m->max_decoded_substream);
1261
0eea2129 1262 if ((ret = output_data(m, m->max_decoded_substream, data, got_frame_ptr)) < 0)
82be06bb 1263 return ret;
b517af05
RP
1264
1265 return length;
1266
d7952be3
RP
1267substream_length_mismatch:
1268 av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
82be06bb 1269 return AVERROR_INVALIDDATA;
d7952be3 1270
b517af05
RP
1271error:
1272 m->params_valid = 0;
82be06bb 1273 return AVERROR_INVALIDDATA;
b517af05
RP
1274}
1275
d36beb3f 1276AVCodec ff_mlp_decoder = {
ec6402b7 1277 .name = "mlp",
b2bed932 1278 .long_name = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
ec6402b7 1279 .type = AVMEDIA_TYPE_AUDIO,
36ef5369 1280 .id = AV_CODEC_ID_MLP,
ec6402b7
AK
1281 .priv_data_size = sizeof(MLPDecodeContext),
1282 .init = mlp_decode_init,
1283 .decode = read_access_unit,
def97856 1284 .capabilities = AV_CODEC_CAP_DR1,
b517af05
RP
1285};
1286
9ba4821d 1287#if CONFIG_TRUEHD_DECODER
d36beb3f 1288AVCodec ff_truehd_decoder = {
ec6402b7 1289 .name = "truehd",
b2bed932 1290 .long_name = NULL_IF_CONFIG_SMALL("TrueHD"),
ec6402b7 1291 .type = AVMEDIA_TYPE_AUDIO,
36ef5369 1292 .id = AV_CODEC_ID_TRUEHD,
ec6402b7
AK
1293 .priv_data_size = sizeof(MLPDecodeContext),
1294 .init = mlp_decode_init,
1295 .decode = read_access_unit,
def97856 1296 .capabilities = AV_CODEC_CAP_DR1,
9ba4821d
RP
1297};
1298#endif /* CONFIG_TRUEHD_DECODER */