Browse code

Windows Media Audio Lossless decoder

Decodes 16-bit WMA Lossless encoded files. 24-bit is not supported yet.

Bitstream parser written by Andreas Öman with contributions from
Baptiste Coudurier and Ulion.

Includes a number of bug-fixes from Benjamin Larsson, Michael Niedermayer and
Konstantin Shishkov, shine and polish by Diego Biurrun.

Signed-off-by: Diego Biurrun <diego@biurrun.de>

Mashiat Sarker Shakkhar authored on 2012/03/01 21:43:00
Showing 6 changed files
... ...
@@ -11,6 +11,7 @@ version <next>:
11 11
 - Sun Rasterfile Encoder
12 12
 - remove libpostproc
13 13
 - ID3v2 attached pictures reading and writing
14
+- WMA Lossless decoder
14 15
 
15 16
 
16 17
 version 0.8:
... ...
@@ -768,6 +768,7 @@ following image formats are supported:
768 768
 @item Westwood Audio (SND1)  @tab     @tab  X
769 769
 @item Windows Media Audio 1  @tab  X  @tab  X
770 770
 @item Windows Media Audio 2  @tab  X  @tab  X
771
+@item Windows Media Audio Lossless @tab  @tab  X
771 772
 @item Windows Media Audio Pro @tab    @tab  X
772 773
 @item Windows Media Audio Voice @tab  @tab  X
773 774
 @end multitable
... ...
@@ -418,6 +418,7 @@ OBJS-$(CONFIG_VP6_DECODER)             += vp6.o vp56.o vp56data.o vp56dsp.o \
418 418
 OBJS-$(CONFIG_VP8_DECODER)             += vp8.o vp8dsp.o vp56rac.o
419 419
 OBJS-$(CONFIG_VQA_DECODER)             += vqavideo.o
420 420
 OBJS-$(CONFIG_WAVPACK_DECODER)         += wavpack.o
421
+OBJS-$(CONFIG_WMALOSSLESS_DECODER)     += wmalosslessdec.o wma.o
421 422
 OBJS-$(CONFIG_WMAPRO_DECODER)          += wmaprodec.o wma.o
422 423
 OBJS-$(CONFIG_WMAV1_DECODER)           += wmadec.o wma.o aactab.o
423 424
 OBJS-$(CONFIG_WMAV1_ENCODER)           += wmaenc.o wma.o aactab.o
... ...
@@ -289,6 +289,7 @@ void avcodec_register_all(void)
289 289
     REGISTER_DECODER (VMDAUDIO, vmdaudio);
290 290
     REGISTER_ENCDEC  (VORBIS, vorbis);
291 291
     REGISTER_DECODER (WAVPACK, wavpack);
292
+    REGISTER_DECODER (WMALOSSLESS, wmalossless);
292 293
     REGISTER_DECODER (WMAPRO, wmapro);
293 294
     REGISTER_ENCDEC  (WMAV1, wmav1);
294 295
     REGISTER_ENCDEC  (WMAV2, wmav2);
... ...
@@ -21,7 +21,7 @@
21 21
 #define AVCODEC_VERSION_H
22 22
 
23 23
 #define LIBAVCODEC_VERSION_MAJOR 54
24
-#define LIBAVCODEC_VERSION_MINOR  4
24
+#define LIBAVCODEC_VERSION_MINOR  5
25 25
 #define LIBAVCODEC_VERSION_MICRO  0
26 26
 
27 27
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
28 28
new file mode 100644
... ...
@@ -0,0 +1,1248 @@
0
+/*
1
+ * Windows Media Audio Lossless decoder
2
+ * Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion
3
+ * Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson
4
+ * Copyright (c) 2011 Andreas Öman
5
+ * Copyright (c) 2011 - 2012 Mashiat Sarker Shakkhar
6
+ *
7
+ * This file is part of Libav.
8
+ *
9
+ * Libav is free software; you can redistribute it and/or
10
+ * modify it under the terms of the GNU Lesser General Public
11
+ * License as published by the Free Software Foundation; either
12
+ * version 2.1 of the License, or (at your option) any later version.
13
+ *
14
+ * Libav is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
+ * Lesser General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU Lesser General Public
20
+ * License along with Libav; if not, write to the Free Software
21
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22
+ */
23
+
24
+#include "avcodec.h"
25
+#include "internal.h"
26
+#include "get_bits.h"
27
+#include "put_bits.h"
28
+#include "wma.h"
29
+
30
+/** current decoder limitations */
31
+#define WMALL_MAX_CHANNELS      8                       ///< max number of handled channels
32
+#define MAX_SUBFRAMES          32                       ///< max number of subframes per channel
33
+#define MAX_BANDS              29                       ///< max number of scale factor bands
34
+#define MAX_FRAMESIZE       32768                       ///< maximum compressed frame size
35
+
36
+#define WMALL_BLOCK_MIN_BITS    6                       ///< log2 of min block size
37
+#define WMALL_BLOCK_MAX_BITS   12                       ///< log2 of max block size
38
+#define WMALL_BLOCK_MAX_SIZE (1 << WMALL_BLOCK_MAX_BITS)    ///< maximum block size
39
+#define WMALL_BLOCK_SIZES    (WMALL_BLOCK_MAX_BITS - WMALL_BLOCK_MIN_BITS + 1) ///< possible block sizes
40
+
41
+
42
+/**
43
+ * @brief frame-specific decoder context for a single channel
44
+ */
45
+typedef struct {
46
+    int16_t     prev_block_len;                         ///< length of the previous block
47
+    uint8_t     transmit_coefs;
48
+    uint8_t     num_subframes;
49
+    uint16_t    subframe_len[MAX_SUBFRAMES];            ///< subframe length in samples
50
+    uint16_t    subframe_offsets[MAX_SUBFRAMES];        ///< subframe positions in the current frame
51
+    uint8_t     cur_subframe;                           ///< current subframe number
52
+    uint16_t    decoded_samples;                        ///< number of already processed samples
53
+    int         quant_step;                             ///< quantization step for the current subframe
54
+    int         transient_counter;                      ///< number of transient samples from the beginning of the transient zone
55
+} WmallChannelCtx;
56
+
57
+/**
58
+ * @brief main decoder context
59
+ */
60
+typedef struct WmallDecodeCtx {
61
+    /* generic decoder variables */
62
+    AVCodecContext  *avctx;
63
+    AVFrame         frame;
64
+    uint8_t         frame_data[MAX_FRAMESIZE + FF_INPUT_BUFFER_PADDING_SIZE];  ///< compressed frame data
65
+    PutBitContext   pb;                             ///< context for filling the frame_data buffer
66
+
67
+    /* frame size dependent frame information (set during initialization) */
68
+    uint32_t        decode_flags;                   ///< used compression features
69
+    int             len_prefix;                     ///< frame is prefixed with its length
70
+    int             dynamic_range_compression;      ///< frame contains DRC data
71
+    uint8_t         bits_per_sample;                ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
72
+    uint16_t        samples_per_frame;              ///< number of samples to output
73
+    uint16_t        log2_frame_size;
74
+    int8_t          num_channels;                   ///< number of channels in the stream (same as AVCodecContext.num_channels)
75
+    int8_t          lfe_channel;                    ///< lfe channel index
76
+    uint8_t         max_num_subframes;
77
+    uint8_t         subframe_len_bits;              ///< number of bits used for the subframe length
78
+    uint8_t         max_subframe_len_bit;           ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
79
+    uint16_t        min_samples_per_subframe;
80
+
81
+    /* packet decode state */
82
+    GetBitContext   pgb;                            ///< bitstream reader context for the packet
83
+    int             next_packet_start;              ///< start offset of the next WMA packet in the demuxer packet
84
+    uint8_t         packet_offset;                  ///< offset to the frame in the packet
85
+    uint8_t         packet_sequence_number;         ///< current packet number
86
+    int             num_saved_bits;                 ///< saved number of bits
87
+    int             frame_offset;                   ///< frame offset in the bit reservoir
88
+    int             subframe_offset;                ///< subframe offset in the bit reservoir
89
+    uint8_t         packet_loss;                    ///< set in case of bitstream error
90
+    uint8_t         packet_done;                    ///< set when a packet is fully decoded
91
+
92
+    /* frame decode state */
93
+    uint32_t        frame_num;                      ///< current frame number (not used for decoding)
94
+    GetBitContext   gb;                             ///< bitstream reader context
95
+    int             buf_bit_size;                   ///< buffer size in bits
96
+    int16_t         *samples_16;                    ///< current samplebuffer pointer (16-bit)
97
+    int16_t         *samples_16_end;                ///< maximum samplebuffer pointer
98
+    int             *samples_32;                    ///< current samplebuffer pointer (24-bit)
99
+    int             *samples_32_end;                ///< maximum samplebuffer pointer
100
+    uint8_t         drc_gain;                       ///< gain for the DRC tool
101
+    int8_t          skip_frame;                     ///< skip output step
102
+    int8_t          parsed_all_subframes;           ///< all subframes decoded?
103
+
104
+    /* subframe/block decode state */
105
+    int16_t         subframe_len;                   ///< current subframe length
106
+    int8_t          channels_for_cur_subframe;      ///< number of channels that contain the subframe
107
+    int8_t          channel_indexes_for_cur_subframe[WMALL_MAX_CHANNELS];
108
+
109
+    WmallChannelCtx channel[WMALL_MAX_CHANNELS];    ///< per channel data
110
+
111
+    // WMA Lossless-specific
112
+
113
+    uint8_t do_arith_coding;
114
+    uint8_t do_ac_filter;
115
+    uint8_t do_inter_ch_decorr;
116
+    uint8_t do_mclms;
117
+    uint8_t do_lpc;
118
+
119
+    int8_t  acfilter_order;
120
+    int8_t  acfilter_scaling;
121
+    int64_t acfilter_coeffs[16];
122
+    int     acfilter_prevvalues[2][16];
123
+
124
+    int8_t  mclms_order;
125
+    int8_t  mclms_scaling;
126
+    int16_t mclms_coeffs[128];
127
+    int16_t mclms_coeffs_cur[4];
128
+    int16_t mclms_prevvalues[64];
129
+    int16_t mclms_updates[64];
130
+    int     mclms_recent;
131
+
132
+    int     movave_scaling;
133
+    int     quant_stepsize;
134
+
135
+    struct {
136
+        int order;
137
+        int scaling;
138
+        int coefsend;
139
+        int bitsend;
140
+        int16_t coefs[256];
141
+        int16_t lms_prevvalues[512];
142
+        int16_t lms_updates[512];
143
+        int recent;
144
+    } cdlms[2][9];
145
+
146
+    int cdlms_ttl[2];
147
+
148
+    int bV3RTM;
149
+
150
+    int is_channel_coded[2];
151
+    int update_speed[2];
152
+
153
+    int transient[2];
154
+    int transient_pos[2];
155
+    int seekable_tile;
156
+
157
+    int ave_sum[2];
158
+
159
+    int channel_residues[2][2048];
160
+
161
+    int lpc_coefs[2][40];
162
+    int lpc_order;
163
+    int lpc_scaling;
164
+    int lpc_intbits;
165
+
166
+    int channel_coeffs[2][2048];
167
+} WmallDecodeCtx;
168
+
169
+
170
+static av_cold int decode_init(AVCodecContext *avctx)
171
+{
172
+    WmallDecodeCtx *s  = avctx->priv_data;
173
+    uint8_t *edata_ptr = avctx->extradata;
174
+    unsigned int channel_mask;
175
+    int i, log2_max_num_subframes, num_possible_block_sizes;
176
+
177
+    s->avctx = avctx;
178
+    init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
179
+
180
+    if (avctx->extradata_size >= 18) {
181
+        s->decode_flags    = AV_RL16(edata_ptr + 14);
182
+        channel_mask       = AV_RL32(edata_ptr +  2);
183
+        s->bits_per_sample = AV_RL16(edata_ptr);
184
+        if (s->bits_per_sample == 16)
185
+            avctx->sample_fmt = AV_SAMPLE_FMT_S16;
186
+        else if (s->bits_per_sample == 24) {
187
+            avctx->sample_fmt = AV_SAMPLE_FMT_S32;
188
+            av_log_missing_feature(avctx, "bit-depth higher than 16", 0);
189
+            return AVERROR_PATCHWELCOME;
190
+        } else {
191
+            av_log(avctx, AV_LOG_ERROR, "Unknown bit-depth: %d\n",
192
+                   s->bits_per_sample);
193
+            return AVERROR_INVALIDDATA;
194
+        }
195
+        /* dump the extradata */
196
+        for (i = 0; i < avctx->extradata_size; i++)
197
+            av_dlog(avctx, AV_LOG_DEBUG, "[%x] ", avctx->extradata[i]);
198
+        av_dlog(avctx, AV_LOG_DEBUG, "\n");
199
+
200
+    } else {
201
+        av_log_ask_for_sample(avctx, "Unsupported extradata size\n");
202
+        return AVERROR_INVALIDDATA;
203
+    }
204
+
205
+    /* generic init */
206
+    s->log2_frame_size = av_log2(avctx->block_align) + 4;
207
+
208
+    /* frame info */
209
+    s->skip_frame  = 1; /* skip first frame */
210
+    s->packet_loss = 1;
211
+    s->len_prefix  = s->decode_flags & 0x40;
212
+
213
+    /* get frame len */
214
+    s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
215
+                                                          3, s->decode_flags);
216
+
217
+    /* init previous block len */
218
+    for (i = 0; i < avctx->channels; i++)
219
+        s->channel[i].prev_block_len = s->samples_per_frame;
220
+
221
+    /* subframe info */
222
+    log2_max_num_subframes  = (s->decode_flags & 0x38) >> 3;
223
+    s->max_num_subframes    = 1 << log2_max_num_subframes;
224
+    s->max_subframe_len_bit = 0;
225
+    s->subframe_len_bits    = av_log2(log2_max_num_subframes) + 1;
226
+
227
+    num_possible_block_sizes     = log2_max_num_subframes + 1;
228
+    s->min_samples_per_subframe  = s->samples_per_frame / s->max_num_subframes;
229
+    s->dynamic_range_compression = s->decode_flags & 0x80;
230
+    s->bV3RTM                    = s->decode_flags & 0x100;
231
+
232
+    if (s->max_num_subframes > MAX_SUBFRAMES) {
233
+        av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %i\n",
234
+               s->max_num_subframes);
235
+        return AVERROR_INVALIDDATA;
236
+    }
237
+
238
+    s->num_channels = avctx->channels;
239
+
240
+    /* extract lfe channel position */
241
+    s->lfe_channel = -1;
242
+
243
+    if (channel_mask & 8) {
244
+        unsigned int mask;
245
+        for (mask = 1; mask < 16; mask <<= 1)
246
+            if (channel_mask & mask)
247
+                ++s->lfe_channel;
248
+    }
249
+
250
+    if (s->num_channels < 0) {
251
+        av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n",
252
+               s->num_channels);
253
+        return AVERROR_INVALIDDATA;
254
+    } else if (s->num_channels > WMALL_MAX_CHANNELS) {
255
+        av_log_ask_for_sample(avctx, "unsupported number of channels\n");
256
+        return AVERROR_PATCHWELCOME;
257
+    }
258
+
259
+    avcodec_get_frame_defaults(&s->frame);
260
+    avctx->coded_frame    = &s->frame;
261
+    avctx->channel_layout = channel_mask;
262
+    return 0;
263
+}
264
+
265
+/**
266
+ * @brief Decode the subframe length.
267
+ * @param s      context
268
+ * @param offset sample offset in the frame
269
+ * @return decoded subframe length on success, < 0 in case of an error
270
+ */
271
+static int decode_subframe_length(WmallDecodeCtx *s, int offset)
272
+{
273
+    int frame_len_ratio, subframe_len, len;
274
+
275
+    /* no need to read from the bitstream when only one length is possible */
276
+    if (offset == s->samples_per_frame - s->min_samples_per_subframe)
277
+        return s->min_samples_per_subframe;
278
+
279
+    len             = av_log2(s->max_num_subframes - 1) + 1;
280
+    frame_len_ratio = get_bits(&s->gb, len);
281
+    subframe_len    = s->min_samples_per_subframe * (frame_len_ratio + 1);
282
+
283
+    /* sanity check the length */
284
+    if (subframe_len < s->min_samples_per_subframe ||
285
+        subframe_len > s->samples_per_frame) {
286
+        av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
287
+               subframe_len);
288
+        return AVERROR_INVALIDDATA;
289
+    }
290
+    return subframe_len;
291
+}
292
+
293
+/**
294
+ * @brief Decode how the data in the frame is split into subframes.
295
+ *       Every WMA frame contains the encoded data for a fixed number of
296
+ *       samples per channel. The data for every channel might be split
297
+ *       into several subframes. This function will reconstruct the list of
298
+ *       subframes for every channel.
299
+ *
300
+ *       If the subframes are not evenly split, the algorithm estimates the
301
+ *       channels with the lowest number of total samples.
302
+ *       Afterwards, for each of these channels a bit is read from the
303
+ *       bitstream that indicates if the channel contains a subframe with the
304
+ *       next subframe size that is going to be read from the bitstream or not.
305
+ *       If a channel contains such a subframe, the subframe size gets added to
306
+ *       the channel's subframe list.
307
+ *       The algorithm repeats these steps until the frame is properly divided
308
+ *       between the individual channels.
309
+ *
310
+ * @param s context
311
+ * @return 0 on success, < 0 in case of an error
312
+ */
313
+static int decode_tilehdr(WmallDecodeCtx *s)
314
+{
315
+    uint16_t num_samples[WMALL_MAX_CHANNELS] = { 0 }; /* sum of samples for all currently known subframes of a channel */
316
+    uint8_t  contains_subframe[WMALL_MAX_CHANNELS];   /* flag indicating if a channel contains the current subframe */
317
+    int channels_for_cur_subframe = s->num_channels;  /* number of channels that contain the current subframe */
318
+    int fixed_channel_layout = 0;                     /* flag indicating that all channels use the same subfra2me offsets and sizes */
319
+    int min_channel_len = 0;                          /* smallest sum of samples (channels with this length will be processed first) */
320
+    int c, tile_aligned;
321
+
322
+    /* reset tiling information */
323
+    for (c = 0; c < s->num_channels; c++)
324
+        s->channel[c].num_subframes = 0;
325
+
326
+    tile_aligned = get_bits1(&s->gb);
327
+    if (s->max_num_subframes == 1 || tile_aligned)
328
+        fixed_channel_layout = 1;
329
+
330
+    /* loop until the frame data is split between the subframes */
331
+    do {
332
+        int subframe_len;
333
+
334
+        /* check which channels contain the subframe */
335
+        for (c = 0; c < s->num_channels; c++) {
336
+            if (num_samples[c] == min_channel_len) {
337
+                if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
338
+                   (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe)) {
339
+                    contains_subframe[c] = 1;
340
+                } else {
341
+                    contains_subframe[c] = get_bits1(&s->gb);
342
+                }
343
+            } else
344
+                contains_subframe[c] = 0;
345
+        }
346
+
347
+        /* get subframe length, subframe_len == 0 is not allowed */
348
+        if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
349
+            return AVERROR_INVALIDDATA;
350
+        /* add subframes to the individual channels and find new min_channel_len */
351
+        min_channel_len += subframe_len;
352
+        for (c = 0; c < s->num_channels; c++) {
353
+            WmallChannelCtx *chan = &s->channel[c];
354
+
355
+            if (contains_subframe[c]) {
356
+                if (chan->num_subframes >= MAX_SUBFRAMES) {
357
+                    av_log(s->avctx, AV_LOG_ERROR,
358
+                           "broken frame: num subframes > 31\n");
359
+                    return AVERROR_INVALIDDATA;
360
+                }
361
+                chan->subframe_len[chan->num_subframes] = subframe_len;
362
+                num_samples[c] += subframe_len;
363
+                ++chan->num_subframes;
364
+                if (num_samples[c] > s->samples_per_frame) {
365
+                    av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
366
+                           "channel len(%d) > samples_per_frame(%d)\n",
367
+                           num_samples[c], s->samples_per_frame);
368
+                    return AVERROR_INVALIDDATA;
369
+                }
370
+            } else if (num_samples[c] <= min_channel_len) {
371
+                if (num_samples[c] < min_channel_len) {
372
+                    channels_for_cur_subframe = 0;
373
+                    min_channel_len = num_samples[c];
374
+                }
375
+                ++channels_for_cur_subframe;
376
+            }
377
+        }
378
+    } while (min_channel_len < s->samples_per_frame);
379
+
380
+    for (c = 0; c < s->num_channels; c++) {
381
+        int i, offset = 0;
382
+        for (i = 0; i < s->channel[c].num_subframes; i++) {
383
+            s->channel[c].subframe_offsets[i] = offset;
384
+            offset += s->channel[c].subframe_len[i];
385
+        }
386
+    }
387
+
388
+    return 0;
389
+}
390
+
391
+static void decode_ac_filter(WmallDecodeCtx *s)
392
+{
393
+    int i;
394
+    s->acfilter_order   = get_bits(&s->gb, 4) + 1;
395
+    s->acfilter_scaling = get_bits(&s->gb, 4);
396
+
397
+    for (i = 0; i < s->acfilter_order; i++)
398
+        s->acfilter_coeffs[i] = get_bits(&s->gb, s->acfilter_scaling) + 1;
399
+}
400
+
401
+static void decode_mclms(WmallDecodeCtx *s)
402
+{
403
+    s->mclms_order   = (get_bits(&s->gb, 4) + 1) * 2;
404
+    s->mclms_scaling = get_bits(&s->gb, 4);
405
+    if (get_bits1(&s->gb)) {
406
+        int i, send_coef_bits;
407
+        int cbits = av_log2(s->mclms_scaling + 1);
408
+        assert(cbits == my_log2(s->mclms_scaling + 1));
409
+        if (1 << cbits < s->mclms_scaling + 1)
410
+            cbits++;
411
+
412
+        send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2;
413
+
414
+        for (i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++)
415
+            s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits);
416
+
417
+        for (i = 0; i < s->num_channels; i++) {
418
+            int c;
419
+            for (c = 0; c < i; c++)
420
+                s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits);
421
+        }
422
+    }
423
+}
424
+
425
+static void decode_cdlms(WmallDecodeCtx *s)
426
+{
427
+    int c, i;
428
+    int cdlms_send_coef = get_bits1(&s->gb);
429
+
430
+    for (c = 0; c < s->num_channels; c++) {
431
+        s->cdlms_ttl[c] = get_bits(&s->gb, 3) + 1;
432
+        for (i = 0; i < s->cdlms_ttl[c]; i++)
433
+            s->cdlms[c][i].order = (get_bits(&s->gb, 7) + 1) * 8;
434
+
435
+        for (i = 0; i < s->cdlms_ttl[c]; i++)
436
+            s->cdlms[c][i].scaling = get_bits(&s->gb, 4);
437
+
438
+        if (cdlms_send_coef) {
439
+            for (i = 0; i < s->cdlms_ttl[c]; i++) {
440
+                int cbits, shift_l, shift_r, j;
441
+                cbits = av_log2(s->cdlms[c][i].order);
442
+                if ((1 << cbits) < s->cdlms[c][i].order)
443
+                    cbits++;
444
+                s->cdlms[c][i].coefsend = get_bits(&s->gb, cbits) + 1;
445
+
446
+                cbits = av_log2(s->cdlms[c][i].scaling + 1);
447
+                if ((1 << cbits) < s->cdlms[c][i].scaling + 1)
448
+                    cbits++;
449
+
450
+                s->cdlms[c][i].bitsend = get_bits(&s->gb, cbits) + 2;
451
+                shift_l = 32 - s->cdlms[c][i].bitsend;
452
+                shift_r = 32 - s->cdlms[c][i].scaling - 2;
453
+                for (j = 0; j < s->cdlms[c][i].coefsend; j++)
454
+                    s->cdlms[c][i].coefs[j] =
455
+                        (get_bits(&s->gb, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;
456
+            }
457
+        }
458
+    }
459
+}
460
+
461
+static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
462
+{
463
+    int i = 0;
464
+    unsigned int ave_mean;
465
+    s->transient[ch] = get_bits1(&s->gb);
466
+    if (s->transient[ch]) {
467
+        s->transient_pos[ch] = get_bits(&s->gb, av_log2(tile_size));
468
+        if (s->transient_pos[ch])
469
+            s->transient[ch] = 0;
470
+        s->channel[ch].transient_counter =
471
+            FFMAX(s->channel[ch].transient_counter, s->samples_per_frame / 2);
472
+    } else if (s->channel[ch].transient_counter)
473
+        s->transient[ch] = 1;
474
+
475
+    if (s->seekable_tile) {
476
+        ave_mean = get_bits(&s->gb, s->bits_per_sample);
477
+        s->ave_sum[ch] = ave_mean << (s->movave_scaling + 1);
478
+    }
479
+
480
+    if (s->seekable_tile) {
481
+        if (s->do_inter_ch_decorr)
482
+            s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample + 1);
483
+        else
484
+            s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample);
485
+        i++;
486
+    }
487
+    for (; i < tile_size; i++) {
488
+        int quo = 0, rem, rem_bits, residue;
489
+        while(get_bits1(&s->gb)) {
490
+            quo++;
491
+            if (get_bits_left(&s->gb) <= 0)
492
+                return -1;
493
+        }
494
+        if (quo >= 32)
495
+            quo += get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1);
496
+
497
+        ave_mean = (s->ave_sum[ch] + (1 << s->movave_scaling)) >> (s->movave_scaling + 1);
498
+        if (ave_mean <= 1)
499
+            residue = quo;
500
+        else {
501
+            rem_bits = av_ceil_log2(ave_mean);
502
+            rem      = rem_bits ? get_bits(&s->gb, rem_bits) : 0;
503
+            residue  = (quo << rem_bits) + rem;
504
+        }
505
+
506
+        s->ave_sum[ch] = residue + s->ave_sum[ch] -
507
+                         (s->ave_sum[ch] >> s->movave_scaling);
508
+
509
+        if (residue & 1)
510
+            residue = -(residue >> 1) - 1;
511
+        else
512
+            residue = residue >> 1;
513
+        s->channel_residues[ch][i] = residue;
514
+    }
515
+
516
+    return 0;
517
+
518
+}
519
+
520
+static void decode_lpc(WmallDecodeCtx *s)
521
+{
522
+    int ch, i, cbits;
523
+    s->lpc_order   = get_bits(&s->gb, 5) + 1;
524
+    s->lpc_scaling = get_bits(&s->gb, 4);
525
+    s->lpc_intbits = get_bits(&s->gb, 3) + 1;
526
+    cbits = s->lpc_scaling + s->lpc_intbits;
527
+    for (ch = 0; ch < s->num_channels; ch++)
528
+        for (i = 0; i < s->lpc_order; i++)
529
+            s->lpc_coefs[ch][i] = get_sbits(&s->gb, cbits);
530
+}
531
+
532
+static void clear_codec_buffers(WmallDecodeCtx *s)
533
+{
534
+    int ich, ilms;
535
+
536
+    memset(s->acfilter_coeffs,     0, sizeof(s->acfilter_coeffs));
537
+    memset(s->acfilter_prevvalues, 0, sizeof(s->acfilter_prevvalues));
538
+    memset(s->lpc_coefs,           0, sizeof(s->lpc_coefs));
539
+
540
+    memset(s->mclms_coeffs,     0, sizeof(s->mclms_coeffs));
541
+    memset(s->mclms_coeffs_cur, 0, sizeof(s->mclms_coeffs_cur));
542
+    memset(s->mclms_prevvalues, 0, sizeof(s->mclms_prevvalues));
543
+    memset(s->mclms_updates,    0, sizeof(s->mclms_updates));
544
+
545
+    for (ich = 0; ich < s->num_channels; ich++) {
546
+        for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++) {
547
+            memset(s->cdlms[ich][ilms].coefs, 0,
548
+                   sizeof(s->cdlms[ich][ilms].coefs));
549
+            memset(s->cdlms[ich][ilms].lms_prevvalues, 0,
550
+                   sizeof(s->cdlms[ich][ilms].lms_prevvalues));
551
+            memset(s->cdlms[ich][ilms].lms_updates, 0,
552
+                   sizeof(s->cdlms[ich][ilms].lms_updates));
553
+        }
554
+        s->ave_sum[ich] = 0;
555
+    }
556
+}
557
+
558
+/**
559
+ * @brief Reset filter parameters and transient area at new seekable tile.
560
+ */
561
+static void reset_codec(WmallDecodeCtx *s)
562
+{
563
+    int ich, ilms;
564
+    s->mclms_recent = s->mclms_order * s->num_channels;
565
+    for (ich = 0; ich < s->num_channels; ich++) {
566
+        for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++)
567
+            s->cdlms[ich][ilms].recent = s->cdlms[ich][ilms].order;
568
+        /* first sample of a seekable subframe is considered as the starting of
569
+            a transient area which is samples_per_frame samples long */
570
+        s->channel[ich].transient_counter = s->samples_per_frame;
571
+        s->transient[ich]     = 1;
572
+        s->transient_pos[ich] = 0;
573
+    }
574
+}
575
+
576
+static void mclms_update(WmallDecodeCtx *s, int icoef, int *pred)
577
+{
578
+    int i, j, ich, pred_error;
579
+    int order        = s->mclms_order;
580
+    int num_channels = s->num_channels;
581
+    int range        = 1 << (s->bits_per_sample - 1);
582
+
583
+    for (ich = 0; ich < num_channels; ich++) {
584
+        pred_error = s->channel_residues[ich][icoef] - pred[ich];
585
+        if (pred_error > 0) {
586
+            for (i = 0; i < order * num_channels; i++)
587
+                s->mclms_coeffs[i + ich * order * num_channels] +=
588
+                    s->mclms_updates[s->mclms_recent + i];
589
+            for (j = 0; j < ich; j++) {
590
+                if (s->channel_residues[j][icoef] > 0)
591
+                    s->mclms_coeffs_cur[ich * num_channels + j] += 1;
592
+                else if (s->channel_residues[j][icoef] < 0)
593
+                    s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
594
+            }
595
+        } else if (pred_error < 0) {
596
+            for (i = 0; i < order * num_channels; i++)
597
+                s->mclms_coeffs[i + ich * order * num_channels] -=
598
+                    s->mclms_updates[s->mclms_recent + i];
599
+            for (j = 0; j < ich; j++) {
600
+                if (s->channel_residues[j][icoef] > 0)
601
+                    s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
602
+                else if (s->channel_residues[j][icoef] < 0)
603
+                    s->mclms_coeffs_cur[ich * num_channels + j] += 1;
604
+            }
605
+        }
606
+    }
607
+
608
+    for (ich = num_channels - 1; ich >= 0; ich--) {
609
+        s->mclms_recent--;
610
+        s->mclms_prevvalues[s->mclms_recent] = s->channel_residues[ich][icoef];
611
+        if (s->channel_residues[ich][icoef] > range - 1)
612
+            s->mclms_prevvalues[s->mclms_recent] = range - 1;
613
+        else if (s->channel_residues[ich][icoef] < -range)
614
+            s->mclms_prevvalues[s->mclms_recent] = -range;
615
+
616
+        s->mclms_updates[s->mclms_recent] = 0;
617
+        if (s->channel_residues[ich][icoef] > 0)
618
+            s->mclms_updates[s->mclms_recent] = 1;
619
+        else if (s->channel_residues[ich][icoef] < 0)
620
+            s->mclms_updates[s->mclms_recent] = -1;
621
+    }
622
+
623
+    if (s->mclms_recent == 0) {
624
+        memcpy(&s->mclms_prevvalues[order * num_channels],
625
+               s->mclms_prevvalues,
626
+               2 * order * num_channels);
627
+        memcpy(&s->mclms_updates[order * num_channels],
628
+               s->mclms_updates,
629
+               2 * order * num_channels);
630
+        s->mclms_recent = num_channels * order;
631
+    }
632
+}
633
+
634
+static void mclms_predict(WmallDecodeCtx *s, int icoef, int *pred)
635
+{
636
+    int ich, i;
637
+    int order        = s->mclms_order;
638
+    int num_channels = s->num_channels;
639
+
640
+    for (ich = 0; ich < num_channels; ich++) {
641
+        if (!s->is_channel_coded[ich])
642
+            continue;
643
+        pred[ich] = 0;
644
+        for (i = 0; i < order * num_channels; i++)
645
+            pred[ich] += s->mclms_prevvalues[i + s->mclms_recent] *
646
+                         s->mclms_coeffs[i + order * num_channels * ich];
647
+        for (i = 0; i < ich; i++)
648
+            pred[ich] += s->channel_residues[i][icoef] *
649
+                         s->mclms_coeffs_cur[i + num_channels * ich];
650
+        pred[ich] += 1 << s->mclms_scaling - 1;
651
+        pred[ich] >>= s->mclms_scaling;
652
+        s->channel_residues[ich][icoef] += pred[ich];
653
+    }
654
+}
655
+
656
+static void revert_mclms(WmallDecodeCtx *s, int tile_size)
657
+{
658
+    int icoef, pred[WMALL_MAX_CHANNELS] = { 0 };
659
+    for (icoef = 0; icoef < tile_size; icoef++) {
660
+        mclms_predict(s, icoef, pred);
661
+        mclms_update(s, icoef, pred);
662
+    }
663
+}
664
+
665
+static int lms_predict(WmallDecodeCtx *s, int ich, int ilms)
666
+{
667
+    int pred = 0, icoef;
668
+    int recent = s->cdlms[ich][ilms].recent;
669
+
670
+    for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
671
+        pred += s->cdlms[ich][ilms].coefs[icoef] *
672
+                s->cdlms[ich][ilms].lms_prevvalues[icoef + recent];
673
+
674
+    return pred;
675
+}
676
+
677
+static void lms_update(WmallDecodeCtx *s, int ich, int ilms,
678
+                       int input, int residue)
679
+{
680
+    int icoef;
681
+    int recent = s->cdlms[ich][ilms].recent;
682
+    int range  = 1 << s->bits_per_sample - 1;
683
+
684
+    if (residue < 0) {
685
+        for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
686
+            s->cdlms[ich][ilms].coefs[icoef] -=
687
+                s->cdlms[ich][ilms].lms_updates[icoef + recent];
688
+    } else if (residue > 0) {
689
+        for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
690
+            s->cdlms[ich][ilms].coefs[icoef] +=
691
+                s->cdlms[ich][ilms].lms_updates[icoef + recent];
692
+    }
693
+
694
+    if (recent)
695
+        recent--;
696
+    else {
697
+        memcpy(&s->cdlms[ich][ilms].lms_prevvalues[s->cdlms[ich][ilms].order],
698
+               s->cdlms[ich][ilms].lms_prevvalues,
699
+               2 * s->cdlms[ich][ilms].order);
700
+        memcpy(&s->cdlms[ich][ilms].lms_updates[s->cdlms[ich][ilms].order],
701
+               s->cdlms[ich][ilms].lms_updates,
702
+               2 * s->cdlms[ich][ilms].order);
703
+        recent = s->cdlms[ich][ilms].order - 1;
704
+    }
705
+
706
+    s->cdlms[ich][ilms].lms_prevvalues[recent] = av_clip(input, -range, range - 1);
707
+    if (!input)
708
+        s->cdlms[ich][ilms].lms_updates[recent] = 0;
709
+    else if (input < 0)
710
+        s->cdlms[ich][ilms].lms_updates[recent] = -s->update_speed[ich];
711
+    else
712
+        s->cdlms[ich][ilms].lms_updates[recent] = s->update_speed[ich];
713
+
714
+    s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 4)] >>= 2;
715
+    s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 3)] >>= 1;
716
+    s->cdlms[ich][ilms].recent = recent;
717
+}
718
+
719
+static void use_high_update_speed(WmallDecodeCtx *s, int ich)
720
+{
721
+    int ilms, recent, icoef;
722
+    for (ilms = s->cdlms_ttl[ich] - 1; ilms >= 0; ilms--) {
723
+        recent = s->cdlms[ich][ilms].recent;
724
+        if (s->update_speed[ich] == 16)
725
+            continue;
726
+        if (s->bV3RTM) {
727
+            for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
728
+                s->cdlms[ich][ilms].lms_updates[icoef + recent] *= 2;
729
+        } else {
730
+            for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
731
+                s->cdlms[ich][ilms].lms_updates[icoef] *= 2;
732
+        }
733
+    }
734
+    s->update_speed[ich] = 16;
735
+}
736
+
737
+static void use_normal_update_speed(WmallDecodeCtx *s, int ich)
738
+{
739
+    int ilms, recent, icoef;
740
+    for (ilms = s->cdlms_ttl[ich] - 1; ilms >= 0; ilms--) {
741
+        recent = s->cdlms[ich][ilms].recent;
742
+        if (s->update_speed[ich] == 8)
743
+            continue;
744
+        if (s->bV3RTM)
745
+            for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
746
+                s->cdlms[ich][ilms].lms_updates[icoef + recent] /= 2;
747
+        else
748
+            for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
749
+                s->cdlms[ich][ilms].lms_updates[icoef] /= 2;
750
+    }
751
+    s->update_speed[ich] = 8;
752
+}
753
+
754
+static void revert_cdlms(WmallDecodeCtx *s, int ch,
755
+                         int coef_begin, int coef_end)
756
+{
757
+    int icoef, pred, ilms, num_lms, residue, input;
758
+
759
+    num_lms = s->cdlms_ttl[ch];
760
+    for (ilms = num_lms - 1; ilms >= 0; ilms--) {
761
+        for (icoef = coef_begin; icoef < coef_end; icoef++) {
762
+            pred = 1 << (s->cdlms[ch][ilms].scaling - 1);
763
+            residue = s->channel_residues[ch][icoef];
764
+            pred += lms_predict(s, ch, ilms);
765
+            input = residue + (pred >> s->cdlms[ch][ilms].scaling);
766
+            lms_update(s, ch, ilms, input, residue);
767
+            s->channel_residues[ch][icoef] = input;
768
+        }
769
+    }
770
+}
771
+
772
+static void revert_inter_ch_decorr(WmallDecodeCtx *s, int tile_size)
773
+{
774
+    if (s->num_channels != 2)
775
+        return;
776
+    else if (s->is_channel_coded[0] && s->is_channel_coded[1]) {
777
+        int icoef;
778
+        for (icoef = 0; icoef < tile_size; icoef++) {
779
+            s->channel_residues[0][icoef] -= s->channel_residues[1][icoef] >> 1;
780
+            s->channel_residues[1][icoef] += s->channel_residues[0][icoef];
781
+        }
782
+    }
783
+}
784
+
785
+static void revert_acfilter(WmallDecodeCtx *s, int tile_size)
786
+{
787
+    int ich, pred, i, j;
788
+    int64_t *filter_coeffs = s->acfilter_coeffs;
789
+    int scaling            = s->acfilter_scaling;
790
+    int order              = s->acfilter_order;
791
+
792
+    for (ich = 0; ich < s->num_channels; ich++) {
793
+        int *prevvalues = s->acfilter_prevvalues[ich];
794
+        for (i = 0; i < order; i++) {
795
+            pred = 0;
796
+            for (j = 0; j < order; j++) {
797
+                if (i <= j)
798
+                    pred += filter_coeffs[j] * prevvalues[j - i];
799
+                else
800
+                    pred += s->channel_residues[ich][i - j - 1] * filter_coeffs[j];
801
+            }
802
+            pred >>= scaling;
803
+            s->channel_residues[ich][i] += pred;
804
+        }
805
+        for (i = order; i < tile_size; i++) {
806
+            pred = 0;
807
+            for (j = 0; j < order; j++)
808
+                pred += s->channel_residues[ich][i - j - 1] * filter_coeffs[j];
809
+            pred >>= scaling;
810
+            s->channel_residues[ich][i] += pred;
811
+        }
812
+        for (j = 0; j < order; j++)
813
+            prevvalues[j] = s->channel_residues[ich][tile_size - j - 1];
814
+    }
815
+}
816
+
817
+static int decode_subframe(WmallDecodeCtx *s)
818
+{
819
+    int offset        = s->samples_per_frame;
820
+    int subframe_len  = s->samples_per_frame;
821
+    int total_samples = s->samples_per_frame * s->num_channels;
822
+    int i, j, rawpcm_tile, padding_zeroes;
823
+
824
+    s->subframe_offset = get_bits_count(&s->gb);
825
+
826
+    /* reset channel context and find the next block offset and size
827
+        == the next block of the channel with the smallest number of
828
+        decoded samples */
829
+    for (i = 0; i < s->num_channels; i++) {
830
+        if (offset > s->channel[i].decoded_samples) {
831
+            offset = s->channel[i].decoded_samples;
832
+            subframe_len =
833
+                s->channel[i].subframe_len[s->channel[i].cur_subframe];
834
+        }
835
+    }
836
+
837
+    /* get a list of all channels that contain the estimated block */
838
+    s->channels_for_cur_subframe = 0;
839
+    for (i = 0; i < s->num_channels; i++) {
840
+        const int cur_subframe = s->channel[i].cur_subframe;
841
+        /* subtract already processed samples */
842
+        total_samples -= s->channel[i].decoded_samples;
843
+
844
+        /* and count if there are multiple subframes that match our profile */
845
+        if (offset == s->channel[i].decoded_samples &&
846
+            subframe_len == s->channel[i].subframe_len[cur_subframe]) {
847
+            total_samples -= s->channel[i].subframe_len[cur_subframe];
848
+            s->channel[i].decoded_samples +=
849
+                s->channel[i].subframe_len[cur_subframe];
850
+            s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
851
+            ++s->channels_for_cur_subframe;
852
+        }
853
+    }
854
+
855
+    /* check if the frame will be complete after processing the
856
+        estimated block */
857
+    if (!total_samples)
858
+        s->parsed_all_subframes = 1;
859
+
860
+
861
+    s->seekable_tile = get_bits1(&s->gb);
862
+    if (s->seekable_tile) {
863
+        clear_codec_buffers(s);
864
+
865
+        s->do_arith_coding    = get_bits1(&s->gb);
866
+        if (s->do_arith_coding) {
867
+            av_dlog(s->avctx, AV_LOG_DEBUG, "do_arith_coding == 1");
868
+            abort();
869
+        }
870
+        s->do_ac_filter       = get_bits1(&s->gb);
871
+        s->do_inter_ch_decorr = get_bits1(&s->gb);
872
+        s->do_mclms           = get_bits1(&s->gb);
873
+
874
+        if (s->do_ac_filter)
875
+            decode_ac_filter(s);
876
+
877
+        if (s->do_mclms)
878
+            decode_mclms(s);
879
+
880
+        decode_cdlms(s);
881
+        s->movave_scaling = get_bits(&s->gb, 3);
882
+        s->quant_stepsize = get_bits(&s->gb, 8) + 1;
883
+
884
+        reset_codec(s);
885
+    }
886
+
887
+    rawpcm_tile = get_bits1(&s->gb);
888
+
889
+    for (i = 0; i < s->num_channels; i++)
890
+        s->is_channel_coded[i] = 1;
891
+
892
+    if (!rawpcm_tile) {
893
+        for (i = 0; i < s->num_channels; i++)
894
+            s->is_channel_coded[i] = get_bits1(&s->gb);
895
+
896
+        if (s->bV3RTM) {
897
+            // LPC
898
+            s->do_lpc = get_bits1(&s->gb);
899
+            if (s->do_lpc) {
900
+                decode_lpc(s);
901
+                av_log_ask_for_sample(s->avctx, "Inverse LPC filter not "
902
+                                      "implemented. Expect wrong output.\n");
903
+            }
904
+        } else
905
+            s->do_lpc = 0;
906
+    }
907
+
908
+
909
+    if (get_bits1(&s->gb))
910
+        padding_zeroes = get_bits(&s->gb, 5);
911
+    else
912
+        padding_zeroes = 0;
913
+
914
+    if (rawpcm_tile) {
915
+        int bits = s->bits_per_sample - padding_zeroes;
916
+        av_dlog(s->avctx, AV_LOG_DEBUG, "RAWPCM %d bits per sample. "
917
+                "total %d bits, remain=%d\n", bits,
918
+                bits * s->num_channels * subframe_len, get_bits_count(&s->gb));
919
+        for (i = 0; i < s->num_channels; i++)
920
+            for (j = 0; j < subframe_len; j++)
921
+                s->channel_coeffs[i][j] = get_sbits(&s->gb, bits);
922
+    } else {
923
+        for (i = 0; i < s->num_channels; i++)
924
+            if (s->is_channel_coded[i]) {
925
+                decode_channel_residues(s, i, subframe_len);
926
+                if (s->seekable_tile)
927
+                    use_high_update_speed(s, i);
928
+                else
929
+                    use_normal_update_speed(s, i);
930
+                revert_cdlms(s, i, 0, subframe_len);
931
+            }
932
+    }
933
+    if (s->do_mclms)
934
+        revert_mclms(s, subframe_len);
935
+    if (s->do_inter_ch_decorr)
936
+        revert_inter_ch_decorr(s, subframe_len);
937
+    if (s->do_ac_filter)
938
+        revert_acfilter(s, subframe_len);
939
+
940
+    /* Dequantize */
941
+    if (s->quant_stepsize != 1)
942
+        for (i = 0; i < s->num_channels; i++)
943
+            for (j = 0; j < subframe_len; j++)
944
+                s->channel_residues[i][j] *= s->quant_stepsize;
945
+
946
+    /* Write to proper output buffer depending on bit-depth */
947
+    for (i = 0; i < subframe_len; i++)
948
+        for (j = 0; j < s->num_channels; j++) {
949
+            if (s->bits_per_sample == 16)
950
+                *s->samples_16++ = (int16_t) s->channel_residues[j][i];
951
+            else
952
+                *s->samples_32++ = s->channel_residues[j][i];
953
+        }
954
+
955
+    /* handled one subframe */
956
+    for (i = 0; i < s->channels_for_cur_subframe; i++) {
957
+        int c = s->channel_indexes_for_cur_subframe[i];
958
+        if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
959
+            av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
960
+            return AVERROR_INVALIDDATA;
961
+        }
962
+        ++s->channel[c].cur_subframe;
963
+    }
964
+    return 0;
965
+}
966
+
967
+/**
968
+ * @brief Decode one WMA frame.
969
+ * @param s codec context
970
+ * @return 0 if the trailer bit indicates that this is the last frame,
971
+ *         1 if there are additional frames
972
+ */
973
+static int decode_frame(WmallDecodeCtx *s)
974
+{
975
+    GetBitContext* gb = &s->gb;
976
+    int more_frames = 0, len = 0, i, ret;
977
+
978
+    s->frame.nb_samples = s->samples_per_frame;
979
+    if ((ret = s->avctx->get_buffer(s->avctx, &s->frame)) < 0) {
980
+        /* return an error if no frame could be decoded at all */
981
+        av_log(s->avctx, AV_LOG_ERROR,
982
+               "not enough space for the output samples\n");
983
+        s->packet_loss = 1;
984
+        return ret;
985
+    }
986
+    s->samples_16 = (int16_t *)s->frame.data[0];
987
+    s->samples_32 = (int32_t *)s->frame.data[0];
988
+
989
+    /* get frame length */
990
+    if (s->len_prefix)
991
+        len = get_bits(gb, s->log2_frame_size);
992
+
993
+    /* decode tile information */
994
+    if (decode_tilehdr(s)) {
995
+        s->packet_loss = 1;
996
+        return 0;
997
+    }
998
+
999
+    /* read drc info */
1000
+    if (s->dynamic_range_compression)
1001
+        s->drc_gain = get_bits(gb, 8);
1002
+
1003
+    /* no idea what these are for, might be the number of samples
1004
+       that need to be skipped at the beginning or end of a stream */
1005
+    if (get_bits1(gb)) {
1006
+        int skip;
1007
+
1008
+        /* usually true for the first frame */
1009
+        if (get_bits1(gb)) {
1010
+            skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1011
+            av_dlog(s->avctx, AV_LOG_DEBUG, "start skip: %i\n", skip);
1012
+        }
1013
+
1014
+        /* sometimes true for the last frame */
1015
+        if (get_bits1(gb)) {
1016
+            skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1017
+            av_dlog(s->avctx, AV_LOG_DEBUG, "end skip: %i\n", skip);
1018
+        }
1019
+
1020
+    }
1021
+
1022
+    /* reset subframe states */
1023
+    s->parsed_all_subframes = 0;
1024
+    for (i = 0; i < s->num_channels; i++) {
1025
+        s->channel[i].decoded_samples = 0;
1026
+        s->channel[i].cur_subframe    = 0;
1027
+    }
1028
+
1029
+    /* decode all subframes */
1030
+    while (!s->parsed_all_subframes) {
1031
+        if (decode_subframe(s) < 0) {
1032
+            s->packet_loss = 1;
1033
+            return 0;
1034
+        }
1035
+    }
1036
+
1037
+    av_dlog(s->avctx, AV_LOG_DEBUG, "Frame done\n");
1038
+
1039
+    if (s->skip_frame)
1040
+        s->skip_frame = 0;
1041
+
1042
+    if (s->len_prefix) {
1043
+        if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
1044
+            /* FIXME: not sure if this is always an error */
1045
+            av_log(s->avctx, AV_LOG_ERROR,
1046
+                   "frame[%i] would have to skip %i bits\n", s->frame_num,
1047
+                   len - (get_bits_count(gb) - s->frame_offset) - 1);
1048
+            s->packet_loss = 1;
1049
+            return 0;
1050
+        }
1051
+
1052
+        /* skip the rest of the frame data */
1053
+        skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
1054
+    }
1055
+
1056
+    /* decode trailer bit */
1057
+    more_frames = get_bits1(gb);
1058
+    ++s->frame_num;
1059
+    return more_frames;
1060
+}
1061
+
1062
+/**
1063
+ * @brief Calculate remaining input buffer length.
1064
+ * @param s  codec context
1065
+ * @param gb bitstream reader context
1066
+ * @return remaining size in bits
1067
+ */
1068
+static int remaining_bits(WmallDecodeCtx *s, GetBitContext *gb)
1069
+{
1070
+    return s->buf_bit_size - get_bits_count(gb);
1071
+}
1072
+
1073
+/**
1074
+ * @brief Fill the bit reservoir with a (partial) frame.
1075
+ * @param s      codec context
1076
+ * @param gb     bitstream reader context
1077
+ * @param len    length of the partial frame
1078
+ * @param append decides whether to reset the buffer or not
1079
+ */
1080
+static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
1081
+                      int append)
1082
+{
1083
+    int buflen;
1084
+    PutBitContext tmp;
1085
+
1086
+    /* when the frame data does not need to be concatenated, the input buffer
1087
+        is reset and additional bits from the previous frame are copied
1088
+        and skipped later so that a fast byte copy is possible */
1089
+
1090
+    if (!append) {
1091
+        s->frame_offset   = get_bits_count(gb) & 7;
1092
+        s->num_saved_bits = s->frame_offset;
1093
+        init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
1094
+    }
1095
+
1096
+    buflen = (s->num_saved_bits + len + 8) >> 3;
1097
+
1098
+    if (len <= 0 || buflen > MAX_FRAMESIZE) {
1099
+        av_log_ask_for_sample(s->avctx, "input buffer too small\n");
1100
+        s->packet_loss = 1;
1101
+        return;
1102
+    }
1103
+
1104
+    s->num_saved_bits += len;
1105
+    if (!append) {
1106
+        avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
1107
+                         s->num_saved_bits);
1108
+    } else {
1109
+        int align = 8 - (get_bits_count(gb) & 7);
1110
+        align = FFMIN(align, len);
1111
+        put_bits(&s->pb, align, get_bits(gb, align));
1112
+        len -= align;
1113
+        avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
1114
+    }
1115
+    skip_bits_long(gb, len);
1116
+
1117
+    tmp = s->pb;
1118
+    flush_put_bits(&tmp);
1119
+
1120
+    init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
1121
+    skip_bits(&s->gb, s->frame_offset);
1122
+}
1123
+
1124
+/**
1125
+ * @brief Decode a single WMA packet.
1126
+ * @param avctx     codec context
1127
+ * @param data      the output buffer
1128
+ * @param data_size number of bytes that were written to the output buffer
1129
+ * @param avpkt     input packet
1130
+ * @return number of bytes that were read from the input buffer
1131
+ */
1132
+static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr,
1133
+                         AVPacket* avpkt)
1134
+{
1135
+    WmallDecodeCtx *s = avctx->priv_data;
1136
+    GetBitContext* gb  = &s->pgb;
1137
+    const uint8_t* buf = avpkt->data;
1138
+    int buf_size       = avpkt->size;
1139
+    int num_bits_prev_frame, packet_sequence_number,
1140
+        seekable_frame_in_packet, spliced_packet;
1141
+
1142
+    if (s->packet_done || s->packet_loss) {
1143
+        s->packet_done = 0;
1144
+
1145
+        /* sanity check for the buffer length */
1146
+        if (buf_size < avctx->block_align)
1147
+            return 0;
1148
+
1149
+        s->next_packet_start = buf_size - avctx->block_align;
1150
+        buf_size             = avctx->block_align;
1151
+        s->buf_bit_size      = buf_size << 3;
1152
+
1153
+        /* parse packet header */
1154
+        init_get_bits(gb, buf, s->buf_bit_size);
1155
+        packet_sequence_number   = get_bits(gb, 4);
1156
+        seekable_frame_in_packet = get_bits1(gb);
1157
+        spliced_packet           = get_bits1(gb);
1158
+
1159
+        /* get number of bits that need to be added to the previous frame */
1160
+        num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
1161
+
1162
+        /* check for packet loss */
1163
+        if (!s->packet_loss &&
1164
+            ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
1165
+            s->packet_loss = 1;
1166
+            av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",
1167
+                   s->packet_sequence_number, packet_sequence_number);
1168
+        }
1169
+        s->packet_sequence_number = packet_sequence_number;
1170
+
1171
+        if (num_bits_prev_frame > 0) {
1172
+            int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
1173
+            if (num_bits_prev_frame >= remaining_packet_bits) {
1174
+                num_bits_prev_frame = remaining_packet_bits;
1175
+                s->packet_done = 1;
1176
+            }
1177
+
1178
+            /* Append the previous frame data to the remaining data from the
1179
+             * previous packet to create a full frame. */
1180
+            save_bits(s, gb, num_bits_prev_frame, 1);
1181
+
1182
+            /* decode the cross packet frame if it is valid */
1183
+            if (!s->packet_loss)
1184
+                decode_frame(s);
1185
+        } else if (s->num_saved_bits - s->frame_offset) {
1186
+            av_dlog(avctx, AV_LOG_DEBUG, "ignoring %x previously saved bits\n",
1187
+                    s->num_saved_bits - s->frame_offset);
1188
+        }
1189
+
1190
+        if (s->packet_loss) {
1191
+            /* Reset number of saved bits so that the decoder does not start
1192
+             * to decode incomplete frames in the s->len_prefix == 0 case. */
1193
+            s->num_saved_bits = 0;
1194
+            s->packet_loss    = 0;
1195
+        }
1196
+
1197
+    } else {
1198
+        int frame_size;
1199
+
1200
+        s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
1201
+        init_get_bits(gb, avpkt->data, s->buf_bit_size);
1202
+        skip_bits(gb, s->packet_offset);
1203
+
1204
+        if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
1205
+            (frame_size = show_bits(gb, s->log2_frame_size)) &&
1206
+            frame_size <= remaining_bits(s, gb)) {
1207
+            save_bits(s, gb, frame_size, 0);
1208
+            s->packet_done = !decode_frame(s);
1209
+        } else if (!s->len_prefix
1210
+                   && s->num_saved_bits > get_bits_count(&s->gb)) {
1211
+            /* when the frames do not have a length prefix, we don't know the
1212
+             * compressed length of the individual frames however, we know what
1213
+             * part of a new packet belongs to the previous frame therefore we
1214
+             * save the incoming packet first, then we append the "previous
1215
+             * frame" data from the next packet so that we get a buffer that
1216
+             * only contains full frames */
1217
+            s->packet_done = !decode_frame(s);
1218
+        } else {
1219
+            s->packet_done = 1;
1220
+        }
1221
+    }
1222
+
1223
+    if (s->packet_done && !s->packet_loss &&
1224
+        remaining_bits(s, gb) > 0) {
1225
+        /* save the rest of the data so that it can be decoded
1226
+         * with the next packet */
1227
+        save_bits(s, gb, remaining_bits(s, gb), 0);
1228
+    }
1229
+
1230
+    *(AVFrame *)data = s->frame;
1231
+    *got_frame_ptr   = 1;
1232
+    s->packet_offset = get_bits_count(gb) & 7;
1233
+
1234
+    return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
1235
+}
1236
+
1237
+
1238
+AVCodec ff_wmalossless_decoder = {
1239
+    .name           = "wmalossless",
1240
+    .type           = AVMEDIA_TYPE_AUDIO,
1241
+    .id             = CODEC_ID_WMALOSSLESS,
1242
+    .priv_data_size = sizeof(WmallDecodeCtx),
1243
+    .init           = decode_init,
1244
+    .decode         = decode_packet,
1245
+    .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1246
+    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio Lossless"),
1247
+};