Browse code

MLP/TrueHD decoder.

Originally committed as revision 14067 to svn://svn.ffmpeg.org/ffmpeg/trunk

Ramiro Polla authored on 2008/07/05 00:44:13
Showing 7 changed files
... ...
@@ -122,6 +122,7 @@ version <next>
122 122
 - MAXIS EA XA (.xa) demuxer / decoder
123 123
 - BFI video decoder
124 124
 - OMA demuxer
125
+- MLP/TrueHD decoder
125 126
 
126 127
 version 0.4.9-pre1:
127 128
 
... ...
@@ -832,6 +832,7 @@ ac3_decoder_deps="gpl"
832 832
 dxa_decoder_deps="zlib"
833 833
 flashsv_decoder_deps="zlib"
834 834
 flashsv_encoder_deps="zlib"
835
+mlp_decoder_deps="mlp_parser"
835 836
 mpeg_xvmc_decoder_deps="xvmc"
836 837
 png_decoder_deps="zlib"
837 838
 png_encoder_deps="zlib"
... ...
@@ -259,6 +259,7 @@ following image formats are supported:
259 259
 @item Renderware TXD         @tab     @tab  X @tab Texture dictionaries used by the Renderware Engine.
260 260
 @item AMV                    @tab     @tab  X @tab Used in Chinese MP3 players.
261 261
 @item Mimic                  @tab     @tab  X @tab Used in MSN Messenger Webcam streams.
262
+@item MLP/TrueHD             @tab     @tab  X @tab Used in DVD-Audio and Blu-Ray discs.
262 263
 @end multitable
263 264
 
264 265
 @code{X} means that encoding (resp. decoding) is supported.
... ...
@@ -107,6 +107,7 @@ OBJS-$(CONFIG_MIMIC_DECODER)           += mimic.o
107 107
 OBJS-$(CONFIG_MJPEG_DECODER)           += mjpegdec.o mjpeg.o
108 108
 OBJS-$(CONFIG_MJPEG_ENCODER)           += mjpegenc.o mjpeg.o mpegvideo_enc.o motion_est.o ratecontrol.o mpeg12data.o mpegvideo.o
109 109
 OBJS-$(CONFIG_MJPEGB_DECODER)          += mjpegbdec.o mjpegdec.o mjpeg.o
110
+OBJS-$(CONFIG_MLP_DECODER)             += mlpdec.o
110 111
 OBJS-$(CONFIG_MMVIDEO_DECODER)         += mmvideo.o
111 112
 OBJS-$(CONFIG_MP2_DECODER)             += mpegaudiodec.o mpegaudiodecheader.o mpegaudio.o mpegaudiodata.o
112 113
 OBJS-$(CONFIG_MP2_ENCODER)             += mpegaudioenc.o mpegaudio.o mpegaudiodata.o
... ...
@@ -189,6 +189,7 @@ void avcodec_register_all(void)
189 189
     REGISTER_DECODER (IMC, imc);
190 190
     REGISTER_DECODER (MACE3, mace3);
191 191
     REGISTER_DECODER (MACE6, mace6);
192
+    REGISTER_DECODER (MLP, mlp);
192 193
     REGISTER_ENCDEC  (MP2, mp2);
193 194
     REGISTER_DECODER (MP3, mp3);
194 195
     REGISTER_DECODER (MP3ADU, mp3adu);
... ...
@@ -30,8 +30,8 @@
30 30
 #include "libavutil/avutil.h"
31 31
 
32 32
 #define LIBAVCODEC_VERSION_MAJOR 51
33
-#define LIBAVCODEC_VERSION_MINOR 57
34
-#define LIBAVCODEC_VERSION_MICRO  2
33
+#define LIBAVCODEC_VERSION_MINOR 58
34
+#define LIBAVCODEC_VERSION_MICRO  0
35 35
 
36 36
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
37 37
                                                LIBAVCODEC_VERSION_MINOR, \
38 38
new file mode 100644
... ...
@@ -0,0 +1,1180 @@
0
+/*
1
+ * MLP decoder
2
+ * Copyright (c) 2007-2008 Ian Caulfield
3
+ *
4
+ * This file is part of FFmpeg.
5
+ *
6
+ * FFmpeg is free software; you can redistribute it and/or
7
+ * modify it under the terms of the GNU Lesser General Public
8
+ * License as published by the Free Software Foundation; either
9
+ * version 2.1 of the License, or (at your option) any later version.
10
+ *
11
+ * FFmpeg is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
+ * Lesser General Public License for more details.
15
+ *
16
+ * You should have received a copy of the GNU Lesser General Public
17
+ * License along with FFmpeg; if not, write to the Free Software
18
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
+ */
20
+
21
+/**
22
+ * @file mlpdec.c
23
+ * MLP decoder
24
+ */
25
+
26
+#include "avcodec.h"
27
+#include "libavutil/intreadwrite.h"
28
+#include "bitstream.h"
29
+#include "libavutil/crc.h"
30
+#include "parser.h"
31
+#include "mlp_parser.h"
32
+
33
+/** Maximum number of channels that can be decoded. */
34
+#define MAX_CHANNELS        16
35
+
36
+/** Maximum number of matrices used in decoding. Most streams have one matrix
37
+ *  per output channel, but some rematrix a channel (usually 0) more than once.
38
+ */
39
+
40
+#define MAX_MATRICES        15
41
+
42
+/** Maximum number of substreams that can be decoded. This could also be set
43
+ *  higher, but again I haven't seen any examples with more than two. */
44
+#define MAX_SUBSTREAMS      2
45
+
46
+/** Maximum sample frequency seen in files. */
47
+#define MAX_SAMPLERATE      192000
48
+
49
+/** The maximum number of audio samples within one access unit. */
50
+#define MAX_BLOCKSIZE       (40 * (MAX_SAMPLERATE / 48000))
51
+/** The next power of two greater than MAX_BLOCKSIZE. */
52
+#define MAX_BLOCKSIZE_POW2  (64 * (MAX_SAMPLERATE / 48000))
53
+
54
+/** Number of allowed filters. */
55
+#define NUM_FILTERS         2
56
+
57
+/** The maximum number of taps in either the IIR or FIR filter.
58
+ *  I believe MLP actually specifies the maximum order for IIR filters as four,
59
+ *  and that the sum of the orders of both filters must be <= 8. */
60
+#define MAX_FILTER_ORDER    8
61
+
62
+/** Number of bits used for VLC lookup - longest huffman code is 9. */
63
+#define VLC_BITS            9
64
+
65
+
66
+static const char* sample_message =
67
+    "Please file a bug report following the instructions at "
68
+    "http://ffmpeg.mplayerhq.hu/bugreports.html and include "
69
+    "a sample of this file.";
70
+
71
+typedef struct SubStream {
72
+    //! Set if a valid restart header has been read. Otherwise the substream can not be decoded.
73
+    uint8_t     restart_seen;
74
+
75
+    //@{
76
+    /** restart header data */
77
+    //! The type of noise to be used in the rematrix stage.
78
+    uint16_t    noise_type;
79
+
80
+    //! The index of the first channel coded in this substream.
81
+    uint8_t     min_channel;
82
+    //! The index of the last channel coded in this substream.
83
+    uint8_t     max_channel;
84
+    //! The number of channels input into the rematrix stage.
85
+    uint8_t     max_matrix_channel;
86
+
87
+    //! The left shift applied to random noise in 0x31ea substreams.
88
+    uint8_t     noise_shift;
89
+    //! The current seed value for the pseudorandom noise generator(s).
90
+    uint32_t    noisegen_seed;
91
+
92
+    //! Set if the substream contains extra info to check the size of VLC blocks.
93
+    uint8_t     data_check_present;
94
+
95
+    //! Bitmask of which parameter sets are conveyed in a decoding parameter block.
96
+    uint8_t     param_presence_flags;
97
+#define PARAM_BLOCKSIZE     (1 << 7)
98
+#define PARAM_MATRIX        (1 << 6)
99
+#define PARAM_OUTSHIFT      (1 << 5)
100
+#define PARAM_QUANTSTEP     (1 << 4)
101
+#define PARAM_FIR           (1 << 3)
102
+#define PARAM_IIR           (1 << 2)
103
+#define PARAM_HUFFOFFSET    (1 << 1)
104
+    //@}
105
+
106
+    //@{
107
+    /** matrix data */
108
+
109
+    //! Number of matrices to be applied.
110
+    uint8_t     num_primitive_matrices;
111
+
112
+    //! matrix output channel
113
+    uint8_t     matrix_out_ch[MAX_MATRICES];
114
+
115
+    //! Whether the LSBs of the matrix output are encoded in the bitstream.
116
+    uint8_t     lsb_bypass[MAX_MATRICES];
117
+    //! Matrix coefficients, stored as 2.14 fixed point.
118
+    int32_t     matrix_coeff[MAX_MATRICES][MAX_CHANNELS+2];
119
+    //! Left shift to apply to noise values in 0x31eb substreams.
120
+    uint8_t     matrix_noise_shift[MAX_MATRICES];
121
+    //@}
122
+
123
+    //! Left shift to apply to huffman-decoded residuals.
124
+    uint8_t     quant_step_size[MAX_CHANNELS];
125
+
126
+    //! Number of PCM samples in current audio block.
127
+    uint16_t    blocksize;
128
+    //! Number of PCM samples decoded so far in this frame.
129
+    uint16_t    blockpos;
130
+
131
+    //! Left shift to apply to decoded PCM values to get final 24-bit output.
132
+    int8_t      output_shift[MAX_CHANNELS];
133
+
134
+    //! Running XOR of all output samples.
135
+    int32_t     lossless_check_data;
136
+
137
+} SubStream;
138
+
139
+typedef struct MLPDecodeContext {
140
+    AVCodecContext *avctx;
141
+
142
+    //! Set if a valid major sync block has been read. Otherwise no decoding is possible.
143
+    uint8_t     params_valid;
144
+
145
+    //! Number of substreams contained within this stream.
146
+    uint8_t     num_substreams;
147
+
148
+    //! Index of the last substream to decode - further substreams are skipped.
149
+    uint8_t     max_decoded_substream;
150
+
151
+    //! Number of PCM samples contained in each frame.
152
+    int         access_unit_size;
153
+    //! Next power of two above the number of samples in each frame.
154
+    int         access_unit_size_pow2;
155
+
156
+    SubStream   substream[MAX_SUBSTREAMS];
157
+
158
+    //@{
159
+    /** filter data */
160
+#define FIR 0
161
+#define IIR 1
162
+    //! Number of taps in filter.
163
+    uint8_t     filter_order[MAX_CHANNELS][NUM_FILTERS];
164
+    //! Right shift to apply to output of filter.
165
+    uint8_t     filter_shift[MAX_CHANNELS][NUM_FILTERS];
166
+
167
+    int32_t     filter_coeff[MAX_CHANNELS][NUM_FILTERS][MAX_FILTER_ORDER];
168
+    int32_t     filter_state[MAX_CHANNELS][NUM_FILTERS][MAX_FILTER_ORDER];
169
+    //@}
170
+
171
+    //@{
172
+    /** sample data coding infomation */
173
+    //! Offset to apply to residual values.
174
+    int16_t     huff_offset[MAX_CHANNELS];
175
+    //! Sign/rounding corrected version of huff_offset.
176
+    int32_t     sign_huff_offset[MAX_CHANNELS];
177
+    //! Which VLC codebook to use to read residuals.
178
+    uint8_t     codebook[MAX_CHANNELS];
179
+    //! Size of residual suffix not encoded using VLC.
180
+    uint8_t     huff_lsbs[MAX_CHANNELS];
181
+    //@}
182
+
183
+    int8_t      noise_buffer[MAX_BLOCKSIZE_POW2];
184
+    int8_t      bypassed_lsbs[MAX_BLOCKSIZE][MAX_CHANNELS];
185
+    int32_t     sample_buffer[MAX_BLOCKSIZE][MAX_CHANNELS+2];
186
+} MLPDecodeContext;
187
+
188
+/** Tables defining the huffman codes.
189
+ *  There are three entropy coding methods used in MLP (four if you count
190
+ *  "none" as a method). These use the same sequences for codes starting with
191
+ *  00 or 01, but have different codes starting with 1. */
192
+
193
+static const uint8_t huffman_tables[3][18][2] = {
194
+    {    /* huffman table 0, -7 - +10 */
195
+        {0x01, 9}, {0x01, 8}, {0x01, 7}, {0x01, 6}, {0x01, 5}, {0x01, 4}, {0x01, 3},
196
+        {0x04, 3}, {0x05, 3}, {0x06, 3}, {0x07, 3},
197
+        {0x03, 3}, {0x05, 4}, {0x09, 5}, {0x11, 6}, {0x21, 7}, {0x41, 8}, {0x81, 9},
198
+    }, { /* huffman table 1, -7 - +8 */
199
+        {0x01, 9}, {0x01, 8}, {0x01, 7}, {0x01, 6}, {0x01, 5}, {0x01, 4}, {0x01, 3},
200
+        {0x02, 2}, {0x03, 2},
201
+        {0x03, 3}, {0x05, 4}, {0x09, 5}, {0x11, 6}, {0x21, 7}, {0x41, 8}, {0x81, 9},
202
+    }, { /* huffman table 2, -7 - +7 */
203
+        {0x01, 9}, {0x01, 8}, {0x01, 7}, {0x01, 6}, {0x01, 5}, {0x01, 4}, {0x01, 3},
204
+        {0x01, 1},
205
+        {0x03, 3}, {0x05, 4}, {0x09, 5}, {0x11, 6}, {0x21, 7}, {0x41, 8}, {0x81, 9},
206
+    }
207
+};
208
+
209
+static VLC huff_vlc[3];
210
+
211
+static int crc_init = 0;
212
+static AVCRC crc_63[1024];
213
+static AVCRC crc_1D[1024];
214
+
215
+
216
+/** Initialize static data, constant between all invocations of the codec. */
217
+
218
+static av_cold void init_static()
219
+{
220
+    INIT_VLC_STATIC(&huff_vlc[0], VLC_BITS, 18,
221
+                &huffman_tables[0][0][1], 2, 1,
222
+                &huffman_tables[0][0][0], 2, 1, 512);
223
+    INIT_VLC_STATIC(&huff_vlc[1], VLC_BITS, 16,
224
+                &huffman_tables[1][0][1], 2, 1,
225
+                &huffman_tables[1][0][0], 2, 1, 512);
226
+    INIT_VLC_STATIC(&huff_vlc[2], VLC_BITS, 15,
227
+                &huffman_tables[2][0][1], 2, 1,
228
+                &huffman_tables[2][0][0], 2, 1, 512);
229
+
230
+    if (!crc_init) {
231
+        av_crc_init(crc_63, 0,  8,   0x63, sizeof(crc_63));
232
+        av_crc_init(crc_1D, 0,  8,   0x1D, sizeof(crc_1D));
233
+        crc_init = 1;
234
+    }
235
+}
236
+
237
+
238
+/** MLP uses checksums that seem to be based on the standard CRC algorithm,
239
+ *  but not (in implementation terms, the table lookup and XOR are reversed).
240
+ *  We can implement this behavior using a standard av_crc on all but the
241
+ *  last element, then XOR that with the last element. */
242
+
243
+static uint8_t mlp_checksum8(const uint8_t *buf, unsigned int buf_size)
244
+{
245
+    uint8_t checksum = av_crc(crc_63, 0x3c, buf, buf_size - 1); // crc_63[0xa2] == 0x3c
246
+    checksum ^= buf[buf_size-1];
247
+    return checksum;
248
+}
249
+
250
+/** Calculate an 8-bit checksum over a restart header -- a non-multiple-of-8
251
+ *  number of bits, starting two bits into the first byte of buf. */
252
+
253
+static uint8_t mlp_restart_checksum(const uint8_t *buf, unsigned int bit_size)
254
+{
255
+    int i;
256
+    int num_bytes = (bit_size + 2) / 8;
257
+
258
+    int crc = crc_1D[buf[0] & 0x3f];
259
+    crc = av_crc(crc_1D, crc, buf + 1, num_bytes - 2);
260
+    crc ^= buf[num_bytes - 1];
261
+
262
+    for (i = 0; i < ((bit_size + 2) & 7); i++) {
263
+        crc <<= 1;
264
+        if (crc & 0x100)
265
+            crc ^= 0x11D;
266
+        crc ^= (buf[num_bytes] >> (7 - i)) & 1;
267
+    }
268
+
269
+    return crc;
270
+}
271
+
272
+static inline int32_t calculate_sign_huff(MLPDecodeContext *m,
273
+                                          unsigned int substr, unsigned int ch)
274
+{
275
+    SubStream *s = &m->substream[substr];
276
+    int lsb_bits = m->huff_lsbs[ch] - s->quant_step_size[ch];
277
+    int sign_shift = lsb_bits + (m->codebook[ch] ? 2 - m->codebook[ch] : -1);
278
+    int32_t sign_huff_offset = m->huff_offset[ch];
279
+
280
+    if (m->codebook[ch] > 0)
281
+        sign_huff_offset -= 7 << lsb_bits;
282
+
283
+    if (sign_shift >= 0)
284
+        sign_huff_offset -= 1 << sign_shift;
285
+
286
+    return sign_huff_offset;
287
+}
288
+
289
+/** Read a sample, consisting of either, both or neither of entropy-coded MSBs
290
+ *  and plain LSBs. */
291
+
292
+static inline int read_huff_channels(MLPDecodeContext *m, GetBitContext *gbp,
293
+                                     unsigned int substr, unsigned int pos)
294
+{
295
+    SubStream *s = &m->substream[substr];
296
+    unsigned int mat, channel;
297
+
298
+    for (mat = 0; mat < s->num_primitive_matrices; mat++)
299
+        if (s->lsb_bypass[mat])
300
+            m->bypassed_lsbs[pos + s->blockpos][mat] = get_bits1(gbp);
301
+
302
+    for (channel = s->min_channel; channel <= s->max_channel; channel++) {
303
+        int codebook = m->codebook[channel];
304
+        int quant_step_size = s->quant_step_size[channel];
305
+        int lsb_bits = m->huff_lsbs[channel] - quant_step_size;
306
+        int result = 0;
307
+
308
+        if (codebook > 0)
309
+            result = get_vlc2(gbp, huff_vlc[codebook-1].table,
310
+                            VLC_BITS, (9 + VLC_BITS - 1) / VLC_BITS);
311
+
312
+        if (result < 0)
313
+            return -1;
314
+
315
+        if (lsb_bits > 0)
316
+            result = (result << lsb_bits) + get_bits(gbp, lsb_bits);
317
+
318
+        result  += m->sign_huff_offset[channel];
319
+        result <<= quant_step_size;
320
+
321
+        m->sample_buffer[pos + s->blockpos][channel] = result;
322
+    }
323
+
324
+    return 0;
325
+}
326
+
327
+static av_cold int mlp_decode_init(AVCodecContext *avctx)
328
+{
329
+    MLPDecodeContext *m = avctx->priv_data;
330
+    int substr;
331
+
332
+    init_static();
333
+    m->avctx = avctx;
334
+    for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
335
+        m->substream[substr].lossless_check_data = 0xffffffff;
336
+    return 0;
337
+}
338
+
339
+/** Read a major sync info header - contains high level information about
340
+ *  the stream - sample rate, channel arrangement etc. Most of this
341
+ *  information is not actually necessary for decoding, only for playback.
342
+ */
343
+
344
+static int read_major_sync(MLPDecodeContext *m, GetBitContext *gb)
345
+{
346
+    MLPHeaderInfo mh;
347
+    int substr;
348
+
349
+    if (ff_mlp_read_major_sync(m->avctx, &mh, gb) != 0)
350
+        return -1;
351
+
352
+    if (mh.group1_bits == 0) {
353
+        av_log(m->avctx, AV_LOG_ERROR, "Invalid/unknown bits per sample\n");
354
+        return -1;
355
+    }
356
+    if (mh.group2_bits > mh.group1_bits) {
357
+        av_log(m->avctx, AV_LOG_ERROR,
358
+               "Channel group 2 cannot have more bits per sample than group 1\n");
359
+        return -1;
360
+    }
361
+
362
+    if (mh.group2_samplerate && mh.group2_samplerate != mh.group1_samplerate) {
363
+        av_log(m->avctx, AV_LOG_ERROR,
364
+               "Channel groups with differing sample rates not currently supported\n");
365
+        return -1;
366
+    }
367
+
368
+    if (mh.group1_samplerate == 0) {
369
+        av_log(m->avctx, AV_LOG_ERROR, "Invalid/unknown sampling rate\n");
370
+        return -1;
371
+    }
372
+    if (mh.group1_samplerate > MAX_SAMPLERATE) {
373
+        av_log(m->avctx, AV_LOG_ERROR,
374
+               "Sampling rate %d is greater than maximum supported (%d)\n",
375
+               mh.group1_samplerate, MAX_SAMPLERATE);
376
+        return -1;
377
+    }
378
+    if (mh.access_unit_size > MAX_BLOCKSIZE) {
379
+        av_log(m->avctx, AV_LOG_ERROR,
380
+               "Block size %d is greater than maximum supported (%d)\n",
381
+               mh.access_unit_size, MAX_BLOCKSIZE);
382
+        return -1;
383
+    }
384
+    if (mh.access_unit_size_pow2 > MAX_BLOCKSIZE_POW2) {
385
+        av_log(m->avctx, AV_LOG_ERROR,
386
+               "Block size pow2 %d is greater than maximum supported (%d)\n",
387
+               mh.access_unit_size_pow2, MAX_BLOCKSIZE_POW2);
388
+        return -1;
389
+    }
390
+
391
+    if (mh.num_substreams == 0)
392
+        return -1;
393
+    if (mh.num_substreams > MAX_SUBSTREAMS) {
394
+        av_log(m->avctx, AV_LOG_ERROR,
395
+               "Number of substreams %d is more than maximum supported by "
396
+               "decoder. %s\n", mh.num_substreams, sample_message);
397
+        return -1;
398
+    }
399
+
400
+    m->access_unit_size      = mh.access_unit_size;
401
+    m->access_unit_size_pow2 = mh.access_unit_size_pow2;
402
+
403
+    m->num_substreams        = mh.num_substreams;
404
+    m->max_decoded_substream = m->num_substreams - 1;
405
+
406
+    m->avctx->sample_rate    = mh.group1_samplerate;
407
+    m->avctx->frame_size     = mh.access_unit_size;
408
+
409
+#ifdef CONFIG_AUDIO_NONSHORT
410
+    m->avctx->bits_per_sample = mh.group1_bits;
411
+    if (mh.group1_bits > 16) {
412
+        m->avctx->sample_fmt = SAMPLE_FMT_S32;
413
+    }
414
+#endif
415
+
416
+    m->params_valid = 1;
417
+    for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
418
+        m->substream[substr].restart_seen = 0;
419
+
420
+    return 0;
421
+}
422
+
423
+/** Read a restart header from a block in a substream. This contains parameters
424
+ *  required to decode the audio that do not change very often. Generally
425
+ *  (always) present only in blocks following a major sync. */
426
+
427
+static int read_restart_header(MLPDecodeContext *m, GetBitContext *gbp,
428
+                               const uint8_t *buf, unsigned int substr)
429
+{
430
+    SubStream *s = &m->substream[substr];
431
+    unsigned int ch;
432
+    int sync_word, tmp;
433
+    uint8_t checksum;
434
+    uint8_t lossless_check;
435
+    int start_count = get_bits_count(gbp);
436
+
437
+    sync_word = get_bits(gbp, 13);
438
+
439
+    if (sync_word != 0x31ea >> 1) {
440
+        av_log(m->avctx, AV_LOG_ERROR,
441
+               "Restart header sync incorrect (got 0x%04x)\n", sync_word);
442
+        return -1;
443
+    }
444
+    s->noise_type = get_bits1(gbp);
445
+
446
+    skip_bits(gbp, 16); /* Output timestamp */
447
+
448
+    s->min_channel        = get_bits(gbp, 4);
449
+    s->max_channel        = get_bits(gbp, 4);
450
+    s->max_matrix_channel = get_bits(gbp, 4);
451
+
452
+    if (s->min_channel > s->max_channel) {
453
+        av_log(m->avctx, AV_LOG_ERROR,
454
+               "Substream min channel cannot be greater than max channel.\n");
455
+        return -1;
456
+    }
457
+
458
+    if (m->avctx->request_channels > 0
459
+        && s->max_channel + 1 >= m->avctx->request_channels
460
+        && substr < m->max_decoded_substream) {
461
+        av_log(m->avctx, AV_LOG_INFO,
462
+               "Extracting %d channel downmix from substream %d. "
463
+               "Further substreams will be skipped.\n",
464
+               s->max_channel + 1, substr);
465
+        m->max_decoded_substream = substr;
466
+    }
467
+
468
+    s->noise_shift   = get_bits(gbp,  4);
469
+    s->noisegen_seed = get_bits(gbp, 23);
470
+
471
+    skip_bits(gbp, 19);
472
+
473
+    s->data_check_present = get_bits1(gbp);
474
+    lossless_check = get_bits(gbp, 8);
475
+    if (substr == m->max_decoded_substream
476
+        && s->lossless_check_data != 0xffffffff) {
477
+        tmp = s->lossless_check_data;
478
+        tmp ^= tmp >> 16;
479
+        tmp ^= tmp >> 8;
480
+        tmp &= 0xff;
481
+        if (tmp != lossless_check)
482
+            av_log(m->avctx, AV_LOG_WARNING,
483
+                   "Lossless check failed - expected %02x, calculated %02x\n",
484
+                   lossless_check, tmp);
485
+        else
486
+            dprintf(m->avctx, "Lossless check passed for substream %d (%x)\n",
487
+                    substr, tmp);
488
+    }
489
+
490
+    skip_bits(gbp, 16);
491
+
492
+    for (ch = 0; ch <= s->max_matrix_channel; ch++) {
493
+        int ch_assign = get_bits(gbp, 6);
494
+        dprintf(m->avctx, "ch_assign[%d][%d] = %d\n", substr, ch,
495
+                ch_assign);
496
+        if (ch_assign != ch) {
497
+            av_log(m->avctx, AV_LOG_ERROR,
498
+                   "Non 1:1 channel assignments are used in this stream. %s\n",
499
+                   sample_message);
500
+            return -1;
501
+        }
502
+    }
503
+
504
+    checksum = mlp_restart_checksum(buf, get_bits_count(gbp) - start_count);
505
+
506
+    if (checksum != get_bits(gbp, 8))
507
+        av_log(m->avctx, AV_LOG_ERROR, "Restart header checksum error\n");
508
+
509
+    /* Set default decoding parameters */
510
+    s->param_presence_flags   = 0xff;
511
+    s->num_primitive_matrices = 0;
512
+    s->blocksize              = 8;
513
+    s->lossless_check_data    = 0;
514
+
515
+    memset(s->output_shift   , 0, sizeof(s->output_shift   ));
516
+    memset(s->quant_step_size, 0, sizeof(s->quant_step_size));
517
+
518
+    for (ch = s->min_channel; ch <= s->max_channel; ch++) {
519
+        m->filter_order[ch][FIR] = 0;
520
+        m->filter_order[ch][IIR] = 0;
521
+        m->filter_shift[ch][FIR] = 0;
522
+        m->filter_shift[ch][IIR] = 0;
523
+
524
+        /* Default audio coding is 24-bit raw PCM */
525
+        m->huff_offset     [ch] = 0;
526
+        m->sign_huff_offset[ch] = (-1) << 23;
527
+        m->codebook        [ch] = 0;
528
+        m->huff_lsbs       [ch] = 24;
529
+    }
530
+
531
+    if (substr == m->max_decoded_substream) {
532
+        m->avctx->channels = s->max_channel + 1;
533
+    }
534
+
535
+    return 0;
536
+}
537
+
538
+/** Read parameters for one of the prediction filters. */
539
+
540
+static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp,
541
+                              unsigned int channel, unsigned int filter)
542
+{
543
+    const char fchar = filter ? 'I' : 'F';
544
+    int i, order;
545
+
546
+    // filter is 0 for FIR, 1 for IIR
547
+    assert(filter < 2);
548
+
549
+    order = get_bits(gbp, 4);
550
+    if (order > MAX_FILTER_ORDER) {
551
+        av_log(m->avctx, AV_LOG_ERROR,
552
+               "%cIR filter order %d is greater than maximum %d\n",
553
+               fchar, order, MAX_FILTER_ORDER);
554
+        return -1;
555
+    }
556
+    m->filter_order[channel][filter] = order;
557
+
558
+    if (order > 0) {
559
+        int coeff_bits, coeff_shift;
560
+
561
+        m->filter_shift[channel][filter] = get_bits(gbp, 4);
562
+
563
+        coeff_bits  = get_bits(gbp, 5);
564
+        coeff_shift = get_bits(gbp, 3);
565
+        if (coeff_bits < 1 || coeff_bits > 16) {
566
+            av_log(m->avctx, AV_LOG_ERROR,
567
+                   "%cIR filter coeff_bits must be between 1 and 16\n",
568
+                   fchar);
569
+            return -1;
570
+        }
571
+        if (coeff_bits + coeff_shift > 16) {
572
+            av_log(m->avctx, AV_LOG_ERROR,
573
+                   "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less\n",
574
+                   fchar);
575
+            return -1;
576
+        }
577
+
578
+        for (i = 0; i < order; i++)
579
+            m->filter_coeff[channel][filter][i] =
580
+                    get_sbits(gbp, coeff_bits) << coeff_shift;
581
+
582
+        if (get_bits1(gbp)) {
583
+            int state_bits, state_shift;
584
+
585
+            if (filter == FIR) {
586
+                av_log(m->avctx, AV_LOG_ERROR,
587
+                       "FIR filter has state data specified\n");
588
+                return -1;
589
+            }
590
+
591
+            state_bits  = get_bits(gbp, 4);
592
+            state_shift = get_bits(gbp, 4);
593
+
594
+            /* TODO: check validity of state data */
595
+
596
+            for (i = 0; i < order; i++)
597
+                m->filter_state[channel][filter][i] =
598
+                    get_sbits(gbp, state_bits) << state_shift;
599
+        }
600
+    }
601
+
602
+    return 0;
603
+}
604
+
605
+/** Read decoding parameters that change more often than those in the restart
606
+ *  header. */
607
+
608
+static int read_decoding_params(MLPDecodeContext *m, GetBitContext *gbp,
609
+                                unsigned int substr)
610
+{
611
+    SubStream *s = &m->substream[substr];
612
+    unsigned int mat, ch;
613
+
614
+    if (get_bits1(gbp))
615
+        s->param_presence_flags = get_bits(gbp, 8);
616
+
617
+    if (s->param_presence_flags & PARAM_BLOCKSIZE)
618
+        if (get_bits1(gbp)) {
619
+            s->blocksize = get_bits(gbp, 9);
620
+            if (s->blocksize > MAX_BLOCKSIZE) {
621
+                av_log(m->avctx, AV_LOG_ERROR, "Block size too large\n");
622
+                s->blocksize = 0;
623
+                return -1;
624
+            }
625
+        }
626
+
627
+    if (s->param_presence_flags & PARAM_MATRIX)
628
+        if (get_bits1(gbp)) {
629
+            s->num_primitive_matrices = get_bits(gbp, 4);
630
+
631
+            for (mat = 0; mat < s->num_primitive_matrices; mat++) {
632
+                int frac_bits, max_chan;
633
+                s->matrix_out_ch[mat] = get_bits(gbp, 4);
634
+                frac_bits             = get_bits(gbp, 4);
635
+                s->lsb_bypass   [mat] = get_bits1(gbp);
636
+
637
+                if (s->matrix_out_ch[mat] > s->max_channel) {
638
+                    av_log(m->avctx, AV_LOG_ERROR,
639
+                           "Invalid channel %d specified as output from matrix\n",
640
+                           s->matrix_out_ch[mat]);
641
+                    return -1;
642
+                }
643
+                if (frac_bits > 14) {
644
+                    av_log(m->avctx, AV_LOG_ERROR,
645
+                           "Too many fractional bits specified\n");
646
+                    return -1;
647
+                }
648
+
649
+                max_chan = s->max_matrix_channel;
650
+                if (!s->noise_type)
651
+                    max_chan+=2;
652
+
653
+                for (ch = 0; ch <= max_chan; ch++) {
654
+                    int coeff_val = 0;
655
+                    if (get_bits1(gbp))
656
+                        coeff_val = get_sbits(gbp, frac_bits + 2);
657
+
658
+                    s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
659
+                }
660
+
661
+                if (s->noise_type)
662
+                    s->matrix_noise_shift[mat] = get_bits(gbp, 4);
663
+                else
664
+                    s->matrix_noise_shift[mat] = 0;
665
+            }
666
+        }
667
+
668
+    if (s->param_presence_flags & PARAM_OUTSHIFT)
669
+        if (get_bits1(gbp))
670
+            for (ch = 0; ch <= s->max_matrix_channel; ch++) {
671
+                s->output_shift[ch] = get_bits(gbp, 4);
672
+                dprintf(m->avctx, "output shift[%d] = %d\n",
673
+                        ch, s->output_shift[ch]);
674
+                /* TODO: validate */
675
+            }
676
+
677
+    if (s->param_presence_flags & PARAM_QUANTSTEP)
678
+        if (get_bits1(gbp))
679
+            for (ch = 0; ch <= s->max_channel; ch++) {
680
+                s->quant_step_size[ch] = get_bits(gbp, 4);
681
+                /* TODO: validate */
682
+
683
+                m->sign_huff_offset[ch] = calculate_sign_huff(m, substr, ch);
684
+            }
685
+
686
+    for (ch = s->min_channel; ch <= s->max_channel; ch++)
687
+        if (get_bits1(gbp)) {
688
+            if (s->param_presence_flags & PARAM_FIR)
689
+                if (get_bits1(gbp))
690
+                    if (read_filter_params(m, gbp, ch, FIR) < 0)
691
+                        return -1;
692
+
693
+            if (s->param_presence_flags & PARAM_IIR)
694
+                if (get_bits1(gbp))
695
+                    if (read_filter_params(m, gbp, ch, IIR) < 0)
696
+                        return -1;
697
+
698
+            if (m->filter_order[ch][FIR] && m->filter_order[ch][IIR] &&
699
+                m->filter_shift[ch][FIR] != m->filter_shift[ch][IIR]) {
700
+                av_log(m->avctx, AV_LOG_ERROR,
701
+                       "FIR and IIR filters must use same precision\n");
702
+                return -1;
703
+            }
704
+            /* The FIR and IIR filters must have the same precision.
705
+             * To simplify the filtering code, only the precision of the
706
+             * FIR filter is considered. If only the IIR filter is employed,
707
+             * the FIR filter precision is set to that of the IIR filter, so
708
+             * that the filtering code can use it. */
709
+            if (!m->filter_order[ch][FIR] && m->filter_order[ch][IIR])
710
+                m->filter_shift[ch][FIR] = m->filter_shift[ch][IIR];
711
+
712
+            if (s->param_presence_flags & PARAM_HUFFOFFSET)
713
+                if (get_bits1(gbp))
714
+                    m->huff_offset[ch] = get_sbits(gbp, 15);
715
+
716
+            m->codebook [ch] = get_bits(gbp, 2);
717
+            m->huff_lsbs[ch] = get_bits(gbp, 5);
718
+
719
+            m->sign_huff_offset[ch] = calculate_sign_huff(m, substr, ch);
720
+
721
+            /* TODO: validate */
722
+        }
723
+
724
+    return 0;
725
+}
726
+
727
+#define MSB_MASK(bits)  (-1u << bits)
728
+
729
+/** Generate PCM samples using the prediction filters and residual values
730
+ *  read from the data stream, and update the filter state. */
731
+
732
+static void filter_channel(MLPDecodeContext *m, unsigned int substr,
733
+                           unsigned int channel)
734
+{
735
+    SubStream *s = &m->substream[substr];
736
+    int32_t filter_state_buffer[NUM_FILTERS][MAX_BLOCKSIZE + MAX_FILTER_ORDER];
737
+    unsigned int filter_shift = m->filter_shift[channel][FIR];
738
+    int32_t mask = MSB_MASK(s->quant_step_size[channel]);
739
+    int index = MAX_BLOCKSIZE;
740
+    int j, i;
741
+
742
+    for (j = 0; j < NUM_FILTERS; j++) {
743
+        memcpy(&   filter_state_buffer  [j][MAX_BLOCKSIZE],
744
+               &m->filter_state[channel][j][0],
745
+               MAX_FILTER_ORDER * sizeof(int32_t));
746
+    }
747
+
748
+    for (i = 0; i < s->blocksize; i++) {
749
+        int32_t residual = m->sample_buffer[i + s->blockpos][channel];
750
+        unsigned int order;
751
+        int64_t accum = 0;
752
+        int32_t result;
753
+
754
+        /* TODO: Move this code to DSPContext? */
755
+
756
+        for (j = 0; j < NUM_FILTERS; j++)
757
+            for (order = 0; order < m->filter_order[channel][j]; order++)
758
+                accum += (int64_t)filter_state_buffer[j][index + order] *
759
+                        m->filter_coeff[channel][j][order];
760
+
761
+        accum  = accum >> filter_shift;
762
+        result = (accum + residual) & mask;
763
+
764
+        --index;
765
+
766
+        filter_state_buffer[FIR][index] = result;
767
+        filter_state_buffer[IIR][index] = result - accum;
768
+
769
+        m->sample_buffer[i + s->blockpos][channel] = result;
770
+    }
771
+
772
+    for (j = 0; j < NUM_FILTERS; j++) {
773
+        memcpy(&m->filter_state[channel][j][0],
774
+               &   filter_state_buffer  [j][index],
775
+               MAX_FILTER_ORDER * sizeof(int32_t));
776
+    }
777
+}
778
+
779
+/** Read a block of PCM residual data (or actual if no filtering active). */
780
+
781
+static int read_block_data(MLPDecodeContext *m, GetBitContext *gbp,
782
+                           unsigned int substr)
783
+{
784
+    SubStream *s = &m->substream[substr];
785
+    unsigned int i, ch, expected_stream_pos = 0;
786
+
787
+    if (s->data_check_present) {
788
+        expected_stream_pos  = get_bits_count(gbp);
789
+        expected_stream_pos += get_bits(gbp, 16);
790
+        av_log(m->avctx, AV_LOG_WARNING, "This file contains some features "
791
+               "we have not tested yet. %s\n", sample_message);
792
+    }
793
+
794
+    if (s->blockpos + s->blocksize > m->access_unit_size) {
795
+        av_log(m->avctx, AV_LOG_ERROR, "Too many audio samples in frame\n");
796
+        return -1;
797
+    }
798
+
799
+    memset(&m->bypassed_lsbs[s->blockpos][0], 0,
800
+           s->blocksize * sizeof(m->bypassed_lsbs[0]));
801
+
802
+    for (i = 0; i < s->blocksize; i++) {
803
+        if (read_huff_channels(m, gbp, substr, i) < 0)
804
+            return -1;
805
+    }
806
+
807
+    for (ch = s->min_channel; ch <= s->max_channel; ch++) {
808
+        filter_channel(m, substr, ch);
809
+    }
810
+
811
+    s->blockpos += s->blocksize;
812
+
813
+    if (s->data_check_present) {
814
+        if (get_bits_count(gbp) != expected_stream_pos)
815
+            av_log(m->avctx, AV_LOG_ERROR, "Block data length mismatch\n");
816
+        skip_bits(gbp, 8);
817
+    }
818
+
819
+    return 0;
820
+}
821
+
822
+/** Data table used for TrueHD noise generation function */
823
+
824
+static const int8_t noise_table[256] = {
825
+     30,  51,  22,  54,   3,   7,  -4,  38,  14,  55,  46,  81,  22,  58,  -3,   2,
826
+     52,  31,  -7,  51,  15,  44,  74,  30,  85, -17,  10,  33,  18,  80,  28,  62,
827
+     10,  32,  23,  69,  72,  26,  35,  17,  73,  60,   8,  56,   2,   6,  -2,  -5,
828
+     51,   4,  11,  50,  66,  76,  21,  44,  33,  47,   1,  26,  64,  48,  57,  40,
829
+     38,  16, -10, -28,  92,  22, -18,  29, -10,   5, -13,  49,  19,  24,  70,  34,
830
+     61,  48,  30,  14,  -6,  25,  58,  33,  42,  60,  67,  17,  54,  17,  22,  30,
831
+     67,  44,  -9,  50, -11,  43,  40,  32,  59,  82,  13,  49, -14,  55,  60,  36,
832
+     48,  49,  31,  47,  15,  12,   4,  65,   1,  23,  29,  39,  45,  -2,  84,  69,
833
+      0,  72,  37,  57,  27,  41, -15, -16,  35,  31,  14,  61,  24,   0,  27,  24,
834
+     16,  41,  55,  34,  53,   9,  56,  12,  25,  29,  53,   5,  20, -20,  -8,  20,
835
+     13,  28,  -3,  78,  38,  16,  11,  62,  46,  29,  21,  24,  46,  65,  43, -23,
836
+     89,  18,  74,  21,  38, -12,  19,  12, -19,   8,  15,  33,   4,  57,   9,  -8,
837
+     36,  35,  26,  28,   7,  83,  63,  79,  75,  11,   3,  87,  37,  47,  34,  40,
838
+     39,  19,  20,  42,  27,  34,  39,  77,  13,  42,  59,  64,  45,  -1,  32,  37,
839
+     45,  -5,  53,  -6,   7,  36,  50,  23,   6,  32,   9, -21,  18,  71,  27,  52,
840
+    -25,  31,  35,  42,  -1,  68,  63,  52,  26,  43,  66,  37,  41,  25,  40,  70,
841
+};
842
+
843
+/** Noise generation functions.
844
+ *  I'm not sure what these are for - they seem to be some kind of pseudorandom
845
+ *  sequence generators, used to generate noise data which is used when the
846
+ *  channels are rematrixed. I'm not sure if they provide a practical benefit
847
+ *  to compression, or just obfuscate the decoder. Are they for some kind of
848
+ *  dithering? */
849
+
850
+/** Generate two channels of noise, used in the matrix when
851
+ *  restart sync word == 0x31ea. */
852
+
853
+static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr)
854
+{
855
+    SubStream *s = &m->substream[substr];
856
+    unsigned int i;
857
+    uint32_t seed = s->noisegen_seed;
858
+    unsigned int maxchan = s->max_matrix_channel;
859
+
860
+    for (i = 0; i < s->blockpos; i++) {
861
+        uint16_t seed_shr7 = seed >> 7;
862
+        m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift;
863
+        m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7)   << s->noise_shift;
864
+
865
+        seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);
866
+    }
867
+
868
+    s->noisegen_seed = seed;
869
+}
870
+
871
+/** Generate a block of noise, used when restart sync word == 0x31eb. */
872
+
873
+static void fill_noise_buffer(MLPDecodeContext *m, unsigned int substr)
874
+{
875
+    SubStream *s = &m->substream[substr];
876
+    unsigned int i;
877
+    uint32_t seed = s->noisegen_seed;
878
+
879
+    for (i = 0; i < m->access_unit_size_pow2; i++) {
880
+        uint8_t seed_shr15 = seed >> 15;
881
+        m->noise_buffer[i] = noise_table[seed_shr15];
882
+        seed = (seed << 8) ^ seed_shr15 ^ (seed_shr15 << 5);
883
+    }
884
+
885
+    s->noisegen_seed = seed;
886
+}
887
+
888
+
889
+/** Apply the channel matrices in turn to reconstruct the original audio
890
+ *  samples. */
891
+
892
+static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
893
+{
894
+    SubStream *s = &m->substream[substr];
895
+    unsigned int mat, src_ch, i;
896
+    unsigned int maxchan;
897
+
898
+    maxchan = s->max_matrix_channel;
899
+    if (!s->noise_type) {
900
+        generate_2_noise_channels(m, substr);
901
+        maxchan += 2;
902
+    } else {
903
+        fill_noise_buffer(m, substr);
904
+    }
905
+
906
+    for (mat = 0; mat < s->num_primitive_matrices; mat++) {
907
+        int matrix_noise_shift = s->matrix_noise_shift[mat];
908
+        unsigned int dest_ch = s->matrix_out_ch[mat];
909
+        int32_t mask = MSB_MASK(s->quant_step_size[dest_ch]);
910
+
911
+        /* TODO: DSPContext? */
912
+
913
+        for (i = 0; i < s->blockpos; i++) {
914
+            int64_t accum = 0;
915
+            for (src_ch = 0; src_ch <= maxchan; src_ch++) {
916
+                accum += (int64_t)m->sample_buffer[i][src_ch]
917
+                                  * s->matrix_coeff[mat][src_ch];
918
+            }
919
+            if (matrix_noise_shift) {
920
+                uint32_t index = s->num_primitive_matrices - mat;
921
+                index = (i * (index * 2 + 1) + index) & (m->access_unit_size_pow2 - 1);
922
+                accum += m->noise_buffer[index] << (matrix_noise_shift + 7);
923
+            }
924
+            m->sample_buffer[i][dest_ch] = ((accum >> 14) & mask)
925
+                                             + m->bypassed_lsbs[i][mat];
926
+        }
927
+    }
928
+}
929
+
930
+/** Write the audio data into the output buffer. */
931
+
932
+static int output_data_internal(MLPDecodeContext *m, unsigned int substr,
933
+                                uint8_t *data, unsigned int *data_size, int is32)
934
+{
935
+    SubStream *s = &m->substream[substr];
936
+    unsigned int i, ch = 0;
937
+    int32_t *data_32 = (int32_t*) data;
938
+    int16_t *data_16 = (int16_t*) data;
939
+
940
+    if (*data_size < (s->max_channel + 1) * s->blockpos * (is32 ? 4 : 2))
941
+        return -1;
942
+
943
+    for (i = 0; i < s->blockpos; i++) {
944
+        for (ch = 0; ch <= s->max_channel; ch++) {
945
+            int32_t sample = m->sample_buffer[i][ch] << s->output_shift[ch];
946
+            s->lossless_check_data ^= (sample & 0xffffff) << ch;
947
+            if (is32) *data_32++ = sample << 8;
948
+            else      *data_16++ = sample >> 8;
949
+        }
950
+    }
951
+
952
+    *data_size = i * ch * (is32 ? 4 : 2);
953
+
954
+    return 0;
955
+}
956
+
957
+static int output_data(MLPDecodeContext *m, unsigned int substr,
958
+                       uint8_t *data, unsigned int *data_size)
959
+{
960
+    if (m->avctx->sample_fmt == SAMPLE_FMT_S32)
961
+        return output_data_internal(m, substr, data, data_size, 1);
962
+    else
963
+        return output_data_internal(m, substr, data, data_size, 0);
964
+}
965
+
966
+
967
+/** XOR together all the bytes of a buffer.
968
+ *  Does this belong in dspcontext? */
969
+
970
+static uint8_t calculate_parity(const uint8_t *buf, unsigned int buf_size)
971
+{
972
+    uint32_t scratch = 0;
973
+    const uint8_t *buf_end = buf + buf_size;
974
+
975
+    for (; buf < buf_end - 3; buf += 4)
976
+        scratch ^= *((const uint32_t*)buf);
977
+
978
+    scratch ^= scratch >> 16;
979
+    scratch ^= scratch >> 8;
980
+
981
+    for (; buf < buf_end; buf++)
982
+        scratch ^= *buf;
983
+
984
+    return scratch;
985
+}
986
+
987
+/** Read an access unit from the stream.
988
+ *  Returns < 0 on error, 0 if not enough data is present in the input stream
989
+ *  otherwise returns the number of bytes consumed. */
990
+
991
+static int read_access_unit(AVCodecContext *avctx, void* data, int *data_size,
992
+                            const uint8_t *buf, int buf_size)
993
+{
994
+    MLPDecodeContext *m = avctx->priv_data;
995
+    GetBitContext gb;
996
+    unsigned int length, substr;
997
+    unsigned int substream_start;
998
+    unsigned int header_size = 4;
999
+    unsigned int substr_header_size = 0;
1000
+    uint8_t substream_parity_present[MAX_SUBSTREAMS];
1001
+    uint16_t substream_data_len[MAX_SUBSTREAMS];
1002
+    uint8_t parity_bits;
1003
+
1004
+    if (buf_size < 4)
1005
+        return 0;
1006
+
1007
+    length = (AV_RB16(buf) & 0xfff) * 2;
1008
+
1009
+    if (length > buf_size)
1010
+        return -1;
1011
+
1012
+    init_get_bits(&gb, (buf + 4), (length - 4) * 8);
1013
+
1014
+    if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {
1015
+        dprintf(m->avctx, "Found major sync\n");
1016
+        if (read_major_sync(m, &gb) < 0)
1017
+            goto error;
1018
+        header_size += 28;
1019
+    }
1020
+
1021
+    if (!m->params_valid) {
1022
+        av_log(m->avctx, AV_LOG_WARNING,
1023
+               "Stream parameters not seen; skipping frame\n");
1024
+        *data_size = 0;
1025
+        return length;
1026
+    }
1027
+
1028
+    substream_start = 0;
1029
+
1030
+    for (substr = 0; substr < m->num_substreams; substr++) {
1031
+        int extraword_present, checkdata_present, end;
1032
+
1033
+        extraword_present = get_bits1(&gb);
1034
+        skip_bits1(&gb);
1035
+        checkdata_present = get_bits1(&gb);
1036
+        skip_bits1(&gb);
1037
+
1038
+        end = get_bits(&gb, 12) * 2;
1039
+
1040
+        substr_header_size += 2;
1041
+
1042
+        if (extraword_present) {
1043
+            skip_bits(&gb, 16);
1044
+            substr_header_size += 2;
1045
+        }
1046
+
1047
+        if (end + header_size + substr_header_size > length) {
1048
+            av_log(m->avctx, AV_LOG_ERROR,
1049
+                   "Indicated length of substream %d data goes off end of "
1050
+                   "packet.\n", substr);
1051
+            end = length - header_size - substr_header_size;
1052
+        }
1053
+
1054
+        if (end < substream_start) {
1055
+            av_log(avctx, AV_LOG_ERROR,
1056
+                   "Indicated end offset of substream %d data "
1057
+                   "is smaller than calculated start offset.\n",
1058
+                   substr);
1059
+            goto error;
1060
+        }
1061
+
1062
+        if (substr > m->max_decoded_substream)
1063
+            continue;
1064
+
1065
+        substream_parity_present[substr] = checkdata_present;
1066
+        substream_data_len[substr] = end - substream_start;
1067
+        substream_start = end;
1068
+    }
1069
+
1070
+    parity_bits  = calculate_parity(buf, 4);
1071
+    parity_bits ^= calculate_parity(buf + header_size, substr_header_size);
1072
+
1073
+    if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {
1074
+        av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");
1075
+        goto error;
1076
+    }
1077
+
1078
+    buf += header_size + substr_header_size;
1079
+
1080
+    for (substr = 0; substr <= m->max_decoded_substream; substr++) {
1081
+        SubStream *s = &m->substream[substr];
1082
+        init_get_bits(&gb, buf, substream_data_len[substr] * 8);
1083
+
1084
+        s->blockpos = 0;
1085
+        do {
1086
+            if (get_bits1(&gb)) {
1087
+                if (get_bits1(&gb)) {
1088
+                    /* A restart header should be present */
1089
+                    if (read_restart_header(m, &gb, buf, substr) < 0)
1090
+                        goto next_substr;
1091
+                    s->restart_seen = 1;
1092
+                }
1093
+
1094
+                if (!s->restart_seen) {
1095
+                    av_log(m->avctx, AV_LOG_ERROR,
1096
+                           "No restart header present in substream %d.\n",
1097
+                           substr);
1098
+                    goto next_substr;
1099
+                }
1100
+
1101
+                if (read_decoding_params(m, &gb, substr) < 0)
1102
+                    goto next_substr;
1103
+            }
1104
+
1105
+            if (!s->restart_seen) {
1106
+                av_log(m->avctx, AV_LOG_ERROR,
1107
+                       "No restart header present in substream %d.\n",
1108
+                       substr);
1109
+                goto next_substr;
1110
+            }
1111
+
1112
+            if (read_block_data(m, &gb, substr) < 0)
1113
+                return -1;
1114
+
1115
+        } while ((get_bits_count(&gb) < substream_data_len[substr] * 8)
1116
+                 && get_bits1(&gb) == 0);
1117
+
1118
+        skip_bits(&gb, (-get_bits_count(&gb)) & 15);
1119
+        if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 48 &&
1120
+            (show_bits_long(&gb, 32) == 0xd234d234 ||
1121
+             show_bits_long(&gb, 20) == 0xd234e)) {
1122
+            skip_bits(&gb, 18);
1123
+            if (substr == m->max_decoded_substream)
1124
+                av_log(m->avctx, AV_LOG_INFO, "End of stream indicated\n");
1125
+
1126
+            if (get_bits1(&gb)) {
1127
+                int shorten_by = get_bits(&gb, 13);
1128
+                shorten_by = FFMIN(shorten_by, s->blockpos);
1129
+                s->blockpos -= shorten_by;
1130
+            } else
1131
+                skip_bits(&gb, 13);
1132
+        }
1133
+        if (substream_parity_present[substr]) {
1134
+            uint8_t parity, checksum;
1135
+
1136
+            parity = calculate_parity(buf, substream_data_len[substr] - 2);
1137
+            if ((parity ^ get_bits(&gb, 8)) != 0xa9)
1138
+                av_log(m->avctx, AV_LOG_ERROR,
1139
+                       "Substream %d parity check failed\n", substr);
1140
+
1141
+            checksum = mlp_checksum8(buf, substream_data_len[substr] - 2);
1142
+            if (checksum != get_bits(&gb, 8))
1143
+                av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed\n",
1144
+                       substr);
1145
+        }
1146
+        if (substream_data_len[substr] * 8 != get_bits_count(&gb)) {
1147
+            av_log(m->avctx, AV_LOG_ERROR, "Substream %d length mismatch.\n",
1148
+                   substr);
1149
+            return -1;
1150
+        }
1151
+
1152
+next_substr:
1153
+        buf += substream_data_len[substr];
1154
+    }
1155
+
1156
+    rematrix_channels(m, m->max_decoded_substream);
1157
+
1158
+    if (output_data(m, m->max_decoded_substream, data, data_size) < 0)
1159
+        return -1;
1160
+
1161
+    return length;
1162
+
1163
+error:
1164
+    m->params_valid = 0;
1165
+    return -1;
1166
+}
1167
+
1168
+AVCodec mlp_decoder = {
1169
+    "mlp",
1170
+    CODEC_TYPE_AUDIO,
1171
+    CODEC_ID_MLP,
1172
+    sizeof(MLPDecodeContext),
1173
+    mlp_decode_init,
1174
+    NULL,
1175
+    NULL,
1176
+    read_access_unit,
1177
+    .long_name = NULL_IF_CONFIG_SMALL("Meridian Lossless Packing"),
1178
+};
1179
+