]> git.sesse.net Git - ffmpeg/blob - libavcodec/wmalosslessdec.c
vda: undef Picture.
[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 } WmallChannelCtx;
143
144                                                     /* XXX: probably we don't need subframe_config[],
145                                                     WmallChannelCtx holds all the necessary data. */
146
147 /**
148  * @brief channel group for channel transformations
149  */
150 typedef struct {
151     uint8_t num_channels;                                     ///< number of channels in the group
152     int8_t  transform;                                        ///< transform on / off
153     int8_t  transform_band[MAX_BANDS];                        ///< controls if the transform is enabled for a certain band
154     float   decorrelation_matrix[WMALL_MAX_CHANNELS*WMALL_MAX_CHANNELS];
155     float*  channel_data[WMALL_MAX_CHANNELS];                ///< transformation coefficients
156 } WmallChannelGrp;
157
158 /**
159  * @brief main decoder context
160  */
161 typedef struct WmallDecodeCtx {
162     /* generic decoder variables */
163     AVCodecContext*  avctx;                         ///< codec context for av_log
164     DSPContext       dsp;                           ///< accelerated DSP functions
165     uint8_t          frame_data[MAX_FRAMESIZE +
166                       FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
167     PutBitContext    pb;                            ///< context for filling the frame_data buffer
168     FFTContext       mdct_ctx[WMALL_BLOCK_SIZES];  ///< MDCT context per block size
169     DECLARE_ALIGNED(16, float, tmp)[WMALL_BLOCK_MAX_SIZE]; ///< IMDCT output buffer
170     float*           windows[WMALL_BLOCK_SIZES];   ///< windows for the different block sizes
171
172     /* frame size dependent frame information (set during initialization) */
173     uint32_t         decode_flags;                  ///< used compression features
174     uint8_t          len_prefix;                    ///< frame is prefixed with its length
175     uint8_t          dynamic_range_compression;     ///< frame contains DRC data
176     uint8_t          bits_per_sample;               ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
177     uint16_t         samples_per_frame;             ///< number of samples to output
178     uint16_t         log2_frame_size;
179     int8_t           num_channels;                  ///< number of channels in the stream (same as AVCodecContext.num_channels)
180     int8_t           lfe_channel;                   ///< lfe channel index
181     uint8_t          max_num_subframes;
182     uint8_t          subframe_len_bits;             ///< number of bits used for the subframe length
183     uint8_t          max_subframe_len_bit;          ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
184     uint16_t         min_samples_per_subframe;
185     int8_t           num_sfb[WMALL_BLOCK_SIZES];   ///< scale factor bands per block size
186     int16_t          sfb_offsets[WMALL_BLOCK_SIZES][MAX_BANDS];                    ///< scale factor band offsets (multiples of 4)
187     int8_t           sf_offsets[WMALL_BLOCK_SIZES][WMALL_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
188     int16_t          subwoofer_cutoffs[WMALL_BLOCK_SIZES]; ///< subwoofer cutoff values
189
190     /* packet decode state */
191     GetBitContext    pgb;                           ///< bitstream reader context for the packet
192     int              next_packet_start;             ///< start offset of the next wma packet in the demuxer packet
193     uint8_t          packet_offset;                 ///< frame offset in the packet
194     uint8_t          packet_sequence_number;        ///< current packet number
195     int              num_saved_bits;                ///< saved number of bits
196     int              frame_offset;                  ///< frame offset in the bit reservoir
197     int              subframe_offset;               ///< subframe offset in the bit reservoir
198     uint8_t          packet_loss;                   ///< set in case of bitstream error
199     uint8_t          packet_done;                   ///< set when a packet is fully decoded
200
201     /* frame decode state */
202     uint32_t         frame_num;                     ///< current frame number (not used for decoding)
203     GetBitContext    gb;                            ///< bitstream reader context
204     int              buf_bit_size;                  ///< buffer size in bits
205     float*           samples;                       ///< current samplebuffer pointer
206     float*           samples_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     int acfilter_coeffs[16];
237
238     int8_t mclms_order;
239     int8_t mclms_scaling;
240     int16_t mclms_coeffs[128];
241     int16_t mclms_coeffs_cur[4];
242     int mclms_prevvalues[64];   // FIXME: should be 32-bit / 16-bit depending on bit-depth
243     int16_t mclms_updates[64];
244     int mclms_recent;
245
246     int movave_scaling;
247     int quant_stepsize;
248
249     struct {
250         int order;
251         int scaling;
252         int coefsend;
253         int bitsend;
254         int16_t coefs[256];
255     int lms_prevvalues[512];    // FIXME: see above
256     int16_t lms_updates[512];   // and here too
257     int recent;
258     } cdlms[2][9];              /* XXX: Here, 2 is the max. no. of channels allowed,
259                                         9 is the maximum no. of filters per channel.
260                                         Question is, why 2 if WMALL_MAX_CHANNELS == 8 */
261
262
263     int cdlms_ttl[2];
264
265     int bV3RTM;
266
267     int is_channel_coded[2];    // XXX: same question as above applies here too (and below)
268     int update_speed[2];
269
270     int transient[2];
271     int transient_pos[2];
272     int seekable_tile;
273
274     int ave_sum[2];
275
276     int channel_residues[2][2048];
277
278
279     int lpc_coefs[2][40];
280     int lpc_order;
281     int lpc_scaling;
282     int lpc_intbits;
283
284     int channel_coeffs[2][2048];
285
286 } WmallDecodeCtx;
287
288
289 #undef dprintf
290 #define dprintf(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
291
292
293 static int num_logged_tiles = 0;
294
295 /**
296  *@brief helper function to print the most important members of the context
297  *@param s context
298  */
299 static void av_cold dump_context(WmallDecodeCtx *s)
300 {
301 #define PRINT(a, b)     av_log(s->avctx, AV_LOG_DEBUG, " %s = %d\n", a, b);
302 #define PRINT_HEX(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %x\n", a, b);
303
304     PRINT("ed sample bit depth", s->bits_per_sample);
305     PRINT_HEX("ed decode flags", s->decode_flags);
306     PRINT("samples per frame",   s->samples_per_frame);
307     PRINT("log2 frame size",     s->log2_frame_size);
308     PRINT("max num subframes",   s->max_num_subframes);
309     PRINT("len prefix",          s->len_prefix);
310     PRINT("num channels",        s->num_channels);
311 }
312
313 /**
314  *@brief Uninitialize the decoder and free all resources.
315  *@param avctx codec context
316  *@return 0 on success, < 0 otherwise
317  */
318 static av_cold int decode_end(AVCodecContext *avctx)
319 {
320     WmallDecodeCtx *s = avctx->priv_data;
321     int i;
322
323     for (i = 0; i < WMALL_BLOCK_SIZES; i++)
324         ff_mdct_end(&s->mdct_ctx[i]);
325
326     return 0;
327 }
328
329 /**
330  *@brief Initialize the decoder.
331  *@param avctx codec context
332  *@return 0 on success, -1 otherwise
333  */
334 static av_cold int decode_init(AVCodecContext *avctx)
335 {
336     WmallDecodeCtx *s = avctx->priv_data;
337     uint8_t *edata_ptr = avctx->extradata;
338     unsigned int channel_mask;
339     int i;
340     int log2_max_num_subframes;
341     int num_possible_block_sizes;
342
343     s->avctx = avctx;
344     dsputil_init(&s->dsp, avctx);
345     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
346
347     avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
348
349     if (avctx->extradata_size >= 18) {
350         s->decode_flags    = AV_RL16(edata_ptr+14);
351         channel_mask       = AV_RL32(edata_ptr+2);
352         s->bits_per_sample = AV_RL16(edata_ptr);
353         /** dump the extradata */
354         for (i = 0; i < avctx->extradata_size; i++)
355             dprintf(avctx, "[%x] ", avctx->extradata[i]);
356         dprintf(avctx, "\n");
357
358     } else {
359         av_log_ask_for_sample(avctx, "Unknown extradata size\n");
360         return AVERROR_INVALIDDATA;
361     }
362
363     /** generic init */
364     s->log2_frame_size = av_log2(avctx->block_align) + 4;
365
366     /** frame info */
367     s->skip_frame  = 1; /* skip first frame */
368     s->packet_loss = 1;
369     s->len_prefix  = (s->decode_flags & 0x40);
370
371     /** get frame len */
372     s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
373                                                           3, s->decode_flags);
374
375     /** init previous block len */
376     for (i = 0; i < avctx->channels; i++)
377         s->channel[i].prev_block_len = s->samples_per_frame;
378
379     /** subframe info */
380     log2_max_num_subframes  = ((s->decode_flags & 0x38) >> 3);
381     s->max_num_subframes    = 1 << log2_max_num_subframes;
382     s->max_subframe_len_bit = 0;
383     s->subframe_len_bits    = av_log2(log2_max_num_subframes) + 1;
384
385     num_possible_block_sizes     = log2_max_num_subframes + 1;
386     s->min_samples_per_subframe  = s->samples_per_frame / s->max_num_subframes;
387     s->dynamic_range_compression = (s->decode_flags & 0x80);
388
389     s->bV3RTM = s->decode_flags & 0x100;
390
391     if (s->max_num_subframes > MAX_SUBFRAMES) {
392         av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %i\n",
393                s->max_num_subframes);
394         return AVERROR_INVALIDDATA;
395     }
396
397     s->num_channels = avctx->channels;
398
399     /** extract lfe channel position */
400     s->lfe_channel = -1;
401
402     if (channel_mask & 8) {
403         unsigned int mask;
404         for (mask = 1; mask < 16; mask <<= 1) {
405             if (channel_mask & mask)
406                 ++s->lfe_channel;
407         }
408     }
409
410     if (s->num_channels < 0) {
411         av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n", s->num_channels);
412         return AVERROR_INVALIDDATA;
413     } else if (s->num_channels > WMALL_MAX_CHANNELS) {
414         av_log_ask_for_sample(avctx, "unsupported number of channels\n");
415         return AVERROR_PATCHWELCOME;
416     }
417
418     avctx->channel_layout = channel_mask;
419     return 0;
420 }
421
422 /**
423  *@brief Decode the subframe length.
424  *@param s context
425  *@param offset sample offset in the frame
426  *@return decoded subframe length on success, < 0 in case of an error
427  */
428 static int decode_subframe_length(WmallDecodeCtx *s, int offset)
429 {
430     int frame_len_ratio;
431     int subframe_len, len;
432
433     /** no need to read from the bitstream when only one length is possible */
434     if (offset == s->samples_per_frame - s->min_samples_per_subframe)
435         return s->min_samples_per_subframe;
436
437     len = av_log2(s->max_num_subframes - 1) + 1;    // XXX: 5.3.3
438     frame_len_ratio = get_bits(&s->gb, len);        // XXX: tile_size_ratio
439
440     subframe_len = s->min_samples_per_subframe * (frame_len_ratio + 1);
441
442     /** sanity check the length */
443     if (subframe_len < s->min_samples_per_subframe ||
444         subframe_len > s->samples_per_frame) {
445         av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
446                subframe_len);
447         return AVERROR_INVALIDDATA;
448     }
449     return subframe_len;
450 }
451
452 /**
453  *@brief Decode how the data in the frame is split into subframes.
454  *       Every WMA frame contains the encoded data for a fixed number of
455  *       samples per channel. The data for every channel might be split
456  *       into several subframes. This function will reconstruct the list of
457  *       subframes for every channel.
458  *
459  *       If the subframes are not evenly split, the algorithm estimates the
460  *       channels with the lowest number of total samples.
461  *       Afterwards, for each of these channels a bit is read from the
462  *       bitstream that indicates if the channel contains a subframe with the
463  *       next subframe size that is going to be read from the bitstream or not.
464  *       If a channel contains such a subframe, the subframe size gets added to
465  *       the channel's subframe list.
466  *       The algorithm repeats these steps until the frame is properly divided
467  *       between the individual channels.
468  *
469  *@param s context
470  *@return 0 on success, < 0 in case of an error
471  */
472 static int decode_tilehdr(WmallDecodeCtx *s)        /* XXX: decode_tile_configuration() [Table 9] */
473 {
474     uint16_t num_samples[WMALL_MAX_CHANNELS];        /**< sum of samples for all currently known subframes of a channel */
475     uint8_t  contains_subframe[WMALL_MAX_CHANNELS];  /**< flag indicating if a channel contains the current subframe */
476     int channels_for_cur_subframe = s->num_channels;  /**< number of channels that contain the current subframe */
477     int fixed_channel_layout = 0;                     /**< flag indicating that all channels use the same subfra2me offsets and sizes */
478     int min_channel_len = 0;                          /**< smallest sum of samples (channels with this length will be processed first) */
479     int c;
480
481     /* Should never consume more than 3073 bits (256 iterations for the
482      * while loop when always the minimum amount of 128 samples is substracted
483      * from missing samples in the 8 channel case).
484      * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS  + 4)
485      */
486
487     /** reset tiling information */
488     for (c = 0; c < s->num_channels; c++)
489         s->channel[c].num_subframes = 0;
490
491     memset(num_samples, 0, sizeof(num_samples));
492
493     if (s->max_num_subframes == 1 || get_bits1(&s->gb))     // XXX: locate in the spec
494         fixed_channel_layout = 1;                           // XXX: tile_aligned ?
495
496     /** loop until the frame data is split between the subframes */
497     do {
498         int subframe_len;
499
500         /** check which channels contain the subframe */
501         for (c = 0; c < s->num_channels; c++) {
502             if (num_samples[c] == min_channel_len) {
503                 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
504                     (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe)) {
505                     contains_subframe[c] = 1;
506                 }
507                 else {
508                     contains_subframe[c] = get_bits1(&s->gb);   // XXX: locate in the spec
509                 }
510             } else
511                 contains_subframe[c] = 0;
512         }
513
514         /** get subframe length, subframe_len == 0 is not allowed */
515         if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)   //XXX: this reads tile_size_ratio
516             return AVERROR_INVALIDDATA;
517         /** add subframes to the individual channels and find new min_channel_len */
518         min_channel_len += subframe_len;
519         for (c = 0; c < s->num_channels; c++) {
520             WmallChannelCtx* chan = &s->channel[c];
521
522             if (contains_subframe[c]) {
523                 if (chan->num_subframes >= MAX_SUBFRAMES) {
524                     av_log(s->avctx, AV_LOG_ERROR,
525                            "broken frame: num subframes > 31\n");
526                     return AVERROR_INVALIDDATA;
527                 }
528                 chan->subframe_len[chan->num_subframes] = subframe_len;
529                 num_samples[c] += subframe_len;
530                 ++chan->num_subframes;
531                 if (num_samples[c] > s->samples_per_frame) {
532                     av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
533                            "channel len(%d) > samples_per_frame(%d)\n",
534                            num_samples[c], s->samples_per_frame);
535                     return AVERROR_INVALIDDATA;
536                 }
537             } else if (num_samples[c] <= min_channel_len) {
538                 if (num_samples[c] < min_channel_len) {
539                     channels_for_cur_subframe = 0;
540                     min_channel_len = num_samples[c];
541                 }
542                 ++channels_for_cur_subframe;
543             }
544         }
545     } while (min_channel_len < s->samples_per_frame);
546
547     for (c = 0; c < s->num_channels; c++) {
548         int i;
549         int offset = 0;
550         for (i = 0; i < s->channel[c].num_subframes; i++) {
551             s->channel[c].subframe_offset[i] = offset;
552             offset += s->channel[c].subframe_len[i];
553         }
554     }
555
556     return 0;
557 }
558
559
560 static int my_log2(unsigned int i)
561 {
562     unsigned int iLog2 = 0;
563     while ((i >> iLog2) > 1)
564         iLog2++;
565     return iLog2;
566 }
567
568
569 /**
570  *
571  */
572 static void decode_ac_filter(WmallDecodeCtx *s)
573 {
574     int i;
575     s->acfilter_order = get_bits(&s->gb, 4) + 1;
576     s->acfilter_scaling = get_bits(&s->gb, 4);
577
578     for(i = 0; i < s->acfilter_order; i++) {
579         s->acfilter_coeffs[i] = get_bits(&s->gb, s->acfilter_scaling) + 1;
580     }
581 }
582
583
584 /**
585  *
586  */
587 static void decode_mclms(WmallDecodeCtx *s)
588 {
589     s->mclms_order = (get_bits(&s->gb, 4) + 1) * 2;
590     s->mclms_scaling = get_bits(&s->gb, 4);
591     if(get_bits1(&s->gb)) {
592         // mclms_send_coef
593         int i;
594         int send_coef_bits;
595         int cbits = av_log2(s->mclms_scaling + 1);
596         assert(cbits == my_log2(s->mclms_scaling + 1));
597         if(1 << cbits < s->mclms_scaling + 1)
598             cbits++;
599
600         send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2;
601
602         for(i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++) {
603             s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits);
604         }
605
606         for(i = 0; i < s->num_channels; i++) {
607             int c;
608             for(c = 0; c < i; c++) {
609                 s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits);
610             }
611         }
612     }
613 }
614
615
616 /**
617  *
618  */
619 static void decode_cdlms(WmallDecodeCtx *s)
620 {
621     int c, i;
622     int cdlms_send_coef = get_bits1(&s->gb);
623
624     for(c = 0; c < s->num_channels; c++) {
625         s->cdlms_ttl[c] = get_bits(&s->gb, 3) + 1;
626         for(i = 0; i < s->cdlms_ttl[c]; i++) {
627             s->cdlms[c][i].order = (get_bits(&s->gb, 7) + 1) * 8;
628         }
629
630         for(i = 0; i < s->cdlms_ttl[c]; i++) {
631             s->cdlms[c][i].scaling = get_bits(&s->gb, 4);
632         }
633
634         if(cdlms_send_coef) {
635             for(i = 0; i < s->cdlms_ttl[c]; i++) {
636                 int cbits, shift_l, shift_r, j;
637                 cbits = av_log2(s->cdlms[c][i].order);
638                 if(1 << cbits < s->cdlms[c][i].order)
639                     cbits++;
640                 s->cdlms[c][i].coefsend = get_bits(&s->gb, cbits) + 1;
641
642                 cbits = av_log2(s->cdlms[c][i].scaling + 1);
643                 if(1 << cbits < s->cdlms[c][i].scaling + 1)
644                     cbits++;
645
646                 s->cdlms[c][i].bitsend = get_bits(&s->gb, cbits) + 2;
647                 shift_l = 32 - s->cdlms[c][i].bitsend;
648                 shift_r = 32 - 2 - s->cdlms[c][i].scaling;
649                 for(j = 0; j < s->cdlms[c][i].coefsend; j++) {
650                     s->cdlms[c][i].coefs[j] =
651                         (get_bits(&s->gb, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;
652                 }
653             }
654         }
655     }
656 }
657
658 /**
659  *
660  */
661 static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
662 {
663     int i = 0;
664     unsigned int ave_mean;
665     s->transient[ch] = get_bits1(&s->gb);
666     if(s->transient[ch])
667         s->transient_pos[ch] = get_bits(&s->gb, av_log2(tile_size));
668
669     if(s->seekable_tile) {
670         ave_mean = get_bits(&s->gb, s->bits_per_sample);
671         s->ave_sum[ch] = ave_mean << (s->movave_scaling + 1);
672 //        s->ave_sum[ch] *= 2;
673     }
674
675     if(s->seekable_tile) {
676         if(s->do_inter_ch_decorr)
677             s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample + 1);
678         else
679             s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample);
680         i++;
681     }
682     av_log(0, 0, "%8d: ", num_logged_tiles++);
683     for(; i < tile_size; i++) {
684         int quo = 0, rem, rem_bits, residue;
685         while(get_bits1(&s->gb))
686             quo++;
687         if(quo >= 32)
688             quo += get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1);
689
690                ave_mean = (s->ave_sum[ch] + (1 << s->movave_scaling)) >> (s->movave_scaling + 1);
691         rem_bits = av_ceil_log2(ave_mean);
692         rem = rem_bits ? get_bits(&s->gb, rem_bits) : 0;
693         residue = (quo << rem_bits) + rem;
694
695         s->ave_sum[ch] = residue + s->ave_sum[ch] - (s->ave_sum[ch] >> s->movave_scaling);
696
697         if(residue & 1)
698             residue = -(residue >> 1) - 1;
699         else
700             residue = residue >> 1;
701         s->channel_residues[ch][i] = residue;
702
703     //if (num_logged_tiles < 1)
704         av_log(0, 0, "%4d ", residue);
705 //        dprintf(s->avctx, "%5d: %5d %10d %12d %12d %5d %-16d %04x\n",i, quo, ave_mean, s->ave_sum[ch], rem, rem_bits, s->channel_residues[ch][i], show_bits(&s->gb, 16));
706     }
707     av_log(0, 0, "\n Tile size = %d\n", tile_size);
708
709     return 0;
710
711 }
712
713
714 /**
715  *
716  */
717 static void
718 decode_lpc(WmallDecodeCtx *s)
719 {
720     int ch, i, cbits;
721     s->lpc_order = get_bits(&s->gb, 5) + 1;
722     s->lpc_scaling = get_bits(&s->gb, 4);
723     s->lpc_intbits = get_bits(&s->gb, 3) + 1;
724     cbits = s->lpc_scaling + s->lpc_intbits;
725     for(ch = 0; ch < s->num_channels; ch++) {
726         for(i = 0; i < s->lpc_order; i++) {
727             s->lpc_coefs[ch][i] = get_sbits(&s->gb, cbits);
728         }
729     }
730 }
731
732
733 static void clear_codec_buffers(WmallDecodeCtx *s)
734 {
735     int ich, ilms;
736
737     memset(s->acfilter_coeffs, 0,     16 * sizeof(int));
738     memset(s->lpc_coefs      , 0, 40 * 2 * sizeof(int));
739
740     memset(s->mclms_coeffs    , 0, 128 * sizeof(int16_t));
741     memset(s->mclms_coeffs_cur, 0,   4 * sizeof(int16_t));
742     memset(s->mclms_prevvalues, 0,  64 * sizeof(int));
743     memset(s->mclms_updates   , 0,  64 * sizeof(int16_t));
744
745     for (ich = 0; ich < s->num_channels; ich++) {
746         for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++) {
747             memset(s->cdlms[ich][ilms].coefs         , 0, 256 * sizeof(int16_t));
748             memset(s->cdlms[ich][ilms].lms_prevvalues, 0, 512 * sizeof(int));
749             memset(s->cdlms[ich][ilms].lms_updates   , 0, 512 * sizeof(int16_t));
750         }
751         s->ave_sum[ich] = 0;
752     }
753 }
754
755 static void reset_codec(WmallDecodeCtx *s)
756 {
757     int ich, ilms;
758     s->mclms_recent = s->mclms_order * s->num_channels;
759     for (ich = 0; ich < s->num_channels; ich++)
760         for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++)
761             s->cdlms[ich][ilms].recent = s->cdlms[ich][ilms].order;
762 }
763
764
765
766 static int lms_predict(WmallDecodeCtx *s, int ich, int ilms)
767 {
768     int32_t pred, icoef;
769     int recent = s->cdlms[ich][ilms].recent;
770
771     for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
772         pred += s->cdlms[ich][ilms].coefs[icoef] *
773                     s->cdlms[ich][ilms].lms_prevvalues[icoef + recent];
774
775     pred += (1 << (s->cdlms[ich][ilms].scaling - 1));
776     /* XXX: Table 29 has:
777             iPred >= cdlms[iCh][ilms].scaling;
778        seems to me like a missing > */
779     pred >>= s->cdlms[ich][ilms].scaling;
780     return pred;
781 }
782
783 static void lms_update(WmallDecodeCtx *s, int ich, int ilms, int32_t input, int32_t pred)
784 {
785     int icoef;
786     int recent = s->cdlms[ich][ilms].recent;
787     int range = 1 << (s->bits_per_sample - 1);
788     int bps = s->bits_per_sample > 16 ? 4 : 2; // bytes per sample
789
790     if (input > pred) {
791         for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
792             s->cdlms[ich][ilms].coefs[icoef] +=
793                 s->cdlms[ich][ilms].lms_updates[icoef + recent];
794     } else {
795         for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
796             s->cdlms[ich][ilms].coefs[icoef] -=
797                 s->cdlms[ich][ilms].lms_updates[icoef];     // XXX: [icoef + recent] ?
798     }
799     s->cdlms[ich][ilms].recent--;
800     s->cdlms[ich][ilms].lms_prevvalues[recent] = av_clip(input, -range, range - 1);
801
802     if (input > pred)
803         s->cdlms[ich][ilms].lms_updates[recent] = s->update_speed[ich];
804     else if (input < pred)
805         s->cdlms[ich][ilms].lms_updates[recent] = -s->update_speed[ich];
806
807     /* XXX: spec says:
808     cdlms[iCh][ilms].updates[iRecent + cdlms[iCh][ilms].order >> 4] >>= 2;
809     lms_updates[iCh][ilms][iRecent + cdlms[iCh][ilms].order >> 3] >>= 1;
810
811         Questions is - are cdlms[iCh][ilms].updates[] and lms_updates[][][] two
812         seperate buffers? Here I've assumed that the two are same which makes
813         more sense to me.
814     */
815     s->cdlms[ich][ilms].lms_updates[recent + s->cdlms[ich][ilms].order >> 4] >>= 2;
816     s->cdlms[ich][ilms].lms_updates[recent + s->cdlms[ich][ilms].order >> 3] >>= 1;
817     /* XXX: recent + (s->cdlms[ich][ilms].order >> 4) ? */
818
819     if (s->cdlms[ich][ilms].recent == 0) {
820         /* XXX: This memcpy()s will probably fail if a fixed 32-bit buffer is used.
821                 follow kshishkov's suggestion of using a union. */
822         memcpy(s->cdlms[ich][ilms].lms_prevvalues + s->cdlms[ich][ilms].order,
823                s->cdlms[ich][ilms].lms_prevvalues,
824                bps * s->cdlms[ich][ilms].order);
825         memcpy(s->cdlms[ich][ilms].lms_updates + s->cdlms[ich][ilms].order,
826                s->cdlms[ich][ilms].lms_updates,
827                bps * s->cdlms[ich][ilms].order);
828         s->cdlms[ich][ilms].recent = s->cdlms[ich][ilms].order;
829     }
830 }
831
832 static void use_high_update_speed(WmallDecodeCtx *s, int ich)
833 {
834     int ilms, recent, icoef;
835     s->update_speed[ich] = 16;
836     for (ilms = s->cdlms_ttl[ich]; ilms >= 0; ilms--) {
837         recent = s->cdlms[ich][ilms].recent;
838         if (s->bV3RTM) {
839             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
840                 s->cdlms[ich][ilms].lms_updates[icoef + recent] *= 2;
841         } else {
842             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
843                 s->cdlms[ich][ilms].lms_updates[icoef] *= 2;
844         }
845     }
846 }
847
848 static void use_normal_update_speed(WmallDecodeCtx *s, int ich)
849 {
850     int ilms, recent, icoef;
851     s->update_speed[ich] = 8;
852     for (ilms = s->cdlms_ttl[ich]; ilms >= 0; ilms--) {
853         recent = s->cdlms[ich][ilms].recent;
854         if (s->bV3RTM) {
855             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
856                 s->cdlms[ich][ilms].lms_updates[icoef + recent] /= 2;
857         } else {
858             for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
859                 s->cdlms[ich][ilms].lms_updates[icoef] /= 2;
860         }
861     }
862 }
863
864 /**
865  *@brief Decode a single subframe (block).
866  *@param s codec context
867  *@return 0 on success, < 0 when decoding failed
868  */
869 static int decode_subframe(WmallDecodeCtx *s)
870 {
871     int offset = s->samples_per_frame;
872     int subframe_len = s->samples_per_frame;
873     int i;
874     int total_samples   = s->samples_per_frame * s->num_channels;
875     int rawpcm_tile;
876     int padding_zeroes;
877
878     s->subframe_offset = get_bits_count(&s->gb);
879
880     /** reset channel context and find the next block offset and size
881         == the next block of the channel with the smallest number of
882         decoded samples
883     */
884     for (i = 0; i < s->num_channels; i++) {
885         s->channel[i].grouped = 0;
886         if (offset > s->channel[i].decoded_samples) {
887             offset = s->channel[i].decoded_samples;
888             subframe_len =
889                 s->channel[i].subframe_len[s->channel[i].cur_subframe];
890         }
891     }
892
893     /** get a list of all channels that contain the estimated block */
894     s->channels_for_cur_subframe = 0;
895     for (i = 0; i < s->num_channels; i++) {
896         const int cur_subframe = s->channel[i].cur_subframe;
897         /** substract already processed samples */
898         total_samples -= s->channel[i].decoded_samples;
899
900         /** and count if there are multiple subframes that match our profile */
901         if (offset == s->channel[i].decoded_samples &&
902             subframe_len == s->channel[i].subframe_len[cur_subframe]) {
903             total_samples -= s->channel[i].subframe_len[cur_subframe];
904             s->channel[i].decoded_samples +=
905                 s->channel[i].subframe_len[cur_subframe];
906             s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
907             ++s->channels_for_cur_subframe;
908         }
909     }
910
911     /** check if the frame will be complete after processing the
912         estimated block */
913     if (!total_samples)
914         s->parsed_all_subframes = 1;
915
916
917     s->seekable_tile = get_bits1(&s->gb);
918     if(s->seekable_tile) {
919         clear_codec_buffers(s);
920
921         s->do_arith_coding    = get_bits1(&s->gb);
922         if(s->do_arith_coding) {
923             dprintf(s->avctx, "do_arith_coding == 1");
924             abort();
925         }
926         s->do_ac_filter       = get_bits1(&s->gb);
927         s->do_inter_ch_decorr = get_bits1(&s->gb);
928         s->do_mclms           = get_bits1(&s->gb);
929
930         if(s->do_ac_filter)
931             decode_ac_filter(s);
932
933         if(s->do_mclms)
934             decode_mclms(s);
935
936         decode_cdlms(s);
937         s->movave_scaling = get_bits(&s->gb, 3);
938         s->quant_stepsize = get_bits(&s->gb, 8) + 1;
939
940             reset_codec(s);
941     }
942
943     rawpcm_tile = get_bits1(&s->gb);
944
945     for(i = 0; i < s->num_channels; i++) {
946         s->is_channel_coded[i] = 1;
947     }
948
949     if(!rawpcm_tile) {
950
951         for(i = 0; i < s->num_channels; i++) {
952             s->is_channel_coded[i] = get_bits1(&s->gb);
953         }
954
955         if(s->bV3RTM) {
956             // LPC
957             s->do_lpc = get_bits1(&s->gb);
958             if(s->do_lpc) {
959                 decode_lpc(s);
960             }
961         } else {
962             s->do_lpc = 0;
963         }
964     }
965
966
967     if(get_bits1(&s->gb)) {
968         padding_zeroes = get_bits(&s->gb, 5);
969     } else {
970         padding_zeroes = 0;
971     }
972
973     if(rawpcm_tile) {
974
975         int bits = s->bits_per_sample - padding_zeroes;
976         int j;
977         dprintf(s->avctx, "RAWPCM %d bits per sample. total %d bits, remain=%d\n", bits,
978                 bits * s->num_channels * subframe_len, get_bits_count(&s->gb));
979         for(i = 0; i < s->num_channels; i++) {
980             for(j = 0; j < subframe_len; j++) {
981                 s->channel_coeffs[i][j] = get_sbits(&s->gb, bits);
982 //                dprintf(s->avctx, "PCM[%d][%d] = 0x%04x\n", i, j, s->channel_coeffs[i][j]);
983             }
984         }
985     } else {
986         for(i = 0; i < s->num_channels; i++)
987             if(s->is_channel_coded[i])
988                 decode_channel_residues(s, i, subframe_len);
989     }
990
991     /** handled one subframe */
992
993     for (i = 0; i < s->channels_for_cur_subframe; i++) {
994         int c = s->channel_indexes_for_cur_subframe[i];
995         if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
996             av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
997             return AVERROR_INVALIDDATA;
998         }
999         ++s->channel[c].cur_subframe;       // XXX: 6.4
1000     }
1001     return 0;
1002 }
1003
1004 /**
1005  *@brief Decode one WMA frame.
1006  *@param s codec context
1007  *@return 0 if the trailer bit indicates that this is the last frame,
1008  *        1 if there are additional frames
1009  */
1010 static int decode_frame(WmallDecodeCtx *s)
1011 {
1012     GetBitContext* gb = &s->gb;
1013     int more_frames = 0;
1014     int len = 0;
1015     int i;
1016
1017     /** check for potential output buffer overflow */
1018     if (s->num_channels * s->samples_per_frame > s->samples_end - s->samples) {
1019         /** return an error if no frame could be decoded at all */
1020         av_log(s->avctx, AV_LOG_ERROR,
1021                "not enough space for the output samples\n");
1022         s->packet_loss = 1;
1023         return 0;
1024     }
1025
1026     /** get frame length */
1027     if (s->len_prefix)
1028         len = get_bits(gb, s->log2_frame_size);     // XXX: compressed_frame_size_bits [Table 8]
1029
1030     /** decode tile information */
1031     if (decode_tilehdr(s)) {    // should include decode_tile_configuration() [Table 9]
1032         s->packet_loss = 1;
1033         return 0;
1034     }
1035
1036     /** read drc info */
1037     if (s->dynamic_range_compression) {
1038         s->drc_gain = get_bits(gb, 8);      // XXX: drc_frame_scale_factor [Table 8]
1039     }
1040
1041     /** no idea what these are for, might be the number of samples
1042         that need to be skipped at the beginning or end of a stream */
1043     if (get_bits1(gb)) {
1044         int skip;
1045
1046         /** usually true for the first frame */
1047         if (get_bits1(gb)) {
1048             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1049             dprintf(s->avctx, "start skip: %i\n", skip);
1050         }
1051
1052         /** sometimes true for the last frame */
1053         if (get_bits1(gb)) {
1054             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1055             dprintf(s->avctx, "end skip: %i\n", skip);
1056         }
1057
1058     }
1059
1060     /** reset subframe states */
1061     s->parsed_all_subframes = 0;
1062     for (i = 0; i < s->num_channels; i++) {
1063         s->channel[i].decoded_samples = 0;
1064         s->channel[i].cur_subframe    = 0;
1065         s->channel[i].reuse_sf        = 0;
1066     }
1067
1068     /** decode all subframes */
1069     while (!s->parsed_all_subframes) {
1070         if (decode_subframe(s) < 0) {
1071             s->packet_loss = 1;
1072             return 0;
1073         }
1074     }
1075
1076     dprintf(s->avctx, "Frame done\n");
1077
1078     if (s->skip_frame) {
1079         s->skip_frame = 0;
1080     } else
1081         s->samples += s->num_channels * s->samples_per_frame;
1082
1083     if (s->len_prefix) {
1084         if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
1085             /** FIXME: not sure if this is always an error */
1086             av_log(s->avctx, AV_LOG_ERROR,
1087                    "frame[%i] would have to skip %i bits\n", s->frame_num,
1088                    len - (get_bits_count(gb) - s->frame_offset) - 1);
1089             s->packet_loss = 1;
1090             return 0;
1091         }
1092
1093         /** skip the rest of the frame data */
1094         skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
1095     } else {
1096 /*
1097         while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
1098             dprintf(s->avctx, "skip1\n");
1099         }
1100 */
1101     }
1102
1103     /** decode trailer bit */
1104     more_frames = get_bits1(gb);
1105     ++s->frame_num;
1106     return more_frames;
1107 }
1108
1109 /**
1110  *@brief Calculate remaining input buffer length.
1111  *@param s codec context
1112  *@param gb bitstream reader context
1113  *@return remaining size in bits
1114  */
1115 static int remaining_bits(WmallDecodeCtx *s, GetBitContext *gb)
1116 {
1117     return s->buf_bit_size - get_bits_count(gb);
1118 }
1119
1120 /**
1121  *@brief Fill the bit reservoir with a (partial) frame.
1122  *@param s codec context
1123  *@param gb bitstream reader context
1124  *@param len length of the partial frame
1125  *@param append decides wether to reset the buffer or not
1126  */
1127 static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
1128                       int append)
1129 {
1130     int buflen;
1131
1132     /** when the frame data does not need to be concatenated, the input buffer
1133         is resetted and additional bits from the previous frame are copyed
1134         and skipped later so that a fast byte copy is possible */
1135
1136     if (!append) {
1137         s->frame_offset = get_bits_count(gb) & 7;
1138         s->num_saved_bits = s->frame_offset;
1139         init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
1140     }
1141
1142     buflen = (s->num_saved_bits + len + 8) >> 3;
1143
1144     if (len <= 0 || buflen > MAX_FRAMESIZE) {
1145         av_log_ask_for_sample(s->avctx, "input buffer too small\n");
1146         s->packet_loss = 1;
1147         return;
1148     }
1149
1150     s->num_saved_bits += len;
1151     if (!append) {
1152         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
1153                      s->num_saved_bits);
1154     } else {
1155         int align = 8 - (get_bits_count(gb) & 7);
1156         align = FFMIN(align, len);
1157         put_bits(&s->pb, align, get_bits(gb, align));
1158         len -= align;
1159         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
1160     }
1161     skip_bits_long(gb, len);
1162
1163     {
1164         PutBitContext tmp = s->pb;
1165         flush_put_bits(&tmp);
1166     }
1167
1168     init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
1169     skip_bits(&s->gb, s->frame_offset);
1170 }
1171
1172 /**
1173  *@brief Decode a single WMA packet.
1174  *@param avctx codec context
1175  *@param data the output buffer
1176  *@param data_size number of bytes that were written to the output buffer
1177  *@param avpkt input packet
1178  *@return number of bytes that were read from the input buffer
1179  */
1180 static int decode_packet(AVCodecContext *avctx,
1181                          void *data, int *data_size, AVPacket* avpkt)
1182 {
1183     WmallDecodeCtx *s = avctx->priv_data;
1184     GetBitContext* gb  = &s->pgb;
1185     const uint8_t* buf = avpkt->data;
1186     int buf_size       = avpkt->size;
1187     int num_bits_prev_frame;
1188     int packet_sequence_number;
1189
1190     s->samples       = data;
1191     s->samples_end   = (float*)((int8_t*)data + *data_size);
1192     *data_size = 0;
1193
1194     if (s->packet_done || s->packet_loss) {
1195         s->packet_done = 0;
1196
1197         /** sanity check for the buffer length */
1198         if (buf_size < avctx->block_align)
1199             return 0;
1200
1201         s->next_packet_start = buf_size - avctx->block_align;
1202         buf_size = avctx->block_align;
1203         s->buf_bit_size = buf_size << 3;
1204
1205         /** parse packet header */
1206         init_get_bits(gb, buf, s->buf_bit_size);
1207         packet_sequence_number = get_bits(gb, 4);
1208         int seekable_frame_in_packet = get_bits1(gb);
1209         int spliced_packet = get_bits1(gb);
1210
1211         /** get number of bits that need to be added to the previous frame */
1212         num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
1213
1214         /** check for packet loss */
1215         if (!s->packet_loss &&
1216             ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
1217             s->packet_loss = 1;
1218             av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",
1219                    s->packet_sequence_number, packet_sequence_number);
1220         }
1221         s->packet_sequence_number = packet_sequence_number;
1222
1223         if (num_bits_prev_frame > 0) {
1224             int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
1225             if (num_bits_prev_frame >= remaining_packet_bits) {
1226                 num_bits_prev_frame = remaining_packet_bits;
1227                 s->packet_done = 1;
1228             }
1229
1230             /** append the previous frame data to the remaining data from the
1231                 previous packet to create a full frame */
1232             save_bits(s, gb, num_bits_prev_frame, 1);
1233
1234             /** decode the cross packet frame if it is valid */
1235             if (!s->packet_loss)
1236                 decode_frame(s);
1237         } else if (s->num_saved_bits - s->frame_offset) {
1238             dprintf(avctx, "ignoring %x previously saved bits\n",
1239                     s->num_saved_bits - s->frame_offset);
1240         }
1241
1242         if (s->packet_loss) {
1243             /** reset number of saved bits so that the decoder
1244                 does not start to decode incomplete frames in the
1245                 s->len_prefix == 0 case */
1246             s->num_saved_bits = 0;
1247             s->packet_loss = 0;
1248         }
1249
1250     } else {
1251         int frame_size;
1252
1253         s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
1254         init_get_bits(gb, avpkt->data, s->buf_bit_size);
1255         skip_bits(gb, s->packet_offset);
1256
1257         if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
1258             (frame_size = show_bits(gb, s->log2_frame_size)) &&
1259             frame_size <= remaining_bits(s, gb)) {
1260             save_bits(s, gb, frame_size, 0);
1261             s->packet_done = !decode_frame(s);
1262         } else if (!s->len_prefix
1263                    && s->num_saved_bits > get_bits_count(&s->gb)) {
1264             /** when the frames do not have a length prefix, we don't know
1265                 the compressed length of the individual frames
1266                 however, we know what part of a new packet belongs to the
1267                 previous frame
1268                 therefore we save the incoming packet first, then we append
1269                 the "previous frame" data from the next packet so that
1270                 we get a buffer that only contains full frames */
1271             s->packet_done = !decode_frame(s);
1272         } else {
1273             s->packet_done = 1;
1274         }
1275     }
1276
1277     if (s->packet_done && !s->packet_loss &&
1278         remaining_bits(s, gb) > 0) {
1279         /** save the rest of the data so that it can be decoded
1280             with the next packet */
1281         save_bits(s, gb, remaining_bits(s, gb), 0);
1282     }
1283
1284     *data_size = 0; // (int8_t *)s->samples - (int8_t *)data;
1285     s->packet_offset = get_bits_count(gb) & 7;
1286
1287     return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
1288 }
1289
1290 /**
1291  *@brief Clear decoder buffers (for seeking).
1292  *@param avctx codec context
1293  */
1294 static void flush(AVCodecContext *avctx)
1295 {
1296     WmallDecodeCtx *s = avctx->priv_data;
1297     int i;
1298     /** reset output buffer as a part of it is used during the windowing of a
1299         new frame */
1300     for (i = 0; i < s->num_channels; i++)
1301         memset(s->channel[i].out, 0, s->samples_per_frame *
1302                sizeof(*s->channel[i].out));
1303     s->packet_loss = 1;
1304 }
1305
1306
1307 /**
1308  *@brief wmall decoder
1309  */
1310 AVCodec ff_wmalossless_decoder = {
1311     "wmalossless",
1312     AVMEDIA_TYPE_AUDIO,
1313     CODEC_ID_WMALOSSLESS,
1314     sizeof(WmallDecodeCtx),
1315     decode_init,
1316     NULL,
1317     decode_end,
1318     decode_packet,
1319     .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_EXPERIMENTAL,
1320     .flush= flush,
1321     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Lossless"),
1322 };