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