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