More cleaning for libwmapro; use codeclib's bitstream functions and drop those from...
[kugel-rb.git] / apps / codecs / libwmapro / wmaprodec.c
blobea4cbe3a441602d943b69888d3cff36f9a726491
1 /*
2 * Wmapro compatible decoder
3 * Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion
4 * Copyright (c) 2008 - 2009 Sascha Sommer, Benjamin Larsson
6 * This file is part of FFmpeg.
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.
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.
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
23 /**
24 * @file libavcodec/wmaprodec.c
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
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.
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.
47 * Example wmapro bitstream (in samples):
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 * ---------------------------------------------------
58 * The frame layouts for the individual channels of a wma frame does not need
59 * to be the same.
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.
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.
89 #include "ffmpeg_get_bits.h"
90 #include "ffmpeg_put_bits.h"
91 #include "wmaprodata.h"
92 #include "wma.h"
93 #include "wmaprodec.h"
94 #include "wmapro_mdct.h"
95 #include "mdct_tables.h"
96 #include "quant.h"
97 #include "types.h"
98 #include "wmapro_math.h"
99 #include "codecs.h"
100 #include "codeclib.h"
101 #include "../libasf/asf.h"
103 /* Uncomment the following line to enable some debug output */
104 //#define WMAPRO_DUMP_CTX_EN
106 #undef DEBUGF
107 #ifdef WMAPRO_DUMP_CTX_EN
108 # define DEBUGF printf
109 #else
110 # define DEBUGF(...)
111 #endif
113 /* Some defines to make it compile */
114 #define AVERROR_INVALIDDATA -1
115 #define AVERROR_PATCHWELCOME -2
116 #define av_log_ask_for_sample(...)
118 /* Taken from avcodec.h */
119 #define FF_INPUT_BUFFER_PADDING_SIZE 8
121 /* Taken from libavutil/mem.h */
122 #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
124 /* Taken from libavutil/common.h */
125 #define FFMIN(a,b) ((a) > (b) ? (b) : (a))
126 #define FFMAX(a,b) ((a) > (b) ? (a) : (b))
128 /** current decoder limitations */
129 #define WMAPRO_MAX_CHANNELS 8 ///< max number of handled channels
130 #define MAX_SUBFRAMES 32 ///< max number of subframes per channel
131 #define MAX_BANDS 29 ///< max number of scale factor bands
132 #define MAX_FRAMESIZE 32768 ///< maximum compressed frame size
134 #define WMAPRO_BLOCK_MAX_BITS 12 ///< log2 of max block size
135 #define WMAPRO_BLOCK_MAX_SIZE (1 << WMAPRO_BLOCK_MAX_BITS) ///< maximum block size
136 #define WMAPRO_BLOCK_SIZES (WMAPRO_BLOCK_MAX_BITS - BLOCK_MIN_BITS + 1) ///< possible block sizes
139 #define VLCBITS 9
140 #define SCALEVLCBITS 8
141 #define VEC4MAXDEPTH ((HUFF_VEC4_MAXBITS+VLCBITS-1)/VLCBITS)
142 #define VEC2MAXDEPTH ((HUFF_VEC2_MAXBITS+VLCBITS-1)/VLCBITS)
143 #define VEC1MAXDEPTH ((HUFF_VEC1_MAXBITS+VLCBITS-1)/VLCBITS)
144 #define SCALEMAXDEPTH ((HUFF_SCALE_MAXBITS+SCALEVLCBITS-1)/SCALEVLCBITS)
145 #define SCALERLMAXDEPTH ((HUFF_SCALE_RL_MAXBITS+VLCBITS-1)/VLCBITS)
147 static VLC sf_vlc; ///< scale factor DPCM vlc
148 static VLC sf_rl_vlc; ///< scale factor run length vlc
149 static VLC vec4_vlc; ///< 4 coefficients per symbol
150 static VLC vec2_vlc; ///< 2 coefficients per symbol
151 static VLC vec1_vlc; ///< 1 coefficient per symbol
152 static VLC coef_vlc[2]; ///< coefficient run length vlc codes
153 //static float sin64[33]; ///< sinus table for decorrelation
156 * @brief frame specific decoder context for a single channel
158 typedef struct {
159 int16_t prev_block_len; ///< length of the previous block
160 uint8_t transmit_coefs;
161 uint8_t num_subframes;
162 uint16_t subframe_len[MAX_SUBFRAMES]; ///< subframe length in samples
163 uint16_t subframe_offset[MAX_SUBFRAMES]; ///< subframe positions in the current frame
164 uint8_t cur_subframe; ///< current subframe number
165 uint16_t decoded_samples; ///< number of already processed samples
166 uint8_t grouped; ///< channel is part of a group
167 int quant_step; ///< quantization step for the current subframe
168 int8_t reuse_sf; ///< share scale factors between subframes
169 int8_t scale_factor_step; ///< scaling step for the current subframe
170 int max_scale_factor; ///< maximum scale factor for the current subframe
171 int saved_scale_factors[2][MAX_BANDS]; ///< resampled and (previously) transmitted scale factor values
172 int8_t scale_factor_idx; ///< index for the transmitted scale factor values (used for resampling)
173 int* scale_factors; ///< pointer to the scale factor values used for decoding
174 uint8_t table_idx; ///< index in sf_offsets for the scale factor reference block
175 FIXED* coeffs; ///< pointer to the subframe decode buffer
176 DECLARE_ALIGNED(16, FIXED, out)[WMAPRO_BLOCK_MAX_SIZE + WMAPRO_BLOCK_MAX_SIZE / 2]; ///< output buffer
177 } WMAProChannelCtx;
180 * @brief channel group for channel transformations
182 typedef struct {
183 uint8_t num_channels; ///< number of channels in the group
184 int8_t transform; ///< transform on / off
185 int8_t transform_band[MAX_BANDS]; ///< controls if the transform is enabled for a certain band
186 //float decorrelation_matrix[WMAPRO_MAX_CHANNELS*WMAPRO_MAX_CHANNELS];
187 FIXED* channel_data[WMAPRO_MAX_CHANNELS]; ///< transformation coefficients
188 FIXED fixdecorrelation_matrix[WMAPRO_MAX_CHANNELS*WMAPRO_MAX_CHANNELS];
189 } WMAProChannelGrp;
192 * @brief main decoder context
194 typedef struct WMAProDecodeCtx {
195 /* generic decoder variables */
196 uint8_t frame_data[MAX_FRAMESIZE +
197 FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
198 PutBitContext pb; ///< context for filling the frame_data buffer
199 DECLARE_ALIGNED(16, FIXED, tmp)[WMAPRO_BLOCK_MAX_SIZE]; ///< IMDCT input buffer
201 /* frame size dependent frame information (set during initialization) */
202 uint32_t decode_flags; ///< used compression features
203 uint8_t len_prefix; ///< frame is prefixed with its length
204 uint8_t dynamic_range_compression; ///< frame contains DRC data
205 uint8_t bits_per_sample; ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
206 uint16_t samples_per_frame; ///< number of samples to output
207 uint16_t log2_frame_size;
208 int8_t num_channels; ///< number of channels in the stream (same as AVCodecContext.num_channels)
209 int8_t lfe_channel; ///< lfe channel index
210 uint8_t max_num_subframes;
211 uint8_t subframe_len_bits; ///< number of bits used for the subframe length
212 uint8_t max_subframe_len_bit; ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
213 uint16_t min_samples_per_subframe;
214 int8_t num_sfb[WMAPRO_BLOCK_SIZES]; ///< scale factor bands per block size
215 int16_t sfb_offsets[WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor band offsets (multiples of 4)
216 int8_t sf_offsets[WMAPRO_BLOCK_SIZES][WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
217 int16_t subwoofer_cutoffs[WMAPRO_BLOCK_SIZES]; ///< subwoofer cutoff values
219 /* packet decode state */
220 GetBitContext pgb; ///< bitstream reader context for the packet
221 uint8_t packet_offset; ///< frame offset in the packet
222 uint8_t packet_sequence_number; ///< current packet number
223 int num_saved_bits; ///< saved number of bits
224 int frame_offset; ///< frame offset in the bit reservoir
225 int subframe_offset; ///< subframe offset in the bit reservoir
226 uint8_t packet_loss; ///< set in case of bitstream error
227 uint8_t packet_done; ///< set when a packet is fully decoded
229 /* frame decode state */
230 uint32_t frame_num; ///< current frame number
231 GetBitContext gb; ///< bitstream reader context
232 int buf_bit_size; ///< buffer size in bits
233 FIXED* samples;
234 FIXED* samples_end; ///< maximum samplebuffer pointer
235 uint8_t drc_gain; ///< gain for the DRC tool
236 int8_t skip_frame; ///< skip output step
237 int8_t parsed_all_subframes; ///< all subframes decoded?
239 /* subframe/block decode state */
240 int16_t subframe_len; ///< current subframe length
241 int8_t channels_for_cur_subframe; ///< number of channels that contain the subframe
242 int8_t channel_indexes_for_cur_subframe[WMAPRO_MAX_CHANNELS];
243 int8_t num_bands; ///< number of scale factor bands
244 int16_t* cur_sfb_offsets; ///< sfb offsets for the current block
245 uint8_t table_idx; ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
246 int8_t esc_len; ///< length of escaped coefficients
248 uint8_t num_chgroups; ///< number of channel groups
249 WMAProChannelGrp chgroup[WMAPRO_MAX_CHANNELS]; ///< channel group information
251 WMAProChannelCtx channel[WMAPRO_MAX_CHANNELS]; ///< per channel data
252 } WMAProDecodeCtx;
254 /* static decode context, to avoid malloc */
255 static WMAProDecodeCtx globWMAProDecCtx;
258 *@brief helper function to print the most important members of the context
259 *@param s context
261 #ifdef WMAPRO_DUMP_CTX_EN
262 static void dump_context(WMAProDecodeCtx *s)
264 #define PRINT(a, b) printf(" %s = %d\n", a, b);
265 #define PRINT_HEX(a, b) printf(" %s = %x\n", a, b);
267 PRINT("ed sample bit depth", s->bits_per_sample);
268 PRINT_HEX("ed decode flags", s->decode_flags);
269 PRINT("samples per frame", s->samples_per_frame);
270 PRINT("log2 frame size", s->log2_frame_size);
271 PRINT("max num subframes", s->max_num_subframes);
272 PRINT("len prefix", s->len_prefix);
273 PRINT("num channels", s->num_channels);
275 #endif
278 *@brief Initialize the decoder.
279 *@param avctx codec context
280 *@return 0 on success, -1 otherwise
282 int decode_init(asf_waveformatex_t *wfx)
284 memset(&globWMAProDecCtx, 0, sizeof(WMAProDecodeCtx));
285 WMAProDecodeCtx *s = &globWMAProDecCtx;
286 uint8_t *edata_ptr = wfx->data;
287 unsigned int channel_mask;
288 int i;
289 int log2_max_num_subframes;
290 int num_possible_block_sizes;
292 init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
294 if (wfx->datalen >= 18) {
295 s->decode_flags = AV_RL16(edata_ptr+14);
296 channel_mask = AV_RL32(edata_ptr+2);
297 s->bits_per_sample = AV_RL16(edata_ptr);
298 /** dump the extradata */
299 for (i = 0; i < wfx->datalen; i++)
300 DEBUGF("[%x] ", wfx->data[i]);
301 DEBUGF("\n");
303 } else {
304 DEBUGF("Unknown extradata size\n");
305 return AVERROR_INVALIDDATA;
308 /** generic init */
309 s->log2_frame_size = av_log2(wfx->blockalign) + 4;
311 /** frame info */
312 s->skip_frame = 1; /** skip first frame */
313 s->packet_loss = 1;
314 s->len_prefix = (s->decode_flags & 0x40);
316 if (!s->len_prefix) {
317 DEBUGF("no length prefix\n");
318 return AVERROR_INVALIDDATA;
321 /** get frame len */
322 s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(wfx->rate,
323 3, s->decode_flags);
325 /** init previous block len */
326 for (i = 0; i < wfx->channels; i++)
327 s->channel[i].prev_block_len = s->samples_per_frame;
329 /** subframe info */
330 log2_max_num_subframes = ((s->decode_flags & 0x38) >> 3);
331 s->max_num_subframes = 1 << log2_max_num_subframes;
332 if (s->max_num_subframes == 16)
333 s->max_subframe_len_bit = 1;
334 s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
336 num_possible_block_sizes = log2_max_num_subframes + 1;
337 s->min_samples_per_subframe = s->samples_per_frame / s->max_num_subframes;
338 s->dynamic_range_compression = (s->decode_flags & 0x80);
340 if (s->max_num_subframes > MAX_SUBFRAMES) {
341 DEBUGF("invalid number of subframes %i\n",
342 s->max_num_subframes);
343 return AVERROR_INVALIDDATA;
346 s->num_channels = wfx->channels;
348 /** extract lfe channel position */
349 s->lfe_channel = -1;
351 if (channel_mask & 8) {
352 unsigned int mask;
353 for (mask = 1; mask < 16; mask <<= 1) {
354 if (channel_mask & mask)
355 ++s->lfe_channel;
359 if (s->num_channels < 0) {
360 DEBUGF("invalid number of channels %d\n", s->num_channels);
361 return AVERROR_INVALIDDATA;
362 } else if (s->num_channels > WMAPRO_MAX_CHANNELS) {
363 DEBUGF("unsupported number of channels\n");
364 return AVERROR_PATCHWELCOME;
367 INIT_VLC_STATIC(&sf_vlc, SCALEVLCBITS, HUFF_SCALE_SIZE,
368 scale_huffbits, 1, 1,
369 scale_huffcodes, 2, 2, 616);
371 INIT_VLC_STATIC(&sf_rl_vlc, VLCBITS, HUFF_SCALE_RL_SIZE,
372 scale_rl_huffbits, 1, 1,
373 scale_rl_huffcodes, 4, 4, 1406);
375 INIT_VLC_STATIC(&coef_vlc[0], VLCBITS, HUFF_COEF0_SIZE,
376 coef0_huffbits, 1, 1,
377 coef0_huffcodes, 4, 4, 2108);
379 INIT_VLC_STATIC(&coef_vlc[1], VLCBITS, HUFF_COEF1_SIZE,
380 coef1_huffbits, 1, 1,
381 coef1_huffcodes, 4, 4, 3912);
383 INIT_VLC_STATIC(&vec4_vlc, VLCBITS, HUFF_VEC4_SIZE,
384 vec4_huffbits, 1, 1,
385 vec4_huffcodes, 2, 2, 604);
387 INIT_VLC_STATIC(&vec2_vlc, VLCBITS, HUFF_VEC2_SIZE,
388 vec2_huffbits, 1, 1,
389 vec2_huffcodes, 2, 2, 562);
391 INIT_VLC_STATIC(&vec1_vlc, VLCBITS, HUFF_VEC1_SIZE,
392 vec1_huffbits, 1, 1,
393 vec1_huffcodes, 2, 2, 562);
395 /** calculate number of scale factor bands and their offsets
396 for every possible block size */
397 for (i = 0; i < num_possible_block_sizes; i++) {
398 int subframe_len = s->samples_per_frame >> i;
399 int x;
400 int band = 1;
402 s->sfb_offsets[i][0] = 0;
404 for (x = 0; x < MAX_BANDS-1 && s->sfb_offsets[i][band - 1] < subframe_len; x++) {
405 int offset = (subframe_len * 2 * critical_freq[x])
406 / wfx->rate + 2;
407 offset &= ~3;
408 if (offset > s->sfb_offsets[i][band - 1])
409 s->sfb_offsets[i][band++] = offset;
411 s->sfb_offsets[i][band - 1] = subframe_len;
412 s->num_sfb[i] = band - 1;
416 /** Scale factors can be shared between blocks of different size
417 as every block has a different scale factor band layout.
418 The matrix sf_offsets is needed to find the correct scale factor.
421 for (i = 0; i < num_possible_block_sizes; i++) {
422 int b;
423 for (b = 0; b < s->num_sfb[i]; b++) {
424 int x;
425 int offset = ((s->sfb_offsets[i][b]
426 + s->sfb_offsets[i][b + 1] - 1) << i) >> 1;
427 for (x = 0; x < num_possible_block_sizes; x++) {
428 int v = 0;
429 while (s->sfb_offsets[x][v + 1] << x < offset)
430 ++v;
431 s->sf_offsets[i][x][b] = v;
436 /** calculate subwoofer cutoff values */
437 for (i = 0; i < num_possible_block_sizes; i++) {
438 int block_size = s->samples_per_frame >> i;
439 int cutoff = (440*block_size + 3 * (wfx->rate >> 1) - 1)
440 / wfx->rate;
441 s->subwoofer_cutoffs[i] = av_clip(cutoff, 4, block_size);
444 #if 0
445 /** calculate sine values for the decorrelation matrix */
446 for (i = 0; i < 33; i++)
447 sin64[i] = sin(i*M_PI / 64.0);
448 #endif
450 #ifdef WMAPRO_DUMP_CTX_EN
451 dump_context(s);
452 #endif
453 return 0;
457 *@brief Decode the subframe length.
458 *@param s context
459 *@param offset sample offset in the frame
460 *@return decoded subframe length on success, < 0 in case of an error
462 static int decode_subframe_length(WMAProDecodeCtx *s, int offset)
464 int frame_len_shift = 0;
465 int subframe_len;
467 /** no need to read from the bitstream when only one length is possible */
468 if (offset == s->samples_per_frame - s->min_samples_per_subframe)
469 return s->min_samples_per_subframe;
471 /** 1 bit indicates if the subframe is of maximum length */
472 if (s->max_subframe_len_bit) {
473 if (get_bits1(&s->gb))
474 frame_len_shift = 1 + get_bits(&s->gb, s->subframe_len_bits-1);
475 } else
476 frame_len_shift = get_bits(&s->gb, s->subframe_len_bits);
478 subframe_len = s->samples_per_frame >> frame_len_shift;
480 /** sanity check the length */
481 if (subframe_len < s->min_samples_per_subframe ||
482 subframe_len > s->samples_per_frame) {
483 DEBUGF("broken frame: subframe_len %i\n",
484 subframe_len);
485 return AVERROR_INVALIDDATA;
487 return subframe_len;
491 *@brief Decode how the data in the frame is split into subframes.
492 * Every WMA frame contains the encoded data for a fixed number of
493 * samples per channel. The data for every channel might be split
494 * into several subframes. This function will reconstruct the list of
495 * subframes for every channel.
497 * If the subframes are not evenly split, the algorithm estimates the
498 * channels with the lowest number of total samples.
499 * Afterwards, for each of these channels a bit is read from the
500 * bitstream that indicates if the channel contains a subframe with the
501 * next subframe size that is going to be read from the bitstream or not.
502 * If a channel contains such a subframe, the subframe size gets added to
503 * the channel's subframe list.
504 * The algorithm repeats these steps until the frame is properly divided
505 * between the individual channels.
507 *@param s context
508 *@return 0 on success, < 0 in case of an error
510 static int decode_tilehdr(WMAProDecodeCtx *s)
512 uint16_t num_samples[WMAPRO_MAX_CHANNELS]; /** sum of samples for all currently known subframes of a channel */
513 uint8_t contains_subframe[WMAPRO_MAX_CHANNELS]; /** flag indicating if a channel contains the current subframe */
514 int channels_for_cur_subframe = s->num_channels; /** number of channels that contain the current subframe */
515 int fixed_channel_layout = 0; /** flag indicating that all channels use the same subframe offsets and sizes */
516 int min_channel_len = 0; /** smallest sum of samples (channels with this length will be processed first) */
517 int c;
519 /* Should never consume more than 3073 bits (256 iterations for the
520 * while loop when always the minimum amount of 128 samples is substracted
521 * from missing samples in the 8 channel case).
522 * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS + 4)
525 /** reset tiling information */
526 for (c = 0; c < s->num_channels; c++)
527 s->channel[c].num_subframes = 0;
529 memset(num_samples, 0, sizeof(num_samples));
531 if (s->max_num_subframes == 1 || get_bits1(&s->gb))
532 fixed_channel_layout = 1;
534 /** loop until the frame data is split between the subframes */
535 do {
536 int subframe_len;
538 /** check which channels contain the subframe */
539 for (c = 0; c < s->num_channels; c++) {
540 if (num_samples[c] == min_channel_len) {
541 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
542 (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe))
543 contains_subframe[c] = 1;
544 else
545 contains_subframe[c] = get_bits1(&s->gb);
546 } else
547 contains_subframe[c] = 0;
550 /** get subframe length, subframe_len == 0 is not allowed */
551 if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
552 return AVERROR_INVALIDDATA;
554 /** add subframes to the individual channels and find new min_channel_len */
555 min_channel_len += subframe_len;
556 for (c = 0; c < s->num_channels; c++) {
557 WMAProChannelCtx* chan = &s->channel[c];
559 if (contains_subframe[c]) {
560 if (chan->num_subframes >= MAX_SUBFRAMES) {
561 DEBUGF("broken frame: num subframes > 31\n");
562 return AVERROR_INVALIDDATA;
564 chan->subframe_len[chan->num_subframes] = subframe_len;
565 num_samples[c] += subframe_len;
566 ++chan->num_subframes;
567 if (num_samples[c] > s->samples_per_frame) {
568 DEBUGF("broken frame: "
569 "channel len > samples_per_frame\n");
570 return AVERROR_INVALIDDATA;
572 } else if (num_samples[c] <= min_channel_len) {
573 if (num_samples[c] < min_channel_len) {
574 channels_for_cur_subframe = 0;
575 min_channel_len = num_samples[c];
577 ++channels_for_cur_subframe;
580 } while (min_channel_len < s->samples_per_frame);
582 for (c = 0; c < s->num_channels; c++) {
583 int i;
584 int offset = 0;
585 for (i = 0; i < s->channel[c].num_subframes; i++) {
586 DEBUGF("frame[%i] channel[%i] subframe[%i]"
587 " len %i\n", s->frame_num, c, i,
588 s->channel[c].subframe_len[i]);
589 s->channel[c].subframe_offset[i] = offset;
590 offset += s->channel[c].subframe_len[i];
594 return 0;
597 #if 0
599 *@brief Calculate a decorrelation matrix from the bitstream parameters.
600 *@param s codec context
601 *@param chgroup channel group for which the matrix needs to be calculated
603 static void decode_decorrelation_matrix(WMAProDecodeCtx *s,
604 WMAProChannelGrp *chgroup)
606 int i;
607 int offset = 0;
608 int8_t rotation_offset[WMAPRO_MAX_CHANNELS * WMAPRO_MAX_CHANNELS];
609 memset(chgroup->decorrelation_matrix, 0, s->num_channels *
610 s->num_channels * sizeof(*chgroup->decorrelation_matrix));
612 for (i = 0; i < chgroup->num_channels * (chgroup->num_channels - 1) >> 1; i++)
613 rotation_offset[i] = get_bits(&s->gb, 6);
615 for (i = 0; i < chgroup->num_channels; i++) {
616 chgroup->decorrelation_matrix[chgroup->num_channels * i + i] =
617 get_bits1(&s->gb) ? 1.0 : -1.0;
619 if(chgroup->decorrelation_matrix[chgroup->num_channels * i + i] > 0)
620 chgroup->fixdecorrelation_matrix[chgroup->num_channels * i + i] = 0x10000;
621 else
622 chgroup->fixdecorrelation_matrix[chgroup->num_channels * i + i] = -0x10000;
625 for (i = 1; i < chgroup->num_channels; i++) {
626 int x;
627 for (x = 0; x < i; x++) {
628 int y;
629 for (y = 0; y < i + 1; y++) {
630 float v1 = chgroup->decorrelation_matrix[x * chgroup->num_channels + y];
631 float v2 = chgroup->decorrelation_matrix[i * chgroup->num_channels + y];
632 FIXED f1 = chgroup->fixdecorrelation_matrix[x * chgroup->num_channels + y];
633 FIXED f2 = chgroup->fixdecorrelation_matrix[i * chgroup->num_channels + y];
634 int n = rotation_offset[offset + x];
635 float sinv;
636 float cosv;
637 FIXED fixsinv;
638 FIXED fixcosv;
640 if (n < 32) {
641 sinv = sin64[n];
642 cosv = sin64[32 - n];
643 fixsinv = fixed_sin64[n];
644 fixcosv = fixed_sin64[32-n];
645 } else {
646 sinv = sin64[64 - n];
647 cosv = -sin64[n - 32];
648 fixsinv = fixed_sin64[64-n];
649 fixcosv = -fixed_sin64[n-32];
652 chgroup->decorrelation_matrix[y + x * chgroup->num_channels] =
653 (v1 * sinv) - (v2 * cosv);
654 chgroup->decorrelation_matrix[y + i * chgroup->num_channels] =
655 (v1 * cosv) + (v2 * sinv);
656 chgroup->fixdecorrelation_matrix[y + x * chgroup->num_channels] =
657 fixmulshift(f1, fixsinv, 31) - fixmulshift(f2, fixcosv, 31);
658 chgroup->fixdecorrelation_matrix[y + i * chgroup->num_channels] =
659 fixmulshift(f1, fixcosv, 31) + fixmulshift(f2, fixsinv, 31);
663 offset += i;
666 #endif
669 *@brief Decode channel transformation parameters
670 *@param s codec context
671 *@return 0 in case of success, < 0 in case of bitstream errors
673 static int decode_channel_transform(WMAProDecodeCtx* s)
675 int i;
676 /* should never consume more than 1921 bits for the 8 channel case
677 * 1 + MAX_CHANNELS * (MAX_CHANNELS + 2 + 3 * MAX_CHANNELS * MAX_CHANNELS
678 * + MAX_CHANNELS + MAX_BANDS + 1)
681 /** in the one channel case channel transforms are pointless */
682 s->num_chgroups = 0;
683 if (s->num_channels > 1) {
684 int remaining_channels = s->channels_for_cur_subframe;
686 if (get_bits1(&s->gb)) {
687 DEBUGF("unsupported channel transform bit\n");
688 return AVERROR_INVALIDDATA;
691 for (s->num_chgroups = 0; remaining_channels &&
692 s->num_chgroups < s->channels_for_cur_subframe; s->num_chgroups++) {
693 WMAProChannelGrp* chgroup = &s->chgroup[s->num_chgroups];
694 FIXED** channel_data = chgroup->channel_data;
695 chgroup->num_channels = 0;
696 chgroup->transform = 0;
698 /** decode channel mask */
699 if (remaining_channels > 2) {
700 for (i = 0; i < s->channels_for_cur_subframe; i++) {
701 int channel_idx = s->channel_indexes_for_cur_subframe[i];
702 if (!s->channel[channel_idx].grouped
703 && get_bits1(&s->gb)) {
704 ++chgroup->num_channels;
705 s->channel[channel_idx].grouped = 1;
706 *channel_data++ = s->channel[channel_idx].coeffs;
709 } else {
710 chgroup->num_channels = remaining_channels;
711 for (i = 0; i < s->channels_for_cur_subframe; i++) {
712 int channel_idx = s->channel_indexes_for_cur_subframe[i];
713 if (!s->channel[channel_idx].grouped)
714 *channel_data++ = s->channel[channel_idx].coeffs;
715 s->channel[channel_idx].grouped = 1;
719 /** decode transform type */
720 if (chgroup->num_channels == 2) {
721 if (get_bits1(&s->gb)) {
722 if (get_bits1(&s->gb)) {
723 DEBUGF("unsupported channel transform type\n");
725 } else {
726 chgroup->transform = 1;
727 if (s->num_channels == 2) {
728 chgroup->fixdecorrelation_matrix[0] = 0x10000;
729 chgroup->fixdecorrelation_matrix[1] = -0x10000;
730 chgroup->fixdecorrelation_matrix[2] = 0x10000;
731 chgroup->fixdecorrelation_matrix[3] = 0x10000;
732 } else {
733 /** cos(pi/4) */
734 chgroup->fixdecorrelation_matrix[0] = 0xB500;
735 chgroup->fixdecorrelation_matrix[1] = -0xB500;
736 chgroup->fixdecorrelation_matrix[2] = 0xB500;
737 chgroup->fixdecorrelation_matrix[3] = 0xB500;
740 } else if (chgroup->num_channels > 2) {
741 DEBUGF("in wmaprodec.c: Multichannel streams still not supported\n");
742 return -1;
743 #if 0
744 if (get_bits1(&s->gb)) {
745 chgroup->transform = 1;
746 if (get_bits1(&s->gb)) {
747 decode_decorrelation_matrix(s, chgroup);
748 } else {
749 /** FIXME: more than 6 coupled channels not supported */
750 if (chgroup->num_channels > 6) {
751 av_log_ask_for_sample(s->avctx,
752 "coupled channels > 6\n");
753 } else {
754 memcpy(chgroup->decorrelation_matrix,
755 default_decorrelation[chgroup->num_channels],
756 chgroup->num_channels * chgroup->num_channels *
757 sizeof(*chgroup->decorrelation_matrix));
761 #endif
764 /** decode transform on / off */
765 if (chgroup->transform) {
766 if (!get_bits1(&s->gb)) {
767 int i;
768 /** transform can be enabled for individual bands */
769 for (i = 0; i < s->num_bands; i++) {
770 chgroup->transform_band[i] = get_bits1(&s->gb);
772 } else {
773 memset(chgroup->transform_band, 1, s->num_bands);
776 remaining_channels -= chgroup->num_channels;
779 return 0;
783 *@brief Extract the coefficients from the bitstream.
784 *@param s codec context
785 *@param c current channel number
786 *@return 0 on success, < 0 in case of bitstream errors
788 static int decode_coeffs(WMAProDecodeCtx *s, int c)
790 int vlctable;
791 VLC* vlc;
792 WMAProChannelCtx* ci = &s->channel[c];
793 int rl_mode = 0;
794 int cur_coeff = 0;
795 int num_zeros = 0;
796 const uint16_t* run;
797 const FIXED* level;
799 DEBUGF("decode coefficients for channel %i\n", c);
801 vlctable = get_bits1(&s->gb);
802 vlc = &coef_vlc[vlctable];
804 if (vlctable) {
805 run = coef1_run;
806 level = coef1_level;
807 } else {
808 run = coef0_run;
809 level = coef0_level;
812 /** decode vector coefficients (consumes up to 167 bits per iteration for
813 4 vector coded large values) */
814 while (!rl_mode && cur_coeff + 3 < s->subframe_len) {
815 int32_t vals[4];
816 int i;
817 unsigned int idx;
819 idx = get_vlc2(&s->gb, vec4_vlc.table, VLCBITS, VEC4MAXDEPTH);
821 if (idx == HUFF_VEC4_SIZE - 1) {
822 for (i = 0; i < 4; i += 2) {
823 idx = get_vlc2(&s->gb, vec2_vlc.table, VLCBITS, VEC2MAXDEPTH);
824 if (idx == HUFF_VEC2_SIZE - 1) {
825 int v0, v1;
826 v0 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
827 if (v0 == HUFF_VEC1_SIZE - 1)
828 v0 += ff_wma_get_large_val(&s->gb);
829 v1 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
830 if (v1 == HUFF_VEC1_SIZE - 1)
831 v1 += ff_wma_get_large_val(&s->gb);
833 vals[i] = v0;
834 vals[i+1] = v1;
835 } else {
836 vals[i] = symbol_to_vec2[idx] >> 4;
837 vals[i+1] = symbol_to_vec2[idx] & 0xF;
840 } else {
841 vals[0] = symbol_to_vec4[idx] >> 12;
842 vals[1] = (symbol_to_vec4[idx] >> 8) & 0xF;
843 vals[2] = (symbol_to_vec4[idx] >> 4) & 0xF;
844 vals[3] = symbol_to_vec4[idx] & 0xF;
847 /** decode sign */
848 for (i = 0; i < 4; i++) {
849 if (vals[i]) {
850 int sign = get_bits1(&s->gb) - 1;
851 ci->coeffs[cur_coeff] = (sign == -1)? -vals[i]<<16 : vals[i]<<16;
852 num_zeros = 0;
853 } else {
854 ci->coeffs[cur_coeff] = 0;
855 /** switch to run level mode when subframe_len / 128 zeros
856 were found in a row */
857 rl_mode |= (++num_zeros > s->subframe_len >> 8);
859 ++cur_coeff;
863 /** decode run level coded coefficients */
864 if (rl_mode) {
865 memset(&ci->coeffs[cur_coeff], 0,
866 sizeof(*ci->coeffs) * (s->subframe_len - cur_coeff));
868 if (ff_wma_run_level_decode(&s->gb, vlc,
869 level, run, 1, ci->coeffs,
870 cur_coeff, s->subframe_len,
871 s->subframe_len, s->esc_len, 0))
872 return AVERROR_INVALIDDATA;
875 return 0;
879 *@brief Extract scale factors from the bitstream.
880 *@param s codec context
881 *@return 0 on success, < 0 in case of bitstream errors
883 static int decode_scale_factors(WMAProDecodeCtx* s)
885 int i;
887 /** should never consume more than 5344 bits
888 * MAX_CHANNELS * (1 + MAX_BANDS * 23)
891 for (i = 0; i < s->channels_for_cur_subframe; i++) {
892 int c = s->channel_indexes_for_cur_subframe[i];
893 int* sf;
894 int* sf_end;
895 s->channel[c].scale_factors = s->channel[c].saved_scale_factors[!s->channel[c].scale_factor_idx];
896 sf_end = s->channel[c].scale_factors + s->num_bands;
898 /** resample scale factors for the new block size
899 * as the scale factors might need to be resampled several times
900 * before some new values are transmitted, a backup of the last
901 * transmitted scale factors is kept in saved_scale_factors
903 if (s->channel[c].reuse_sf) {
904 const int8_t* sf_offsets = s->sf_offsets[s->table_idx][s->channel[c].table_idx];
905 int b;
906 for (b = 0; b < s->num_bands; b++)
907 s->channel[c].scale_factors[b] =
908 s->channel[c].saved_scale_factors[s->channel[c].scale_factor_idx][*sf_offsets++];
911 if (!s->channel[c].cur_subframe || get_bits1(&s->gb)) {
913 if (!s->channel[c].reuse_sf) {
914 int val;
915 /** decode DPCM coded scale factors */
916 s->channel[c].scale_factor_step = get_bits(&s->gb, 2) + 1;
917 val = 45 / s->channel[c].scale_factor_step;
918 for (sf = s->channel[c].scale_factors; sf < sf_end; sf++) {
919 val += get_vlc2(&s->gb, sf_vlc.table, SCALEVLCBITS, SCALEMAXDEPTH) - 60;
920 *sf = val;
922 } else {
923 int i;
924 /** run level decode differences to the resampled factors */
925 for (i = 0; i < s->num_bands; i++) {
926 int idx;
927 int skip;
928 int val;
929 int sign;
931 idx = get_vlc2(&s->gb, sf_rl_vlc.table, VLCBITS, SCALERLMAXDEPTH);
933 if (!idx) {
934 uint32_t code = get_bits(&s->gb, 14);
935 val = code >> 6;
936 sign = (code & 1) - 1;
937 skip = (code & 0x3f) >> 1;
938 } else if (idx == 1) {
939 break;
940 } else {
941 skip = scale_rl_run[idx];
942 val = scale_rl_level[idx];
943 sign = get_bits1(&s->gb)-1;
946 i += skip;
947 if (i >= s->num_bands) {
948 DEBUGF("invalid scale factor coding\n");
949 return AVERROR_INVALIDDATA;
951 s->channel[c].scale_factors[i] += (val ^ sign) - sign;
955 /** swap buffers */
956 s->channel[c].scale_factor_idx = !s->channel[c].scale_factor_idx;
957 s->channel[c].table_idx = s->table_idx;
958 s->channel[c].reuse_sf = 1;
961 /** calculate new scale factor maximum */
962 s->channel[c].max_scale_factor = s->channel[c].scale_factors[0];
963 for (sf = s->channel[c].scale_factors + 1; sf < sf_end; sf++) {
964 s->channel[c].max_scale_factor =
965 FFMAX(s->channel[c].max_scale_factor, *sf);
969 return 0;
973 *@brief Reconstruct the individual channel data.
974 *@param s codec context
976 static void inverse_channel_transform(WMAProDecodeCtx *s)
978 int i;
980 for (i = 0; i < s->num_chgroups; i++) {
981 if (s->chgroup[i].transform) {
982 const int num_channels = s->chgroup[i].num_channels;
983 FIXED data[WMAPRO_MAX_CHANNELS];
984 FIXED** ch_data = s->chgroup[i].channel_data;
985 FIXED** ch_end = ch_data + num_channels;
986 const int8_t* tb = s->chgroup[i].transform_band;
987 int16_t* sfb;
989 /** multichannel decorrelation */
990 for (sfb = s->cur_sfb_offsets;
991 sfb < s->cur_sfb_offsets + s->num_bands; sfb++) {
992 int y;
993 if (*tb++ == 1) {
994 /** multiply values with the decorrelation_matrix */
995 for (y = sfb[0]; y < FFMIN(sfb[1], s->subframe_len); y++) {
996 const FIXED* mat = s->chgroup[i].fixdecorrelation_matrix;
997 const FIXED* data_end = data + num_channels;
998 FIXED* data_ptr = data;
999 FIXED** ch;
1001 for (ch = ch_data; ch < ch_end; ch++)
1002 *data_ptr++ = (*ch)[y];
1004 for (ch = ch_data; ch < ch_end; ch++) {
1005 FIXED sum = 0;
1006 data_ptr = data;
1008 while (data_ptr < data_end)
1009 sum += fixmulshift(*data_ptr++, *mat++, 16);
1011 (*ch)[y] = sum;
1014 } else if (s->num_channels == 2) {
1016 int len = FFMIN(sfb[1], s->subframe_len) - sfb[0];
1017 vector_fixmul_scalar(ch_data[0] + sfb[0],
1018 ch_data[0] + sfb[0],
1019 0x00016A00, len,16);
1020 vector_fixmul_scalar(ch_data[1] + sfb[0],
1021 ch_data[1] + sfb[0],
1022 0x00016A00, len,16);
1031 *@brief Apply sine window and reconstruct the output buffer.
1032 *@param s codec context
1034 static void wmapro_window(WMAProDecodeCtx *s)
1036 int i;
1038 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1039 int c = s->channel_indexes_for_cur_subframe[i];
1040 const FIXED* window;
1041 int winlen = s->channel[c].prev_block_len;
1042 FIXED *xstart= s->channel[c].coeffs - (winlen >> 1);
1044 if (s->subframe_len < winlen) {
1045 xstart += (winlen - s->subframe_len) >> 1;
1046 winlen = s->subframe_len;
1049 window = sine_windows[av_log2(winlen) - BLOCK_MIN_BITS];
1051 winlen >>= 1;
1053 vector_fixmul_window(xstart, xstart, xstart + winlen,
1054 window, 0, winlen);
1056 s->channel[c].prev_block_len = s->subframe_len;
1062 *@brief Decode a single subframe (block).
1063 *@param s codec context
1064 *@return 0 on success, < 0 when decoding failed
1066 static int decode_subframe(WMAProDecodeCtx *s)
1068 int offset = s->samples_per_frame;
1069 int subframe_len = s->samples_per_frame;
1070 int i;
1071 int total_samples = s->samples_per_frame * s->num_channels;
1072 int transmit_coeffs = 0;
1073 int cur_subwoofer_cutoff;
1075 s->subframe_offset = get_bits_count(&s->gb);
1077 /** reset channel context and find the next block offset and size
1078 == the next block of the channel with the smallest number of
1079 decoded samples
1081 for (i = 0; i < s->num_channels; i++) {
1082 s->channel[i].grouped = 0;
1083 if (offset > s->channel[i].decoded_samples) {
1084 offset = s->channel[i].decoded_samples;
1085 subframe_len =
1086 s->channel[i].subframe_len[s->channel[i].cur_subframe];
1090 DEBUGF("processing subframe with offset %i len %i\n", offset, subframe_len);
1092 /** get a list of all channels that contain the estimated block */
1093 s->channels_for_cur_subframe = 0;
1094 for (i = 0; i < s->num_channels; i++) {
1095 const int cur_subframe = s->channel[i].cur_subframe;
1096 /** substract already processed samples */
1097 total_samples -= s->channel[i].decoded_samples;
1099 /** and count if there are multiple subframes that match our profile */
1100 if (offset == s->channel[i].decoded_samples &&
1101 subframe_len == s->channel[i].subframe_len[cur_subframe]) {
1102 total_samples -= s->channel[i].subframe_len[cur_subframe];
1103 s->channel[i].decoded_samples +=
1104 s->channel[i].subframe_len[cur_subframe];
1105 s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
1106 ++s->channels_for_cur_subframe;
1110 /** check if the frame will be complete after processing the
1111 estimated block */
1112 if (!total_samples)
1113 s->parsed_all_subframes = 1;
1116 DEBUGF("subframe is part of %i channels\n", s->channels_for_cur_subframe);
1118 /** calculate number of scale factor bands and their offsets */
1119 s->table_idx = av_log2(s->samples_per_frame/subframe_len);
1120 s->num_bands = s->num_sfb[s->table_idx];
1121 s->cur_sfb_offsets = s->sfb_offsets[s->table_idx];
1122 cur_subwoofer_cutoff = s->subwoofer_cutoffs[s->table_idx];
1124 /** configure the decoder for the current subframe */
1125 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1126 int c = s->channel_indexes_for_cur_subframe[i];
1128 s->channel[c].coeffs = &s->channel[c].out[(s->samples_per_frame >> 1)
1129 + offset];
1132 s->subframe_len = subframe_len;
1133 s->esc_len = av_log2(s->subframe_len - 1) + 1;
1135 /** skip extended header if any */
1136 if (get_bits1(&s->gb)) {
1137 int num_fill_bits;
1138 if (!(num_fill_bits = get_bits(&s->gb, 2))) {
1139 int len = get_bits(&s->gb, 4);
1140 num_fill_bits = get_bits(&s->gb, len) + 1;
1143 if (num_fill_bits >= 0) {
1144 if (get_bits_count(&s->gb) + num_fill_bits > s->num_saved_bits) {
1145 DEBUGF("invalid number of fill bits\n");
1146 return AVERROR_INVALIDDATA;
1149 skip_bits_long(&s->gb, num_fill_bits);
1153 /** no idea for what the following bit is used */
1154 if (get_bits1(&s->gb)) {
1155 DEBUGF("reserved bit set\n");
1156 return AVERROR_INVALIDDATA;
1159 if (decode_channel_transform(s) < 0)
1160 return AVERROR_INVALIDDATA;
1162 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1163 int c = s->channel_indexes_for_cur_subframe[i];
1164 if ((s->channel[c].transmit_coefs = get_bits1(&s->gb)))
1165 transmit_coeffs = 1;
1168 if (transmit_coeffs) {
1169 int step;
1170 int quant_step = 90 * s->bits_per_sample >> 4;
1171 if ((get_bits1(&s->gb))) {
1172 /** FIXME: might change run level mode decision */
1173 DEBUGF("unsupported quant step coding\n");
1174 return AVERROR_INVALIDDATA;
1176 /** decode quantization step */
1177 step = get_sbits(&s->gb, 6);
1178 quant_step += step;
1179 if (step == -32 || step == 31) {
1180 const int sign = (step == 31) - 1;
1181 int quant = 0;
1182 while (get_bits_count(&s->gb) + 5 < s->num_saved_bits &&
1183 (step = get_bits(&s->gb, 5)) == 31) {
1184 quant += 31;
1186 quant_step += ((quant + step) ^ sign) - sign;
1188 if (quant_step < 0) {
1189 DEBUGF("negative quant step\n");
1192 /** decode quantization step modifiers for every channel */
1194 if (s->channels_for_cur_subframe == 1) {
1195 s->channel[s->channel_indexes_for_cur_subframe[0]].quant_step = quant_step;
1196 } else {
1197 int modifier_len = get_bits(&s->gb, 3);
1198 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1199 int c = s->channel_indexes_for_cur_subframe[i];
1200 s->channel[c].quant_step = quant_step;
1201 if (get_bits1(&s->gb)) {
1202 if (modifier_len) {
1203 s->channel[c].quant_step += get_bits(&s->gb, modifier_len) + 1;
1204 } else
1205 ++s->channel[c].quant_step;
1210 /** decode scale factors */
1211 if (decode_scale_factors(s) < 0)
1212 return AVERROR_INVALIDDATA;
1215 DEBUGF("BITSTREAM: subframe header length was %i\n",
1216 get_bits_count(&s->gb) - s->subframe_offset);
1218 /** parse coefficients */
1219 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1220 int c = s->channel_indexes_for_cur_subframe[i];
1221 if (s->channel[c].transmit_coefs &&
1222 get_bits_count(&s->gb) < s->num_saved_bits) {
1223 decode_coeffs(s, c);
1224 } else {
1225 memset(s->channel[c].coeffs, 0,
1226 sizeof(*s->channel[c].coeffs) * subframe_len);
1230 DEBUGF("BITSTREAM: subframe length was %i\n",
1231 get_bits_count(&s->gb) - s->subframe_offset);
1233 if (transmit_coeffs) {
1234 /** reconstruct the per channel data */
1235 inverse_channel_transform(s);
1236 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1237 int c = s->channel_indexes_for_cur_subframe[i];
1238 const int* sf = s->channel[c].scale_factors;
1239 int b;
1241 if (c == s->lfe_channel)
1242 memset(&s->tmp[cur_subwoofer_cutoff], 0, sizeof(*s->tmp) *
1243 (subframe_len - cur_subwoofer_cutoff));
1245 /** inverse quantization and rescaling */
1246 for (b = 0; b < s->num_bands; b++) {
1247 const int end = FFMIN(s->cur_sfb_offsets[b+1], s->subframe_len);
1248 const int exp = s->channel[c].quant_step -
1249 (s->channel[c].max_scale_factor - *sf++) *
1250 s->channel[c].scale_factor_step;
1252 if(exp < EXP_MIN || exp > EXP_MAX) {
1253 DEBUGF("in wmaprodec.c : unhandled value for exp, please report sample.\n");
1254 return -1;
1256 const FIXED quant = QUANT(exp);
1257 int start = s->cur_sfb_offsets[b];
1259 vector_fixmul_scalar(s->tmp+start,
1260 s->channel[c].coeffs + start,
1261 quant, end-start, 24);
1266 /** apply imdct (ff_imdct_half == DCTIV with reverse) */
1267 imdct_half(av_log2(subframe_len)+1,
1268 s->channel[c].coeffs, s->tmp);
1273 /** window and overlapp-add */
1274 wmapro_window(s);
1276 /** handled one subframe */
1277 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1278 int c = s->channel_indexes_for_cur_subframe[i];
1279 if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
1280 DEBUGF("broken subframe\n");
1281 return AVERROR_INVALIDDATA;
1283 ++s->channel[c].cur_subframe;
1286 return 0;
1290 *@brief Decode one WMA frame.
1291 *@param s codec context
1292 *@return 0 if the trailer bit indicates that this is the last frame,
1293 * 1 if there are additional frames
1295 static int decode_frame(WMAProDecodeCtx *s)
1297 GetBitContext* gb = &s->gb;
1298 int more_frames = 0;
1299 int len = 0;
1300 int i;
1302 /** check for potential output buffer overflow */
1303 if (s->num_channels * s->samples_per_frame > s->samples_end - s->samples) {
1304 /** return an error if no frame could be decoded at all */
1305 DEBUGF("not enough space for the output samples\n");
1306 s->packet_loss = 1;
1307 return 0;
1310 /** get frame length */
1311 if (s->len_prefix)
1312 len = get_bits(gb, s->log2_frame_size);
1314 DEBUGF("decoding frame with length %x\n", len);
1316 /** decode tile information */
1317 if (decode_tilehdr(s)) {
1318 s->packet_loss = 1;
1319 return 0;
1322 /** read postproc transform */
1323 if (s->num_channels > 1 && get_bits1(gb)) {
1324 DEBUGF("Unsupported postproc transform found\n");
1325 s->packet_loss = 1;
1326 return 0;
1329 /** read drc info */
1330 if (s->dynamic_range_compression) {
1331 s->drc_gain = get_bits(gb, 8);
1332 DEBUGF("drc_gain %i\n", s->drc_gain);
1335 /** no idea what these are for, might be the number of samples
1336 that need to be skipped at the beginning or end of a stream */
1337 if (get_bits1(gb)) {
1338 int skip;
1340 /** usually true for the first frame */
1341 if (get_bits1(gb)) {
1342 skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1343 DEBUGF("start skip: %i\n", skip);
1346 /** sometimes true for the last frame */
1347 if (get_bits1(gb)) {
1348 skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1349 DEBUGF("end skip: %i\n", skip);
1354 DEBUGF("BITSTREAM: frame header length was %i\n",
1355 get_bits_count(gb) - s->frame_offset);
1357 /** reset subframe states */
1358 s->parsed_all_subframes = 0;
1359 for (i = 0; i < s->num_channels; i++) {
1360 s->channel[i].decoded_samples = 0;
1361 s->channel[i].cur_subframe = 0;
1362 s->channel[i].reuse_sf = 0;
1365 /** decode all subframes */
1366 while (!s->parsed_all_subframes) {
1367 if (decode_subframe(s) < 0) {
1368 s->packet_loss = 1;
1369 return 0;
1373 /** interleave samples and write them to the output buffer */
1374 for (i = 0; i < s->num_channels; i++) {
1375 FIXED* ptr = s->samples + i;
1376 int incr = s->num_channels;
1377 FIXED* iptr = s->channel[i].out;
1378 FIXED* iend = iptr + s->samples_per_frame;
1380 while (iptr < iend) {
1381 *ptr = *iptr++ << 1;
1382 ptr += incr;
1385 /** reuse second half of the IMDCT output for the next frame */
1386 memcpy(&s->channel[i].out[0],
1387 &s->channel[i].out[s->samples_per_frame],
1388 s->samples_per_frame * sizeof(*s->channel[i].out) >> 1);
1391 if (s->skip_frame) {
1392 s->skip_frame = 0;
1393 } else
1394 s->samples += s->num_channels * s->samples_per_frame;
1396 if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
1397 /** FIXME: not sure if this is always an error */
1398 DEBUGF("frame[%i] would have to skip %i bits\n",
1399 (int)s->frame_num, len - (get_bits_count(gb) - s->frame_offset) - 1);
1400 s->packet_loss = 1;
1401 return 0;
1404 /** skip the rest of the frame data */
1405 skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
1407 /** decode trailer bit */
1408 more_frames = get_bits1(gb);
1410 ++s->frame_num;
1411 return more_frames;
1415 *@brief Calculate remaining input buffer length.
1416 *@param s codec context
1417 *@param gb bitstream reader context
1418 *@return remaining size in bits
1420 static int remaining_bits(WMAProDecodeCtx *s, GetBitContext *gb)
1422 return s->buf_bit_size - get_bits_count(gb);
1426 *@brief Fill the bit reservoir with a (partial) frame.
1427 *@param s codec context
1428 *@param gb bitstream reader context
1429 *@param len length of the partial frame
1430 *@param append decides wether to reset the buffer or not
1432 static void save_bits(WMAProDecodeCtx *s, GetBitContext* gb, int len,
1433 int append)
1435 int buflen;
1437 /** when the frame data does not need to be concatenated, the input buffer
1438 is resetted and additional bits from the previous frame are copyed
1439 and skipped later so that a fast byte copy is possible */
1441 if (!append) {
1442 s->frame_offset = get_bits_count(gb) & 7;
1443 s->num_saved_bits = s->frame_offset;
1444 init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
1447 buflen = (s->num_saved_bits + len + 8) >> 3;
1449 if (len <= 0 || buflen > MAX_FRAMESIZE) {
1450 DEBUGF("input buffer too small\n");
1451 s->packet_loss = 1;
1452 return;
1455 s->num_saved_bits += len;
1456 if (!append) {
1457 ff_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
1458 s->num_saved_bits);
1459 } else {
1460 int align = 8 - (get_bits_count(gb) & 7);
1461 align = FFMIN(align, len);
1462 put_bits(&s->pb, align, get_bits(gb, align));
1463 len -= align;
1464 ff_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
1466 skip_bits_long(gb, len);
1469 PutBitContext tmp = s->pb;
1470 flush_put_bits(&tmp);
1473 init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
1474 skip_bits(&s->gb, s->frame_offset);
1478 *@brief Decode a single WMA packet.
1479 *@param avctx codec context
1480 *@param data the output buffer
1481 *@param data_size number of bytes that were written to the output buffer
1482 *@param avpkt input packet
1483 *@return number of bytes that were read from the input buffer
1485 int decode_packet(asf_waveformatex_t *wfx, void *data, int *data_size,
1486 void* pktdata, int size)
1488 WMAProDecodeCtx *s = &globWMAProDecCtx;
1489 GetBitContext* gb = &s->pgb;
1490 const uint8_t* buf = pktdata;
1491 int buf_size = size;
1492 int num_bits_prev_frame;
1493 int packet_sequence_number;
1495 s->samples = data;
1496 s->samples_end = (FIXED*)((int8_t*)data + *data_size);
1497 *data_size = 0;
1499 if (s->packet_done || s->packet_loss) {
1500 s->packet_done = 0;
1501 s->buf_bit_size = buf_size << 3;
1503 /** sanity check for the buffer length */
1504 if (buf_size < wfx->blockalign)
1505 return 0;
1507 buf_size = wfx->blockalign;
1509 /** parse packet header */
1510 init_get_bits(gb, buf, s->buf_bit_size);
1511 packet_sequence_number = get_bits(gb, 4);
1512 skip_bits(gb, 2);
1514 /** get number of bits that need to be added to the previous frame */
1515 num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
1516 DEBUGF("packet[%d]: nbpf %x\n", s->frame_num,
1517 num_bits_prev_frame);
1519 /** check for packet loss */
1520 if (!s->packet_loss &&
1521 ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
1522 s->packet_loss = 1;
1523 DEBUGF("Packet loss detected! seq %x vs %x\n",
1524 s->packet_sequence_number, packet_sequence_number);
1526 s->packet_sequence_number = packet_sequence_number;
1528 if (num_bits_prev_frame > 0) {
1529 /** append the previous frame data to the remaining data from the
1530 previous packet to create a full frame */
1531 save_bits(s, gb, num_bits_prev_frame, 1);
1532 DEBUGF("accumulated %x bits of frame data\n",
1533 s->num_saved_bits - s->frame_offset);
1535 /** decode the cross packet frame if it is valid */
1536 if (!s->packet_loss)
1537 decode_frame(s);
1538 } else if (s->num_saved_bits - s->frame_offset) {
1539 DEBUGF("ignoring %x previously saved bits\n",
1540 s->num_saved_bits - s->frame_offset);
1543 s->packet_loss = 0;
1545 } else {
1546 int frame_size;
1547 s->buf_bit_size = size << 3;
1548 init_get_bits(gb, pktdata, s->buf_bit_size);
1549 skip_bits(gb, s->packet_offset);
1550 if (remaining_bits(s, gb) > s->log2_frame_size &&
1551 (frame_size = show_bits(gb, s->log2_frame_size)) &&
1552 frame_size <= remaining_bits(s, gb)) {
1553 save_bits(s, gb, frame_size, 0);
1554 s->packet_done = !decode_frame(s);
1555 } else
1556 s->packet_done = 1;
1559 if (s->packet_done && !s->packet_loss &&
1560 remaining_bits(s, gb) > 0) {
1561 /** save the rest of the data so that it can be decoded
1562 with the next packet */
1563 save_bits(s, gb, remaining_bits(s, gb), 0);
1566 *data_size = (int8_t *)s->samples - (int8_t *)data;
1567 s->packet_offset = get_bits_count(gb) & 7;
1569 s->frame_num++;
1570 return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
1573 #if 0
1575 *@brief wmapro decoder
1577 AVCodec wmapro_decoder = {
1578 "wmapro",
1579 AVMEDIA_TYPE_AUDIO,
1580 CODEC_ID_WMAPRO,
1581 sizeof(WMAProDecodeCtx),
1582 decode_init,
1583 NULL,
1584 decode_end,
1585 decode_packet,
1586 .capabilities = CODEC_CAP_SUBFRAMES,
1587 .flush= flush,
1588 .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Professional"),
1590 #endif