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