]> git.sesse.net Git - ffmpeg/blob - libavcodec/mlpdec.c
lavfi: Drop unused and empty header file
[ffmpeg] / libavcodec / mlpdec.c
1 /*
2  * MLP decoder
3  * Copyright (c) 2007-2008 Ian Caulfield
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * MLP decoder
25  */
26
27 #include <stdint.h>
28
29 #include "libavutil/internal.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/crc.h"
33
34 #include "avcodec.h"
35 #include "bitstream.h"
36 #include "internal.h"
37 #include "parser.h"
38 #include "mlp_parser.h"
39 #include "mlpdsp.h"
40 #include "mlp.h"
41 #include "config.h"
42
43 /** number of bits used for VLC lookup - longest Huffman code is 9 */
44 #if ARCH_ARM
45 #define VLC_BITS            5
46 #define VLC_STATIC_SIZE     64
47 #else
48 #define VLC_BITS            9
49 #define VLC_STATIC_SIZE     512
50 #endif
51
52 typedef struct SubStream {
53     /// Set if a valid restart header has been read. Otherwise the substream cannot be decoded.
54     uint8_t     restart_seen;
55
56     //@{
57     /** restart header data */
58     /// The type of noise to be used in the rematrix stage.
59     uint16_t    noise_type;
60
61     /// The index of the first channel coded in this substream.
62     uint8_t     min_channel;
63     /// The index of the last channel coded in this substream.
64     uint8_t     max_channel;
65     /// The number of channels input into the rematrix stage.
66     uint8_t     max_matrix_channel;
67     /// For each channel output by the matrix, the output channel to map it to
68     uint8_t     ch_assign[MAX_CHANNELS];
69     /// The channel layout for this substream
70     uint64_t    ch_layout;
71     /// The matrix encoding mode for this substream
72     enum AVMatrixEncoding matrix_encoding;
73
74     /// Channel coding parameters for channels in the substream
75     ChannelParams channel_params[MAX_CHANNELS];
76
77     /// The left shift applied to random noise in 0x31ea substreams.
78     uint8_t     noise_shift;
79     /// The current seed value for the pseudorandom noise generator(s).
80     uint32_t    noisegen_seed;
81
82     /// Set if the substream contains extra info to check the size of VLC blocks.
83     uint8_t     data_check_present;
84
85     /// Bitmask of which parameter sets are conveyed in a decoding parameter block.
86     uint8_t     param_presence_flags;
87 #define PARAM_BLOCKSIZE     (1 << 7)
88 #define PARAM_MATRIX        (1 << 6)
89 #define PARAM_OUTSHIFT      (1 << 5)
90 #define PARAM_QUANTSTEP     (1 << 4)
91 #define PARAM_FIR           (1 << 3)
92 #define PARAM_IIR           (1 << 2)
93 #define PARAM_HUFFOFFSET    (1 << 1)
94 #define PARAM_PRESENCE      (1 << 0)
95     //@}
96
97     //@{
98     /** matrix data */
99
100     /// Number of matrices to be applied.
101     uint8_t     num_primitive_matrices;
102
103     /// matrix output channel
104     uint8_t     matrix_out_ch[MAX_MATRICES];
105
106     /// Whether the LSBs of the matrix output are encoded in the bitstream.
107     uint8_t     lsb_bypass[MAX_MATRICES];
108     /// Matrix coefficients, stored as 2.14 fixed point.
109     int32_t     matrix_coeff[MAX_MATRICES][MAX_CHANNELS];
110     /// Left shift to apply to noise values in 0x31eb substreams.
111     uint8_t     matrix_noise_shift[MAX_MATRICES];
112     //@}
113
114     /// Left shift to apply to Huffman-decoded residuals.
115     uint8_t     quant_step_size[MAX_CHANNELS];
116
117     /// number of PCM samples in current audio block
118     uint16_t    blocksize;
119     /// Number of PCM samples decoded so far in this frame.
120     uint16_t    blockpos;
121
122     /// Left shift to apply to decoded PCM values to get final 24-bit output.
123     int8_t      output_shift[MAX_CHANNELS];
124
125     /// Running XOR of all output samples.
126     int32_t     lossless_check_data;
127
128 } SubStream;
129
130 typedef struct MLPDecodeContext {
131     AVCodecContext *avctx;
132
133     /// Current access unit being read has a major sync.
134     int         is_major_sync_unit;
135
136     /// Size of the major sync unit, in bytes
137     int         major_sync_header_size;
138
139     /// Set if a valid major sync block has been read. Otherwise no decoding is possible.
140     uint8_t     params_valid;
141
142     /// Number of substreams contained within this stream.
143     uint8_t     num_substreams;
144
145     /// Index of the last substream to decode - further substreams are skipped.
146     uint8_t     max_decoded_substream;
147
148     /// number of PCM samples contained in each frame
149     int         access_unit_size;
150     /// next power of two above the number of samples in each frame
151     int         access_unit_size_pow2;
152
153     SubStream   substream[MAX_SUBSTREAMS];
154
155     int         matrix_changed;
156     int         filter_changed[MAX_CHANNELS][NUM_FILTERS];
157
158     int8_t      noise_buffer[MAX_BLOCKSIZE_POW2];
159     int8_t      bypassed_lsbs[MAX_BLOCKSIZE][MAX_CHANNELS];
160     int32_t     sample_buffer[MAX_BLOCKSIZE][MAX_CHANNELS];
161
162     MLPDSPContext dsp;
163 } MLPDecodeContext;
164
165 static const uint64_t thd_channel_order[] = {
166     AV_CH_FRONT_LEFT, AV_CH_FRONT_RIGHT,                     // LR
167     AV_CH_FRONT_CENTER,                                      // C
168     AV_CH_LOW_FREQUENCY,                                     // LFE
169     AV_CH_SIDE_LEFT, AV_CH_SIDE_RIGHT,                       // LRs
170     AV_CH_TOP_FRONT_LEFT, AV_CH_TOP_FRONT_RIGHT,             // LRvh
171     AV_CH_FRONT_LEFT_OF_CENTER, AV_CH_FRONT_RIGHT_OF_CENTER, // LRc
172     AV_CH_BACK_LEFT, AV_CH_BACK_RIGHT,                       // LRrs
173     AV_CH_BACK_CENTER,                                       // Cs
174     AV_CH_TOP_CENTER,                                        // Ts
175     AV_CH_SURROUND_DIRECT_LEFT, AV_CH_SURROUND_DIRECT_RIGHT, // LRsd
176     AV_CH_WIDE_LEFT, AV_CH_WIDE_RIGHT,                       // LRw
177     AV_CH_TOP_FRONT_CENTER,                                  // Cvh
178     AV_CH_LOW_FREQUENCY_2,                                   // LFE2
179 };
180
181 static 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
195 static VLC huff_vlc[3];
196
197 /** Initialize static data, constant between all invocations of the codec. */
198
199 static av_cold void init_static(void)
200 {
201     if (!huff_vlc[0].bits) {
202         INIT_VLC_STATIC(&huff_vlc[0], VLC_BITS, 18,
203                     &ff_mlp_huffman_tables[0][0][1], 2, 1,
204                     &ff_mlp_huffman_tables[0][0][0], 2, 1, VLC_STATIC_SIZE);
205         INIT_VLC_STATIC(&huff_vlc[1], VLC_BITS, 16,
206                     &ff_mlp_huffman_tables[1][0][1], 2, 1,
207                     &ff_mlp_huffman_tables[1][0][0], 2, 1, VLC_STATIC_SIZE);
208         INIT_VLC_STATIC(&huff_vlc[2], VLC_BITS, 15,
209                     &ff_mlp_huffman_tables[2][0][1], 2, 1,
210                     &ff_mlp_huffman_tables[2][0][0], 2, 1, VLC_STATIC_SIZE);
211     }
212
213     ff_mlp_init_crc();
214 }
215
216 static inline int32_t calculate_sign_huff(MLPDecodeContext *m,
217                                           unsigned int substr, unsigned int ch)
218 {
219     SubStream *s = &m->substream[substr];
220     ChannelParams *cp = &s->channel_params[ch];
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;
224
225     if (cp->codebook > 0)
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
237 static inline int read_huff_channels(MLPDecodeContext *m, BitstreamContext *bc,
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])
245             m->bypassed_lsbs[pos + s->blockpos][mat] = bitstream_read_bit(bc);
246
247     for (channel = s->min_channel; channel <= s->max_channel; channel++) {
248         ChannelParams *cp = &s->channel_params[channel];
249         int codebook = cp->codebook;
250         int quant_step_size = s->quant_step_size[channel];
251         int lsb_bits = cp->huff_lsbs - quant_step_size;
252         int result = 0;
253
254         if (codebook > 0)
255             result = bitstream_read_vlc(bc, huff_vlc[codebook-1].table,
256                                         VLC_BITS,
257                                         (9 + VLC_BITS - 1) / VLC_BITS);
258
259         if (result < 0)
260             return AVERROR_INVALIDDATA;
261
262         if (lsb_bits > 0)
263             result = (result << lsb_bits) + bitstream_read(bc, lsb_bits);
264
265         result  += cp->sign_huff_offset;
266         result <<= quant_step_size;
267
268         m->sample_buffer[pos + s->blockpos][channel] = result;
269     }
270
271     return 0;
272 }
273
274 static 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;
283     ff_mlpdsp_init(&m->dsp);
284
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
293 static int read_major_sync(MLPDecodeContext *m, BitstreamContext *bc)
294 {
295     MLPHeaderInfo mh;
296     int substr, ret;
297
298     if ((ret = ff_mlp_read_major_sync(m->avctx, &mh, bc)) != 0)
299         return ret;
300
301     if (mh.group1_bits == 0) {
302         av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown bits per sample\n");
303         return AVERROR_INVALIDDATA;
304     }
305     if (mh.group2_bits > mh.group1_bits) {
306         av_log(m->avctx, AV_LOG_ERROR,
307                "Channel group 2 cannot have more bits per sample than group 1.\n");
308         return AVERROR_INVALIDDATA;
309     }
310
311     if (mh.group2_samplerate && mh.group2_samplerate != mh.group1_samplerate) {
312         av_log(m->avctx, AV_LOG_ERROR,
313                "Channel groups with differing sample rates are not currently supported.\n");
314         return AVERROR_INVALIDDATA;
315     }
316
317     if (mh.group1_samplerate == 0) {
318         av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown sampling rate\n");
319         return AVERROR_INVALIDDATA;
320     }
321     if (mh.group1_samplerate > MAX_SAMPLERATE) {
322         av_log(m->avctx, AV_LOG_ERROR,
323                "Sampling rate %d is greater than the supported maximum (%d).\n",
324                mh.group1_samplerate, MAX_SAMPLERATE);
325         return AVERROR_INVALIDDATA;
326     }
327     if (mh.access_unit_size > MAX_BLOCKSIZE) {
328         av_log(m->avctx, AV_LOG_ERROR,
329                "Block size %d is greater than the supported maximum (%d).\n",
330                mh.access_unit_size, MAX_BLOCKSIZE);
331         return AVERROR_INVALIDDATA;
332     }
333     if (mh.access_unit_size_pow2 > MAX_BLOCKSIZE_POW2) {
334         av_log(m->avctx, AV_LOG_ERROR,
335                "Block size pow2 %d is greater than the supported maximum (%d).\n",
336                mh.access_unit_size_pow2, MAX_BLOCKSIZE_POW2);
337         return AVERROR_INVALIDDATA;
338     }
339
340     if (mh.num_substreams == 0)
341         return AVERROR_INVALIDDATA;
342     if (m->avctx->codec_id == AV_CODEC_ID_MLP && mh.num_substreams > 2) {
343         av_log(m->avctx, AV_LOG_ERROR, "MLP only supports up to 2 substreams.\n");
344         return AVERROR_INVALIDDATA;
345     }
346     if (mh.num_substreams > MAX_SUBSTREAMS) {
347         avpriv_request_sample(m->avctx,
348                               "%d substreams (more than the "
349                               "maximum supported by the decoder)",
350                               mh.num_substreams);
351         return AVERROR_PATCHWELCOME;
352     }
353
354     m->major_sync_header_size = mh.header_size;
355
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;
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);
363
364     m->avctx->sample_rate    = mh.group1_samplerate;
365     m->avctx->frame_size     = mh.access_unit_size;
366
367     m->avctx->bits_per_raw_sample = mh.group1_bits;
368     if (mh.group1_bits > 16)
369         m->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
370     else
371         m->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
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);
376
377     m->params_valid = 1;
378     for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
379         m->substream[substr].restart_seen = 0;
380
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)))
386             m->substream[0].ch_layout = AV_CH_LAYOUT_STEREO;
387         m->substream[substr].ch_layout = mh.channel_layout_mlp;
388     } else {
389         if ((substr = (mh.num_substreams > 1)))
390             m->substream[0].ch_layout = AV_CH_LAYOUT_STEREO;
391         if (mh.num_substreams > 2)
392             if (mh.channel_layout_thd_stream2)
393                 m->substream[2].ch_layout = mh.channel_layout_thd_stream2;
394             else
395                 m->substream[2].ch_layout = mh.channel_layout_thd_stream1;
396         m->substream[substr].ch_layout = mh.channel_layout_thd_stream1;
397     }
398
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
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
446 static int read_restart_header(MLPDecodeContext *m, BitstreamContext *bc,
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;
454     int start_count = bitstream_tell(bc);
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;
459
460     sync_word = bitstream_read(bc, 13);
461
462     if (sync_word != 0x31ea >> 1) {
463         av_log(m->avctx, AV_LOG_ERROR,
464                "restart header sync incorrect (got 0x%04x)\n", sync_word);
465         return AVERROR_INVALIDDATA;
466     }
467
468     s->noise_type = bitstream_read_bit(bc);
469
470     if (m->avctx->codec_id == AV_CODEC_ID_MLP && s->noise_type) {
471         av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n");
472         return AVERROR_INVALIDDATA;
473     }
474
475     bitstream_skip(bc, 16); /* Output timestamp */
476
477     min_channel        = bitstream_read(bc, 4);
478     max_channel        = bitstream_read(bc, 4);
479     max_matrix_channel = bitstream_read(bc, 4);
480
481     if (max_matrix_channel > std_max_matrix_channel) {
482         av_log(m->avctx, AV_LOG_ERROR,
483                "Max matrix channel cannot be greater than %d.\n",
484                max_matrix_channel);
485         return AVERROR_INVALIDDATA;
486     }
487
488     if (max_channel != max_matrix_channel) {
489         av_log(m->avctx, AV_LOG_ERROR,
490                "Max channel must be equal max matrix channel.\n");
491         return AVERROR_INVALIDDATA;
492     }
493
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) {
497         avpriv_request_sample(m->avctx,
498                               "%d channels (more than the "
499                               "maximum supported by the decoder)",
500                               s->max_channel + 2);
501         return AVERROR_PATCHWELCOME;
502     }
503
504     if (min_channel > max_channel) {
505         av_log(m->avctx, AV_LOG_ERROR,
506                "Substream min channel cannot be greater than max channel.\n");
507         return AVERROR_INVALIDDATA;
508     }
509
510     s->min_channel        = min_channel;
511     s->max_channel        = max_channel;
512     s->max_matrix_channel = max_matrix_channel;
513
514     if (m->avctx->request_channel_layout && (s->ch_layout & m->avctx->request_channel_layout) ==
515         m->avctx->request_channel_layout && m->max_decoded_substream > substr) {
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",
519                s->max_channel + 1, s->ch_layout, substr);
520         m->max_decoded_substream = substr;
521     }
522
523     s->noise_shift   = bitstream_read(bc,  4);
524     s->noisegen_seed = bitstream_read(bc, 23);
525
526     bitstream_skip(bc, 19);
527
528     s->data_check_present = bitstream_read_bit(bc);
529     lossless_check = bitstream_read(bc, 8);
530     if (substr == m->max_decoded_substream
531         && s->lossless_check_data != 0xffffffff) {
532         tmp = xor_32_to_8(s->lossless_check_data);
533         if (tmp != lossless_check)
534             av_log(m->avctx, AV_LOG_WARNING,
535                    "Lossless check failed - expected %02x, calculated %02x.\n",
536                    lossless_check, tmp);
537     }
538
539     bitstream_skip(bc, 16);
540
541     memset(s->ch_assign, 0, sizeof(s->ch_assign));
542
543     for (ch = 0; ch <= s->max_matrix_channel; ch++) {
544         int ch_assign = bitstream_read(bc, 6);
545         if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD) {
546             uint64_t channel = thd_channel_layout_extract_channel(s->ch_layout,
547                                                                   ch_assign);
548             ch_assign = av_get_channel_layout_channel_index(s->ch_layout,
549                                                             channel);
550         }
551         if (ch_assign < 0 || ch_assign > s->max_matrix_channel) {
552             avpriv_request_sample(m->avctx,
553                                   "Assignment of matrix channel %d to invalid output channel %d",
554                                   ch, ch_assign);
555             return AVERROR_PATCHWELCOME;
556         }
557         s->ch_assign[ch_assign] = ch;
558     }
559
560     checksum = ff_mlp_restart_checksum(buf, bitstream_tell(bc) - start_count);
561
562     if (checksum != bitstream_read(bc, 8))
563         av_log(m->avctx, AV_LOG_ERROR, "restart header checksum error\n");
564
565     /* Set default decoding parameters. */
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++) {
575         ChannelParams *cp = &s->channel_params[ch];
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;
580
581         /* Default audio coding is 24-bit raw PCM. */
582         cp->huff_offset      = 0;
583         cp->sign_huff_offset = -(1 << 23);
584         cp->codebook         = 0;
585         cp->huff_lsbs        = 24;
586     }
587
588     if (substr == m->max_decoded_substream) {
589         m->avctx->channels       = s->max_matrix_channel + 1;
590         m->avctx->channel_layout = s->ch_layout;
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);
595     }
596
597     return 0;
598 }
599
600 /** Read parameters for one of the prediction filters. */
601
602 static int read_filter_params(MLPDecodeContext *m, BitstreamContext *bc,
603                               unsigned int substr, unsigned int channel,
604                               unsigned int filter)
605 {
606     SubStream *s = &m->substream[substr];
607     FilterParams *fp = &s->channel_params[channel].filter_params[filter];
608     const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;
609     const char fchar = filter ? 'I' : 'F';
610     int i, order;
611
612     // Filter is 0 for FIR, 1 for IIR.
613     assert(filter < 2);
614
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");
617         return AVERROR_INVALIDDATA;
618     }
619
620     order = bitstream_read(bc, 4);
621     if (order > max_order) {
622         av_log(m->avctx, AV_LOG_ERROR,
623                "%cIR filter order %d is greater than maximum %d.\n",
624                fchar, order, max_order);
625         return AVERROR_INVALIDDATA;
626     }
627     fp->order = order;
628
629     if (order > 0) {
630         int32_t *fcoeff = s->channel_params[channel].coeff[filter];
631         int coeff_bits, coeff_shift;
632
633         fp->shift = bitstream_read(bc, 4);
634
635         coeff_bits  = bitstream_read(bc, 5);
636         coeff_shift = bitstream_read(bc, 3);
637         if (coeff_bits < 1 || coeff_bits > 16) {
638             av_log(m->avctx, AV_LOG_ERROR,
639                    "%cIR filter coeff_bits must be between 1 and 16.\n",
640                    fchar);
641             return AVERROR_INVALIDDATA;
642         }
643         if (coeff_bits + coeff_shift > 16) {
644             av_log(m->avctx, AV_LOG_ERROR,
645                    "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",
646                    fchar);
647             return AVERROR_INVALIDDATA;
648         }
649
650         for (i = 0; i < order; i++)
651             fcoeff[i] = bitstream_read_signed(bc, coeff_bits) << coeff_shift;
652
653         if (bitstream_read_bit(bc)) {
654             int state_bits, state_shift;
655
656             if (filter == FIR) {
657                 av_log(m->avctx, AV_LOG_ERROR,
658                        "FIR filter has state data specified.\n");
659                 return AVERROR_INVALIDDATA;
660             }
661
662             state_bits  = bitstream_read(bc, 4);
663             state_shift = bitstream_read(bc, 4);
664
665             /* TODO: Check validity of state data. */
666
667             for (i = 0; i < order; i++)
668                 fp->state[i] = bitstream_read_signed(bc, state_bits) << state_shift;
669         }
670     }
671
672     return 0;
673 }
674
675 /** Read parameters for primitive matrices. */
676
677 static int read_matrix_params(MLPDecodeContext *m, unsigned int substr,
678                               BitstreamContext *bc)
679 {
680     SubStream *s = &m->substream[substr];
681     unsigned int mat, ch;
682     const int max_primitive_matrices = m->avctx->codec_id == AV_CODEC_ID_MLP
683                                      ? MAX_MATRICES_MLP
684                                      : MAX_MATRICES_TRUEHD;
685
686     if (m->matrix_changed++ > 1) {
687         av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");
688         return AVERROR_INVALIDDATA;
689     }
690
691     s->num_primitive_matrices = bitstream_read(bc, 4);
692
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);
697         return AVERROR_INVALIDDATA;
698     }
699
700     for (mat = 0; mat < s->num_primitive_matrices; mat++) {
701         int frac_bits, max_chan;
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);
705
706         if (s->matrix_out_ch[mat] > s->max_matrix_channel) {
707             av_log(m->avctx, AV_LOG_ERROR,
708                     "Invalid channel %d specified as output from matrix.\n",
709                     s->matrix_out_ch[mat]);
710             return AVERROR_INVALIDDATA;
711         }
712         if (frac_bits > 14) {
713             av_log(m->avctx, AV_LOG_ERROR,
714                     "Too many fractional bits specified.\n");
715             return AVERROR_INVALIDDATA;
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;
724             if (bitstream_read_bit(bc))
725                 coeff_val = bitstream_read_signed(bc, frac_bits + 2);
726
727             s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
728         }
729
730         if (s->noise_type)
731             s->matrix_noise_shift[mat] = bitstream_read(bc, 4);
732         else
733             s->matrix_noise_shift[mat] = 0;
734     }
735
736     return 0;
737 }
738
739 /** Read channel parameters. */
740
741 static int read_channel_params(MLPDecodeContext *m, unsigned int substr,
742                                BitstreamContext *bc, unsigned int ch)
743 {
744     SubStream *s = &m->substream[substr];
745     ChannelParams *cp = &s->channel_params[ch];
746     FilterParams *fir = &cp->filter_params[FIR];
747     FilterParams *iir = &cp->filter_params[IIR];
748     int ret;
749
750     if (s->param_presence_flags & PARAM_FIR)
751         if (bitstream_read_bit(bc))
752             if ((ret = read_filter_params(m, bc, substr, ch, FIR)) < 0)
753                 return ret;
754
755     if (s->param_presence_flags & PARAM_IIR)
756         if (bitstream_read_bit(bc))
757             if ((ret = read_filter_params(m, bc, substr, ch, IIR)) < 0)
758                 return ret;
759
760     if (fir->order + iir->order > 8) {
761         av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");
762         return AVERROR_INVALIDDATA;
763     }
764
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");
769         return AVERROR_INVALIDDATA;
770     }
771     /* The FIR and IIR filters must have the same precision.
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. */
776     if (!fir->order && iir->order)
777         fir->shift = iir->shift;
778
779     if (s->param_presence_flags & PARAM_HUFFOFFSET)
780         if (bitstream_read_bit(bc))
781             cp->huff_offset = bitstream_read_signed(bc, 15);
782
783     cp->codebook  = bitstream_read(bc, 2);
784     cp->huff_lsbs = bitstream_read(bc, 5);
785
786     if (cp->huff_lsbs > 24) {
787         av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");
788         return AVERROR_INVALIDDATA;
789     }
790
791     cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
792
793     return 0;
794 }
795
796 /** Read decoding parameters that change more often than those in the restart
797  *  header. */
798
799 static int read_decoding_params(MLPDecodeContext *m, BitstreamContext *bc,
800                                 unsigned int substr)
801 {
802     SubStream *s = &m->substream[substr];
803     unsigned int ch;
804     int ret;
805
806     if (s->param_presence_flags & PARAM_PRESENCE)
807         if (bitstream_read_bit(bc))
808             s->param_presence_flags = bitstream_read(bc, 8);
809
810     if (s->param_presence_flags & PARAM_BLOCKSIZE)
811         if (bitstream_read_bit(bc)) {
812             s->blocksize = bitstream_read(bc, 9);
813             if (s->blocksize < 8 || s->blocksize > m->access_unit_size) {
814                 av_log(m->avctx, AV_LOG_ERROR, "Invalid blocksize.");
815                 s->blocksize = 0;
816                 return AVERROR_INVALIDDATA;
817             }
818         }
819
820     if (s->param_presence_flags & PARAM_MATRIX)
821         if (bitstream_read_bit(bc))
822             if ((ret = read_matrix_params(m, substr, bc)) < 0)
823                 return ret;
824
825     if (s->param_presence_flags & PARAM_OUTSHIFT)
826         if (bitstream_read_bit(bc)) {
827             for (ch = 0; ch <= s->max_matrix_channel; ch++)
828                 s->output_shift[ch] = bitstream_read_signed(bc, 4);
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         }
835
836     if (s->param_presence_flags & PARAM_QUANTSTEP)
837         if (bitstream_read_bit(bc))
838             for (ch = 0; ch <= s->max_channel; ch++) {
839                 ChannelParams *cp = &s->channel_params[ch];
840
841                 s->quant_step_size[ch] = bitstream_read(bc, 4);
842
843                 cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
844             }
845
846     for (ch = s->min_channel; ch <= s->max_channel; ch++)
847         if (bitstream_read_bit(bc))
848             if ((ret = read_channel_params(m, substr, bc, ch)) < 0)
849                 return ret;
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
859 static void filter_channel(MLPDecodeContext *m, unsigned int substr,
860                            unsigned int channel)
861 {
862     SubStream *s = &m->substream[substr];
863     const int32_t *fircoeff = s->channel_params[channel].coeff[FIR];
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;
867     FilterParams *fir = &s->channel_params[channel].filter_params[FIR];
868     FilterParams *iir = &s->channel_params[channel].filter_params[IIR];
869     unsigned int filter_shift = fir->shift;
870     int32_t mask = MSB_MASK(s->quant_step_size[channel]);
871
872     memcpy(firbuf, fir->state, MAX_FIR_ORDER * sizeof(int32_t));
873     memcpy(iirbuf, iir->state, MAX_IIR_ORDER * sizeof(int32_t));
874
875     m->dsp.mlp_filter_channel(firbuf, fircoeff,
876                               fir->order, iir->order,
877                               filter_shift, mask, s->blocksize,
878                               &m->sample_buffer[s->blockpos][channel]);
879
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));
882 }
883
884 /** Read a block of PCM residual data (or actual if no filtering active). */
885
886 static int read_block_data(MLPDecodeContext *m, BitstreamContext *bc,
887                            unsigned int substr)
888 {
889     SubStream *s = &m->substream[substr];
890     unsigned int i, ch, expected_stream_pos = 0;
891     int ret;
892
893     if (s->data_check_present) {
894         expected_stream_pos  = bitstream_tell(bc);
895         expected_stream_pos += bitstream_read(bc, 16);
896         avpriv_request_sample(m->avctx,
897                               "Substreams with VLC block size check info");
898     }
899
900     if (s->blockpos + s->blocksize > m->access_unit_size) {
901         av_log(m->avctx, AV_LOG_ERROR, "too many audio samples in frame\n");
902         return AVERROR_INVALIDDATA;
903     }
904
905     memset(&m->bypassed_lsbs[s->blockpos][0], 0,
906            s->blocksize * sizeof(m->bypassed_lsbs[0]));
907
908     for (i = 0; i < s->blocksize; i++)
909         if ((ret = read_huff_channels(m, bc, substr, i)) < 0)
910             return ret;
911
912     for (ch = s->min_channel; ch <= s->max_channel; ch++)
913         filter_channel(m, substr, ch);
914
915     s->blockpos += s->blocksize;
916
917     if (s->data_check_present) {
918         if (bitstream_tell(bc) != expected_stream_pos)
919             av_log(m->avctx, AV_LOG_ERROR, "block data length mismatch\n");
920         bitstream_skip(bc, 8);
921     }
922
923     return 0;
924 }
925
926 /** Data table used for TrueHD noise generation function. */
927
928 static 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
957 static 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
977 static 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
996 static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
997 {
998     SubStream *s = &m->substream[substr];
999     unsigned int mat;
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++) {
1011         unsigned int dest_ch = s->matrix_out_ch[mat];
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]));
1023     }
1024 }
1025
1026 /** Write the audio data into the output buffer. */
1027
1028 static int output_data(MLPDecodeContext *m, unsigned int substr,
1029                        AVFrame *frame, int *got_frame_ptr)
1030 {
1031     AVCodecContext *avctx = m->avctx;
1032     SubStream *s = &m->substream[substr];
1033     int ret;
1034     int is32 = (m->avctx->sample_fmt == AV_SAMPLE_FMT_S32);
1035
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     }
1040
1041     if (!s->blockpos) {
1042         av_log(avctx, AV_LOG_ERROR, "No samples to output.\n");
1043         return AVERROR_INVALIDDATA;
1044     }
1045
1046     /* get output buffer */
1047     frame->nb_samples = s->blockpos;
1048     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1049         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1050         return ret;
1051     }
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);
1060
1061     /* Update matrix encoding side data */
1062     if ((ret = ff_side_data_update_matrix_encoding(frame, s->matrix_encoding)) < 0)
1063         return ret;
1064
1065     *got_frame_ptr = 1;
1066
1067     return 0;
1068 }
1069
1070 /** Read an access unit from the stream.
1071  *  @return negative on error, 0 if not enough data is present in the input stream,
1072  *  otherwise the number of bytes consumed. */
1073
1074 static int read_access_unit(AVCodecContext *avctx, void* data,
1075                             int *got_frame_ptr, AVPacket *avpkt)
1076 {
1077     const uint8_t *buf = avpkt->data;
1078     int buf_size = avpkt->size;
1079     MLPDecodeContext *m = avctx->priv_data;
1080     BitstreamContext bc;
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;
1088     int ret;
1089
1090     if (buf_size < 4)
1091         return 0;
1092
1093     length = (AV_RB16(buf) & 0xfff) * 2;
1094
1095     if (length < 4 || length > buf_size)
1096         return AVERROR_INVALIDDATA;
1097
1098     bitstream_init8(&bc, buf + 4, length - 4);
1099
1100     m->is_major_sync_unit = 0;
1101     if (bitstream_peek(&bc, 31) == (0xf8726fba >> 1)) {
1102         if (read_major_sync(m, &bc) < 0)
1103             goto error;
1104         m->is_major_sync_unit = 1;
1105         header_size += m->major_sync_header_size;
1106     }
1107
1108     if (!m->params_valid) {
1109         av_log(m->avctx, AV_LOG_WARNING,
1110                "Stream parameters not seen; skipping frame.\n");
1111         *got_frame_ptr = 0;
1112         return length;
1113     }
1114
1115     substream_start = 0;
1116
1117     for (substr = 0; substr < m->num_substreams; substr++) {
1118         int extraword_present, checkdata_present, end, nonrestart_substr;
1119
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);
1124
1125         end = bitstream_read(&bc, 12) * 2;
1126
1127         substr_header_size += 2;
1128
1129         if (extraword_present) {
1130             if (m->avctx->codec_id == AV_CODEC_ID_MLP) {
1131                 av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
1132                 goto error;
1133             }
1134             bitstream_skip(&bc, 16);
1135             substr_header_size += 2;
1136         }
1137
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
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
1166     parity_bits  = ff_mlp_calculate_parity(buf, 4);
1167     parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);
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];
1178         bitstream_init8(&bc, buf, substream_data_len[substr]);
1179
1180         m->matrix_changed = 0;
1181         memset(m->filter_changed, 0, sizeof(m->filter_changed));
1182
1183         s->blockpos = 0;
1184         do {
1185             if (bitstream_read_bit(&bc)) {
1186                 if (bitstream_read_bit(&bc)) {
1187                     /* A restart header should be present. */
1188                     if (read_restart_header(m, &bc, buf, substr) < 0)
1189                         goto next_substr;
1190                     s->restart_seen = 1;
1191                 }
1192
1193                 if (!s->restart_seen)
1194                     goto next_substr;
1195                 if (read_decoding_params(m, &bc, substr) < 0)
1196                     goto next_substr;
1197             }
1198
1199             if (!s->restart_seen)
1200                 goto next_substr;
1201
1202             if ((ret = read_block_data(m, &bc, substr)) < 0)
1203                 return ret;
1204
1205             if (bitstream_tell(&bc) >= substream_data_len[substr] * 8)
1206                 goto substream_length_mismatch;
1207
1208         } while (!bitstream_read_bit(&bc));
1209
1210         bitstream_skip(&bc, (-bitstream_tell(&bc)) & 15);
1211
1212         if (substream_data_len[substr] * 8 - bitstream_tell(&bc) >= 32) {
1213             int shorten_by;
1214
1215             if (bitstream_read(&bc, 16) != 0xD234)
1216                 return AVERROR_INVALIDDATA;
1217
1218             shorten_by = bitstream_read(&bc, 16);
1219             if      (m->avctx->codec_id == AV_CODEC_ID_TRUEHD && shorten_by  & 0x2000)
1220                 s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
1221             else if (m->avctx->codec_id == AV_CODEC_ID_MLP    && shorten_by != 0xD234)
1222                 return AVERROR_INVALIDDATA;
1223
1224             if (substr == m->max_decoded_substream)
1225                 av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");
1226         }
1227
1228         if (substream_parity_present[substr]) {
1229             uint8_t parity, checksum;
1230
1231             if (substream_data_len[substr] * 8 - bitstream_tell(&bc) != 16)
1232                 goto substream_length_mismatch;
1233
1234             parity   = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);
1235             checksum = ff_mlp_checksum8       (buf, substream_data_len[substr] - 2);
1236
1237             if ((bitstream_read(&bc, 8) ^ parity) != 0xa9)
1238                 av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);
1239             if (bitstream_read(&bc, 8) != checksum)
1240                 av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n"    , substr);
1241         }
1242
1243         if (substream_data_len[substr] * 8 != bitstream_tell(&bc))
1244             goto substream_length_mismatch;
1245
1246 next_substr:
1247         if (!s->restart_seen)
1248             av_log(m->avctx, AV_LOG_ERROR,
1249                    "No restart header present in substream %d.\n", substr);
1250
1251         buf += substream_data_len[substr];
1252     }
1253
1254     rematrix_channels(m, m->max_decoded_substream);
1255
1256     if ((ret = output_data(m, m->max_decoded_substream, data, got_frame_ptr)) < 0)
1257         return ret;
1258
1259     return length;
1260
1261 substream_length_mismatch:
1262     av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
1263     return AVERROR_INVALIDDATA;
1264
1265 error:
1266     m->params_valid = 0;
1267     return AVERROR_INVALIDDATA;
1268 }
1269
1270 AVCodec ff_mlp_decoder = {
1271     .name           = "mlp",
1272     .long_name      = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
1273     .type           = AVMEDIA_TYPE_AUDIO,
1274     .id             = AV_CODEC_ID_MLP,
1275     .priv_data_size = sizeof(MLPDecodeContext),
1276     .init           = mlp_decode_init,
1277     .decode         = read_access_unit,
1278     .capabilities   = AV_CODEC_CAP_DR1,
1279 };
1280
1281 #if CONFIG_TRUEHD_DECODER
1282 AVCodec ff_truehd_decoder = {
1283     .name           = "truehd",
1284     .long_name      = NULL_IF_CONFIG_SMALL("TrueHD"),
1285     .type           = AVMEDIA_TYPE_AUDIO,
1286     .id             = AV_CODEC_ID_TRUEHD,
1287     .priv_data_size = sizeof(MLPDecodeContext),
1288     .init           = mlp_decode_init,
1289     .decode         = read_access_unit,
1290     .capabilities   = AV_CODEC_CAP_DR1,
1291 };
1292 #endif /* CONFIG_TRUEHD_DECODER */