]> git.sesse.net Git - ffmpeg/blob - libavcodec/wmaprodec.c
Merge commit '325aa63dd1a3abc2453914d0bc111d297833d725'
[ffmpeg] / libavcodec / wmaprodec.c
1 /*
2  * Wmapro compatible decoder
3  * Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion
4  * Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * @brief wmapro decoder implementation
26  * Wmapro is an MDCT based codec comparable to wma standard or AAC.
27  * The decoding therefore consists of the following steps:
28  * - bitstream decoding
29  * - reconstruction of per-channel data
30  * - rescaling and inverse quantization
31  * - IMDCT
32  * - windowing and overlapp-add
33  *
34  * The compressed wmapro bitstream is split into individual packets.
35  * Every such packet contains one or more wma frames.
36  * The compressed frames may have a variable length and frames may
37  * cross packet boundaries.
38  * Common to all wmapro frames is the number of samples that are stored in
39  * a frame.
40  * The number of samples and a few other decode flags are stored
41  * as extradata that has to be passed to the decoder.
42  *
43  * The wmapro frames themselves are again split into a variable number of
44  * subframes. Every subframe contains the data for 2^N time domain samples
45  * where N varies between 7 and 12.
46  *
47  * Example wmapro bitstream (in samples):
48  *
49  * ||   packet 0           || packet 1 || packet 2      packets
50  * ---------------------------------------------------
51  * || frame 0      || frame 1       || frame 2    ||    frames
52  * ---------------------------------------------------
53  * ||   |      |   ||   |   |   |   ||            ||    subframes of channel 0
54  * ---------------------------------------------------
55  * ||      |   |   ||   |   |   |   ||            ||    subframes of channel 1
56  * ---------------------------------------------------
57  *
58  * The frame layouts for the individual channels of a wma frame does not need
59  * to be the same.
60  *
61  * However, if the offsets and lengths of several subframes of a frame are the
62  * same, the subframes of the channels can be grouped.
63  * Every group may then use special coding techniques like M/S stereo coding
64  * to improve the compression ratio. These channel transformations do not
65  * need to be applied to a whole subframe. Instead, they can also work on
66  * individual scale factor bands (see below).
67  * The coefficients that carry the audio signal in the frequency domain
68  * are transmitted as huffman-coded vectors with 4, 2 and 1 elements.
69  * In addition to that, the encoder can switch to a runlevel coding scheme
70  * by transmitting subframe_length / 128 zero coefficients.
71  *
72  * Before the audio signal can be converted to the time domain, the
73  * coefficients have to be rescaled and inverse quantized.
74  * A subframe is therefore split into several scale factor bands that get
75  * scaled individually.
76  * Scale factors are submitted for every frame but they might be shared
77  * between the subframes of a channel. Scale factors are initially DPCM-coded.
78  * Once scale factors are shared, the differences are transmitted as runlevel
79  * codes.
80  * Every subframe length and offset combination in the frame layout shares a
81  * common quantization factor that can be adjusted for every channel by a
82  * modifier.
83  * After the inverse quantization, the coefficients get processed by an IMDCT.
84  * The resulting values are then windowed with a sine window and the first half
85  * of the values are added to the second half of the output from the previous
86  * subframe in order to reconstruct the output samples.
87  */
88
89 #include <inttypes.h>
90
91 #include "libavutil/ffmath.h"
92 #include "libavutil/float_dsp.h"
93 #include "libavutil/intfloat.h"
94 #include "libavutil/intreadwrite.h"
95 #include "avcodec.h"
96 #include "internal.h"
97 #include "get_bits.h"
98 #include "put_bits.h"
99 #include "wmaprodata.h"
100 #include "sinewin.h"
101 #include "wma.h"
102 #include "wma_common.h"
103
104 /** current decoder limitations */
105 #define WMAPRO_MAX_CHANNELS    8                             ///< max number of handled channels
106 #define MAX_SUBFRAMES  32                                    ///< max number of subframes per channel
107 #define MAX_BANDS      29                                    ///< max number of scale factor bands
108 #define MAX_FRAMESIZE  32768                                 ///< maximum compressed frame size
109 #define XMA_MAX_STREAMS         8
110 #define XMA_MAX_CHANNELS_STREAM 2
111 #define XMA_MAX_CHANNELS        (XMA_MAX_STREAMS * XMA_MAX_CHANNELS_STREAM)
112
113 #define WMAPRO_BLOCK_MIN_BITS  6                                           ///< log2 of min block size
114 #define WMAPRO_BLOCK_MAX_BITS 13                                           ///< log2 of max block size
115 #define WMAPRO_BLOCK_MIN_SIZE (1 << WMAPRO_BLOCK_MIN_BITS)                 ///< minimum block size
116 #define WMAPRO_BLOCK_MAX_SIZE (1 << WMAPRO_BLOCK_MAX_BITS)                 ///< maximum block size
117 #define WMAPRO_BLOCK_SIZES    (WMAPRO_BLOCK_MAX_BITS - WMAPRO_BLOCK_MIN_BITS + 1) ///< possible block sizes
118
119
120 #define VLCBITS            9
121 #define SCALEVLCBITS       8
122 #define VEC4MAXDEPTH    ((HUFF_VEC4_MAXBITS+VLCBITS-1)/VLCBITS)
123 #define VEC2MAXDEPTH    ((HUFF_VEC2_MAXBITS+VLCBITS-1)/VLCBITS)
124 #define VEC1MAXDEPTH    ((HUFF_VEC1_MAXBITS+VLCBITS-1)/VLCBITS)
125 #define SCALEMAXDEPTH   ((HUFF_SCALE_MAXBITS+SCALEVLCBITS-1)/SCALEVLCBITS)
126 #define SCALERLMAXDEPTH ((HUFF_SCALE_RL_MAXBITS+VLCBITS-1)/VLCBITS)
127
128 static VLC              sf_vlc;           ///< scale factor DPCM vlc
129 static VLC              sf_rl_vlc;        ///< scale factor run length vlc
130 static VLC              vec4_vlc;         ///< 4 coefficients per symbol
131 static VLC              vec2_vlc;         ///< 2 coefficients per symbol
132 static VLC              vec1_vlc;         ///< 1 coefficient per symbol
133 static VLC              coef_vlc[2];      ///< coefficient run length vlc codes
134 static float            sin64[33];        ///< sine table for decorrelation
135
136 /**
137  * @brief frame specific decoder context for a single channel
138  */
139 typedef struct WMAProChannelCtx {
140     int16_t  prev_block_len;                          ///< length of the previous block
141     uint8_t  transmit_coefs;
142     uint8_t  num_subframes;
143     uint16_t subframe_len[MAX_SUBFRAMES];             ///< subframe length in samples
144     uint16_t subframe_offset[MAX_SUBFRAMES];          ///< subframe positions in the current frame
145     uint8_t  cur_subframe;                            ///< current subframe number
146     uint16_t decoded_samples;                         ///< number of already processed samples
147     uint8_t  grouped;                                 ///< channel is part of a group
148     int      quant_step;                              ///< quantization step for the current subframe
149     int8_t   reuse_sf;                                ///< share scale factors between subframes
150     int8_t   scale_factor_step;                       ///< scaling step for the current subframe
151     int      max_scale_factor;                        ///< maximum scale factor for the current subframe
152     int      saved_scale_factors[2][MAX_BANDS];       ///< resampled and (previously) transmitted scale factor values
153     int8_t   scale_factor_idx;                        ///< index for the transmitted scale factor values (used for resampling)
154     int*     scale_factors;                           ///< pointer to the scale factor values used for decoding
155     uint8_t  table_idx;                               ///< index in sf_offsets for the scale factor reference block
156     float*   coeffs;                                  ///< pointer to the subframe decode buffer
157     uint16_t num_vec_coeffs;                          ///< number of vector coded coefficients
158     DECLARE_ALIGNED(32, float, out)[WMAPRO_BLOCK_MAX_SIZE + WMAPRO_BLOCK_MAX_SIZE / 2]; ///< output buffer
159 } WMAProChannelCtx;
160
161 /**
162  * @brief channel group for channel transformations
163  */
164 typedef struct WMAProChannelGrp {
165     uint8_t num_channels;                                     ///< number of channels in the group
166     int8_t  transform;                                        ///< transform on / off
167     int8_t  transform_band[MAX_BANDS];                        ///< controls if the transform is enabled for a certain band
168     float   decorrelation_matrix[WMAPRO_MAX_CHANNELS*WMAPRO_MAX_CHANNELS];
169     float*  channel_data[WMAPRO_MAX_CHANNELS];                ///< transformation coefficients
170 } WMAProChannelGrp;
171
172 /**
173  * @brief main decoder context
174  */
175 typedef struct WMAProDecodeCtx {
176     /* generic decoder variables */
177     AVCodecContext*  avctx;                         ///< codec context for av_log
178     AVFloatDSPContext *fdsp;
179     uint8_t          frame_data[MAX_FRAMESIZE +
180                       AV_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
181     PutBitContext    pb;                            ///< context for filling the frame_data buffer
182     FFTContext       mdct_ctx[WMAPRO_BLOCK_SIZES];  ///< MDCT context per block size
183     DECLARE_ALIGNED(32, float, tmp)[WMAPRO_BLOCK_MAX_SIZE]; ///< IMDCT output buffer
184     const float*     windows[WMAPRO_BLOCK_SIZES];   ///< windows for the different block sizes
185
186     /* frame size dependent frame information (set during initialization) */
187     uint32_t         decode_flags;                  ///< used compression features
188     uint8_t          len_prefix;                    ///< frame is prefixed with its length
189     uint8_t          dynamic_range_compression;     ///< frame contains DRC data
190     uint8_t          bits_per_sample;               ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
191     uint16_t         samples_per_frame;             ///< number of samples to output
192     uint16_t         log2_frame_size;
193     int8_t           lfe_channel;                   ///< lfe channel index
194     uint8_t          max_num_subframes;
195     uint8_t          subframe_len_bits;             ///< number of bits used for the subframe length
196     uint8_t          max_subframe_len_bit;          ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
197     uint16_t         min_samples_per_subframe;
198     int8_t           num_sfb[WMAPRO_BLOCK_SIZES];   ///< scale factor bands per block size
199     int16_t          sfb_offsets[WMAPRO_BLOCK_SIZES][MAX_BANDS];                    ///< scale factor band offsets (multiples of 4)
200     int8_t           sf_offsets[WMAPRO_BLOCK_SIZES][WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
201     int16_t          subwoofer_cutoffs[WMAPRO_BLOCK_SIZES]; ///< subwoofer cutoff values
202
203     /* packet decode state */
204     GetBitContext    pgb;                           ///< bitstream reader context for the packet
205     int              next_packet_start;             ///< start offset of the next wma packet in the demuxer packet
206     uint8_t          packet_offset;                 ///< frame offset in the packet
207     uint8_t          packet_sequence_number;        ///< current packet number
208     int              num_saved_bits;                ///< saved number of bits
209     int              frame_offset;                  ///< frame offset in the bit reservoir
210     int              subframe_offset;               ///< subframe offset in the bit reservoir
211     uint8_t          packet_loss;                   ///< set in case of bitstream error
212     uint8_t          packet_done;                   ///< set when a packet is fully decoded
213
214     /* frame decode state */
215     uint32_t         frame_num;                     ///< current frame number (not used for decoding)
216     GetBitContext    gb;                            ///< bitstream reader context
217     int              buf_bit_size;                  ///< buffer size in bits
218     uint8_t          drc_gain;                      ///< gain for the DRC tool
219     int8_t           skip_frame;                    ///< skip output step
220     int8_t           parsed_all_subframes;          ///< all subframes decoded?
221     uint8_t          skip_packets;                  ///< packets to skip to find next packet in a stream (XMA1/2)
222
223     /* subframe/block decode state */
224     int16_t          subframe_len;                  ///< current subframe length
225     int8_t           nb_channels;                   ///< number of channels in stream (XMA1/2)
226     int8_t           channels_for_cur_subframe;     ///< number of channels that contain the subframe
227     int8_t           channel_indexes_for_cur_subframe[WMAPRO_MAX_CHANNELS];
228     int8_t           num_bands;                     ///< number of scale factor bands
229     int8_t           transmit_num_vec_coeffs;       ///< number of vector coded coefficients is part of the bitstream
230     int16_t*         cur_sfb_offsets;               ///< sfb offsets for the current block
231     uint8_t          table_idx;                     ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
232     int8_t           esc_len;                       ///< length of escaped coefficients
233
234     uint8_t          num_chgroups;                  ///< number of channel groups
235     WMAProChannelGrp chgroup[WMAPRO_MAX_CHANNELS];  ///< channel group information
236
237     WMAProChannelCtx channel[WMAPRO_MAX_CHANNELS];  ///< per channel data
238 } WMAProDecodeCtx;
239
240 typedef struct XMADecodeCtx {
241     WMAProDecodeCtx xma[XMA_MAX_STREAMS];
242     AVFrame *frames[XMA_MAX_STREAMS];
243     int current_stream;
244     int num_streams;
245     float samples[XMA_MAX_CHANNELS][512 * 64];
246     int offset[XMA_MAX_STREAMS];
247     int start_channel[XMA_MAX_STREAMS];
248 } XMADecodeCtx;
249
250 /**
251  *@brief helper function to print the most important members of the context
252  *@param s context
253  */
254 static av_cold void dump_context(WMAProDecodeCtx *s)
255 {
256 #define PRINT(a, b)     av_log(s->avctx, AV_LOG_DEBUG, " %s = %d\n", a, b);
257 #define PRINT_HEX(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %"PRIx32"\n", a, b);
258
259     PRINT("ed sample bit depth", s->bits_per_sample);
260     PRINT_HEX("ed decode flags", s->decode_flags);
261     PRINT("samples per frame",   s->samples_per_frame);
262     PRINT("log2 frame size",     s->log2_frame_size);
263     PRINT("max num subframes",   s->max_num_subframes);
264     PRINT("len prefix",          s->len_prefix);
265     PRINT("num channels",        s->nb_channels);
266 }
267
268 /**
269  *@brief Uninitialize the decoder and free all resources.
270  *@param avctx codec context
271  *@return 0 on success, < 0 otherwise
272  */
273 static av_cold int decode_end(WMAProDecodeCtx *s)
274 {
275     int i;
276
277     av_freep(&s->fdsp);
278
279     for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
280         ff_mdct_end(&s->mdct_ctx[i]);
281
282     return 0;
283 }
284
285 static av_cold int wmapro_decode_end(AVCodecContext *avctx)
286 {
287     WMAProDecodeCtx *s = avctx->priv_data;
288
289     decode_end(s);
290
291     return 0;
292 }
293
294 static av_cold int get_rate(AVCodecContext *avctx)
295 {
296     if (avctx->codec_id != AV_CODEC_ID_WMAPRO) { // XXX: is this really only for XMA?
297         if (avctx->sample_rate > 44100)
298             return 48000;
299         else if (avctx->sample_rate > 32000)
300             return 44100;
301         else if (avctx->sample_rate > 24000)
302             return 32000;
303         return 24000;
304     }
305
306     return avctx->sample_rate;
307 }
308
309 /**
310  *@brief Initialize the decoder.
311  *@param avctx codec context
312  *@return 0 on success, -1 otherwise
313  */
314 static av_cold int decode_init(WMAProDecodeCtx *s, AVCodecContext *avctx, int num_stream)
315 {
316     uint8_t *edata_ptr = avctx->extradata;
317     unsigned int channel_mask;
318     int i, bits;
319     int log2_max_num_subframes;
320     int num_possible_block_sizes;
321
322     if (avctx->codec_id == AV_CODEC_ID_XMA1 || avctx->codec_id == AV_CODEC_ID_XMA2)
323         avctx->block_align = 2048;
324
325     if (!avctx->block_align) {
326         av_log(avctx, AV_LOG_ERROR, "block_align is not set\n");
327         return AVERROR(EINVAL);
328     }
329
330     s->avctx = avctx;
331
332     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
333
334     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
335
336     /** dump the extradata */
337     av_log(avctx, AV_LOG_DEBUG, "extradata:\n");
338     for (i = 0; i < avctx->extradata_size; i++)
339         av_log(avctx, AV_LOG_DEBUG, "[%x] ", avctx->extradata[i]);
340     av_log(avctx, AV_LOG_DEBUG, "\n");
341
342     if (avctx->codec_id == AV_CODEC_ID_XMA2 && avctx->extradata_size == 34) { /* XMA2WAVEFORMATEX */
343         s->decode_flags    = 0x10d6;
344         s->bits_per_sample = 16;
345         channel_mask       = 0; //AV_RL32(edata_ptr+2); /* not always in expected order */
346         if ((num_stream+1) * XMA_MAX_CHANNELS_STREAM > avctx->channels) /* stream config is 2ch + 2ch + ... + 1/2ch */
347             s->nb_channels = 1;
348         else
349             s->nb_channels = 2;
350     } else if (avctx->codec_id == AV_CODEC_ID_XMA2) { /* XMA2WAVEFORMAT */
351         s->decode_flags    = 0x10d6;
352         s->bits_per_sample = 16;
353         channel_mask       = 0; /* would need to aggregate from all streams */
354         s->nb_channels = edata_ptr[32 + ((edata_ptr[0]==3)?0:8) + 4*num_stream + 0]; /* nth stream config */
355     } else if (avctx->codec_id == AV_CODEC_ID_XMA1) { /* XMAWAVEFORMAT */
356         s->decode_flags    = 0x10d6;
357         s->bits_per_sample = 16;
358         channel_mask       = 0; /* would need to aggregate from all streams */
359         s->nb_channels     = edata_ptr[8 + 20*num_stream + 17]; /* nth stream config */
360     } else if (avctx->codec_id == AV_CODEC_ID_WMAPRO && avctx->extradata_size >= 18) {
361         s->decode_flags    = AV_RL16(edata_ptr+14);
362         channel_mask       = AV_RL32(edata_ptr+2);
363         s->bits_per_sample = AV_RL16(edata_ptr);
364         s->nb_channels     = avctx->channels;
365
366         if (s->bits_per_sample > 32 || s->bits_per_sample < 1) {
367             avpriv_request_sample(avctx, "bits per sample is %d", s->bits_per_sample);
368             return AVERROR_PATCHWELCOME;
369         }
370     } else {
371         avpriv_request_sample(avctx, "Unknown extradata size");
372         return AVERROR_PATCHWELCOME;
373     }
374
375     /** generic init */
376     s->log2_frame_size = av_log2(avctx->block_align) + 4;
377     if (s->log2_frame_size > 25) {
378         avpriv_request_sample(avctx, "Large block align");
379         return AVERROR_PATCHWELCOME;
380     }
381
382     /** frame info */
383     if (avctx->codec_id != AV_CODEC_ID_WMAPRO)
384         s->skip_frame = 0;
385     else
386         s->skip_frame = 1; /* skip first frame */
387
388     s->packet_loss = 1;
389     s->len_prefix  = (s->decode_flags & 0x40);
390
391     /** get frame len */
392     if (avctx->codec_id == AV_CODEC_ID_WMAPRO) {
393         bits = ff_wma_get_frame_len_bits(avctx->sample_rate, 3, s->decode_flags);
394         if (bits > WMAPRO_BLOCK_MAX_BITS) {
395             avpriv_request_sample(avctx, "14-bit block sizes");
396             return AVERROR_PATCHWELCOME;
397         }
398         s->samples_per_frame = 1 << bits;
399     } else {
400         s->samples_per_frame = 512;
401     }
402
403     /** subframe info */
404     log2_max_num_subframes       = ((s->decode_flags & 0x38) >> 3);
405     s->max_num_subframes         = 1 << log2_max_num_subframes;
406     if (s->max_num_subframes == 16 || s->max_num_subframes == 4)
407         s->max_subframe_len_bit = 1;
408     s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
409
410     num_possible_block_sizes     = log2_max_num_subframes + 1;
411     s->min_samples_per_subframe  = s->samples_per_frame / s->max_num_subframes;
412     s->dynamic_range_compression = (s->decode_flags & 0x80);
413
414     if (s->max_num_subframes > MAX_SUBFRAMES) {
415         av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %"PRId8"\n",
416                s->max_num_subframes);
417         return AVERROR_INVALIDDATA;
418     }
419
420     if (s->min_samples_per_subframe < WMAPRO_BLOCK_MIN_SIZE) {
421         av_log(avctx, AV_LOG_ERROR, "min_samples_per_subframe of %d too small\n",
422                s->min_samples_per_subframe);
423         return AVERROR_INVALIDDATA;
424     }
425
426     if (s->avctx->sample_rate <= 0) {
427         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
428         return AVERROR_INVALIDDATA;
429     }
430
431     if (s->nb_channels <= 0) {
432         av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n",
433                s->nb_channels);
434         return AVERROR_INVALIDDATA;
435     } else if (avctx->codec_id != AV_CODEC_ID_WMAPRO && s->nb_channels > XMA_MAX_CHANNELS_STREAM) {
436         av_log(avctx, AV_LOG_ERROR, "invalid number of channels per XMA stream %d\n",
437                s->nb_channels);
438         return AVERROR_INVALIDDATA;
439     } else if (s->nb_channels > WMAPRO_MAX_CHANNELS) {
440         avpriv_request_sample(avctx,
441                               "More than %d channels", WMAPRO_MAX_CHANNELS);
442         return AVERROR_PATCHWELCOME;
443     }
444
445     /** init previous block len */
446     for (i = 0; i < s->nb_channels; i++)
447         s->channel[i].prev_block_len = s->samples_per_frame;
448
449     /** extract lfe channel position */
450     s->lfe_channel = -1;
451
452     if (channel_mask & 8) {
453         unsigned int mask;
454         for (mask = 1; mask < 16; mask <<= 1) {
455             if (channel_mask & mask)
456                 ++s->lfe_channel;
457         }
458     }
459
460     INIT_VLC_STATIC(&sf_vlc, SCALEVLCBITS, HUFF_SCALE_SIZE,
461                     scale_huffbits, 1, 1,
462                     scale_huffcodes, 2, 2, 616);
463
464     INIT_VLC_STATIC(&sf_rl_vlc, VLCBITS, HUFF_SCALE_RL_SIZE,
465                     scale_rl_huffbits, 1, 1,
466                     scale_rl_huffcodes, 4, 4, 1406);
467
468     INIT_VLC_STATIC(&coef_vlc[0], VLCBITS, HUFF_COEF0_SIZE,
469                     coef0_huffbits, 1, 1,
470                     coef0_huffcodes, 4, 4, 2108);
471
472     INIT_VLC_STATIC(&coef_vlc[1], VLCBITS, HUFF_COEF1_SIZE,
473                     coef1_huffbits, 1, 1,
474                     coef1_huffcodes, 4, 4, 3912);
475
476     INIT_VLC_STATIC(&vec4_vlc, VLCBITS, HUFF_VEC4_SIZE,
477                     vec4_huffbits, 1, 1,
478                     vec4_huffcodes, 2, 2, 604);
479
480     INIT_VLC_STATIC(&vec2_vlc, VLCBITS, HUFF_VEC2_SIZE,
481                     vec2_huffbits, 1, 1,
482                     vec2_huffcodes, 2, 2, 562);
483
484     INIT_VLC_STATIC(&vec1_vlc, VLCBITS, HUFF_VEC1_SIZE,
485                     vec1_huffbits, 1, 1,
486                     vec1_huffcodes, 2, 2, 562);
487
488     /** calculate number of scale factor bands and their offsets
489         for every possible block size */
490     for (i = 0; i < num_possible_block_sizes; i++) {
491         int subframe_len = s->samples_per_frame >> i;
492         int x;
493         int band = 1;
494         int rate = get_rate(avctx);
495
496         s->sfb_offsets[i][0] = 0;
497
498         for (x = 0; x < MAX_BANDS-1 && s->sfb_offsets[i][band - 1] < subframe_len; x++) {
499             int offset = (subframe_len * 2 * critical_freq[x]) / rate + 2;
500             offset &= ~3;
501             if (offset > s->sfb_offsets[i][band - 1])
502                 s->sfb_offsets[i][band++] = offset;
503
504             if (offset >= subframe_len)
505                 break;
506         }
507         s->sfb_offsets[i][band - 1] = subframe_len;
508         s->num_sfb[i]               = band - 1;
509         if (s->num_sfb[i] <= 0) {
510             av_log(avctx, AV_LOG_ERROR, "num_sfb invalid\n");
511             return AVERROR_INVALIDDATA;
512         }
513     }
514
515
516     /** Scale factors can be shared between blocks of different size
517         as every block has a different scale factor band layout.
518         The matrix sf_offsets is needed to find the correct scale factor.
519      */
520
521     for (i = 0; i < num_possible_block_sizes; i++) {
522         int b;
523         for (b = 0; b < s->num_sfb[i]; b++) {
524             int x;
525             int offset = ((s->sfb_offsets[i][b]
526                            + s->sfb_offsets[i][b + 1] - 1) << i) >> 1;
527             for (x = 0; x < num_possible_block_sizes; x++) {
528                 int v = 0;
529                 while (s->sfb_offsets[x][v + 1] << x < offset) {
530                     v++;
531                     av_assert0(v < MAX_BANDS);
532                 }
533                 s->sf_offsets[i][x][b] = v;
534             }
535         }
536     }
537
538     s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
539     if (!s->fdsp)
540         return AVERROR(ENOMEM);
541
542     /** init MDCT, FIXME: only init needed sizes */
543     for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
544         ff_mdct_init(&s->mdct_ctx[i], WMAPRO_BLOCK_MIN_BITS+1+i, 1,
545                      1.0 / (1 << (WMAPRO_BLOCK_MIN_BITS + i - 1))
546                      / (1 << (s->bits_per_sample - 1)));
547
548     /** init MDCT windows: simple sine window */
549     for (i = 0; i < WMAPRO_BLOCK_SIZES; i++) {
550         const int win_idx = WMAPRO_BLOCK_MAX_BITS - i;
551         ff_init_ff_sine_windows(win_idx);
552         s->windows[WMAPRO_BLOCK_SIZES - i - 1] = ff_sine_windows[win_idx];
553     }
554
555     /** calculate subwoofer cutoff values */
556     for (i = 0; i < num_possible_block_sizes; i++) {
557         int block_size = s->samples_per_frame >> i;
558         int cutoff = (440*block_size + 3LL * (s->avctx->sample_rate >> 1) - 1)
559                      / s->avctx->sample_rate;
560         s->subwoofer_cutoffs[i] = av_clip(cutoff, 4, block_size);
561     }
562
563     /** calculate sine values for the decorrelation matrix */
564     for (i = 0; i < 33; i++)
565         sin64[i] = sin(i*M_PI / 64.0);
566
567     if (avctx->debug & FF_DEBUG_BITSTREAM)
568         dump_context(s);
569
570     avctx->channel_layout = channel_mask;
571
572     return 0;
573 }
574
575 /**
576  *@brief Initialize the decoder.
577  *@param avctx codec context
578  *@return 0 on success, -1 otherwise
579  */
580 static av_cold int wmapro_decode_init(AVCodecContext *avctx)
581 {
582     WMAProDecodeCtx *s = avctx->priv_data;
583
584     return decode_init(s, avctx, 0);
585 }
586
587 /**
588  *@brief Decode the subframe length.
589  *@param s context
590  *@param offset sample offset in the frame
591  *@return decoded subframe length on success, < 0 in case of an error
592  */
593 static int decode_subframe_length(WMAProDecodeCtx *s, int offset)
594 {
595     int frame_len_shift = 0;
596     int subframe_len;
597
598     /** no need to read from the bitstream when only one length is possible */
599     if (offset == s->samples_per_frame - s->min_samples_per_subframe)
600         return s->min_samples_per_subframe;
601
602     if (get_bits_left(&s->gb) < 1)
603         return AVERROR_INVALIDDATA;
604
605     /** 1 bit indicates if the subframe is of maximum length */
606     if (s->max_subframe_len_bit) {
607         if (get_bits1(&s->gb))
608             frame_len_shift = 1 + get_bits(&s->gb, s->subframe_len_bits-1);
609     } else
610         frame_len_shift = get_bits(&s->gb, s->subframe_len_bits);
611
612     subframe_len = s->samples_per_frame >> frame_len_shift;
613
614     /** sanity check the length */
615     if (subframe_len < s->min_samples_per_subframe ||
616         subframe_len > s->samples_per_frame) {
617         av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
618                subframe_len);
619         return AVERROR_INVALIDDATA;
620     }
621     return subframe_len;
622 }
623
624 /**
625  *@brief Decode how the data in the frame is split into subframes.
626  *       Every WMA frame contains the encoded data for a fixed number of
627  *       samples per channel. The data for every channel might be split
628  *       into several subframes. This function will reconstruct the list of
629  *       subframes for every channel.
630  *
631  *       If the subframes are not evenly split, the algorithm estimates the
632  *       channels with the lowest number of total samples.
633  *       Afterwards, for each of these channels a bit is read from the
634  *       bitstream that indicates if the channel contains a subframe with the
635  *       next subframe size that is going to be read from the bitstream or not.
636  *       If a channel contains such a subframe, the subframe size gets added to
637  *       the channel's subframe list.
638  *       The algorithm repeats these steps until the frame is properly divided
639  *       between the individual channels.
640  *
641  *@param s context
642  *@return 0 on success, < 0 in case of an error
643  */
644 static int decode_tilehdr(WMAProDecodeCtx *s)
645 {
646     uint16_t num_samples[WMAPRO_MAX_CHANNELS] = { 0 };/**< sum of samples for all currently known subframes of a channel */
647     uint8_t  contains_subframe[WMAPRO_MAX_CHANNELS];  /**< flag indicating if a channel contains the current subframe */
648     int channels_for_cur_subframe = s->nb_channels;   /**< number of channels that contain the current subframe */
649     int fixed_channel_layout = 0;                     /**< flag indicating that all channels use the same subframe offsets and sizes */
650     int min_channel_len = 0;                          /**< smallest sum of samples (channels with this length will be processed first) */
651     int c;
652
653     /* Should never consume more than 3073 bits (256 iterations for the
654      * while loop when always the minimum amount of 128 samples is subtracted
655      * from missing samples in the 8 channel case).
656      * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS  + 4)
657      */
658
659     /** reset tiling information */
660     for (c = 0; c < s->nb_channels; c++)
661         s->channel[c].num_subframes = 0;
662
663     if (s->max_num_subframes == 1 || get_bits1(&s->gb))
664         fixed_channel_layout = 1;
665
666     /** loop until the frame data is split between the subframes */
667     do {
668         int subframe_len;
669
670         /** check which channels contain the subframe */
671         for (c = 0; c < s->nb_channels; c++) {
672             if (num_samples[c] == min_channel_len) {
673                 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
674                    (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe))
675                     contains_subframe[c] = 1;
676                 else
677                     contains_subframe[c] = get_bits1(&s->gb);
678             } else
679                 contains_subframe[c] = 0;
680         }
681
682         /** get subframe length, subframe_len == 0 is not allowed */
683         if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
684             return AVERROR_INVALIDDATA;
685
686         /** add subframes to the individual channels and find new min_channel_len */
687         min_channel_len += subframe_len;
688         for (c = 0; c < s->nb_channels; c++) {
689             WMAProChannelCtx* chan = &s->channel[c];
690
691             if (contains_subframe[c]) {
692                 if (chan->num_subframes >= MAX_SUBFRAMES) {
693                     av_log(s->avctx, AV_LOG_ERROR,
694                            "broken frame: num subframes > 31\n");
695                     return AVERROR_INVALIDDATA;
696                 }
697                 chan->subframe_len[chan->num_subframes] = subframe_len;
698                 num_samples[c] += subframe_len;
699                 ++chan->num_subframes;
700                 if (num_samples[c] > s->samples_per_frame) {
701                     av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
702                            "channel len > samples_per_frame\n");
703                     return AVERROR_INVALIDDATA;
704                 }
705             } else if (num_samples[c] <= min_channel_len) {
706                 if (num_samples[c] < min_channel_len) {
707                     channels_for_cur_subframe = 0;
708                     min_channel_len = num_samples[c];
709                 }
710                 ++channels_for_cur_subframe;
711             }
712         }
713     } while (min_channel_len < s->samples_per_frame);
714
715     for (c = 0; c < s->nb_channels; c++) {
716         int i;
717         int offset = 0;
718         for (i = 0; i < s->channel[c].num_subframes; i++) {
719             ff_dlog(s->avctx, "frame[%"PRIu32"] channel[%i] subframe[%i]"
720                     " len %i\n", s->frame_num, c, i,
721                     s->channel[c].subframe_len[i]);
722             s->channel[c].subframe_offset[i] = offset;
723             offset += s->channel[c].subframe_len[i];
724         }
725     }
726
727     return 0;
728 }
729
730 /**
731  *@brief Calculate a decorrelation matrix from the bitstream parameters.
732  *@param s codec context
733  *@param chgroup channel group for which the matrix needs to be calculated
734  */
735 static void decode_decorrelation_matrix(WMAProDecodeCtx *s,
736                                         WMAProChannelGrp *chgroup)
737 {
738     int i;
739     int offset = 0;
740     int8_t rotation_offset[WMAPRO_MAX_CHANNELS * WMAPRO_MAX_CHANNELS];
741     memset(chgroup->decorrelation_matrix, 0, s->nb_channels *
742            s->nb_channels * sizeof(*chgroup->decorrelation_matrix));
743
744     for (i = 0; i < chgroup->num_channels * (chgroup->num_channels - 1) >> 1; i++)
745         rotation_offset[i] = get_bits(&s->gb, 6);
746
747     for (i = 0; i < chgroup->num_channels; i++)
748         chgroup->decorrelation_matrix[chgroup->num_channels * i + i] =
749             get_bits1(&s->gb) ? 1.0 : -1.0;
750
751     for (i = 1; i < chgroup->num_channels; i++) {
752         int x;
753         for (x = 0; x < i; x++) {
754             int y;
755             for (y = 0; y < i + 1; y++) {
756                 float v1 = chgroup->decorrelation_matrix[x * chgroup->num_channels + y];
757                 float v2 = chgroup->decorrelation_matrix[i * chgroup->num_channels + y];
758                 int n = rotation_offset[offset + x];
759                 float sinv;
760                 float cosv;
761
762                 if (n < 32) {
763                     sinv = sin64[n];
764                     cosv = sin64[32 - n];
765                 } else {
766                     sinv =  sin64[64 -  n];
767                     cosv = -sin64[n  - 32];
768                 }
769
770                 chgroup->decorrelation_matrix[y + x * chgroup->num_channels] =
771                                                (v1 * sinv) - (v2 * cosv);
772                 chgroup->decorrelation_matrix[y + i * chgroup->num_channels] =
773                                                (v1 * cosv) + (v2 * sinv);
774             }
775         }
776         offset += i;
777     }
778 }
779
780 /**
781  *@brief Decode channel transformation parameters
782  *@param s codec context
783  *@return >= 0 in case of success, < 0 in case of bitstream errors
784  */
785 static int decode_channel_transform(WMAProDecodeCtx* s)
786 {
787     int i;
788     /* should never consume more than 1921 bits for the 8 channel case
789      * 1 + MAX_CHANNELS * (MAX_CHANNELS + 2 + 3 * MAX_CHANNELS * MAX_CHANNELS
790      * + MAX_CHANNELS + MAX_BANDS + 1)
791      */
792
793     /** in the one channel case channel transforms are pointless */
794     s->num_chgroups = 0;
795     if (s->nb_channels > 1) {
796         int remaining_channels = s->channels_for_cur_subframe;
797
798         if (get_bits1(&s->gb)) {
799             avpriv_request_sample(s->avctx,
800                                   "Channel transform bit");
801             return AVERROR_PATCHWELCOME;
802         }
803
804         for (s->num_chgroups = 0; remaining_channels &&
805              s->num_chgroups < s->channels_for_cur_subframe; s->num_chgroups++) {
806             WMAProChannelGrp* chgroup = &s->chgroup[s->num_chgroups];
807             float** channel_data = chgroup->channel_data;
808             chgroup->num_channels = 0;
809             chgroup->transform = 0;
810
811             /** decode channel mask */
812             if (remaining_channels > 2) {
813                 for (i = 0; i < s->channels_for_cur_subframe; i++) {
814                     int channel_idx = s->channel_indexes_for_cur_subframe[i];
815                     if (!s->channel[channel_idx].grouped
816                         && get_bits1(&s->gb)) {
817                         ++chgroup->num_channels;
818                         s->channel[channel_idx].grouped = 1;
819                         *channel_data++ = s->channel[channel_idx].coeffs;
820                     }
821                 }
822             } else {
823                 chgroup->num_channels = remaining_channels;
824                 for (i = 0; i < s->channels_for_cur_subframe; i++) {
825                     int channel_idx = s->channel_indexes_for_cur_subframe[i];
826                     if (!s->channel[channel_idx].grouped)
827                         *channel_data++ = s->channel[channel_idx].coeffs;
828                     s->channel[channel_idx].grouped = 1;
829                 }
830             }
831
832             /** decode transform type */
833             if (chgroup->num_channels == 2) {
834                 if (get_bits1(&s->gb)) {
835                     if (get_bits1(&s->gb)) {
836                         avpriv_request_sample(s->avctx,
837                                               "Unknown channel transform type");
838                         return AVERROR_PATCHWELCOME;
839                     }
840                 } else {
841                     chgroup->transform = 1;
842                     if (s->nb_channels == 2) {
843                         chgroup->decorrelation_matrix[0] =  1.0;
844                         chgroup->decorrelation_matrix[1] = -1.0;
845                         chgroup->decorrelation_matrix[2] =  1.0;
846                         chgroup->decorrelation_matrix[3] =  1.0;
847                     } else {
848                         /** cos(pi/4) */
849                         chgroup->decorrelation_matrix[0] =  0.70703125;
850                         chgroup->decorrelation_matrix[1] = -0.70703125;
851                         chgroup->decorrelation_matrix[2] =  0.70703125;
852                         chgroup->decorrelation_matrix[3] =  0.70703125;
853                     }
854                 }
855             } else if (chgroup->num_channels > 2) {
856                 if (get_bits1(&s->gb)) {
857                     chgroup->transform = 1;
858                     if (get_bits1(&s->gb)) {
859                         decode_decorrelation_matrix(s, chgroup);
860                     } else {
861                         /** FIXME: more than 6 coupled channels not supported */
862                         if (chgroup->num_channels > 6) {
863                             avpriv_request_sample(s->avctx,
864                                                   "Coupled channels > 6");
865                         } else {
866                             memcpy(chgroup->decorrelation_matrix,
867                                    default_decorrelation[chgroup->num_channels],
868                                    chgroup->num_channels * chgroup->num_channels *
869                                    sizeof(*chgroup->decorrelation_matrix));
870                         }
871                     }
872                 }
873             }
874
875             /** decode transform on / off */
876             if (chgroup->transform) {
877                 if (!get_bits1(&s->gb)) {
878                     int i;
879                     /** transform can be enabled for individual bands */
880                     for (i = 0; i < s->num_bands; i++) {
881                         chgroup->transform_band[i] = get_bits1(&s->gb);
882                     }
883                 } else {
884                     memset(chgroup->transform_band, 1, s->num_bands);
885                 }
886             }
887             remaining_channels -= chgroup->num_channels;
888         }
889     }
890     return 0;
891 }
892
893 /**
894  *@brief Extract the coefficients from the bitstream.
895  *@param s codec context
896  *@param c current channel number
897  *@return 0 on success, < 0 in case of bitstream errors
898  */
899 static int decode_coeffs(WMAProDecodeCtx *s, int c)
900 {
901     /* Integers 0..15 as single-precision floats.  The table saves a
902        costly int to float conversion, and storing the values as
903        integers allows fast sign-flipping. */
904     static const uint32_t fval_tab[16] = {
905         0x00000000, 0x3f800000, 0x40000000, 0x40400000,
906         0x40800000, 0x40a00000, 0x40c00000, 0x40e00000,
907         0x41000000, 0x41100000, 0x41200000, 0x41300000,
908         0x41400000, 0x41500000, 0x41600000, 0x41700000,
909     };
910     int vlctable;
911     VLC* vlc;
912     WMAProChannelCtx* ci = &s->channel[c];
913     int rl_mode = 0;
914     int cur_coeff = 0;
915     int num_zeros = 0;
916     const uint16_t* run;
917     const float* level;
918
919     ff_dlog(s->avctx, "decode coefficients for channel %i\n", c);
920
921     vlctable = get_bits1(&s->gb);
922     vlc = &coef_vlc[vlctable];
923
924     if (vlctable) {
925         run = coef1_run;
926         level = coef1_level;
927     } else {
928         run = coef0_run;
929         level = coef0_level;
930     }
931
932     /** decode vector coefficients (consumes up to 167 bits per iteration for
933       4 vector coded large values) */
934     while ((s->transmit_num_vec_coeffs || !rl_mode) &&
935            (cur_coeff + 3 < ci->num_vec_coeffs)) {
936         uint32_t vals[4];
937         int i;
938         unsigned int idx;
939
940         idx = get_vlc2(&s->gb, vec4_vlc.table, VLCBITS, VEC4MAXDEPTH);
941
942         if (idx == HUFF_VEC4_SIZE - 1) {
943             for (i = 0; i < 4; i += 2) {
944                 idx = get_vlc2(&s->gb, vec2_vlc.table, VLCBITS, VEC2MAXDEPTH);
945                 if (idx == HUFF_VEC2_SIZE - 1) {
946                     uint32_t v0, v1;
947                     v0 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
948                     if (v0 == HUFF_VEC1_SIZE - 1)
949                         v0 += ff_wma_get_large_val(&s->gb);
950                     v1 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
951                     if (v1 == HUFF_VEC1_SIZE - 1)
952                         v1 += ff_wma_get_large_val(&s->gb);
953                     vals[i  ] = av_float2int(v0);
954                     vals[i+1] = av_float2int(v1);
955                 } else {
956                     vals[i]   = fval_tab[symbol_to_vec2[idx] >> 4 ];
957                     vals[i+1] = fval_tab[symbol_to_vec2[idx] & 0xF];
958                 }
959             }
960         } else {
961             vals[0] = fval_tab[ symbol_to_vec4[idx] >> 12      ];
962             vals[1] = fval_tab[(symbol_to_vec4[idx] >> 8) & 0xF];
963             vals[2] = fval_tab[(symbol_to_vec4[idx] >> 4) & 0xF];
964             vals[3] = fval_tab[ symbol_to_vec4[idx]       & 0xF];
965         }
966
967         /** decode sign */
968         for (i = 0; i < 4; i++) {
969             if (vals[i]) {
970                 uint32_t sign = get_bits1(&s->gb) - 1;
971                 AV_WN32A(&ci->coeffs[cur_coeff], vals[i] ^ sign << 31);
972                 num_zeros = 0;
973             } else {
974                 ci->coeffs[cur_coeff] = 0;
975                 /** switch to run level mode when subframe_len / 128 zeros
976                     were found in a row */
977                 rl_mode |= (++num_zeros > s->subframe_len >> 8);
978             }
979             ++cur_coeff;
980         }
981     }
982
983     /** decode run level coded coefficients */
984     if (cur_coeff < s->subframe_len) {
985         memset(&ci->coeffs[cur_coeff], 0,
986                sizeof(*ci->coeffs) * (s->subframe_len - cur_coeff));
987         if (ff_wma_run_level_decode(s->avctx, &s->gb, vlc,
988                                     level, run, 1, ci->coeffs,
989                                     cur_coeff, s->subframe_len,
990                                     s->subframe_len, s->esc_len, 0))
991             return AVERROR_INVALIDDATA;
992     }
993
994     return 0;
995 }
996
997 /**
998  *@brief Extract scale factors from the bitstream.
999  *@param s codec context
1000  *@return 0 on success, < 0 in case of bitstream errors
1001  */
1002 static int decode_scale_factors(WMAProDecodeCtx* s)
1003 {
1004     int i;
1005
1006     /** should never consume more than 5344 bits
1007      *  MAX_CHANNELS * (1 +  MAX_BANDS * 23)
1008      */
1009
1010     for (i = 0; i < s->channels_for_cur_subframe; i++) {
1011         int c = s->channel_indexes_for_cur_subframe[i];
1012         int* sf;
1013         int* sf_end;
1014         s->channel[c].scale_factors = s->channel[c].saved_scale_factors[!s->channel[c].scale_factor_idx];
1015         sf_end = s->channel[c].scale_factors + s->num_bands;
1016
1017         /** resample scale factors for the new block size
1018          *  as the scale factors might need to be resampled several times
1019          *  before some  new values are transmitted, a backup of the last
1020          *  transmitted scale factors is kept in saved_scale_factors
1021          */
1022         if (s->channel[c].reuse_sf) {
1023             const int8_t* sf_offsets = s->sf_offsets[s->table_idx][s->channel[c].table_idx];
1024             int b;
1025             for (b = 0; b < s->num_bands; b++)
1026                 s->channel[c].scale_factors[b] =
1027                     s->channel[c].saved_scale_factors[s->channel[c].scale_factor_idx][*sf_offsets++];
1028         }
1029
1030         if (!s->channel[c].cur_subframe || get_bits1(&s->gb)) {
1031
1032             if (!s->channel[c].reuse_sf) {
1033                 int val;
1034                 /** decode DPCM coded scale factors */
1035                 s->channel[c].scale_factor_step = get_bits(&s->gb, 2) + 1;
1036                 val = 45 / s->channel[c].scale_factor_step;
1037                 for (sf = s->channel[c].scale_factors; sf < sf_end; sf++) {
1038                     val += get_vlc2(&s->gb, sf_vlc.table, SCALEVLCBITS, SCALEMAXDEPTH) - 60;
1039                     *sf = val;
1040                 }
1041             } else {
1042                 int i;
1043                 /** run level decode differences to the resampled factors */
1044                 for (i = 0; i < s->num_bands; i++) {
1045                     int idx;
1046                     int skip;
1047                     int val;
1048                     int sign;
1049
1050                     idx = get_vlc2(&s->gb, sf_rl_vlc.table, VLCBITS, SCALERLMAXDEPTH);
1051
1052                     if (!idx) {
1053                         uint32_t code = get_bits(&s->gb, 14);
1054                         val  =  code >> 6;
1055                         sign = (code & 1) - 1;
1056                         skip = (code & 0x3f) >> 1;
1057                     } else if (idx == 1) {
1058                         break;
1059                     } else {
1060                         skip = scale_rl_run[idx];
1061                         val  = scale_rl_level[idx];
1062                         sign = get_bits1(&s->gb)-1;
1063                     }
1064
1065                     i += skip;
1066                     if (i >= s->num_bands) {
1067                         av_log(s->avctx, AV_LOG_ERROR,
1068                                "invalid scale factor coding\n");
1069                         return AVERROR_INVALIDDATA;
1070                     }
1071                     s->channel[c].scale_factors[i] += (val ^ sign) - sign;
1072                 }
1073             }
1074             /** swap buffers */
1075             s->channel[c].scale_factor_idx = !s->channel[c].scale_factor_idx;
1076             s->channel[c].table_idx = s->table_idx;
1077             s->channel[c].reuse_sf  = 1;
1078         }
1079
1080         /** calculate new scale factor maximum */
1081         s->channel[c].max_scale_factor = s->channel[c].scale_factors[0];
1082         for (sf = s->channel[c].scale_factors + 1; sf < sf_end; sf++) {
1083             s->channel[c].max_scale_factor =
1084                 FFMAX(s->channel[c].max_scale_factor, *sf);
1085         }
1086
1087     }
1088     return 0;
1089 }
1090
1091 /**
1092  *@brief Reconstruct the individual channel data.
1093  *@param s codec context
1094  */
1095 static void inverse_channel_transform(WMAProDecodeCtx *s)
1096 {
1097     int i;
1098
1099     for (i = 0; i < s->num_chgroups; i++) {
1100         if (s->chgroup[i].transform) {
1101             float data[WMAPRO_MAX_CHANNELS];
1102             const int num_channels = s->chgroup[i].num_channels;
1103             float** ch_data = s->chgroup[i].channel_data;
1104             float** ch_end = ch_data + num_channels;
1105             const int8_t* tb = s->chgroup[i].transform_band;
1106             int16_t* sfb;
1107
1108             /** multichannel decorrelation */
1109             for (sfb = s->cur_sfb_offsets;
1110                  sfb < s->cur_sfb_offsets + s->num_bands; sfb++) {
1111                 int y;
1112                 if (*tb++ == 1) {
1113                     /** multiply values with the decorrelation_matrix */
1114                     for (y = sfb[0]; y < FFMIN(sfb[1], s->subframe_len); y++) {
1115                         const float* mat = s->chgroup[i].decorrelation_matrix;
1116                         const float* data_end = data + num_channels;
1117                         float* data_ptr = data;
1118                         float** ch;
1119
1120                         for (ch = ch_data; ch < ch_end; ch++)
1121                             *data_ptr++ = (*ch)[y];
1122
1123                         for (ch = ch_data; ch < ch_end; ch++) {
1124                             float sum = 0;
1125                             data_ptr = data;
1126                             while (data_ptr < data_end)
1127                                 sum += *data_ptr++ * *mat++;
1128
1129                             (*ch)[y] = sum;
1130                         }
1131                     }
1132                 } else if (s->nb_channels == 2) {
1133                     int len = FFMIN(sfb[1], s->subframe_len) - sfb[0];
1134                     s->fdsp->vector_fmul_scalar(ch_data[0] + sfb[0],
1135                                                ch_data[0] + sfb[0],
1136                                                181.0 / 128, len);
1137                     s->fdsp->vector_fmul_scalar(ch_data[1] + sfb[0],
1138                                                ch_data[1] + sfb[0],
1139                                                181.0 / 128, len);
1140                 }
1141             }
1142         }
1143     }
1144 }
1145
1146 /**
1147  *@brief Apply sine window and reconstruct the output buffer.
1148  *@param s codec context
1149  */
1150 static void wmapro_window(WMAProDecodeCtx *s)
1151 {
1152     int i;
1153     for (i = 0; i < s->channels_for_cur_subframe; i++) {
1154         int c = s->channel_indexes_for_cur_subframe[i];
1155         const float* window;
1156         int winlen = s->channel[c].prev_block_len;
1157         float* start = s->channel[c].coeffs - (winlen >> 1);
1158
1159         if (s->subframe_len < winlen) {
1160             start += (winlen - s->subframe_len) >> 1;
1161             winlen = s->subframe_len;
1162         }
1163
1164         window = s->windows[av_log2(winlen) - WMAPRO_BLOCK_MIN_BITS];
1165
1166         winlen >>= 1;
1167
1168         s->fdsp->vector_fmul_window(start, start, start + winlen,
1169                                    window, winlen);
1170
1171         s->channel[c].prev_block_len = s->subframe_len;
1172     }
1173 }
1174
1175 /**
1176  *@brief Decode a single subframe (block).
1177  *@param s codec context
1178  *@return 0 on success, < 0 when decoding failed
1179  */
1180 static int decode_subframe(WMAProDecodeCtx *s)
1181 {
1182     int offset = s->samples_per_frame;
1183     int subframe_len = s->samples_per_frame;
1184     int i;
1185     int total_samples   = s->samples_per_frame * s->nb_channels;
1186     int transmit_coeffs = 0;
1187     int cur_subwoofer_cutoff;
1188
1189     s->subframe_offset = get_bits_count(&s->gb);
1190
1191     /** reset channel context and find the next block offset and size
1192         == the next block of the channel with the smallest number of
1193         decoded samples
1194     */
1195     for (i = 0; i < s->nb_channels; i++) {
1196         s->channel[i].grouped = 0;
1197         if (offset > s->channel[i].decoded_samples) {
1198             offset = s->channel[i].decoded_samples;
1199             subframe_len =
1200                 s->channel[i].subframe_len[s->channel[i].cur_subframe];
1201         }
1202     }
1203
1204     ff_dlog(s->avctx,
1205             "processing subframe with offset %i len %i\n", offset, subframe_len);
1206
1207     /** get a list of all channels that contain the estimated block */
1208     s->channels_for_cur_subframe = 0;
1209     for (i = 0; i < s->nb_channels; i++) {
1210         const int cur_subframe = s->channel[i].cur_subframe;
1211         /** subtract already processed samples */
1212         total_samples -= s->channel[i].decoded_samples;
1213
1214         /** and count if there are multiple subframes that match our profile */
1215         if (offset == s->channel[i].decoded_samples &&
1216             subframe_len == s->channel[i].subframe_len[cur_subframe]) {
1217             total_samples -= s->channel[i].subframe_len[cur_subframe];
1218             s->channel[i].decoded_samples +=
1219                 s->channel[i].subframe_len[cur_subframe];
1220             s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
1221             ++s->channels_for_cur_subframe;
1222         }
1223     }
1224
1225     /** check if the frame will be complete after processing the
1226         estimated block */
1227     if (!total_samples)
1228         s->parsed_all_subframes = 1;
1229
1230
1231     ff_dlog(s->avctx, "subframe is part of %i channels\n",
1232             s->channels_for_cur_subframe);
1233
1234     /** calculate number of scale factor bands and their offsets */
1235     s->table_idx         = av_log2(s->samples_per_frame/subframe_len);
1236     s->num_bands         = s->num_sfb[s->table_idx];
1237     s->cur_sfb_offsets   = s->sfb_offsets[s->table_idx];
1238     cur_subwoofer_cutoff = s->subwoofer_cutoffs[s->table_idx];
1239
1240     /** configure the decoder for the current subframe */
1241     offset += s->samples_per_frame >> 1;
1242
1243     for (i = 0; i < s->channels_for_cur_subframe; i++) {
1244         int c = s->channel_indexes_for_cur_subframe[i];
1245
1246         s->channel[c].coeffs = &s->channel[c].out[offset];
1247     }
1248
1249     s->subframe_len = subframe_len;
1250     s->esc_len = av_log2(s->subframe_len - 1) + 1;
1251
1252     /** skip extended header if any */
1253     if (get_bits1(&s->gb)) {
1254         int num_fill_bits;
1255         if (!(num_fill_bits = get_bits(&s->gb, 2))) {
1256             int len = get_bits(&s->gb, 4);
1257             num_fill_bits = get_bitsz(&s->gb, len) + 1;
1258         }
1259
1260         if (num_fill_bits >= 0) {
1261             if (get_bits_count(&s->gb) + num_fill_bits > s->num_saved_bits) {
1262                 av_log(s->avctx, AV_LOG_ERROR, "invalid number of fill bits\n");
1263                 return AVERROR_INVALIDDATA;
1264             }
1265
1266             skip_bits_long(&s->gb, num_fill_bits);
1267         }
1268     }
1269
1270     /** no idea for what the following bit is used */
1271     if (get_bits1(&s->gb)) {
1272         avpriv_request_sample(s->avctx, "Reserved bit");
1273         return AVERROR_PATCHWELCOME;
1274     }
1275
1276
1277     if (decode_channel_transform(s) < 0)
1278         return AVERROR_INVALIDDATA;
1279
1280
1281     for (i = 0; i < s->channels_for_cur_subframe; i++) {
1282         int c = s->channel_indexes_for_cur_subframe[i];
1283         if ((s->channel[c].transmit_coefs = get_bits1(&s->gb)))
1284             transmit_coeffs = 1;
1285     }
1286
1287     av_assert0(s->subframe_len <= WMAPRO_BLOCK_MAX_SIZE);
1288     if (transmit_coeffs) {
1289         int step;
1290         int quant_step = 90 * s->bits_per_sample >> 4;
1291
1292         /** decode number of vector coded coefficients */
1293         if ((s->transmit_num_vec_coeffs = get_bits1(&s->gb))) {
1294             int num_bits = av_log2((s->subframe_len + 3)/4) + 1;
1295             for (i = 0; i < s->channels_for_cur_subframe; i++) {
1296                 int c = s->channel_indexes_for_cur_subframe[i];
1297                 int num_vec_coeffs = get_bits(&s->gb, num_bits) << 2;
1298                 if (num_vec_coeffs > s->subframe_len) {
1299                     av_log(s->avctx, AV_LOG_ERROR, "num_vec_coeffs %d is too large\n", num_vec_coeffs);
1300                     return AVERROR_INVALIDDATA;
1301                 }
1302                 av_assert0(num_vec_coeffs + offset <= FF_ARRAY_ELEMS(s->channel[c].out));
1303                 s->channel[c].num_vec_coeffs = num_vec_coeffs;
1304             }
1305         } else {
1306             for (i = 0; i < s->channels_for_cur_subframe; i++) {
1307                 int c = s->channel_indexes_for_cur_subframe[i];
1308                 s->channel[c].num_vec_coeffs = s->subframe_len;
1309             }
1310         }
1311         /** decode quantization step */
1312         step = get_sbits(&s->gb, 6);
1313         quant_step += step;
1314         if (step == -32 || step == 31) {
1315             const int sign = (step == 31) - 1;
1316             int quant = 0;
1317             while (get_bits_count(&s->gb) + 5 < s->num_saved_bits &&
1318                    (step = get_bits(&s->gb, 5)) == 31) {
1319                 quant += 31;
1320             }
1321             quant_step += ((quant + step) ^ sign) - sign;
1322         }
1323         if (quant_step < 0) {
1324             av_log(s->avctx, AV_LOG_DEBUG, "negative quant step\n");
1325         }
1326
1327         /** decode quantization step modifiers for every channel */
1328
1329         if (s->channels_for_cur_subframe == 1) {
1330             s->channel[s->channel_indexes_for_cur_subframe[0]].quant_step = quant_step;
1331         } else {
1332             int modifier_len = get_bits(&s->gb, 3);
1333             for (i = 0; i < s->channels_for_cur_subframe; i++) {
1334                 int c = s->channel_indexes_for_cur_subframe[i];
1335                 s->channel[c].quant_step = quant_step;
1336                 if (get_bits1(&s->gb)) {
1337                     if (modifier_len) {
1338                         s->channel[c].quant_step += get_bits(&s->gb, modifier_len) + 1;
1339                     } else
1340                         ++s->channel[c].quant_step;
1341                 }
1342             }
1343         }
1344
1345         /** decode scale factors */
1346         if (decode_scale_factors(s) < 0)
1347             return AVERROR_INVALIDDATA;
1348     }
1349
1350     ff_dlog(s->avctx, "BITSTREAM: subframe header length was %i\n",
1351             get_bits_count(&s->gb) - s->subframe_offset);
1352
1353     /** parse coefficients */
1354     for (i = 0; i < s->channels_for_cur_subframe; i++) {
1355         int c = s->channel_indexes_for_cur_subframe[i];
1356         if (s->channel[c].transmit_coefs &&
1357             get_bits_count(&s->gb) < s->num_saved_bits) {
1358             decode_coeffs(s, c);
1359         } else
1360             memset(s->channel[c].coeffs, 0,
1361                    sizeof(*s->channel[c].coeffs) * subframe_len);
1362     }
1363
1364     ff_dlog(s->avctx, "BITSTREAM: subframe length was %i\n",
1365             get_bits_count(&s->gb) - s->subframe_offset);
1366
1367     if (transmit_coeffs) {
1368         FFTContext *mdct = &s->mdct_ctx[av_log2(subframe_len) - WMAPRO_BLOCK_MIN_BITS];
1369         /** reconstruct the per channel data */
1370         inverse_channel_transform(s);
1371         for (i = 0; i < s->channels_for_cur_subframe; i++) {
1372             int c = s->channel_indexes_for_cur_subframe[i];
1373             const int* sf = s->channel[c].scale_factors;
1374             int b;
1375
1376             if (c == s->lfe_channel)
1377                 memset(&s->tmp[cur_subwoofer_cutoff], 0, sizeof(*s->tmp) *
1378                        (subframe_len - cur_subwoofer_cutoff));
1379
1380             /** inverse quantization and rescaling */
1381             for (b = 0; b < s->num_bands; b++) {
1382                 const int end = FFMIN(s->cur_sfb_offsets[b+1], s->subframe_len);
1383                 const int exp = s->channel[c].quant_step -
1384                             (s->channel[c].max_scale_factor - *sf++) *
1385                             s->channel[c].scale_factor_step;
1386                 const float quant = ff_exp10(exp / 20.0);
1387                 int start = s->cur_sfb_offsets[b];
1388                 s->fdsp->vector_fmul_scalar(s->tmp + start,
1389                                            s->channel[c].coeffs + start,
1390                                            quant, end - start);
1391             }
1392
1393             /** apply imdct (imdct_half == DCTIV with reverse) */
1394             mdct->imdct_half(mdct, s->channel[c].coeffs, s->tmp);
1395         }
1396     }
1397
1398     /** window and overlapp-add */
1399     wmapro_window(s);
1400
1401     /** handled one subframe */
1402     for (i = 0; i < s->channels_for_cur_subframe; i++) {
1403         int c = s->channel_indexes_for_cur_subframe[i];
1404         if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
1405             av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
1406             return AVERROR_INVALIDDATA;
1407         }
1408         ++s->channel[c].cur_subframe;
1409     }
1410
1411     return 0;
1412 }
1413
1414 /**
1415  *@brief Decode one WMA frame.
1416  *@param s codec context
1417  *@return 0 if the trailer bit indicates that this is the last frame,
1418  *        1 if there are additional frames
1419  */
1420 static int decode_frame(WMAProDecodeCtx *s, AVFrame *frame, int *got_frame_ptr)
1421 {
1422     GetBitContext* gb = &s->gb;
1423     int more_frames = 0;
1424     int len = 0;
1425     int i;
1426
1427     /** get frame length */
1428     if (s->len_prefix)
1429         len = get_bits(gb, s->log2_frame_size);
1430
1431     ff_dlog(s->avctx, "decoding frame with length %x\n", len);
1432
1433     /** decode tile information */
1434     if (decode_tilehdr(s)) {
1435         s->packet_loss = 1;
1436         return 0;
1437     }
1438
1439     /** read postproc transform */
1440     if (s->nb_channels > 1 && get_bits1(gb)) {
1441         if (get_bits1(gb)) {
1442             for (i = 0; i < s->nb_channels * s->nb_channels; i++)
1443                 skip_bits(gb, 4);
1444         }
1445     }
1446
1447     /** read drc info */
1448     if (s->dynamic_range_compression) {
1449         s->drc_gain = get_bits(gb, 8);
1450         ff_dlog(s->avctx, "drc_gain %i\n", s->drc_gain);
1451     }
1452
1453     /** no idea what these are for, might be the number of samples
1454         that need to be skipped at the beginning or end of a stream */
1455     if (get_bits1(gb)) {
1456         int av_unused skip;
1457
1458         /** usually true for the first frame */
1459         if (get_bits1(gb)) {
1460             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1461             ff_dlog(s->avctx, "start skip: %i\n", skip);
1462         }
1463
1464         /** sometimes true for the last frame */
1465         if (get_bits1(gb)) {
1466             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1467             ff_dlog(s->avctx, "end skip: %i\n", skip);
1468         }
1469
1470     }
1471
1472     ff_dlog(s->avctx, "BITSTREAM: frame header length was %i\n",
1473             get_bits_count(gb) - s->frame_offset);
1474
1475     /** reset subframe states */
1476     s->parsed_all_subframes = 0;
1477     for (i = 0; i < s->nb_channels; i++) {
1478         s->channel[i].decoded_samples = 0;
1479         s->channel[i].cur_subframe    = 0;
1480         s->channel[i].reuse_sf        = 0;
1481     }
1482
1483     /** decode all subframes */
1484     while (!s->parsed_all_subframes) {
1485         if (decode_subframe(s) < 0) {
1486             s->packet_loss = 1;
1487             return 0;
1488         }
1489     }
1490
1491     /** copy samples to the output buffer */
1492     for (i = 0; i < s->nb_channels; i++)
1493         memcpy(frame->extended_data[i], s->channel[i].out,
1494                s->samples_per_frame * sizeof(*s->channel[i].out));
1495
1496     for (i = 0; i < s->nb_channels; i++) {
1497         /** reuse second half of the IMDCT output for the next frame */
1498         memcpy(&s->channel[i].out[0],
1499                &s->channel[i].out[s->samples_per_frame],
1500                s->samples_per_frame * sizeof(*s->channel[i].out) >> 1);
1501     }
1502
1503     if (s->skip_frame) {
1504         s->skip_frame = 0;
1505         *got_frame_ptr = 0;
1506         av_frame_unref(frame);
1507     } else {
1508         *got_frame_ptr = 1;
1509     }
1510
1511     if (s->len_prefix) {
1512         if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
1513             /** FIXME: not sure if this is always an error */
1514             av_log(s->avctx, AV_LOG_ERROR,
1515                    "frame[%"PRIu32"] would have to skip %i bits\n",
1516                    s->frame_num,
1517                    len - (get_bits_count(gb) - s->frame_offset) - 1);
1518             s->packet_loss = 1;
1519             return 0;
1520         }
1521
1522         /** skip the rest of the frame data */
1523         skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
1524     } else {
1525         while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
1526         }
1527     }
1528
1529     /** decode trailer bit */
1530     more_frames = get_bits1(gb);
1531
1532     ++s->frame_num;
1533     return more_frames;
1534 }
1535
1536 /**
1537  *@brief Calculate remaining input buffer length.
1538  *@param s codec context
1539  *@param gb bitstream reader context
1540  *@return remaining size in bits
1541  */
1542 static int remaining_bits(WMAProDecodeCtx *s, GetBitContext *gb)
1543 {
1544     return s->buf_bit_size - get_bits_count(gb);
1545 }
1546
1547 /**
1548  *@brief Fill the bit reservoir with a (partial) frame.
1549  *@param s codec context
1550  *@param gb bitstream reader context
1551  *@param len length of the partial frame
1552  *@param append decides whether to reset the buffer or not
1553  */
1554 static void save_bits(WMAProDecodeCtx *s, GetBitContext* gb, int len,
1555                       int append)
1556 {
1557     int buflen;
1558
1559     /** when the frame data does not need to be concatenated, the input buffer
1560         is reset and additional bits from the previous frame are copied
1561         and skipped later so that a fast byte copy is possible */
1562
1563     if (!append) {
1564         s->frame_offset = get_bits_count(gb) & 7;
1565         s->num_saved_bits = s->frame_offset;
1566         init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
1567     }
1568
1569     buflen = (put_bits_count(&s->pb) + len + 8) >> 3;
1570
1571     if (len <= 0 || buflen > MAX_FRAMESIZE) {
1572         avpriv_request_sample(s->avctx, "Too small input buffer");
1573         s->packet_loss = 1;
1574         return;
1575     }
1576
1577     av_assert0(len <= put_bits_left(&s->pb));
1578
1579     s->num_saved_bits += len;
1580     if (!append) {
1581         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
1582                      s->num_saved_bits);
1583     } else {
1584         int align = 8 - (get_bits_count(gb) & 7);
1585         align = FFMIN(align, len);
1586         put_bits(&s->pb, align, get_bits(gb, align));
1587         len -= align;
1588         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
1589     }
1590     skip_bits_long(gb, len);
1591
1592     {
1593         PutBitContext tmp = s->pb;
1594         flush_put_bits(&tmp);
1595     }
1596
1597     init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
1598     skip_bits(&s->gb, s->frame_offset);
1599 }
1600
1601 static int decode_packet(AVCodecContext *avctx, WMAProDecodeCtx *s,
1602                          void *data, int *got_frame_ptr, AVPacket *avpkt)
1603 {
1604     GetBitContext* gb  = &s->pgb;
1605     const uint8_t* buf = avpkt->data;
1606     int buf_size       = avpkt->size;
1607     int num_bits_prev_frame;
1608     int packet_sequence_number;
1609
1610     *got_frame_ptr = 0;
1611
1612     if (s->packet_done || s->packet_loss) {
1613         s->packet_done = 0;
1614
1615         /** sanity check for the buffer length */
1616         if (avctx->codec_id == AV_CODEC_ID_WMAPRO && buf_size < avctx->block_align) {
1617             av_log(avctx, AV_LOG_ERROR, "Input packet too small (%d < %d)\n",
1618                    buf_size, avctx->block_align);
1619             return AVERROR_INVALIDDATA;
1620         }
1621
1622         if (avctx->codec_id == AV_CODEC_ID_WMAPRO) {
1623             s->next_packet_start = buf_size - avctx->block_align;
1624             buf_size = avctx->block_align;
1625         } else {
1626             s->next_packet_start = buf_size - FFMIN(buf_size, avctx->block_align);
1627             buf_size = FFMIN(buf_size, avctx->block_align);
1628         }
1629         s->buf_bit_size = buf_size << 3;
1630
1631         /** parse packet header */
1632         init_get_bits(gb, buf, s->buf_bit_size);
1633         if (avctx->codec_id != AV_CODEC_ID_XMA2) {
1634             packet_sequence_number = get_bits(gb, 4);
1635             skip_bits(gb, 2);
1636         } else {
1637             int num_frames = get_bits(gb, 6);
1638             ff_dlog(avctx, "packet[%d]: number of frames %d\n", avctx->frame_number, num_frames);
1639             packet_sequence_number = 0;
1640         }
1641
1642         /** get number of bits that need to be added to the previous frame */
1643         num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
1644         if (avctx->codec_id != AV_CODEC_ID_WMAPRO) {
1645             skip_bits(gb, 3);
1646             s->skip_packets = get_bits(gb, 8);
1647             ff_dlog(avctx, "packet[%d]: skip packets %d\n", avctx->frame_number, s->skip_packets);
1648         }
1649
1650         ff_dlog(avctx, "packet[%d]: nbpf %x\n", avctx->frame_number,
1651                 num_bits_prev_frame);
1652
1653         /** check for packet loss */
1654         if (avctx->codec_id == AV_CODEC_ID_WMAPRO && !s->packet_loss &&
1655             ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
1656             s->packet_loss = 1;
1657             av_log(avctx, AV_LOG_ERROR,
1658                    "Packet loss detected! seq %"PRIx8" vs %x\n",
1659                    s->packet_sequence_number, packet_sequence_number);
1660         }
1661         s->packet_sequence_number = packet_sequence_number;
1662
1663         if (num_bits_prev_frame > 0) {
1664             int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
1665             if (num_bits_prev_frame >= remaining_packet_bits) {
1666                 num_bits_prev_frame = remaining_packet_bits;
1667                 s->packet_done = 1;
1668             }
1669
1670             /** append the previous frame data to the remaining data from the
1671                 previous packet to create a full frame */
1672             save_bits(s, gb, num_bits_prev_frame, 1);
1673             ff_dlog(avctx, "accumulated %x bits of frame data\n",
1674                     s->num_saved_bits - s->frame_offset);
1675
1676             /** decode the cross packet frame if it is valid */
1677             if (!s->packet_loss)
1678                 decode_frame(s, data, got_frame_ptr);
1679         } else if (s->num_saved_bits - s->frame_offset) {
1680             ff_dlog(avctx, "ignoring %x previously saved bits\n",
1681                     s->num_saved_bits - s->frame_offset);
1682         }
1683
1684         if (s->packet_loss) {
1685             /** reset number of saved bits so that the decoder
1686                 does not start to decode incomplete frames in the
1687                 s->len_prefix == 0 case */
1688             s->num_saved_bits = 0;
1689             s->packet_loss = 0;
1690         }
1691     } else {
1692         int frame_size;
1693         s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
1694         init_get_bits(gb, avpkt->data, s->buf_bit_size);
1695         skip_bits(gb, s->packet_offset);
1696         if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
1697             (frame_size = show_bits(gb, s->log2_frame_size)) &&
1698             frame_size <= remaining_bits(s, gb)) {
1699             save_bits(s, gb, frame_size, 0);
1700             if (!s->packet_loss)
1701                 s->packet_done = !decode_frame(s, data, got_frame_ptr);
1702         } else if (!s->len_prefix
1703                    && s->num_saved_bits > get_bits_count(&s->gb)) {
1704             /** when the frames do not have a length prefix, we don't know
1705                 the compressed length of the individual frames
1706                 however, we know what part of a new packet belongs to the
1707                 previous frame
1708                 therefore we save the incoming packet first, then we append
1709                 the "previous frame" data from the next packet so that
1710                 we get a buffer that only contains full frames */
1711             s->packet_done = !decode_frame(s, data, got_frame_ptr);
1712         } else {
1713             s->packet_done = 1;
1714         }
1715     }
1716
1717     if (remaining_bits(s, gb) < 0) {
1718         av_log(avctx, AV_LOG_ERROR, "Overread %d\n", -remaining_bits(s, gb));
1719         s->packet_loss = 1;
1720     }
1721
1722     if (s->packet_done && !s->packet_loss &&
1723         remaining_bits(s, gb) > 0) {
1724         /** save the rest of the data so that it can be decoded
1725             with the next packet */
1726         save_bits(s, gb, remaining_bits(s, gb), 0);
1727     }
1728
1729     s->packet_offset = get_bits_count(gb) & 7;
1730     if (s->packet_loss)
1731         return AVERROR_INVALIDDATA;
1732
1733     return get_bits_count(gb) >> 3;
1734 }
1735
1736 /**
1737  *@brief Decode a single WMA packet.
1738  *@param avctx codec context
1739  *@param data the output buffer
1740  *@param avpkt input packet
1741  *@return number of bytes that were read from the input buffer
1742  */
1743 static int wmapro_decode_packet(AVCodecContext *avctx, void *data,
1744                                 int *got_frame_ptr, AVPacket *avpkt)
1745 {
1746     WMAProDecodeCtx *s = avctx->priv_data;
1747     AVFrame *frame = data;
1748     int ret;
1749
1750     /* get output buffer */
1751     frame->nb_samples = s->samples_per_frame;
1752     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1753         s->packet_loss = 1;
1754         return 0;
1755     }
1756
1757     return decode_packet(avctx, s, data, got_frame_ptr, avpkt);
1758 }
1759
1760 static int xma_decode_packet(AVCodecContext *avctx, void *data,
1761                              int *got_frame_ptr, AVPacket *avpkt)
1762 {
1763     XMADecodeCtx *s = avctx->priv_data;
1764     int got_stream_frame_ptr = 0;
1765     AVFrame *frame = data;
1766     int i, ret, offset = INT_MAX;
1767
1768     /* decode current stream packet */
1769     ret = decode_packet(avctx, &s->xma[s->current_stream], s->frames[s->current_stream],
1770                         &got_stream_frame_ptr, avpkt);
1771
1772     /* copy stream samples (1/2ch) to sample buffer (Nch) */
1773     if (got_stream_frame_ptr) {
1774         int start_ch = s->start_channel[s->current_stream];
1775         memcpy(&s->samples[start_ch + 0][s->offset[s->current_stream] * 512],
1776                s->frames[s->current_stream]->extended_data[0], 512 * 4);
1777         if (s->xma[s->current_stream].nb_channels > 1)
1778             memcpy(&s->samples[start_ch + 1][s->offset[s->current_stream] * 512],
1779                    s->frames[s->current_stream]->extended_data[1], 512 * 4);
1780         s->offset[s->current_stream]++;
1781     } else if (ret < 0) {
1782         memset(s->offset, 0, sizeof(s->offset));
1783         s->current_stream = 0;
1784         return ret;
1785     }
1786
1787     /* find next XMA packet's owner stream, and update.
1788      * XMA streams find their packets following packet_skips
1789      * (at start there is one packet per stream, then interleave non-linearly). */
1790     if (s->xma[s->current_stream].packet_done ||
1791         s->xma[s->current_stream].packet_loss) {
1792
1793         /* select stream with 0 skip_packets (= uses next packet) */
1794         if (s->xma[s->current_stream].skip_packets != 0) {
1795             int min[2];
1796
1797             min[0] = s->xma[0].skip_packets;
1798             min[1] = i = 0;
1799
1800             for (i = 1; i < s->num_streams; i++) {
1801                 if (s->xma[i].skip_packets < min[0]) {
1802                     min[0] = s->xma[i].skip_packets;
1803                     min[1] = i;
1804                 }
1805             }
1806
1807             s->current_stream = min[1];
1808         }
1809
1810         /* all other streams skip next packet */
1811         for (i = 0; i < s->num_streams; i++) {
1812             s->xma[i].skip_packets = FFMAX(0, s->xma[i].skip_packets - 1);
1813         }
1814
1815         /* copy samples from buffer to output if possible */
1816         for (i = 0; i < s->num_streams; i++) {
1817             offset = FFMIN(offset, s->offset[i]);
1818         }
1819         if (offset > 0) {
1820             int bret;
1821
1822             frame->nb_samples = 512 * offset;
1823             if ((bret = ff_get_buffer(avctx, frame, 0)) < 0)
1824                 return bret;
1825
1826             /* copy samples buffer (Nch) to frame samples (Nch), move unconsumed samples */
1827             for (i = 0; i < s->num_streams; i++) {
1828                 int start_ch = s->start_channel[i];
1829                 memcpy(frame->extended_data[start_ch + 0], s->samples[start_ch + 0], frame->nb_samples * 4);
1830                 if (s->xma[i].nb_channels > 1)
1831                     memcpy(frame->extended_data[start_ch + 1], s->samples[start_ch + 1], frame->nb_samples * 4);
1832
1833                 s->offset[i] -= offset;
1834                 if (s->offset[i]) {
1835                     memmove(s->samples[start_ch + 0], s->samples[start_ch + 0] + frame->nb_samples, s->offset[i] * 4 * 512);
1836                     if (s->xma[i].nb_channels > 1)
1837                         memmove(s->samples[start_ch + 1], s->samples[start_ch + 1] + frame->nb_samples, s->offset[i] * 4 * 512);
1838                 }
1839             }
1840
1841             *got_frame_ptr = 1;
1842         }
1843     }
1844
1845     return ret;
1846 }
1847
1848 static av_cold int xma_decode_init(AVCodecContext *avctx)
1849 {
1850     XMADecodeCtx *s = avctx->priv_data;
1851     int i, ret, start_channels = 0;
1852
1853     if (avctx->channels <= 0 || avctx->extradata_size == 0)
1854         return AVERROR_INVALIDDATA;
1855
1856     /* get stream config */
1857     if (avctx->codec_id == AV_CODEC_ID_XMA2 && avctx->extradata_size == 34) { /* XMA2WAVEFORMATEX */
1858         s->num_streams = (avctx->channels + 1) / 2;
1859     } else if (avctx->codec_id == AV_CODEC_ID_XMA2 && avctx->extradata_size >= 2) { /* XMA2WAVEFORMAT */
1860         s->num_streams = avctx->extradata[1];
1861         if (avctx->extradata_size != (32 + ((avctx->extradata[0]==3)?0:8) + 4*s->num_streams)) {
1862             av_log(avctx, AV_LOG_ERROR, "Incorrect XMA2 extradata size\n");
1863             return AVERROR(EINVAL);
1864         }
1865     } else if (avctx->codec_id == AV_CODEC_ID_XMA1 && avctx->extradata_size >= 4) { /* XMAWAVEFORMAT */
1866         s->num_streams = avctx->extradata[4];
1867         if (avctx->extradata_size != (8 + 20*s->num_streams)) {
1868             av_log(avctx, AV_LOG_ERROR, "Incorrect XMA1 extradata size\n");
1869             return AVERROR(EINVAL);
1870         }
1871     } else {
1872         av_log(avctx, AV_LOG_ERROR, "Incorrect XMA config\n");
1873         return AVERROR(EINVAL);
1874     }
1875
1876     /* encoder supports up to 64 streams / 64*2 channels (would have to alloc arrays) */
1877     if (avctx->channels > XMA_MAX_CHANNELS || s->num_streams > XMA_MAX_STREAMS) {
1878         avpriv_request_sample(avctx, "More than %d channels in %d streams", XMA_MAX_CHANNELS, s->num_streams);
1879         return AVERROR_PATCHWELCOME;
1880     }
1881
1882     /* init all streams (several streams of 1/2ch make Nch files) */
1883     for (i = 0; i < s->num_streams; i++) {
1884         ret = decode_init(&s->xma[i], avctx, i);
1885         if (ret < 0)
1886             return ret;
1887         s->frames[i] = av_frame_alloc();
1888         if (!s->frames[i])
1889             return AVERROR(ENOMEM);
1890         s->frames[i]->nb_samples = 512;
1891         if ((ret = ff_get_buffer(avctx, s->frames[i], 0)) < 0) {
1892             return AVERROR(ENOMEM);
1893         }
1894
1895         s->start_channel[i] = start_channels;
1896         start_channels += s->xma[i].nb_channels;
1897     }
1898
1899     return ret;
1900 }
1901
1902 static av_cold int xma_decode_end(AVCodecContext *avctx)
1903 {
1904     XMADecodeCtx *s = avctx->priv_data;
1905     int i;
1906
1907     for (i = 0; i < s->num_streams; i++) {
1908         decode_end(&s->xma[i]);
1909         av_frame_free(&s->frames[i]);
1910     }
1911
1912     return 0;
1913 }
1914
1915 static void flush(WMAProDecodeCtx *s)
1916 {
1917     int i;
1918     /** reset output buffer as a part of it is used during the windowing of a
1919         new frame */
1920     for (i = 0; i < s->nb_channels; i++)
1921         memset(s->channel[i].out, 0, s->samples_per_frame *
1922                sizeof(*s->channel[i].out));
1923     s->packet_loss = 1;
1924     s->skip_packets = 0;
1925 }
1926
1927
1928 /**
1929  *@brief Clear decoder buffers (for seeking).
1930  *@param avctx codec context
1931  */
1932 static void wmapro_flush(AVCodecContext *avctx)
1933 {
1934     WMAProDecodeCtx *s = avctx->priv_data;
1935
1936     flush(s);
1937 }
1938
1939 static void xma_flush(AVCodecContext *avctx)
1940 {
1941     XMADecodeCtx *s = avctx->priv_data;
1942     int i;
1943
1944     for (i = 0; i < s->num_streams; i++)
1945         flush(&s->xma[i]);
1946
1947     memset(s->offset, 0, sizeof(s->offset));
1948     s->current_stream = 0;
1949 }
1950
1951
1952 /**
1953  *@brief wmapro decoder
1954  */
1955 AVCodec ff_wmapro_decoder = {
1956     .name           = "wmapro",
1957     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Professional"),
1958     .type           = AVMEDIA_TYPE_AUDIO,
1959     .id             = AV_CODEC_ID_WMAPRO,
1960     .priv_data_size = sizeof(WMAProDecodeCtx),
1961     .init           = wmapro_decode_init,
1962     .close          = wmapro_decode_end,
1963     .decode         = wmapro_decode_packet,
1964     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
1965     .flush          = wmapro_flush,
1966     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1967                                                       AV_SAMPLE_FMT_NONE },
1968 };
1969
1970 AVCodec ff_xma1_decoder = {
1971     .name           = "xma1",
1972     .long_name      = NULL_IF_CONFIG_SMALL("Xbox Media Audio 1"),
1973     .type           = AVMEDIA_TYPE_AUDIO,
1974     .id             = AV_CODEC_ID_XMA1,
1975     .priv_data_size = sizeof(XMADecodeCtx),
1976     .init           = xma_decode_init,
1977     .close          = xma_decode_end,
1978     .decode         = xma_decode_packet,
1979     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
1980     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1981                                                       AV_SAMPLE_FMT_NONE },
1982 };
1983
1984 AVCodec ff_xma2_decoder = {
1985     .name           = "xma2",
1986     .long_name      = NULL_IF_CONFIG_SMALL("Xbox Media Audio 2"),
1987     .type           = AVMEDIA_TYPE_AUDIO,
1988     .id             = AV_CODEC_ID_XMA2,
1989     .priv_data_size = sizeof(XMADecodeCtx),
1990     .init           = xma_decode_init,
1991     .close          = xma_decode_end,
1992     .decode         = xma_decode_packet,
1993     .flush          = xma_flush,
1994     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
1995     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1996                                                       AV_SAMPLE_FMT_NONE },
1997 };