]> git.sesse.net Git - ffmpeg/blob - libavcodec/wmalosslessdec.c
76dc6c99a8dcaef424ac8b67f3b3ae9fb28d46b8
[ffmpeg] / libavcodec / wmalosslessdec.c
1 /*
2  * Wmall compatible 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  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * @brief wmall decoder implementation
27  * Wmall is an MDCT based codec comparable to wma standard or AAC.
28  * The decoding therefore consists of the following steps:
29  * - bitstream decoding
30  * - reconstruction of per-channel data
31  * - rescaling and inverse quantization
32  * - IMDCT
33  * - windowing and overlapp-add
34  *
35  * The compressed wmall bitstream is split into individual packets.
36  * Every such packet contains one or more wma frames.
37  * The compressed frames may have a variable length and frames may
38  * cross packet boundaries.
39  * Common to all wmall frames is the number of samples that are stored in
40  * a frame.
41  * The number of samples and a few other decode flags are stored
42  * as extradata that has to be passed to the decoder.
43  *
44  * The wmall frames themselves are again split into a variable number of
45  * subframes. Every subframe contains the data for 2^N time domain samples
46  * where N varies between 7 and 12.
47  *
48  * Example wmall bitstream (in samples):
49  *
50  * ||   packet 0           || packet 1 || packet 2      packets
51  * ---------------------------------------------------
52  * || frame 0      || frame 1       || frame 2    ||    frames
53  * ---------------------------------------------------
54  * ||   |      |   ||   |   |   |   ||            ||    subframes of channel 0
55  * ---------------------------------------------------
56  * ||      |   |   ||   |   |   |   ||            ||    subframes of channel 1
57  * ---------------------------------------------------
58  *
59  * The frame layouts for the individual channels of a wma frame does not need
60  * to be the same.
61  *
62  * However, if the offsets and lengths of several subframes of a frame are the
63  * same, the subframes of the channels can be grouped.
64  * Every group may then use special coding techniques like M/S stereo coding
65  * to improve the compression ratio. These channel transformations do not
66  * need to be applied to a whole subframe. Instead, they can also work on
67  * individual scale factor bands (see below).
68  * The coefficients that carry the audio signal in the frequency domain
69  * are transmitted as huffman-coded vectors with 4, 2 and 1 elements.
70  * In addition to that, the encoder can switch to a runlevel coding scheme
71  * by transmitting subframe_length / 128 zero coefficients.
72  *
73  * Before the audio signal can be converted to the time domain, the
74  * coefficients have to be rescaled and inverse quantized.
75  * A subframe is therefore split into several scale factor bands that get
76  * scaled individually.
77  * Scale factors are submitted for every frame but they might be shared
78  * between the subframes of a channel. Scale factors are initially DPCM-coded.
79  * Once scale factors are shared, the differences are transmitted as runlevel
80  * codes.
81  * Every subframe length and offset combination in the frame layout shares a
82  * common quantization factor that can be adjusted for every channel by a
83  * modifier.
84  * After the inverse quantization, the coefficients get processed by an IMDCT.
85  * The resulting values are then windowed with a sine window and the first half
86  * of the values are added to the second half of the output from the previous
87  * subframe in order to reconstruct the output samples.
88  */
89
90 #include "avcodec.h"
91 #include "internal.h"
92 #include "get_bits.h"
93 #include "put_bits.h"
94 #include "dsputil.h"
95 #include "wma.h"
96
97 /** current decoder limitations */
98 #define WMALL_MAX_CHANNELS    8                             ///< max number of handled channels
99 #define MAX_SUBFRAMES  32                                    ///< max number of subframes per channel
100 #define MAX_BANDS      29                                    ///< max number of scale factor bands
101 #define MAX_FRAMESIZE  32768                                 ///< maximum compressed frame size
102
103 #define WMALL_BLOCK_MIN_BITS  6                                           ///< log2 of min block size
104 #define WMALL_BLOCK_MAX_BITS 12                                           ///< log2 of max block size
105 #define WMALL_BLOCK_MAX_SIZE (1 << WMALL_BLOCK_MAX_BITS)                 ///< maximum block size
106 #define WMALL_BLOCK_SIZES    (WMALL_BLOCK_MAX_BITS - WMALL_BLOCK_MIN_BITS + 1) ///< possible block sizes
107
108
109 #define VLCBITS            9
110 #define SCALEVLCBITS       8
111 #define VEC4MAXDEPTH    ((HUFF_VEC4_MAXBITS+VLCBITS-1)/VLCBITS)
112 #define VEC2MAXDEPTH    ((HUFF_VEC2_MAXBITS+VLCBITS-1)/VLCBITS)
113 #define VEC1MAXDEPTH    ((HUFF_VEC1_MAXBITS+VLCBITS-1)/VLCBITS)
114 #define SCALEMAXDEPTH   ((HUFF_SCALE_MAXBITS+SCALEVLCBITS-1)/SCALEVLCBITS)
115 #define SCALERLMAXDEPTH ((HUFF_SCALE_RL_MAXBITS+VLCBITS-1)/VLCBITS)
116
117 static float            sin64[33];        ///< sinus table for decorrelation
118
119 /**
120  * @brief frame specific decoder context for a single channel
121  */
122 typedef struct {
123     int16_t  prev_block_len;                          ///< length of the previous block
124     uint8_t  transmit_coefs;
125     uint8_t  num_subframes;
126     uint16_t subframe_len[MAX_SUBFRAMES];             ///< subframe length in samples
127     uint16_t subframe_offset[MAX_SUBFRAMES];          ///< subframe positions in the current frame
128     uint8_t  cur_subframe;                            ///< current subframe number
129     uint16_t decoded_samples;                         ///< number of already processed samples
130     uint8_t  grouped;                                 ///< channel is part of a group
131     int      quant_step;                              ///< quantization step for the current subframe
132     int8_t   reuse_sf;                                ///< share scale factors between subframes
133     int8_t   scale_factor_step;                       ///< scaling step for the current subframe
134     int      max_scale_factor;                        ///< maximum scale factor for the current subframe
135     int      saved_scale_factors[2][MAX_BANDS];       ///< resampled and (previously) transmitted scale factor values
136     int8_t   scale_factor_idx;                        ///< index for the transmitted scale factor values (used for resampling)
137     int*     scale_factors;                           ///< pointer to the scale factor values used for decoding
138     uint8_t  table_idx;                               ///< index in sf_offsets for the scale factor reference block
139     float*   coeffs;                                  ///< pointer to the subframe decode buffer
140     uint16_t num_vec_coeffs;                          ///< number of vector coded coefficients
141     DECLARE_ALIGNED(16, float, out)[WMALL_BLOCK_MAX_SIZE + WMALL_BLOCK_MAX_SIZE / 2]; ///< output buffer
142     int      transient_counter;                       ///< number of transient samples from the beginning of transient zone
143 } WmallChannelCtx;
144
145 /**
146  * @brief channel group for channel transformations
147  */
148 typedef struct {
149     uint8_t num_channels;                                     ///< number of channels in the group
150     int8_t  transform;                                        ///< transform on / off
151     int8_t  transform_band[MAX_BANDS];                        ///< controls if the transform is enabled for a certain band
152     float   decorrelation_matrix[WMALL_MAX_CHANNELS*WMALL_MAX_CHANNELS];
153     float*  channel_data[WMALL_MAX_CHANNELS];                ///< transformation coefficients
154 } WmallChannelGrp;
155
156 /**
157  * @brief main decoder context
158  */
159 typedef struct WmallDecodeCtx {
160     /* generic decoder variables */
161     AVCodecContext*  avctx;                         ///< codec context for av_log
162     DSPContext       dsp;                           ///< accelerated DSP functions
163     uint8_t          frame_data[MAX_FRAMESIZE +
164                       FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
165     PutBitContext    pb;                            ///< context for filling the frame_data buffer
166     FFTContext       mdct_ctx[WMALL_BLOCK_SIZES];  ///< MDCT context per block size
167     DECLARE_ALIGNED(16, float, tmp)[WMALL_BLOCK_MAX_SIZE]; ///< IMDCT output buffer
168     float*           windows[WMALL_BLOCK_SIZES];   ///< windows for the different block sizes
169
170     /* frame size dependent frame information (set during initialization) */
171     uint32_t         decode_flags;                  ///< used compression features
172     uint8_t          len_prefix;                    ///< frame is prefixed with its length
173     uint8_t          dynamic_range_compression;     ///< frame contains DRC data
174     uint8_t          bits_per_sample;               ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
175     uint16_t         samples_per_frame;             ///< number of samples to output
176     uint16_t         log2_frame_size;
177     int8_t           num_channels;                  ///< number of channels in the stream (same as AVCodecContext.num_channels)
178     int8_t           lfe_channel;                   ///< lfe channel index
179     uint8_t          max_num_subframes;
180     uint8_t          subframe_len_bits;             ///< number of bits used for the subframe length
181     uint8_t          max_subframe_len_bit;          ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
182     uint16_t         min_samples_per_subframe;
183     int8_t           num_sfb[WMALL_BLOCK_SIZES];   ///< scale factor bands per block size
184     int16_t          sfb_offsets[WMALL_BLOCK_SIZES][MAX_BANDS];                    ///< scale factor band offsets (multiples of 4)
185     int8_t           sf_offsets[WMALL_BLOCK_SIZES][WMALL_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
186     int16_t          subwoofer_cutoffs[WMALL_BLOCK_SIZES]; ///< subwoofer cutoff values
187
188     /* packet decode state */
189     GetBitContext    pgb;                           ///< bitstream reader context for the packet
190     int              next_packet_start;             ///< start offset of the next wma packet in the demuxer packet
191     uint8_t          packet_offset;                 ///< frame offset in the packet
192     uint8_t          packet_sequence_number;        ///< current packet number
193     int              num_saved_bits;                ///< saved number of bits
194     int              frame_offset;                  ///< frame offset in the bit reservoir
195     int              subframe_offset;               ///< subframe offset in the bit reservoir
196     uint8_t          packet_loss;                   ///< set in case of bitstream error
197     uint8_t          packet_done;                   ///< set when a packet is fully decoded
198
199     /* frame decode state */
200     uint32_t         frame_num;                     ///< current frame number (not used for decoding)
201     GetBitContext    gb;                            ///< bitstream reader context
202     int              buf_bit_size;                  ///< buffer size in bits
203     float*           samples;                       ///< current samplebuffer pointer
204     float*           samples_end;                   ///< maximum samplebuffer pointer
205     uint8_t          drc_gain;                      ///< gain for the DRC tool
206     int8_t           skip_frame;                    ///< skip output step
207     int8_t           parsed_all_subframes;          ///< all subframes decoded?
208
209     /* subframe/block decode state */
210     int16_t          subframe_len;                  ///< current subframe length
211     int8_t           channels_for_cur_subframe;     ///< number of channels that contain the subframe
212     int8_t           channel_indexes_for_cur_subframe[WMALL_MAX_CHANNELS];
213     int8_t           num_bands;                     ///< number of scale factor bands
214     int8_t           transmit_num_vec_coeffs;       ///< number of vector coded coefficients is part of the bitstream
215     int16_t*         cur_sfb_offsets;               ///< sfb offsets for the current block
216     uint8_t          table_idx;                     ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
217     int8_t           esc_len;                       ///< length of escaped coefficients
218
219     uint8_t          num_chgroups;                  ///< number of channel groups
220     WmallChannelGrp chgroup[WMALL_MAX_CHANNELS];    ///< channel group information
221
222     WmallChannelCtx channel[WMALL_MAX_CHANNELS];    ///< per channel data
223
224     // WMA lossless
225
226     uint8_t do_arith_coding;
227     uint8_t do_ac_filter;
228     uint8_t do_inter_ch_decorr;
229     uint8_t do_mclms;
230     uint8_t do_lpc;
231
232     int8_t acfilter_order;
233     int8_t acfilter_scaling;
234     int acfilter_coeffs[16];
235     int acfilter_prevvalues[16];
236
237     int8_t mclms_order;
238     int8_t mclms_scaling;
239     int16_t mclms_coeffs[128];
240     int16_t mclms_coeffs_cur[4];
241     int16_t mclms_prevvalues[64];   // FIXME: should be 32-bit / 16-bit depending on bit-depth
242     int16_t mclms_updates[64];
243     int mclms_recent;
244
245     int movave_scaling;
246     int quant_stepsize;
247
248     struct {
249         int order;
250         int scaling;
251         int coefsend;
252         int bitsend;
253         int16_t coefs[256];
254     int16_t lms_prevvalues[512];    // FIXME: see above
255     int16_t lms_updates[512];   // and here too
256     int recent;
257     } cdlms[2][9];              /* XXX: Here, 2 is the max. no. of channels allowed,
258                                         9 is the maximum no. of filters per channel.
259                                         Question is, why 2 if WMALL_MAX_CHANNELS == 8 */
260
261
262     int cdlms_ttl[2];
263
264     int bV3RTM;
265
266     int is_channel_coded[2];    // XXX: same question as above applies here too (and below)
267     int update_speed[2];
268
269     int transient[2];
270     int transient_pos[2];
271     int seekable_tile;
272
273     int ave_sum[2];
274
275     int channel_residues[2][2048];
276
277
278     int lpc_coefs[2][40];
279     int lpc_order;
280     int lpc_scaling;
281     int lpc_intbits;
282
283     int channel_coeffs[2][2048]; // FIXME: should be 32-bit / 16-bit depending on bit-depth
284
285 } WmallDecodeCtx;
286
287
288 #undef dprintf
289 #define dprintf(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
290
291
292 static int num_logged_tiles = 0;
293 static int num_logged_subframes = 0;
294 static int num_lms_update_call = 0;
295
296 /**
297  *@brief helper function to print the most important members of the context
298  *@param s context
299  */
300 static void av_cold dump_context(WmallDecodeCtx *s)
301 {
302 #define PRINT(a, b)     av_log(s->avctx, AV_LOG_DEBUG, " %s = %d\n", a, b);
303 #define PRINT_HEX(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %x\n", a, b);
304
305     PRINT("ed sample bit depth", s->bits_per_sample);
306     PRINT_HEX("ed decode flags", s->decode_flags);
307     PRINT("samples per frame",   s->samples_per_frame);
308     PRINT("log2 frame size",     s->log2_frame_size);
309     PRINT("max num subframes",   s->max_num_subframes);
310     PRINT("len prefix",          s->len_prefix);
311     PRINT("num channels",        s->num_channels);
312 }
313
314 static void dump_int_buffer(uint8_t *buffer, int size, int length, int delimiter)
315 {
316     int i;
317
318     for (i=0 ; i<length ; i++) {
319         if (!(i%delimiter))
320             av_log(0, 0, "\n[%d] ", i);
321         av_log(0, 0, "%d, ", *(int16_t *)(buffer + i * size));
322     }
323     av_log(0, 0, "\n");
324
325 }
326
327 /**
328  *@brief Uninitialize the decoder and free all resources.
329  *@param avctx codec context
330  *@return 0 on success, < 0 otherwise
331  */
332 static av_cold int decode_end(AVCodecContext *avctx)
333 {
334     WmallDecodeCtx *s = avctx->priv_data;
335     int i;
336
337     for (i = 0; i < WMALL_BLOCK_SIZES; i++)
338         ff_mdct_end(&s->mdct_ctx[i]);
339
340     return 0;
341 }
342
343 /**
344  *@brief Initialize the decoder.
345  *@param avctx codec context
346  *@return 0 on success, -1 otherwise
347  */
348 static av_cold int decode_init(AVCodecContext *avctx)
349 {
350     WmallDecodeCtx *s = avctx->priv_data;
351     uint8_t *edata_ptr = avctx->extradata;
352     unsigned int channel_mask;
353     int i;
354     int log2_max_num_subframes;
355     int num_possible_block_sizes;
356
357     s->avctx = avctx;
358     dsputil_init(&s->dsp, avctx);
359     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
360
361     avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
362
363     if (avctx->extradata_size >= 18) {
364         s->decode_flags    = AV_RL16(edata_ptr+14);
365         channel_mask       = AV_RL32(edata_ptr+2);
366         s->bits_per_sample = AV_RL16(edata_ptr);
367         /** dump the extradata */
368         for (i = 0; i < avctx->extradata_size; i++)
369             dprintf(avctx, "[%x] ", avctx->extradata[i]);
370         dprintf(avctx, "\n");
371
372     } else {
373         av_log_ask_for_sample(avctx, "Unknown extradata size\n");
374         return AVERROR_INVALIDDATA;
375     }
376
377     /** generic init */
378     s->log2_frame_size = av_log2(avctx->block_align) + 4;
379
380     /** frame info */
381     s->skip_frame  = 1; /* skip first frame */
382     s->packet_loss = 1;
383     s->len_prefix  = (s->decode_flags & 0x40);
384
385     /** get frame len */
386     s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
387                                                           3, s->decode_flags);
388
389     /** init previous block len */
390     for (i = 0; i < avctx->channels; i++)
391         s->channel[i].prev_block_len = s->samples_per_frame;
392
393     /** subframe info */
394     log2_max_num_subframes  = ((s->decode_flags & 0x38) >> 3);
395     s->max_num_subframes    = 1 << log2_max_num_subframes;
396     s->max_subframe_len_bit = 0;
397     s->subframe_len_bits    = av_log2(log2_max_num_subframes) + 1;
398
399     num_possible_block_sizes     = log2_max_num_subframes + 1;
400     s->min_samples_per_subframe  = s->samples_per_frame / s->max_num_subframes;
401     s->dynamic_range_compression = (s->decode_flags & 0x80);
402
403     s->bV3RTM = s->decode_flags & 0x100;
404
405     if (s->max_num_subframes > MAX_SUBFRAMES) {
406         av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %i\n",
407                s->max_num_subframes);
408         return AVERROR_INVALIDDATA;
409     }
410
411     s->num_channels = avctx->channels;
412
413     /** extract lfe channel position */
414     s->lfe_channel = -1;
415
416     if (channel_mask & 8) {
417         unsigned int mask;
418         for (mask = 1; mask < 16; mask <<= 1) {
419             if (channel_mask & mask)
420                 ++s->lfe_channel;
421         }
422     }
423
424     if (s->num_channels < 0) {
425         av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n", s->num_channels);
426         return AVERROR_INVALIDDATA;
427     } else if (s->num_channels > WMALL_MAX_CHANNELS) {
428         av_log_ask_for_sample(avctx, "unsupported number of channels\n");
429         return AVERROR_PATCHWELCOME;
430     }
431
432     avctx->channel_layout = channel_mask;
433     return 0;
434 }
435
436 /**
437  *@brief Decode the subframe length.
438  *@param s context
439  *@param offset sample offset in the frame
440  *@return decoded subframe length on success, < 0 in case of an error
441  */
442 static int decode_subframe_length(WmallDecodeCtx *s, int offset)
443 {
444     int frame_len_ratio;
445     int subframe_len, len;
446
447     /** no need to read from the bitstream when only one length is possible */
448     if (offset == s->samples_per_frame - s->min_samples_per_subframe)
449         return s->min_samples_per_subframe;
450
451     len = av_log2(s->max_num_subframes - 1) + 1;
452     frame_len_ratio = get_bits(&s->gb, len);
453
454     subframe_len = s->min_samples_per_subframe * (frame_len_ratio + 1);
455
456     /** sanity check the length */
457     if (subframe_len < s->min_samples_per_subframe ||
458         subframe_len > s->samples_per_frame) {
459         av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
460                subframe_len);
461         return AVERROR_INVALIDDATA;
462     }
463     return subframe_len;
464 }
465
466 /**
467  *@brief Decode how the data in the frame is split into subframes.
468  *       Every WMA frame contains the encoded data for a fixed number of
469  *       samples per channel. The data for every channel might be split
470  *       into several subframes. This function will reconstruct the list of
471  *       subframes for every channel.
472  *
473  *       If the subframes are not evenly split, the algorithm estimates the
474  *       channels with the lowest number of total samples.
475  *       Afterwards, for each of these channels a bit is read from the
476  *       bitstream that indicates if the channel contains a subframe with the
477  *       next subframe size that is going to be read from the bitstream or not.
478  *       If a channel contains such a subframe, the subframe size gets added to
479  *       the channel's subframe list.
480  *       The algorithm repeats these steps until the frame is properly divided
481  *       between the individual channels.
482  *
483  *@param s context
484  *@return 0 on success, < 0 in case of an error
485  */
486 static int decode_tilehdr(WmallDecodeCtx *s)
487 {
488     uint16_t num_samples[WMALL_MAX_CHANNELS];        /**< sum of samples for all currently known subframes of a channel */
489     uint8_t  contains_subframe[WMALL_MAX_CHANNELS];  /**< flag indicating if a channel contains the current subframe */
490     int channels_for_cur_subframe = s->num_channels;  /**< number of channels that contain the current subframe */
491     int fixed_channel_layout = 0;                     /**< flag indicating that all channels use the same subfra2me offsets and sizes */
492     int min_channel_len = 0;                          /**< smallest sum of samples (channels with this length will be processed first) */
493     int c;
494
495     /* Should never consume more than 3073 bits (256 iterations for the
496      * while loop when always the minimum amount of 128 samples is substracted
497      * from missing samples in the 8 channel case).
498      * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS  + 4)
499      */
500
501     /** reset tiling information */
502     for (c = 0; c < s->num_channels; c++)
503         s->channel[c].num_subframes = 0;
504
505     memset(num_samples, 0, sizeof(num_samples));
506
507     if (s->max_num_subframes == 1 || get_bits1(&s->gb))
508         fixed_channel_layout = 1;
509
510     /** loop until the frame data is split between the subframes */
511     do {
512         int subframe_len;
513
514         /** check which channels contain the subframe */
515         for (c = 0; c < s->num_channels; c++) {
516             if (num_samples[c] == min_channel_len) {
517                 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
518                     (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe)) {
519                     contains_subframe[c] = 1;
520                 }
521                 else {
522                     contains_subframe[c] = get_bits1(&s->gb);
523                 }
524             } else
525                 contains_subframe[c] = 0;
526         }
527
528         /** get subframe length, subframe_len == 0 is not allowed */
529         if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
530             return AVERROR_INVALIDDATA;
531         /** add subframes to the individual channels and find new min_channel_len */
532         min_channel_len += subframe_len;
533         for (c = 0; c < s->num_channels; c++) {
534             WmallChannelCtx* chan = &s->channel[c];
535
536             if (contains_subframe[c]) {
537                 if (chan->num_subframes >= MAX_SUBFRAMES) {
538                     av_log(s->avctx, AV_LOG_ERROR,
539                            "broken frame: num subframes > 31\n");
540                     return AVERROR_INVALIDDATA;
541                 }
542                 chan->subframe_len[chan->num_subframes] = subframe_len;
543                 num_samples[c] += subframe_len;
544                 ++chan->num_subframes;
545                 if (num_samples[c] > s->samples_per_frame) {
546                     av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
547                            "channel len(%d) > samples_per_frame(%d)\n",
548                            num_samples[c], s->samples_per_frame);
549                     return AVERROR_INVALIDDATA;
550                 }
551             } else if (num_samples[c] <= min_channel_len) {
552                 if (num_samples[c] < min_channel_len) {
553                     channels_for_cur_subframe = 0;
554                     min_channel_len = num_samples[c];
555                 }
556                 ++channels_for_cur_subframe;
557             }
558         }
559     } while (min_channel_len < s->samples_per_frame);
560
561     for (c = 0; c < s->num_channels; c++) {
562         int i;
563         int offset = 0;
564         for (i = 0; i < s->channel[c].num_subframes; i++) {
565             s->channel[c].subframe_offset[i] = offset;
566             offset += s->channel[c].subframe_len[i];
567         }
568     }
569
570     return 0;
571 }
572
573
574 static int my_log2(unsigned int i)
575 {
576     unsigned int iLog2 = 0;
577     while ((i >> iLog2) > 1)
578         iLog2++;
579     return iLog2;
580 }
581
582
583 /**
584  *
585  */
586 static void decode_ac_filter(WmallDecodeCtx *s)
587 {
588     int i;
589     s->acfilter_order = get_bits(&s->gb, 4) + 1;
590     s->acfilter_scaling = get_bits(&s->gb, 4);
591
592     for(i = 0; i < s->acfilter_order; i++) {
593         s->acfilter_coeffs[i] = get_bits(&s->gb, s->acfilter_scaling) + 1;
594     }
595 }
596
597
598 /**
599  *
600  */
601 static void decode_mclms(WmallDecodeCtx *s)
602 {
603     s->mclms_order = (get_bits(&s->gb, 4) + 1) * 2;
604     s->mclms_scaling = get_bits(&s->gb, 4);
605     if(get_bits1(&s->gb)) {
606         // mclms_send_coef
607         int i;
608         int send_coef_bits;
609         int cbits = av_log2(s->mclms_scaling + 1);
610         assert(cbits == my_log2(s->mclms_scaling + 1));
611         if(1 << cbits < s->mclms_scaling + 1)
612             cbits++;
613
614         send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2;
615
616         for(i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++) {
617             s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits);
618         }
619
620         for(i = 0; i < s->num_channels; i++) {
621             int c;
622             for(c = 0; c < i; c++) {
623                 s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits);
624             }
625         }
626     }
627 }
628
629
630 /**
631  *
632  */
633 static void decode_cdlms(WmallDecodeCtx *s)
634 {
635     int c, i;
636     int cdlms_send_coef = get_bits1(&s->gb);
637
638     for(c = 0; c < s->num_channels; c++) {
639         s->cdlms_ttl[c] = get_bits(&s->gb, 3) + 1;
640         for(i = 0; i < s->cdlms_ttl[c]; i++) {
641             s->cdlms[c][i].order = (get_bits(&s->gb, 7) + 1) * 8;
642         }
643
644         for(i = 0; i < s->cdlms_ttl[c]; i++) {
645             s->cdlms[c][i].scaling = get_bits(&s->gb, 4);
646         }
647
648         if(cdlms_send_coef) {
649             for(i = 0; i < s->cdlms_ttl[c]; i++) {
650                 int cbits, shift_l, shift_r, j;
651                 cbits = av_log2(s->cdlms[c][i].order);
652                 if(1 << cbits < s->cdlms[c][i].order)
653                     cbits++;
654                 s->cdlms[c][i].coefsend = get_bits(&s->gb, cbits) + 1;
655
656                 cbits = av_log2(s->cdlms[c][i].scaling + 1);
657                 if(1 << cbits < s->cdlms[c][i].scaling + 1)
658                     cbits++;
659
660                 s->cdlms[c][i].bitsend = get_bits(&s->gb, cbits) + 2;
661                 shift_l = 32 - s->cdlms[c][i].bitsend;
662                 shift_r = 32 - 2 - s->cdlms[c][i].scaling;
663                 for(j = 0; j < s->cdlms[c][i].coefsend; j++) {
664                     s->cdlms[c][i].coefs[j] =
665                         (get_bits(&s->gb, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;
666                 }
667             }
668         }
669     }
670 }
671
672 /**
673  *
674  */
675 static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
676 {
677     int i = 0;
678     unsigned int ave_mean;
679     s->transient[ch] = get_bits1(&s->gb);
680     if(s->transient[ch]) {
681             s->transient_pos[ch] = get_bits(&s->gb, av_log2(tile_size));
682         if (s->transient_pos[ch])
683                 s->transient[ch] = 0;
684             s->channel[ch].transient_counter =
685                 FFMAX(s->channel[ch].transient_counter, s->samples_per_frame / 2);
686         } else if (s->channel[ch].transient_counter)
687             s->transient[ch] = 1;
688
689     if(s->seekable_tile) {
690         ave_mean = get_bits(&s->gb, s->bits_per_sample);
691         s->ave_sum[ch] = ave_mean << (s->movave_scaling + 1);
692 //        s->ave_sum[ch] *= 2;
693     }
694
695     if(s->seekable_tile) {
696         if(s->do_inter_ch_decorr)
697             s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample + 1);
698         else
699             s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample);
700         i++;
701     }
702     //av_log(0, 0, "%8d: ", num_logged_tiles++);
703     for(; i < tile_size; i++) {
704         int quo = 0, rem, rem_bits, residue;
705         while(get_bits1(&s->gb))
706             quo++;
707         if(quo >= 32)
708             quo += get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1);
709
710                ave_mean = (s->ave_sum[ch] + (1 << s->movave_scaling)) >> (s->movave_scaling + 1);
711         rem_bits = av_ceil_log2(ave_mean);
712         rem = rem_bits ? get_bits(&s->gb, rem_bits) : 0;
713         residue = (quo << rem_bits) + rem;
714
715         s->ave_sum[ch] = residue + s->ave_sum[ch] - (s->ave_sum[ch] >> s->movave_scaling);
716
717         if(residue & 1)
718             residue = -(residue >> 1) - 1;
719         else
720             residue = residue >> 1;
721         s->channel_residues[ch][i] = residue;
722     }
723     dump_int_buffer(s->channel_residues[ch], 4, tile_size, 16);
724
725     return 0;
726
727 }
728
729
730 /**
731  *
732  */
733 static void
734 decode_lpc(WmallDecodeCtx *s)
735 {
736     int ch, i, cbits;
737     s->lpc_order = get_bits(&s->gb, 5) + 1;
738     s->lpc_scaling = get_bits(&s->gb, 4);
739     s->lpc_intbits = get_bits(&s->gb, 3) + 1;
740     cbits = s->lpc_scaling + s->lpc_intbits;
741     for(ch = 0; ch < s->num_channels; ch++) {
742         for(i = 0; i < s->lpc_order; i++) {
743             s->lpc_coefs[ch][i] = get_sbits(&s->gb, cbits);
744         }
745     }
746 }
747
748
749 static void clear_codec_buffers(WmallDecodeCtx *s)
750 {
751     int ich, ilms;
752
753     memset(s->acfilter_coeffs, 0,     16 * sizeof(int));
754     memset(s->lpc_coefs      , 0, 40 * 2 * sizeof(int));
755
756     memset(s->mclms_coeffs    , 0, 128 * sizeof(int16_t));
757     memset(s->mclms_coeffs_cur, 0,   4 * sizeof(int16_t));
758     memset(s->mclms_prevvalues, 0,  64 * sizeof(int));
759     memset(s->mclms_updates   , 0,  64 * sizeof(int16_t));
760
761     for (ich = 0; ich < s->num_channels; ich++) {
762         for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++) {
763             memset(s->cdlms[ich][ilms].coefs         , 0, 256 * sizeof(int16_t));
764             memset(s->cdlms[ich][ilms].lms_prevvalues, 0, 512 * sizeof(int16_t));
765             memset(s->cdlms[ich][ilms].lms_updates   , 0, 512 * sizeof(int16_t));
766         }
767         s->ave_sum[ich] = 0;
768     }
769 }
770
771 /**
772  *@brief Resets filter parameters and transient area at new seekable tile
773  */
774 static void reset_codec(WmallDecodeCtx *s)
775 {
776     int ich, ilms;
777     s->mclms_recent = s->mclms_order * s->num_channels;
778     for (ich = 0; ich < s->num_channels; ich++) {
779         for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++)
780             s->cdlms[ich][ilms].recent = s->cdlms[ich][ilms].order;
781         /* first sample of a seekable subframe is considered as the starting of
782            a transient area which is samples_per_frame samples long */
783         s->channel[ich].transient_counter = s->samples_per_frame;
784         s->transient[ich] = 1;
785         s->transient_pos[ich] = 0;
786     }
787 }
788
789
790
791 static void mclms_update(WmallDecodeCtx *s, int icoef, int *pred)
792 {
793     int i, j, ich;
794     int pred_error;
795     int order = s->mclms_order;
796     int num_channels = s->num_channels;
797     int range = 1 << (s->bits_per_sample - 1);
798     int bps = s->bits_per_sample > 16 ? 4 : 2; // bytes per sample
799
800     for (ich = 0; ich < num_channels; ich++) {
801         pred_error = s->channel_residues[ich][icoef] - pred[ich];
802         if (pred_error > 0) {
803             for (i = 0; i < order * num_channels; i++)
804                 s->mclms_coeffs[i + ich * order * num_channels] +=
805                     s->mclms_updates[s->mclms_recent + i];
806             for (j = 0; j < ich; j++) {
807                 if (s->channel_residues[j][icoef] > 0)
808                     s->mclms_coeffs_cur[ich * num_channels + j] += 1;
809                 else if (s->channel_residues[j][icoef] < 0)
810                     s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
811             }
812         } else if (pred_error < 0) {
813             for (i = 0; i < order * num_channels; i++)
814                 s->mclms_coeffs[i + ich * order * num_channels] -=
815                     s->mclms_updates[s->mclms_recent + i];
816             for (j = 0; j < ich; j++) {
817                 if (s->channel_residues[j][icoef] > 0)
818                     s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
819                 else if (s->channel_residues[j][icoef] < 0)
820                     s->mclms_coeffs_cur[ich * num_channels + j] += 1;
821             }
822         }
823     }
824
825     for (ich = num_channels - 1; ich >= 0; ich--) {
826         s->mclms_recent--;
827         s->mclms_prevvalues[s->mclms_recent] = s->channel_residues[ich][icoef];
828         if (s->channel_residues[ich][icoef] > range - 1)
829             s->mclms_prevvalues[s->mclms_recent] = range - 1;
830         else if (s->channel_residues[ich][icoef] < -range)
831             s->mclms_prevvalues[s->mclms_recent] = -range;
832
833         s->mclms_updates[s->mclms_recent] = 0;
834         if (s->channel_residues[ich][icoef] > 0)
835             s->mclms_updates[s->mclms_recent] = 1;
836         else if (s->channel_residues[ich][icoef] < 0)
837             s->mclms_updates[s->mclms_recent] = -1;
838     }
839
840     if (s->mclms_recent == 0) {
841         memcpy(&s->mclms_prevvalues[order * num_channels],
842                s->mclms_prevvalues,
843                bps * order * num_channels);
844         memcpy(&s->mclms_updates[order * num_channels],
845                s->mclms_updates,
846                bps * order * num_channels);
847         s->mclms_recent = num_channels * order;
848     }
849 }
850
851 static void mclms_predict(WmallDecodeCtx *s, int icoef, int *pred)
852 {
853     int ich, i;
854     int order = s->mclms_order;
855     int num_channels = s->num_channels;
856
857     for (ich = 0; ich < num_channels; ich++) {
858         if (!s->is_channel_coded[ich])
859             continue;
860         pred[ich] = 0;
861         for (i = 0; i < order * num_channels; i++)
862             pred[ich] += s->mclms_prevvalues[i + s->mclms_recent] *
863                          s->mclms_coeffs[i + order * num_channels * ich];
864         for (i = 0; i < ich; i++)
865             pred[ich] += s->channel_residues[i][icoef] *
866                          s->mclms_coeffs_cur[i + num_channels * ich];
867         pred[ich] += 1 << s->mclms_scaling - 1;
868         pred[ich] >>= s->mclms_scaling;
869         s->channel_residues[ich][icoef] += pred[ich];
870     }
871 }
872
873 static void revert_mclms(WmallDecodeCtx *s, int tile_size)
874 {
875     int icoef, pred[s->num_channels];
876     for (icoef = 0; icoef < tile_size; icoef++) {
877         mclms_predict(s, icoef, pred);
878         mclms_update(s, icoef, pred);
879     }
880 }
881
882 static int lms_predict(WmallDecodeCtx *s, int ich, int ilms)
883 {
884     int pred = 0;
885     int icoef;
886     int recent = s->cdlms[ich][ilms].recent;
887
888     for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
889         pred += s->cdlms[ich][ilms].coefs[icoef] *
890                     s->cdlms[ich][ilms].lms_prevvalues[icoef + recent];
891
892     //pred += (1 << (s->cdlms[ich][ilms].scaling - 1));
893     /* XXX: Table 29 has:
894             iPred >= cdlms[iCh][ilms].scaling;
895        seems to me like a missing > */
896     //pred >>= s->cdlms[ich][ilms].scaling;
897     return pred;
898 }
899
900 static void lms_update(WmallDecodeCtx *s, int ich, int ilms, int input, int residue)
901 {
902     int icoef;
903     int recent = s->cdlms[ich][ilms].recent;
904     int range = 1 << s->bits_per_sample - 1;
905     int bps = s->bits_per_sample > 16 ? 4 : 2; // bytes per sample
906
907     if (residue < 0) {
908         for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
909             s->cdlms[ich][ilms].coefs[icoef] -=
910                 s->cdlms[ich][ilms].lms_updates[icoef + recent];
911     } else if (residue > 0) {
912         for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
913             s->cdlms[ich][ilms].coefs[icoef] +=
914                 s->cdlms[ich][ilms].lms_updates[icoef + recent];    /* spec mistakenly
915                                                                     dropped the recent */
916     }
917
918     if (recent)
919         recent--;
920     else {
921         /* XXX: This memcpy()s will probably fail if a fixed 32-bit buffer is used.
922                 follow kshishkov's suggestion of using a union. */
923         memcpy(&s->cdlms[ich][ilms].lms_prevvalues[s->cdlms[ich][ilms].order],
924                s->cdlms[ich][ilms].lms_prevvalues,
925                bps * s->cdlms[ich][ilms].order);
926         memcpy(&s->cdlms[ich][ilms].lms_updates[s->cdlms[ich][ilms].order],
927                s->cdlms[ich][ilms].lms_updates,
928                bps * s->cdlms[ich][ilms].order);
929         recent = s->cdlms[ich][ilms].order - 1;
930     }
931
932     s->cdlms[ich][ilms].lms_prevvalues[recent] = av_clip(input, -range, range - 1);
933     if (!input)
934         s->cdlms[ich][ilms].lms_updates[recent] = 0;
935     else if (input < 0)
936         s->cdlms[ich][ilms].lms_updates[recent] = -s->update_speed[ich];
937     else
938         s->cdlms[ich][ilms].lms_updates[recent] = s->update_speed[ich];
939
940     /* XXX: spec says:
941     cdlms[iCh][ilms].updates[iRecent + cdlms[iCh][ilms].order >> 4] >>= 2;
942     lms_updates[iCh][ilms][iRecent + cdlms[iCh][ilms].order >> 3] >>= 1;
943
944         Questions is - are cdlms[iCh][ilms].updates[] and lms_updates[][][] two
945         seperate buffers? Here I've assumed that the two are same which makes
946         more sense to me.
947     */
948     s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 4)] >>= 2;
949     s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 3)] >>= 1;
950     s->cdlms[ich][ilms].recent = recent;
951 }
952
953 static void use_high_update_speed(WmallDecodeCtx *s, int ich)
954 {
955     int ilms, recent, icoef;
956     for (ilms = s->cdlms_ttl[ich] - 1; ilms >= 0; ilms--) {
957         recent = s->cdlms[ich][ilms].recent;
958         if (s->update_speed[ich] == 16)
959             continue;
960         if (s->bV3RTM) {
961             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
962                 s->cdlms[ich][ilms].lms_updates[icoef + recent] *= 2;
963         } else {
964             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
965                 s->cdlms[ich][ilms].lms_updates[icoef] *= 2;
966         }
967     }
968     s->update_speed[ich] = 16;
969 }
970
971 static void use_normal_update_speed(WmallDecodeCtx *s, int ich)
972 {
973     int ilms, recent, icoef;
974     for (ilms = s->cdlms_ttl[ich] - 1; ilms >= 0; ilms--) {
975         recent = s->cdlms[ich][ilms].recent;
976         if (s->update_speed[ich] == 8)
977             continue;
978         if (s->bV3RTM) {
979             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
980                 s->cdlms[ich][ilms].lms_updates[icoef + recent] /= 2;
981         } else {
982             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
983                 s->cdlms[ich][ilms].lms_updates[icoef] /= 2;
984         }
985     }
986     s->update_speed[ich] = 8;
987 }
988
989 static void revert_cdlms(WmallDecodeCtx *s, int ch, int coef_begin, int coef_end)
990 {
991     int icoef;
992     int pred;
993     int ilms, num_lms;
994     int residue, input;
995
996     num_lms = s->cdlms_ttl[ch];
997     for (ilms = num_lms - 1; ilms >= 0; ilms--) {
998         //s->cdlms[ch][ilms].recent = s->cdlms[ch][ilms].order;
999         for (icoef = coef_begin; icoef < coef_end; icoef++) {
1000             pred = 1 << (s->cdlms[ch][ilms].scaling - 1);
1001             residue = s->channel_residues[ch][icoef];
1002             pred += lms_predict(s, ch, ilms);
1003             input = residue + (pred >> s->cdlms[ch][ilms].scaling);
1004             lms_update(s, ch, ilms, input, residue);
1005             s->channel_residues[ch][icoef] = input;
1006         }
1007     }
1008 }
1009
1010 static void revert_inter_ch_decorr(WmallDecodeCtx *s, int tile_size)
1011 {
1012     int icoef;
1013     if (s->num_channels != 2)
1014         return;
1015     else {
1016         for (icoef = 0; icoef < tile_size; icoef++) {
1017             s->channel_residues[0][icoef] -= s->channel_residues[1][icoef] >> 1;
1018             s->channel_residues[1][icoef] += s->channel_residues[0][icoef];
1019         }
1020     }
1021 }
1022
1023 static void revert_acfilter(WmallDecodeCtx *s, int tile_size)
1024 {
1025     int ich, icoef;
1026     int pred = 0, itap;
1027     int **ch_coeffs = s->channel_residues;
1028     int *filter_coeffs = s->acfilter_coeffs;
1029     int *prevvalues = s->acfilter_prevvalues;
1030     int scaling = s->acfilter_scaling;
1031     int order = s->acfilter_order;
1032
1033     for (ich = 0; ich < s->num_channels; ich++) {
1034         for (icoef = 0; icoef < tile_size; icoef++) {
1035             for (itap = 0; itap < order; itap++)
1036                 pred += filter_coeffs[itap] * prevvalues[itap];
1037             pred >>= scaling;
1038             ch_coeffs[ich][icoef] += pred;
1039             for (itap = 1; itap < order; itap++)
1040                 prevvalues[itap] = prevvalues[itap - 1];
1041             prevvalues[0] = ch_coeffs[ich][icoef];
1042         }
1043     }
1044 }
1045
1046 /**
1047  *@brief Decode a single subframe (block).
1048  *@param s codec context
1049  *@return 0 on success, < 0 when decoding failed
1050  */
1051 static int decode_subframe(WmallDecodeCtx *s)
1052 {
1053     int offset = s->samples_per_frame;
1054     int subframe_len = s->samples_per_frame;
1055     int i, j;
1056     int total_samples   = s->samples_per_frame * s->num_channels;
1057     int rawpcm_tile;
1058     int padding_zeroes;
1059     int quant_stepsize = s->quant_stepsize;
1060
1061     s->subframe_offset = get_bits_count(&s->gb);
1062
1063     /** reset channel context and find the next block offset and size
1064         == the next block of the channel with the smallest number of
1065         decoded samples
1066     */
1067     for (i = 0; i < s->num_channels; i++) {
1068         s->channel[i].grouped = 0;
1069         if (offset > s->channel[i].decoded_samples) {
1070             offset = s->channel[i].decoded_samples;
1071             subframe_len =
1072                 s->channel[i].subframe_len[s->channel[i].cur_subframe];
1073         }
1074     }
1075
1076     /** get a list of all channels that contain the estimated block */
1077     s->channels_for_cur_subframe = 0;
1078     for (i = 0; i < s->num_channels; i++) {
1079         const int cur_subframe = s->channel[i].cur_subframe;
1080         /** substract already processed samples */
1081         total_samples -= s->channel[i].decoded_samples;
1082
1083         /** and count if there are multiple subframes that match our profile */
1084         if (offset == s->channel[i].decoded_samples &&
1085             subframe_len == s->channel[i].subframe_len[cur_subframe]) {
1086             total_samples -= s->channel[i].subframe_len[cur_subframe];
1087             s->channel[i].decoded_samples +=
1088                 s->channel[i].subframe_len[cur_subframe];
1089             s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
1090             ++s->channels_for_cur_subframe;
1091         }
1092     }
1093
1094     /** check if the frame will be complete after processing the
1095         estimated block */
1096     if (!total_samples)
1097         s->parsed_all_subframes = 1;
1098
1099
1100     s->seekable_tile = get_bits1(&s->gb);
1101     if(s->seekable_tile) {
1102         clear_codec_buffers(s);
1103
1104         s->do_arith_coding    = get_bits1(&s->gb);
1105         if(s->do_arith_coding) {
1106             dprintf(s->avctx, "do_arith_coding == 1");
1107             abort();
1108         }
1109         s->do_ac_filter       = get_bits1(&s->gb);
1110         s->do_inter_ch_decorr = get_bits1(&s->gb);
1111         s->do_mclms           = get_bits1(&s->gb);
1112
1113         if(s->do_ac_filter)
1114             decode_ac_filter(s);
1115
1116         if(s->do_mclms)
1117             decode_mclms(s);
1118
1119         decode_cdlms(s);
1120         s->movave_scaling = get_bits(&s->gb, 3);
1121         s->quant_stepsize = get_bits(&s->gb, 8) + 1;
1122
1123             reset_codec(s);
1124     }
1125
1126     rawpcm_tile = get_bits1(&s->gb);
1127
1128     for(i = 0; i < s->num_channels; i++) {
1129         s->is_channel_coded[i] = 1;
1130     }
1131
1132     if(!rawpcm_tile) {
1133
1134         for(i = 0; i < s->num_channels; i++) {
1135             s->is_channel_coded[i] = get_bits1(&s->gb);
1136         }
1137
1138         if(s->bV3RTM) {
1139             // LPC
1140             s->do_lpc = get_bits1(&s->gb);
1141             if(s->do_lpc) {
1142                 decode_lpc(s);
1143             }
1144         } else {
1145             s->do_lpc = 0;
1146         }
1147     }
1148
1149
1150     if(get_bits1(&s->gb)) {
1151         padding_zeroes = get_bits(&s->gb, 5);
1152     } else {
1153         padding_zeroes = 0;
1154     }
1155
1156     if(rawpcm_tile) {
1157
1158         int bits = s->bits_per_sample - padding_zeroes;
1159         dprintf(s->avctx, "RAWPCM %d bits per sample. total %d bits, remain=%d\n", bits,
1160                 bits * s->num_channels * subframe_len, get_bits_count(&s->gb));
1161         for(i = 0; i < s->num_channels; i++) {
1162             for(j = 0; j < subframe_len; j++) {
1163                 s->channel_coeffs[i][j] = get_sbits(&s->gb, bits);
1164 //                dprintf(s->avctx, "PCM[%d][%d] = 0x%04x\n", i, j, s->channel_coeffs[i][j]);
1165             }
1166         }
1167     } else {
1168         for(i = 0; i < s->num_channels; i++)
1169             if(s->is_channel_coded[i]) {
1170             decode_channel_residues(s, i, subframe_len);
1171             if (s->seekable_tile)
1172                 use_high_update_speed(s, i);
1173             else
1174                 use_normal_update_speed(s, i);
1175             revert_cdlms(s, i, 0, subframe_len);
1176         }
1177     }
1178     if (s->do_mclms)
1179         revert_mclms(s, subframe_len);
1180     if (s->do_inter_ch_decorr)
1181         revert_inter_ch_decorr(s, subframe_len);
1182     if(s->do_ac_filter)
1183         revert_acfilter(s, subframe_len);
1184
1185     /* Dequantize */
1186     for (i = 0; i < s->num_channels; i++)
1187         for (j = 0; j < subframe_len; j++)
1188             s->channel_residues[i][j] *= quant_stepsize;
1189
1190     /** handled one subframe */
1191
1192     for (i = 0; i < s->channels_for_cur_subframe; i++) {
1193         int c = s->channel_indexes_for_cur_subframe[i];
1194         if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
1195             av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
1196             return AVERROR_INVALIDDATA;
1197         }
1198         ++s->channel[c].cur_subframe;
1199     }
1200     num_logged_subframes++;
1201     return 0;
1202 }
1203
1204 /**
1205  *@brief Decode one WMA frame.
1206  *@param s codec context
1207  *@return 0 if the trailer bit indicates that this is the last frame,
1208  *        1 if there are additional frames
1209  */
1210 static int decode_frame(WmallDecodeCtx *s)
1211 {
1212     GetBitContext* gb = &s->gb;
1213     int more_frames = 0;
1214     int len = 0;
1215     int i;
1216
1217     /** check for potential output buffer overflow */
1218     if (s->num_channels * s->samples_per_frame > s->samples_end - s->samples) {
1219         /** return an error if no frame could be decoded at all */
1220         av_log(s->avctx, AV_LOG_ERROR,
1221                "not enough space for the output samples\n");
1222         s->packet_loss = 1;
1223         return 0;
1224     }
1225
1226     /** get frame length */
1227     if (s->len_prefix)
1228         len = get_bits(gb, s->log2_frame_size);
1229
1230     /** decode tile information */
1231     if (decode_tilehdr(s)) {
1232         s->packet_loss = 1;
1233         return 0;
1234     }
1235
1236     /** read drc info */
1237     if (s->dynamic_range_compression) {
1238         s->drc_gain = get_bits(gb, 8);
1239     }
1240
1241     /** no idea what these are for, might be the number of samples
1242         that need to be skipped at the beginning or end of a stream */
1243     if (get_bits1(gb)) {
1244         int skip;
1245
1246         /** usually true for the first frame */
1247         if (get_bits1(gb)) {
1248             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1249             dprintf(s->avctx, "start skip: %i\n", skip);
1250         }
1251
1252         /** sometimes true for the last frame */
1253         if (get_bits1(gb)) {
1254             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1255             dprintf(s->avctx, "end skip: %i\n", skip);
1256         }
1257
1258     }
1259
1260     /** reset subframe states */
1261     s->parsed_all_subframes = 0;
1262     for (i = 0; i < s->num_channels; i++) {
1263         s->channel[i].decoded_samples = 0;
1264         s->channel[i].cur_subframe    = 0;
1265         s->channel[i].reuse_sf        = 0;
1266     }
1267
1268     /** decode all subframes */
1269     while (!s->parsed_all_subframes) {
1270         if (decode_subframe(s) < 0) {
1271             s->packet_loss = 1;
1272             return 0;
1273         }
1274     }
1275
1276     dprintf(s->avctx, "Frame done\n");
1277
1278     if (s->skip_frame) {
1279         s->skip_frame = 0;
1280     } else
1281         s->samples += s->num_channels * s->samples_per_frame;
1282
1283     if (s->len_prefix) {
1284         if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
1285             /** FIXME: not sure if this is always an error */
1286             av_log(s->avctx, AV_LOG_ERROR,
1287                    "frame[%i] would have to skip %i bits\n", s->frame_num,
1288                    len - (get_bits_count(gb) - s->frame_offset) - 1);
1289             s->packet_loss = 1;
1290             return 0;
1291         }
1292
1293         /** skip the rest of the frame data */
1294         skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
1295     } else {
1296 /*
1297         while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
1298             dprintf(s->avctx, "skip1\n");
1299         }
1300 */
1301     }
1302
1303     /** decode trailer bit */
1304     more_frames = get_bits1(gb);
1305     ++s->frame_num;
1306     return more_frames;
1307 }
1308
1309 /**
1310  *@brief Calculate remaining input buffer length.
1311  *@param s codec context
1312  *@param gb bitstream reader context
1313  *@return remaining size in bits
1314  */
1315 static int remaining_bits(WmallDecodeCtx *s, GetBitContext *gb)
1316 {
1317     return s->buf_bit_size - get_bits_count(gb);
1318 }
1319
1320 /**
1321  *@brief Fill the bit reservoir with a (partial) frame.
1322  *@param s codec context
1323  *@param gb bitstream reader context
1324  *@param len length of the partial frame
1325  *@param append decides wether to reset the buffer or not
1326  */
1327 static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
1328                       int append)
1329 {
1330     int buflen;
1331
1332     /** when the frame data does not need to be concatenated, the input buffer
1333         is resetted and additional bits from the previous frame are copyed
1334         and skipped later so that a fast byte copy is possible */
1335
1336     if (!append) {
1337         s->frame_offset = get_bits_count(gb) & 7;
1338         s->num_saved_bits = s->frame_offset;
1339         init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
1340     }
1341
1342     buflen = (s->num_saved_bits + len + 8) >> 3;
1343
1344     if (len <= 0 || buflen > MAX_FRAMESIZE) {
1345         av_log_ask_for_sample(s->avctx, "input buffer too small\n");
1346         s->packet_loss = 1;
1347         return;
1348     }
1349
1350     s->num_saved_bits += len;
1351     if (!append) {
1352         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
1353                      s->num_saved_bits);
1354     } else {
1355         int align = 8 - (get_bits_count(gb) & 7);
1356         align = FFMIN(align, len);
1357         put_bits(&s->pb, align, get_bits(gb, align));
1358         len -= align;
1359         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
1360     }
1361     skip_bits_long(gb, len);
1362
1363     {
1364         PutBitContext tmp = s->pb;
1365         flush_put_bits(&tmp);
1366     }
1367
1368     init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
1369     skip_bits(&s->gb, s->frame_offset);
1370 }
1371
1372 /**
1373  *@brief Decode a single WMA packet.
1374  *@param avctx codec context
1375  *@param data the output buffer
1376  *@param data_size number of bytes that were written to the output buffer
1377  *@param avpkt input packet
1378  *@return number of bytes that were read from the input buffer
1379  */
1380 static int decode_packet(AVCodecContext *avctx,
1381                          void *data, int *data_size, AVPacket* avpkt)
1382 {
1383     WmallDecodeCtx *s = avctx->priv_data;
1384     GetBitContext* gb  = &s->pgb;
1385     const uint8_t* buf = avpkt->data;
1386     int buf_size       = avpkt->size;
1387     int num_bits_prev_frame;
1388     int packet_sequence_number;
1389
1390     s->samples       = data;
1391     s->samples_end   = (float*)((int8_t*)data + *data_size);
1392     *data_size = 0;
1393
1394     if (s->packet_done || s->packet_loss) {
1395         int seekable_frame_in_packet, spliced_packet;
1396         s->packet_done = 0;
1397
1398         /** sanity check for the buffer length */
1399         if (buf_size < avctx->block_align)
1400             return 0;
1401
1402         s->next_packet_start = buf_size - avctx->block_align;
1403         buf_size = avctx->block_align;
1404         s->buf_bit_size = buf_size << 3;
1405
1406         /** parse packet header */
1407         init_get_bits(gb, buf, s->buf_bit_size);
1408         packet_sequence_number = get_bits(gb, 4);
1409         seekable_frame_in_packet = get_bits1(gb);
1410         spliced_packet = get_bits1(gb);
1411
1412         /** get number of bits that need to be added to the previous frame */
1413         num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
1414
1415         /** check for packet loss */
1416         if (!s->packet_loss &&
1417             ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
1418             s->packet_loss = 1;
1419             av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",
1420                    s->packet_sequence_number, packet_sequence_number);
1421         }
1422         s->packet_sequence_number = packet_sequence_number;
1423
1424         if (num_bits_prev_frame > 0) {
1425             int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
1426             if (num_bits_prev_frame >= remaining_packet_bits) {
1427                 num_bits_prev_frame = remaining_packet_bits;
1428                 s->packet_done = 1;
1429             }
1430
1431             /** append the previous frame data to the remaining data from the
1432                 previous packet to create a full frame */
1433             save_bits(s, gb, num_bits_prev_frame, 1);
1434
1435             /** decode the cross packet frame if it is valid */
1436             if (!s->packet_loss)
1437                 decode_frame(s);
1438         } else if (s->num_saved_bits - s->frame_offset) {
1439             dprintf(avctx, "ignoring %x previously saved bits\n",
1440                     s->num_saved_bits - s->frame_offset);
1441         }
1442
1443         if (s->packet_loss) {
1444             /** reset number of saved bits so that the decoder
1445                 does not start to decode incomplete frames in the
1446                 s->len_prefix == 0 case */
1447             s->num_saved_bits = 0;
1448             s->packet_loss = 0;
1449         }
1450
1451     } else {
1452         int frame_size;
1453
1454         s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
1455         init_get_bits(gb, avpkt->data, s->buf_bit_size);
1456         skip_bits(gb, s->packet_offset);
1457
1458         if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
1459             (frame_size = show_bits(gb, s->log2_frame_size)) &&
1460             frame_size <= remaining_bits(s, gb)) {
1461             save_bits(s, gb, frame_size, 0);
1462             s->packet_done = !decode_frame(s);
1463         } else if (!s->len_prefix
1464                    && s->num_saved_bits > get_bits_count(&s->gb)) {
1465             /** when the frames do not have a length prefix, we don't know
1466                 the compressed length of the individual frames
1467                 however, we know what part of a new packet belongs to the
1468                 previous frame
1469                 therefore we save the incoming packet first, then we append
1470                 the "previous frame" data from the next packet so that
1471                 we get a buffer that only contains full frames */
1472             s->packet_done = !decode_frame(s);
1473         } else {
1474             s->packet_done = 1;
1475         }
1476     }
1477
1478     if (s->packet_done && !s->packet_loss &&
1479         remaining_bits(s, gb) > 0) {
1480         /** save the rest of the data so that it can be decoded
1481             with the next packet */
1482         save_bits(s, gb, remaining_bits(s, gb), 0);
1483     }
1484
1485     *data_size = 0; // (int8_t *)s->samples - (int8_t *)data;
1486     s->packet_offset = get_bits_count(gb) & 7;
1487
1488     return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
1489 }
1490
1491 /**
1492  *@brief Clear decoder buffers (for seeking).
1493  *@param avctx codec context
1494  */
1495 static void flush(AVCodecContext *avctx)
1496 {
1497     WmallDecodeCtx *s = avctx->priv_data;
1498     int i;
1499     /** reset output buffer as a part of it is used during the windowing of a
1500         new frame */
1501     for (i = 0; i < s->num_channels; i++)
1502         memset(s->channel[i].out, 0, s->samples_per_frame *
1503                sizeof(*s->channel[i].out));
1504     s->packet_loss = 1;
1505 }
1506
1507
1508 /**
1509  *@brief wmall decoder
1510  */
1511 AVCodec ff_wmalossless_decoder = {
1512     "wmalossless",
1513     AVMEDIA_TYPE_AUDIO,
1514     CODEC_ID_WMALOSSLESS,
1515     sizeof(WmallDecodeCtx),
1516     decode_init,
1517     NULL,
1518     decode_end,
1519     decode_packet,
1520     .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_EXPERIMENTAL,
1521     .flush= flush,
1522     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Lossless"),
1523 };