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