libwmapro: coldfire asm for vector_fixmul_window, gives a speedup of ~13%, drop the...
[kugel-rb.git] / apps / codecs / libwmapro / wmaprodec.c
blobb7879a26445004047eb908a7a34bea69ded8ae8c
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 "wmapro_math.h"
98 #include "codecs.h"
99 #include "codeclib.h"
100 #include "../libasf/asf.h"
102 /* Uncomment the following line to enable some debug output */
103 //#define WMAPRO_DUMP_CTX_EN
105 #undef DEBUGF
106 #ifdef WMAPRO_DUMP_CTX_EN
107 # define DEBUGF printf
108 #else
109 # define DEBUGF(...)
110 #endif
112 /* Some defines to make it compile */
113 #define AVERROR_INVALIDDATA -1
114 #define AVERROR_PATCHWELCOME -2
115 #define av_log_ask_for_sample(...)
117 /* Taken from avcodec.h */
118 #define FF_INPUT_BUFFER_PADDING_SIZE 8
120 /* Taken from libavutil/mem.h */
121 #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
123 /* Taken from libavutil/common.h */
124 #define FFMIN(a,b) ((a) > (b) ? (b) : (a))
125 #define FFMAX(a,b) ((a) > (b) ? (a) : (b))
127 /** current decoder limitations */
128 #define WMAPRO_MAX_CHANNELS 8 ///< max number of handled channels
129 #define MAX_SUBFRAMES 32 ///< max number of subframes per channel
130 #define MAX_BANDS 29 ///< max number of scale factor bands
131 #define MAX_FRAMESIZE 32768 ///< maximum compressed frame size
133 #define WMAPRO_BLOCK_MAX_BITS 12 ///< log2 of max block size
134 #define WMAPRO_BLOCK_MAX_SIZE (1 << WMAPRO_BLOCK_MAX_BITS) ///< maximum block size
135 #define WMAPRO_BLOCK_SIZES (WMAPRO_BLOCK_MAX_BITS - BLOCK_MIN_BITS + 1) ///< possible block sizes
138 #define VLCBITS 9
139 #define SCALEVLCBITS 8
140 #define VEC4MAXDEPTH ((HUFF_VEC4_MAXBITS+VLCBITS-1)/VLCBITS)
141 #define VEC2MAXDEPTH ((HUFF_VEC2_MAXBITS+VLCBITS-1)/VLCBITS)
142 #define VEC1MAXDEPTH ((HUFF_VEC1_MAXBITS+VLCBITS-1)/VLCBITS)
143 #define SCALEMAXDEPTH ((HUFF_SCALE_MAXBITS+SCALEVLCBITS-1)/SCALEVLCBITS)
144 #define SCALERLMAXDEPTH ((HUFF_SCALE_RL_MAXBITS+VLCBITS-1)/VLCBITS)
146 static VLC sf_vlc; ///< scale factor DPCM vlc
147 static VLC sf_rl_vlc; ///< scale factor run length vlc
148 static VLC vec4_vlc; ///< 4 coefficients per symbol
149 static VLC vec2_vlc; ///< 2 coefficients per symbol
150 static VLC vec1_vlc; ///< 1 coefficient per symbol
151 static VLC coef_vlc[2]; ///< coefficient run length vlc codes
152 //static float sin64[33]; ///< sinus table for decorrelation
155 * @brief frame specific decoder context for a single channel
157 typedef struct {
158 int16_t prev_block_len; ///< length of the previous block
159 uint8_t transmit_coefs;
160 uint8_t num_subframes;
161 uint16_t subframe_len[MAX_SUBFRAMES]; ///< subframe length in samples
162 uint16_t subframe_offset[MAX_SUBFRAMES]; ///< subframe positions in the current frame
163 uint8_t cur_subframe; ///< current subframe number
164 uint16_t decoded_samples; ///< number of already processed samples
165 uint8_t grouped; ///< channel is part of a group
166 int quant_step; ///< quantization step for the current subframe
167 int8_t reuse_sf; ///< share scale factors between subframes
168 int8_t scale_factor_step; ///< scaling step for the current subframe
169 int max_scale_factor; ///< maximum scale factor for the current subframe
170 int saved_scale_factors[2][MAX_BANDS]; ///< resampled and (previously) transmitted scale factor values
171 int8_t scale_factor_idx; ///< index for the transmitted scale factor values (used for resampling)
172 int* scale_factors; ///< pointer to the scale factor values used for decoding
173 uint8_t table_idx; ///< index in sf_offsets for the scale factor reference block
174 int32_t* coeffs; ///< pointer to the subframe decode buffer
175 DECLARE_ALIGNED(16, int32_t, out)[WMAPRO_BLOCK_MAX_SIZE + WMAPRO_BLOCK_MAX_SIZE / 2]; ///< output buffer
176 } WMAProChannelCtx;
179 * @brief channel group for channel transformations
181 typedef struct {
182 uint8_t num_channels; ///< number of channels in the group
183 int8_t transform; ///< transform on / off
184 int8_t transform_band[MAX_BANDS]; ///< controls if the transform is enabled for a certain band
185 //float decorrelation_matrix[WMAPRO_MAX_CHANNELS*WMAPRO_MAX_CHANNELS];
186 int32_t* channel_data[WMAPRO_MAX_CHANNELS]; ///< transformation coefficients
187 int32_t fixdecorrelation_matrix[WMAPRO_MAX_CHANNELS*WMAPRO_MAX_CHANNELS];
188 } WMAProChannelGrp;
191 * @brief main decoder context
193 typedef struct WMAProDecodeCtx {
194 /* generic decoder variables */
195 uint8_t frame_data[MAX_FRAMESIZE +
196 FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
197 PutBitContext pb; ///< context for filling the frame_data buffer
198 DECLARE_ALIGNED(16, int32_t, tmp)[WMAPRO_BLOCK_MAX_SIZE]; ///< IMDCT input buffer
200 /* frame size dependent frame information (set during initialization) */
201 uint32_t decode_flags; ///< used compression features
202 uint8_t len_prefix; ///< frame is prefixed with its length
203 uint8_t dynamic_range_compression; ///< frame contains DRC data
204 uint8_t bits_per_sample; ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
205 uint16_t samples_per_frame; ///< number of samples to output
206 uint16_t log2_frame_size;
207 int8_t num_channels; ///< number of channels in the stream (same as AVCodecContext.num_channels)
208 int8_t lfe_channel; ///< lfe channel index
209 uint8_t max_num_subframes;
210 uint8_t subframe_len_bits; ///< number of bits used for the subframe length
211 uint8_t max_subframe_len_bit; ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
212 uint16_t min_samples_per_subframe;
213 int8_t num_sfb[WMAPRO_BLOCK_SIZES]; ///< scale factor bands per block size
214 int16_t sfb_offsets[WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor band offsets (multiples of 4)
215 int8_t sf_offsets[WMAPRO_BLOCK_SIZES][WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
216 int16_t subwoofer_cutoffs[WMAPRO_BLOCK_SIZES]; ///< subwoofer cutoff values
218 /* packet decode state */
219 GetBitContext pgb; ///< bitstream reader context for the packet
220 uint8_t packet_offset; ///< frame offset in the packet
221 uint8_t packet_sequence_number; ///< current packet number
222 int num_saved_bits; ///< saved number of bits
223 int frame_offset; ///< frame offset in the bit reservoir
224 int subframe_offset; ///< subframe offset in the bit reservoir
225 uint8_t packet_loss; ///< set in case of bitstream error
226 uint8_t packet_done; ///< set when a packet is fully decoded
228 /* frame decode state */
229 uint32_t frame_num; ///< current frame number
230 GetBitContext gb; ///< bitstream reader context
231 int buf_bit_size; ///< buffer size in bits
232 int32_t* samples;
233 int32_t* samples_end; ///< maximum samplebuffer pointer
234 uint8_t drc_gain; ///< gain for the DRC tool
235 int8_t skip_frame; ///< skip output step
236 int8_t parsed_all_subframes; ///< all subframes decoded?
238 /* subframe/block decode state */
239 int16_t subframe_len; ///< current subframe length
240 int8_t channels_for_cur_subframe; ///< number of channels that contain the subframe
241 int8_t channel_indexes_for_cur_subframe[WMAPRO_MAX_CHANNELS];
242 int8_t num_bands; ///< number of scale factor bands
243 int16_t* cur_sfb_offsets; ///< sfb offsets for the current block
244 uint8_t table_idx; ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
245 int8_t esc_len; ///< length of escaped coefficients
247 uint8_t num_chgroups; ///< number of channel groups
248 WMAProChannelGrp chgroup[WMAPRO_MAX_CHANNELS]; ///< channel group information
250 WMAProChannelCtx channel[WMAPRO_MAX_CHANNELS]; ///< per channel data
251 } WMAProDecodeCtx;
253 /* static decode context, to avoid malloc */
254 static WMAProDecodeCtx globWMAProDecCtx;
257 *@brief helper function to print the most important members of the context
258 *@param s context
260 #ifdef WMAPRO_DUMP_CTX_EN
261 static void dump_context(WMAProDecodeCtx *s)
263 #define PRINT(a, b) printf(" %s = %d\n", a, b);
264 #define PRINT_HEX(a, b) printf(" %s = %x\n", a, b);
266 PRINT("ed sample bit depth", s->bits_per_sample);
267 PRINT_HEX("ed decode flags", s->decode_flags);
268 PRINT("samples per frame", s->samples_per_frame);
269 PRINT("log2 frame size", s->log2_frame_size);
270 PRINT("max num subframes", s->max_num_subframes);
271 PRINT("len prefix", s->len_prefix);
272 PRINT("num channels", s->num_channels);
274 #endif
277 *@brief Initialize the decoder.
278 *@param avctx codec context
279 *@return 0 on success, -1 otherwise
281 int decode_init(asf_waveformatex_t *wfx)
283 memset(&globWMAProDecCtx, 0, sizeof(WMAProDecodeCtx));
284 WMAProDecodeCtx *s = &globWMAProDecCtx;
285 uint8_t *edata_ptr = wfx->data;
286 unsigned int channel_mask;
287 int i;
288 int log2_max_num_subframes;
289 int num_possible_block_sizes;
291 #if defined(CPU_COLDFIRE)
292 coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
293 #endif
295 init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
297 if (wfx->datalen >= 18) {
298 s->decode_flags = AV_RL16(edata_ptr+14);
299 channel_mask = AV_RL32(edata_ptr+2);
300 s->bits_per_sample = AV_RL16(edata_ptr);
301 /** dump the extradata */
302 for (i = 0; i < wfx->datalen; i++)
303 DEBUGF("[%x] ", wfx->data[i]);
304 DEBUGF("\n");
306 } else {
307 DEBUGF("Unknown extradata size\n");
308 return AVERROR_INVALIDDATA;
311 /** generic init */
312 s->log2_frame_size = av_log2(wfx->blockalign) + 4;
314 /** frame info */
315 s->skip_frame = 1; /** skip first frame */
316 s->packet_loss = 1;
317 s->len_prefix = (s->decode_flags & 0x40);
319 if (!s->len_prefix) {
320 DEBUGF("no length prefix\n");
321 return AVERROR_INVALIDDATA;
324 /** get frame len */
325 s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(wfx->rate,
326 3, s->decode_flags);
328 /** init previous block len */
329 for (i = 0; i < wfx->channels; i++)
330 s->channel[i].prev_block_len = s->samples_per_frame;
332 /** subframe info */
333 log2_max_num_subframes = ((s->decode_flags & 0x38) >> 3);
334 s->max_num_subframes = 1 << log2_max_num_subframes;
335 if (s->max_num_subframes == 16)
336 s->max_subframe_len_bit = 1;
337 s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
339 num_possible_block_sizes = log2_max_num_subframes + 1;
340 s->min_samples_per_subframe = s->samples_per_frame / s->max_num_subframes;
341 s->dynamic_range_compression = (s->decode_flags & 0x80);
343 if (s->max_num_subframes > MAX_SUBFRAMES) {
344 DEBUGF("invalid number of subframes %i\n",
345 s->max_num_subframes);
346 return AVERROR_INVALIDDATA;
349 s->num_channels = wfx->channels;
351 /** extract lfe channel position */
352 s->lfe_channel = -1;
354 if (channel_mask & 8) {
355 unsigned int mask;
356 for (mask = 1; mask < 16; mask <<= 1) {
357 if (channel_mask & mask)
358 ++s->lfe_channel;
362 if (s->num_channels < 0) {
363 DEBUGF("invalid number of channels %d\n", s->num_channels);
364 return AVERROR_INVALIDDATA;
365 } else if (s->num_channels > WMAPRO_MAX_CHANNELS) {
366 DEBUGF("unsupported number of channels\n");
367 return AVERROR_PATCHWELCOME;
370 INIT_VLC_STATIC(&sf_vlc, SCALEVLCBITS, HUFF_SCALE_SIZE,
371 scale_huffbits, 1, 1,
372 scale_huffcodes, 2, 2, 616);
374 INIT_VLC_STATIC(&sf_rl_vlc, VLCBITS, HUFF_SCALE_RL_SIZE,
375 scale_rl_huffbits, 1, 1,
376 scale_rl_huffcodes, 4, 4, 1406);
378 INIT_VLC_STATIC(&coef_vlc[0], VLCBITS, HUFF_COEF0_SIZE,
379 coef0_huffbits, 1, 1,
380 coef0_huffcodes, 4, 4, 2108);
382 INIT_VLC_STATIC(&coef_vlc[1], VLCBITS, HUFF_COEF1_SIZE,
383 coef1_huffbits, 1, 1,
384 coef1_huffcodes, 4, 4, 3912);
386 INIT_VLC_STATIC(&vec4_vlc, VLCBITS, HUFF_VEC4_SIZE,
387 vec4_huffbits, 1, 1,
388 vec4_huffcodes, 2, 2, 604);
390 INIT_VLC_STATIC(&vec2_vlc, VLCBITS, HUFF_VEC2_SIZE,
391 vec2_huffbits, 1, 1,
392 vec2_huffcodes, 2, 2, 562);
394 INIT_VLC_STATIC(&vec1_vlc, VLCBITS, HUFF_VEC1_SIZE,
395 vec1_huffbits, 1, 1,
396 vec1_huffcodes, 2, 2, 562);
398 /** calculate number of scale factor bands and their offsets
399 for every possible block size */
400 for (i = 0; i < num_possible_block_sizes; i++) {
401 int subframe_len = s->samples_per_frame >> i;
402 int x;
403 int band = 1;
405 s->sfb_offsets[i][0] = 0;
407 for (x = 0; x < MAX_BANDS-1 && s->sfb_offsets[i][band - 1] < subframe_len; x++) {
408 int offset = (subframe_len * 2 * critical_freq[x])
409 / wfx->rate + 2;
410 offset &= ~3;
411 if (offset > s->sfb_offsets[i][band - 1])
412 s->sfb_offsets[i][band++] = offset;
414 s->sfb_offsets[i][band - 1] = subframe_len;
415 s->num_sfb[i] = band - 1;
419 /** Scale factors can be shared between blocks of different size
420 as every block has a different scale factor band layout.
421 The matrix sf_offsets is needed to find the correct scale factor.
424 for (i = 0; i < num_possible_block_sizes; i++) {
425 int b;
426 for (b = 0; b < s->num_sfb[i]; b++) {
427 int x;
428 int offset = ((s->sfb_offsets[i][b]
429 + s->sfb_offsets[i][b + 1] - 1) << i) >> 1;
430 for (x = 0; x < num_possible_block_sizes; x++) {
431 int v = 0;
432 while (s->sfb_offsets[x][v + 1] << x < offset)
433 ++v;
434 s->sf_offsets[i][x][b] = v;
439 /** calculate subwoofer cutoff values */
440 for (i = 0; i < num_possible_block_sizes; i++) {
441 int block_size = s->samples_per_frame >> i;
442 int cutoff = (440*block_size + 3 * (wfx->rate >> 1) - 1)
443 / wfx->rate;
444 s->subwoofer_cutoffs[i] = av_clip(cutoff, 4, block_size);
447 #if 0
448 /** calculate sine values for the decorrelation matrix */
449 for (i = 0; i < 33; i++)
450 sin64[i] = sin(i*M_PI / 64.0);
451 #endif
453 #ifdef WMAPRO_DUMP_CTX_EN
454 dump_context(s);
455 #endif
456 return 0;
460 *@brief Decode the subframe length.
461 *@param s context
462 *@param offset sample offset in the frame
463 *@return decoded subframe length on success, < 0 in case of an error
465 static int decode_subframe_length(WMAProDecodeCtx *s, int offset)
467 int frame_len_shift = 0;
468 int subframe_len;
470 /** no need to read from the bitstream when only one length is possible */
471 if (offset == s->samples_per_frame - s->min_samples_per_subframe)
472 return s->min_samples_per_subframe;
474 /** 1 bit indicates if the subframe is of maximum length */
475 if (s->max_subframe_len_bit) {
476 if (get_bits1(&s->gb))
477 frame_len_shift = 1 + get_bits(&s->gb, s->subframe_len_bits-1);
478 } else
479 frame_len_shift = get_bits(&s->gb, s->subframe_len_bits);
481 subframe_len = s->samples_per_frame >> frame_len_shift;
483 /** sanity check the length */
484 if (subframe_len < s->min_samples_per_subframe ||
485 subframe_len > s->samples_per_frame) {
486 DEBUGF("broken frame: subframe_len %i\n",
487 subframe_len);
488 return AVERROR_INVALIDDATA;
490 return subframe_len;
494 *@brief Decode how the data in the frame is split into subframes.
495 * Every WMA frame contains the encoded data for a fixed number of
496 * samples per channel. The data for every channel might be split
497 * into several subframes. This function will reconstruct the list of
498 * subframes for every channel.
500 * If the subframes are not evenly split, the algorithm estimates the
501 * channels with the lowest number of total samples.
502 * Afterwards, for each of these channels a bit is read from the
503 * bitstream that indicates if the channel contains a subframe with the
504 * next subframe size that is going to be read from the bitstream or not.
505 * If a channel contains such a subframe, the subframe size gets added to
506 * the channel's subframe list.
507 * The algorithm repeats these steps until the frame is properly divided
508 * between the individual channels.
510 *@param s context
511 *@return 0 on success, < 0 in case of an error
513 static int decode_tilehdr(WMAProDecodeCtx *s)
515 uint16_t num_samples[WMAPRO_MAX_CHANNELS]; /** sum of samples for all currently known subframes of a channel */
516 uint8_t contains_subframe[WMAPRO_MAX_CHANNELS]; /** flag indicating if a channel contains the current subframe */
517 int channels_for_cur_subframe = s->num_channels; /** number of channels that contain the current subframe */
518 int fixed_channel_layout = 0; /** flag indicating that all channels use the same subframe offsets and sizes */
519 int min_channel_len = 0; /** smallest sum of samples (channels with this length will be processed first) */
520 int c;
522 /* Should never consume more than 3073 bits (256 iterations for the
523 * while loop when always the minimum amount of 128 samples is substracted
524 * from missing samples in the 8 channel case).
525 * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS + 4)
528 /** reset tiling information */
529 for (c = 0; c < s->num_channels; c++)
530 s->channel[c].num_subframes = 0;
532 memset(num_samples, 0, sizeof(num_samples));
534 if (s->max_num_subframes == 1 || get_bits1(&s->gb))
535 fixed_channel_layout = 1;
537 /** loop until the frame data is split between the subframes */
538 do {
539 int subframe_len;
541 /** check which channels contain the subframe */
542 for (c = 0; c < s->num_channels; c++) {
543 if (num_samples[c] == min_channel_len) {
544 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
545 (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe))
546 contains_subframe[c] = 1;
547 else
548 contains_subframe[c] = get_bits1(&s->gb);
549 } else
550 contains_subframe[c] = 0;
553 /** get subframe length, subframe_len == 0 is not allowed */
554 if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
555 return AVERROR_INVALIDDATA;
557 /** add subframes to the individual channels and find new min_channel_len */
558 min_channel_len += subframe_len;
559 for (c = 0; c < s->num_channels; c++) {
560 WMAProChannelCtx* chan = &s->channel[c];
562 if (contains_subframe[c]) {
563 if (chan->num_subframes >= MAX_SUBFRAMES) {
564 DEBUGF("broken frame: num subframes > 31\n");
565 return AVERROR_INVALIDDATA;
567 chan->subframe_len[chan->num_subframes] = subframe_len;
568 num_samples[c] += subframe_len;
569 ++chan->num_subframes;
570 if (num_samples[c] > s->samples_per_frame) {
571 DEBUGF("broken frame: "
572 "channel len > samples_per_frame\n");
573 return AVERROR_INVALIDDATA;
575 } else if (num_samples[c] <= min_channel_len) {
576 if (num_samples[c] < min_channel_len) {
577 channels_for_cur_subframe = 0;
578 min_channel_len = num_samples[c];
580 ++channels_for_cur_subframe;
583 } while (min_channel_len < s->samples_per_frame);
585 for (c = 0; c < s->num_channels; c++) {
586 int i;
587 int offset = 0;
588 for (i = 0; i < s->channel[c].num_subframes; i++) {
589 DEBUGF("frame[%i] channel[%i] subframe[%i]"
590 " len %i\n", s->frame_num, c, i,
591 s->channel[c].subframe_len[i]);
592 s->channel[c].subframe_offset[i] = offset;
593 offset += s->channel[c].subframe_len[i];
597 return 0;
600 #if 0
602 *@brief Calculate a decorrelation matrix from the bitstream parameters.
603 *@param s codec context
604 *@param chgroup channel group for which the matrix needs to be calculated
606 static void decode_decorrelation_matrix(WMAProDecodeCtx *s,
607 WMAProChannelGrp *chgroup)
609 int i;
610 int offset = 0;
611 int8_t rotation_offset[WMAPRO_MAX_CHANNELS * WMAPRO_MAX_CHANNELS];
612 memset(chgroup->decorrelation_matrix, 0, s->num_channels *
613 s->num_channels * sizeof(*chgroup->decorrelation_matrix));
615 for (i = 0; i < chgroup->num_channels * (chgroup->num_channels - 1) >> 1; i++)
616 rotation_offset[i] = get_bits(&s->gb, 6);
618 for (i = 0; i < chgroup->num_channels; i++) {
619 chgroup->decorrelation_matrix[chgroup->num_channels * i + i] =
620 get_bits1(&s->gb) ? 1.0 : -1.0;
622 if(chgroup->decorrelation_matrix[chgroup->num_channels * i + i] > 0)
623 chgroup->fixdecorrelation_matrix[chgroup->num_channels * i + i] = 0x10000;
624 else
625 chgroup->fixdecorrelation_matrix[chgroup->num_channels * i + i] = -0x10000;
628 for (i = 1; i < chgroup->num_channels; i++) {
629 int x;
630 for (x = 0; x < i; x++) {
631 int y;
632 for (y = 0; y < i + 1; y++) {
633 float v1 = chgroup->decorrelation_matrix[x * chgroup->num_channels + y];
634 float v2 = chgroup->decorrelation_matrix[i * chgroup->num_channels + y];
635 int32_t f1 = chgroup->fixdecorrelation_matrix[x * chgroup->num_channels + y];
636 int32_t f2 = chgroup->fixdecorrelation_matrix[i * chgroup->num_channels + y];
637 int n = rotation_offset[offset + x];
638 float sinv;
639 float cosv;
640 int32_t fixsinv;
641 int32_t fixcosv;
643 if (n < 32) {
644 sinv = sin64[n];
645 cosv = sin64[32 - n];
646 fixsinv = fixed_sin64[n];
647 fixcosv = fixed_sin64[32-n];
648 } else {
649 sinv = sin64[64 - n];
650 cosv = -sin64[n - 32];
651 fixsinv = fixed_sin64[64-n];
652 fixcosv = -fixed_sin64[n-32];
655 chgroup->decorrelation_matrix[y + x * chgroup->num_channels] =
656 (v1 * sinv) - (v2 * cosv);
657 chgroup->decorrelation_matrix[y + i * chgroup->num_channels] =
658 (v1 * cosv) + (v2 * sinv);
659 chgroup->fixdecorrelation_matrix[y + x * chgroup->num_channels] =
660 fixmulshift(f1, fixsinv, 31) - fixmulshift(f2, fixcosv, 31);
661 chgroup->fixdecorrelation_matrix[y + i * chgroup->num_channels] =
662 fixmulshift(f1, fixcosv, 31) + fixmulshift(f2, fixsinv, 31);
666 offset += i;
669 #endif
672 *@brief Decode channel transformation parameters
673 *@param s codec context
674 *@return 0 in case of success, < 0 in case of bitstream errors
676 static int decode_channel_transform(WMAProDecodeCtx* s)
678 int i;
679 /* should never consume more than 1921 bits for the 8 channel case
680 * 1 + MAX_CHANNELS * (MAX_CHANNELS + 2 + 3 * MAX_CHANNELS * MAX_CHANNELS
681 * + MAX_CHANNELS + MAX_BANDS + 1)
684 /** in the one channel case channel transforms are pointless */
685 s->num_chgroups = 0;
686 if (s->num_channels > 1) {
687 int remaining_channels = s->channels_for_cur_subframe;
689 if (get_bits1(&s->gb)) {
690 DEBUGF("unsupported channel transform bit\n");
691 return AVERROR_INVALIDDATA;
694 for (s->num_chgroups = 0; remaining_channels &&
695 s->num_chgroups < s->channels_for_cur_subframe; s->num_chgroups++) {
696 WMAProChannelGrp* chgroup = &s->chgroup[s->num_chgroups];
697 int32_t** channel_data = chgroup->channel_data;
698 chgroup->num_channels = 0;
699 chgroup->transform = 0;
701 /** decode channel mask */
702 if (remaining_channels > 2) {
703 for (i = 0; i < s->channels_for_cur_subframe; i++) {
704 int channel_idx = s->channel_indexes_for_cur_subframe[i];
705 if (!s->channel[channel_idx].grouped
706 && get_bits1(&s->gb)) {
707 ++chgroup->num_channels;
708 s->channel[channel_idx].grouped = 1;
709 *channel_data++ = s->channel[channel_idx].coeffs;
712 } else {
713 chgroup->num_channels = remaining_channels;
714 for (i = 0; i < s->channels_for_cur_subframe; i++) {
715 int channel_idx = s->channel_indexes_for_cur_subframe[i];
716 if (!s->channel[channel_idx].grouped)
717 *channel_data++ = s->channel[channel_idx].coeffs;
718 s->channel[channel_idx].grouped = 1;
722 /** decode transform type */
723 if (chgroup->num_channels == 2) {
724 if (get_bits1(&s->gb)) {
725 if (get_bits1(&s->gb)) {
726 DEBUGF("unsupported channel transform type\n");
728 } else {
729 chgroup->transform = 1;
730 if (s->num_channels == 2) {
731 chgroup->fixdecorrelation_matrix[0] = 0x10000;
732 chgroup->fixdecorrelation_matrix[1] = -0x10000;
733 chgroup->fixdecorrelation_matrix[2] = 0x10000;
734 chgroup->fixdecorrelation_matrix[3] = 0x10000;
735 } else {
736 /** cos(pi/4) */
737 chgroup->fixdecorrelation_matrix[0] = 0xB500;
738 chgroup->fixdecorrelation_matrix[1] = -0xB500;
739 chgroup->fixdecorrelation_matrix[2] = 0xB500;
740 chgroup->fixdecorrelation_matrix[3] = 0xB500;
743 } else if (chgroup->num_channels > 2) {
744 DEBUGF("in wmaprodec.c: Multichannel streams still not supported\n");
745 return -1;
746 #if 0
747 if (get_bits1(&s->gb)) {
748 chgroup->transform = 1;
749 if (get_bits1(&s->gb)) {
750 decode_decorrelation_matrix(s, chgroup);
751 } else {
752 /** FIXME: more than 6 coupled channels not supported */
753 if (chgroup->num_channels > 6) {
754 av_log_ask_for_sample(s->avctx,
755 "coupled channels > 6\n");
756 } else {
757 memcpy(chgroup->decorrelation_matrix,
758 default_decorrelation[chgroup->num_channels],
759 chgroup->num_channels * chgroup->num_channels *
760 sizeof(*chgroup->decorrelation_matrix));
764 #endif
767 /** decode transform on / off */
768 if (chgroup->transform) {
769 if (!get_bits1(&s->gb)) {
770 int i;
771 /** transform can be enabled for individual bands */
772 for (i = 0; i < s->num_bands; i++) {
773 chgroup->transform_band[i] = get_bits1(&s->gb);
775 } else {
776 memset(chgroup->transform_band, 1, s->num_bands);
779 remaining_channels -= chgroup->num_channels;
782 return 0;
786 *@brief Extract the coefficients from the bitstream.
787 *@param s codec context
788 *@param c current channel number
789 *@return 0 on success, < 0 in case of bitstream errors
791 static int decode_coeffs(WMAProDecodeCtx *s, int c)
793 int vlctable;
794 VLC* vlc;
795 WMAProChannelCtx* ci = &s->channel[c];
796 int rl_mode = 0;
797 int cur_coeff = 0;
798 int num_zeros = 0;
799 const uint16_t* run;
800 const int32_t* level;
802 DEBUGF("decode coefficients for channel %i\n", c);
804 vlctable = get_bits1(&s->gb);
805 vlc = &coef_vlc[vlctable];
807 if (vlctable) {
808 run = coef1_run;
809 level = coef1_level;
810 } else {
811 run = coef0_run;
812 level = coef0_level;
815 /** decode vector coefficients (consumes up to 167 bits per iteration for
816 4 vector coded large values) */
817 while (!rl_mode && cur_coeff + 3 < s->subframe_len) {
818 int32_t vals[4];
819 int i;
820 unsigned int idx;
822 idx = get_vlc2(&s->gb, vec4_vlc.table, VLCBITS, VEC4MAXDEPTH);
824 if (idx == HUFF_VEC4_SIZE - 1) {
825 for (i = 0; i < 4; i += 2) {
826 idx = get_vlc2(&s->gb, vec2_vlc.table, VLCBITS, VEC2MAXDEPTH);
827 if (idx == HUFF_VEC2_SIZE - 1) {
828 int v0, v1;
829 v0 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
830 if (v0 == HUFF_VEC1_SIZE - 1)
831 v0 += ff_wma_get_large_val(&s->gb);
832 v1 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
833 if (v1 == HUFF_VEC1_SIZE - 1)
834 v1 += ff_wma_get_large_val(&s->gb);
836 vals[i] = v0;
837 vals[i+1] = v1;
838 } else {
839 vals[i] = symbol_to_vec2[idx] >> 4;
840 vals[i+1] = symbol_to_vec2[idx] & 0xF;
843 } else {
844 vals[0] = symbol_to_vec4[idx] >> 12;
845 vals[1] = (symbol_to_vec4[idx] >> 8) & 0xF;
846 vals[2] = (symbol_to_vec4[idx] >> 4) & 0xF;
847 vals[3] = symbol_to_vec4[idx] & 0xF;
850 /** decode sign */
851 for (i = 0; i < 4; i++) {
852 if (vals[i]) {
853 int sign = get_bits1(&s->gb) - 1;
854 ci->coeffs[cur_coeff] = (sign == -1)? -vals[i]<<16 : vals[i]<<16;
855 num_zeros = 0;
856 } else {
857 ci->coeffs[cur_coeff] = 0;
858 /** switch to run level mode when subframe_len / 128 zeros
859 were found in a row */
860 rl_mode |= (++num_zeros > s->subframe_len >> 8);
862 ++cur_coeff;
866 /** decode run level coded coefficients */
867 if (rl_mode) {
868 memset(&ci->coeffs[cur_coeff], 0,
869 sizeof(*ci->coeffs) * (s->subframe_len - cur_coeff));
871 if (ff_wma_run_level_decode(&s->gb, vlc,
872 level, run, 1, ci->coeffs,
873 cur_coeff, s->subframe_len,
874 s->subframe_len, s->esc_len, 0))
875 return AVERROR_INVALIDDATA;
878 return 0;
882 *@brief Extract scale factors from the bitstream.
883 *@param s codec context
884 *@return 0 on success, < 0 in case of bitstream errors
886 static int decode_scale_factors(WMAProDecodeCtx* s)
888 int i;
890 /** should never consume more than 5344 bits
891 * MAX_CHANNELS * (1 + MAX_BANDS * 23)
894 for (i = 0; i < s->channels_for_cur_subframe; i++) {
895 int c = s->channel_indexes_for_cur_subframe[i];
896 int* sf;
897 int* sf_end;
898 s->channel[c].scale_factors = s->channel[c].saved_scale_factors[!s->channel[c].scale_factor_idx];
899 sf_end = s->channel[c].scale_factors + s->num_bands;
901 /** resample scale factors for the new block size
902 * as the scale factors might need to be resampled several times
903 * before some new values are transmitted, a backup of the last
904 * transmitted scale factors is kept in saved_scale_factors
906 if (s->channel[c].reuse_sf) {
907 const int8_t* sf_offsets = s->sf_offsets[s->table_idx][s->channel[c].table_idx];
908 int b;
909 for (b = 0; b < s->num_bands; b++)
910 s->channel[c].scale_factors[b] =
911 s->channel[c].saved_scale_factors[s->channel[c].scale_factor_idx][*sf_offsets++];
914 if (!s->channel[c].cur_subframe || get_bits1(&s->gb)) {
916 if (!s->channel[c].reuse_sf) {
917 int val;
918 /** decode DPCM coded scale factors */
919 s->channel[c].scale_factor_step = get_bits(&s->gb, 2) + 1;
920 val = 45 / s->channel[c].scale_factor_step;
921 for (sf = s->channel[c].scale_factors; sf < sf_end; sf++) {
922 val += get_vlc2(&s->gb, sf_vlc.table, SCALEVLCBITS, SCALEMAXDEPTH) - 60;
923 *sf = val;
925 } else {
926 int i;
927 /** run level decode differences to the resampled factors */
928 for (i = 0; i < s->num_bands; i++) {
929 int idx;
930 int skip;
931 int val;
932 int sign;
934 idx = get_vlc2(&s->gb, sf_rl_vlc.table, VLCBITS, SCALERLMAXDEPTH);
936 if (!idx) {
937 uint32_t code = get_bits(&s->gb, 14);
938 val = code >> 6;
939 sign = (code & 1) - 1;
940 skip = (code & 0x3f) >> 1;
941 } else if (idx == 1) {
942 break;
943 } else {
944 skip = scale_rl_run[idx];
945 val = scale_rl_level[idx];
946 sign = get_bits1(&s->gb)-1;
949 i += skip;
950 if (i >= s->num_bands) {
951 DEBUGF("invalid scale factor coding\n");
952 return AVERROR_INVALIDDATA;
954 s->channel[c].scale_factors[i] += (val ^ sign) - sign;
958 /** swap buffers */
959 s->channel[c].scale_factor_idx = !s->channel[c].scale_factor_idx;
960 s->channel[c].table_idx = s->table_idx;
961 s->channel[c].reuse_sf = 1;
964 /** calculate new scale factor maximum */
965 s->channel[c].max_scale_factor = s->channel[c].scale_factors[0];
966 for (sf = s->channel[c].scale_factors + 1; sf < sf_end; sf++) {
967 s->channel[c].max_scale_factor =
968 FFMAX(s->channel[c].max_scale_factor, *sf);
972 return 0;
976 *@brief Reconstruct the individual channel data.
977 *@param s codec context
979 static void inverse_channel_transform(WMAProDecodeCtx *s)
981 int i;
983 for (i = 0; i < s->num_chgroups; i++) {
984 if (s->chgroup[i].transform) {
985 const int num_channels = s->chgroup[i].num_channels;
986 int32_t data[WMAPRO_MAX_CHANNELS];
987 int32_t** ch_data = s->chgroup[i].channel_data;
988 int32_t** ch_end = ch_data + num_channels;
989 const int8_t* tb = s->chgroup[i].transform_band;
990 int16_t* sfb;
992 /** multichannel decorrelation */
993 for (sfb = s->cur_sfb_offsets;
994 sfb < s->cur_sfb_offsets + s->num_bands; sfb++) {
995 int y;
996 if (*tb++ == 1) {
997 /** multiply values with the decorrelation_matrix */
998 for (y = sfb[0]; y < FFMIN(sfb[1], s->subframe_len); y++) {
999 const int32_t* mat = s->chgroup[i].fixdecorrelation_matrix;
1000 const int32_t* data_end = data + num_channels;
1001 int32_t* data_ptr = data;
1002 int32_t** ch;
1004 for (ch = ch_data; ch < ch_end; ch++)
1005 *data_ptr++ = (*ch)[y];
1007 for (ch = ch_data; ch < ch_end; ch++) {
1008 int32_t sum = 0;
1009 data_ptr = data;
1011 while (data_ptr < data_end)
1012 sum += fixmulshift(*data_ptr++, *mat++, 16);
1014 (*ch)[y] = sum;
1017 } else if (s->num_channels == 2) {
1019 int len = FFMIN(sfb[1], s->subframe_len) - sfb[0];
1020 vector_fixmul_scalar(ch_data[0] + sfb[0],
1021 ch_data[0] + sfb[0],
1022 0x00016A00, len,16);
1023 vector_fixmul_scalar(ch_data[1] + sfb[0],
1024 ch_data[1] + sfb[0],
1025 0x00016A00, len,16);
1034 *@brief Apply sine window and reconstruct the output buffer.
1035 *@param s codec context
1037 static void wmapro_window(WMAProDecodeCtx *s)
1039 int i;
1041 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1042 int c = s->channel_indexes_for_cur_subframe[i];
1043 const int32_t* window;
1044 int winlen = s->channel[c].prev_block_len;
1045 int32_t *xstart= s->channel[c].coeffs - (winlen >> 1);
1047 if (s->subframe_len < winlen) {
1048 xstart += (winlen - s->subframe_len) >> 1;
1049 winlen = s->subframe_len;
1052 window = sine_windows[av_log2(winlen) - BLOCK_MIN_BITS];
1054 winlen >>= 1;
1056 vector_fixmul_window(xstart, xstart, xstart + winlen,
1057 window, winlen);
1059 s->channel[c].prev_block_len = s->subframe_len;
1065 *@brief Decode a single subframe (block).
1066 *@param s codec context
1067 *@return 0 on success, < 0 when decoding failed
1069 static int decode_subframe(WMAProDecodeCtx *s)
1071 int offset = s->samples_per_frame;
1072 int subframe_len = s->samples_per_frame;
1073 int i;
1074 int total_samples = s->samples_per_frame * s->num_channels;
1075 int transmit_coeffs = 0;
1076 int cur_subwoofer_cutoff;
1078 s->subframe_offset = get_bits_count(&s->gb);
1080 /** reset channel context and find the next block offset and size
1081 == the next block of the channel with the smallest number of
1082 decoded samples
1084 for (i = 0; i < s->num_channels; i++) {
1085 s->channel[i].grouped = 0;
1086 if (offset > s->channel[i].decoded_samples) {
1087 offset = s->channel[i].decoded_samples;
1088 subframe_len =
1089 s->channel[i].subframe_len[s->channel[i].cur_subframe];
1093 DEBUGF("processing subframe with offset %i len %i\n", offset, subframe_len);
1095 /** get a list of all channels that contain the estimated block */
1096 s->channels_for_cur_subframe = 0;
1097 for (i = 0; i < s->num_channels; i++) {
1098 const int cur_subframe = s->channel[i].cur_subframe;
1099 /** substract already processed samples */
1100 total_samples -= s->channel[i].decoded_samples;
1102 /** and count if there are multiple subframes that match our profile */
1103 if (offset == s->channel[i].decoded_samples &&
1104 subframe_len == s->channel[i].subframe_len[cur_subframe]) {
1105 total_samples -= s->channel[i].subframe_len[cur_subframe];
1106 s->channel[i].decoded_samples +=
1107 s->channel[i].subframe_len[cur_subframe];
1108 s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
1109 ++s->channels_for_cur_subframe;
1113 /** check if the frame will be complete after processing the
1114 estimated block */
1115 if (!total_samples)
1116 s->parsed_all_subframes = 1;
1119 DEBUGF("subframe is part of %i channels\n", s->channels_for_cur_subframe);
1121 /** calculate number of scale factor bands and their offsets */
1122 s->table_idx = av_log2(s->samples_per_frame/subframe_len);
1123 s->num_bands = s->num_sfb[s->table_idx];
1124 s->cur_sfb_offsets = s->sfb_offsets[s->table_idx];
1125 cur_subwoofer_cutoff = s->subwoofer_cutoffs[s->table_idx];
1127 /** configure the decoder for the current subframe */
1128 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1129 int c = s->channel_indexes_for_cur_subframe[i];
1131 s->channel[c].coeffs = &s->channel[c].out[(s->samples_per_frame >> 1)
1132 + offset];
1135 s->subframe_len = subframe_len;
1136 s->esc_len = av_log2(s->subframe_len - 1) + 1;
1138 /** skip extended header if any */
1139 if (get_bits1(&s->gb)) {
1140 int num_fill_bits;
1141 if (!(num_fill_bits = get_bits(&s->gb, 2))) {
1142 int len = get_bits(&s->gb, 4);
1143 num_fill_bits = get_bits(&s->gb, len) + 1;
1146 if (num_fill_bits >= 0) {
1147 if (get_bits_count(&s->gb) + num_fill_bits > s->num_saved_bits) {
1148 DEBUGF("invalid number of fill bits\n");
1149 return AVERROR_INVALIDDATA;
1152 skip_bits_long(&s->gb, num_fill_bits);
1156 /** no idea for what the following bit is used */
1157 if (get_bits1(&s->gb)) {
1158 DEBUGF("reserved bit set\n");
1159 return AVERROR_INVALIDDATA;
1162 if (decode_channel_transform(s) < 0)
1163 return AVERROR_INVALIDDATA;
1165 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1166 int c = s->channel_indexes_for_cur_subframe[i];
1167 if ((s->channel[c].transmit_coefs = get_bits1(&s->gb)))
1168 transmit_coeffs = 1;
1171 if (transmit_coeffs) {
1172 int step;
1173 int quant_step = 90 * s->bits_per_sample >> 4;
1174 if ((get_bits1(&s->gb))) {
1175 /** FIXME: might change run level mode decision */
1176 DEBUGF("unsupported quant step coding\n");
1177 return AVERROR_INVALIDDATA;
1179 /** decode quantization step */
1180 step = get_sbits(&s->gb, 6);
1181 quant_step += step;
1182 if (step == -32 || step == 31) {
1183 const int sign = (step == 31) - 1;
1184 int quant = 0;
1185 while (get_bits_count(&s->gb) + 5 < s->num_saved_bits &&
1186 (step = get_bits(&s->gb, 5)) == 31) {
1187 quant += 31;
1189 quant_step += ((quant + step) ^ sign) - sign;
1191 if (quant_step < 0) {
1192 DEBUGF("negative quant step\n");
1195 /** decode quantization step modifiers for every channel */
1197 if (s->channels_for_cur_subframe == 1) {
1198 s->channel[s->channel_indexes_for_cur_subframe[0]].quant_step = quant_step;
1199 } else {
1200 int modifier_len = get_bits(&s->gb, 3);
1201 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1202 int c = s->channel_indexes_for_cur_subframe[i];
1203 s->channel[c].quant_step = quant_step;
1204 if (get_bits1(&s->gb)) {
1205 if (modifier_len) {
1206 s->channel[c].quant_step += get_bits(&s->gb, modifier_len) + 1;
1207 } else
1208 ++s->channel[c].quant_step;
1213 /** decode scale factors */
1214 if (decode_scale_factors(s) < 0)
1215 return AVERROR_INVALIDDATA;
1218 DEBUGF("BITSTREAM: subframe header length was %i\n",
1219 get_bits_count(&s->gb) - s->subframe_offset);
1221 /** parse coefficients */
1222 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1223 int c = s->channel_indexes_for_cur_subframe[i];
1224 if (s->channel[c].transmit_coefs &&
1225 get_bits_count(&s->gb) < s->num_saved_bits) {
1226 decode_coeffs(s, c);
1227 } else {
1228 memset(s->channel[c].coeffs, 0,
1229 sizeof(*s->channel[c].coeffs) * subframe_len);
1233 DEBUGF("BITSTREAM: subframe length was %i\n",
1234 get_bits_count(&s->gb) - s->subframe_offset);
1236 if (transmit_coeffs) {
1237 /** reconstruct the per channel data */
1238 inverse_channel_transform(s);
1239 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1240 int c = s->channel_indexes_for_cur_subframe[i];
1241 const int* sf = s->channel[c].scale_factors;
1242 int b;
1244 if (c == s->lfe_channel)
1245 memset(&s->tmp[cur_subwoofer_cutoff], 0, sizeof(*s->tmp) *
1246 (subframe_len - cur_subwoofer_cutoff));
1248 /** inverse quantization and rescaling */
1249 for (b = 0; b < s->num_bands; b++) {
1250 const int end = FFMIN(s->cur_sfb_offsets[b+1], s->subframe_len);
1251 const int exp = s->channel[c].quant_step -
1252 (s->channel[c].max_scale_factor - *sf++) *
1253 s->channel[c].scale_factor_step;
1255 if(exp < EXP_MIN || exp > EXP_MAX) {
1256 DEBUGF("in wmaprodec.c : unhandled value for exp (%d), please report sample.\n", exp);
1257 return -1;
1259 const int32_t quant = QUANT(exp);
1260 int start = s->cur_sfb_offsets[b];
1262 vector_fixmul_scalar(s->tmp+start,
1263 s->channel[c].coeffs + start,
1264 quant, end-start, 24);
1269 /** apply imdct (ff_imdct_half == DCTIV with reverse) */
1270 imdct_half(av_log2(subframe_len)+1,
1271 s->channel[c].coeffs, s->tmp);
1276 /** window and overlapp-add */
1277 wmapro_window(s);
1279 /** handled one subframe */
1280 for (i = 0; i < s->channels_for_cur_subframe; i++) {
1281 int c = s->channel_indexes_for_cur_subframe[i];
1282 if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
1283 DEBUGF("broken subframe\n");
1284 return AVERROR_INVALIDDATA;
1286 ++s->channel[c].cur_subframe;
1289 return 0;
1293 *@brief Decode one WMA frame.
1294 *@param s codec context
1295 *@return 0 if the trailer bit indicates that this is the last frame,
1296 * 1 if there are additional frames
1298 static int decode_frame(WMAProDecodeCtx *s)
1300 GetBitContext* gb = &s->gb;
1301 int more_frames = 0;
1302 int len = 0;
1303 int i;
1305 /** check for potential output buffer overflow */
1306 if (s->num_channels * s->samples_per_frame > s->samples_end - s->samples) {
1307 /** return an error if no frame could be decoded at all */
1308 DEBUGF("not enough space for the output samples\n");
1309 s->packet_loss = 1;
1310 return 0;
1313 /** get frame length */
1314 if (s->len_prefix)
1315 len = get_bits(gb, s->log2_frame_size);
1317 DEBUGF("decoding frame with length %x\n", len);
1319 /** decode tile information */
1320 if (decode_tilehdr(s)) {
1321 s->packet_loss = 1;
1322 return 0;
1325 /** read postproc transform */
1326 if (s->num_channels > 1 && get_bits1(gb)) {
1327 DEBUGF("Unsupported postproc transform found\n");
1328 s->packet_loss = 1;
1329 return 0;
1332 /** read drc info */
1333 if (s->dynamic_range_compression) {
1334 s->drc_gain = get_bits(gb, 8);
1335 DEBUGF("drc_gain %i\n", s->drc_gain);
1338 /** no idea what these are for, might be the number of samples
1339 that need to be skipped at the beginning or end of a stream */
1340 if (get_bits1(gb)) {
1341 int skip;
1343 /** usually true for the first frame */
1344 if (get_bits1(gb)) {
1345 skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1346 DEBUGF("start skip: %i\n", skip);
1349 /** sometimes true for the last frame */
1350 if (get_bits1(gb)) {
1351 skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
1352 DEBUGF("end skip: %i\n", skip);
1357 DEBUGF("BITSTREAM: frame header length was %i\n",
1358 get_bits_count(gb) - s->frame_offset);
1360 /** reset subframe states */
1361 s->parsed_all_subframes = 0;
1362 for (i = 0; i < s->num_channels; i++) {
1363 s->channel[i].decoded_samples = 0;
1364 s->channel[i].cur_subframe = 0;
1365 s->channel[i].reuse_sf = 0;
1368 /** decode all subframes */
1369 while (!s->parsed_all_subframes) {
1370 if (decode_subframe(s) < 0) {
1371 s->packet_loss = 1;
1372 return 0;
1376 /** interleave samples and write them to the output buffer */
1377 for (i = 0; i < s->num_channels; i++) {
1378 int32_t* ptr = s->samples + i;
1379 int incr = s->num_channels;
1380 int32_t* iptr = s->channel[i].out;
1381 int32_t* iend = iptr + s->samples_per_frame;
1383 while (iptr < iend) {
1384 *ptr = *iptr++ << 1;
1385 ptr += incr;
1388 /** reuse second half of the IMDCT output for the next frame */
1389 memcpy(&s->channel[i].out[0],
1390 &s->channel[i].out[s->samples_per_frame],
1391 s->samples_per_frame * sizeof(*s->channel[i].out) >> 1);
1394 if (s->skip_frame) {
1395 s->skip_frame = 0;
1396 } else
1397 s->samples += s->num_channels * s->samples_per_frame;
1399 if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
1400 /** FIXME: not sure if this is always an error */
1401 DEBUGF("frame[%i] would have to skip %i bits\n",
1402 (int)s->frame_num, len - (get_bits_count(gb) - s->frame_offset) - 1);
1403 s->packet_loss = 1;
1404 return 0;
1407 /** skip the rest of the frame data */
1408 skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
1410 /** decode trailer bit */
1411 more_frames = get_bits1(gb);
1413 ++s->frame_num;
1414 return more_frames;
1418 *@brief Calculate remaining input buffer length.
1419 *@param s codec context
1420 *@param gb bitstream reader context
1421 *@return remaining size in bits
1423 static int remaining_bits(WMAProDecodeCtx *s, GetBitContext *gb)
1425 return s->buf_bit_size - get_bits_count(gb);
1429 *@brief Fill the bit reservoir with a (partial) frame.
1430 *@param s codec context
1431 *@param gb bitstream reader context
1432 *@param len length of the partial frame
1433 *@param append decides wether to reset the buffer or not
1435 static void save_bits(WMAProDecodeCtx *s, GetBitContext* gb, int len,
1436 int append)
1438 int buflen;
1440 /** when the frame data does not need to be concatenated, the input buffer
1441 is resetted and additional bits from the previous frame are copyed
1442 and skipped later so that a fast byte copy is possible */
1444 if (!append) {
1445 s->frame_offset = get_bits_count(gb) & 7;
1446 s->num_saved_bits = s->frame_offset;
1447 init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
1450 buflen = (s->num_saved_bits + len + 8) >> 3;
1452 if (len <= 0 || buflen > MAX_FRAMESIZE) {
1453 DEBUGF("input buffer too small\n");
1454 s->packet_loss = 1;
1455 return;
1458 s->num_saved_bits += len;
1459 if (!append) {
1460 ff_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
1461 s->num_saved_bits);
1462 } else {
1463 int align = 8 - (get_bits_count(gb) & 7);
1464 align = FFMIN(align, len);
1465 put_bits(&s->pb, align, get_bits(gb, align));
1466 len -= align;
1467 ff_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
1469 skip_bits_long(gb, len);
1472 PutBitContext tmp = s->pb;
1473 flush_put_bits(&tmp);
1476 init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
1477 skip_bits(&s->gb, s->frame_offset);
1481 *@brief Decode a single WMA packet.
1482 *@param avctx codec context
1483 *@param data the output buffer
1484 *@param data_size number of bytes that were written to the output buffer
1485 *@param avpkt input packet
1486 *@return number of bytes that were read from the input buffer
1488 int decode_packet(asf_waveformatex_t *wfx, void *data, int *data_size,
1489 void* pktdata, int size)
1491 WMAProDecodeCtx *s = &globWMAProDecCtx;
1492 GetBitContext* gb = &s->pgb;
1493 const uint8_t* buf = pktdata;
1494 int buf_size = size;
1495 int num_bits_prev_frame;
1496 int packet_sequence_number;
1498 s->samples = data;
1499 s->samples_end = (int32_t*)((int8_t*)data + *data_size);
1500 *data_size = 0;
1502 if (s->packet_done || s->packet_loss) {
1503 s->packet_done = 0;
1504 s->buf_bit_size = buf_size << 3;
1506 /** sanity check for the buffer length */
1507 if (buf_size < wfx->blockalign)
1508 return 0;
1510 buf_size = wfx->blockalign;
1512 /** parse packet header */
1513 init_get_bits(gb, buf, s->buf_bit_size);
1514 packet_sequence_number = get_bits(gb, 4);
1515 skip_bits(gb, 2);
1517 /** get number of bits that need to be added to the previous frame */
1518 num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
1519 DEBUGF("packet[%d]: nbpf %x\n", s->frame_num,
1520 num_bits_prev_frame);
1522 /** check for packet loss */
1523 if (!s->packet_loss &&
1524 ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
1525 s->packet_loss = 1;
1526 DEBUGF("Packet loss detected! seq %x vs %x\n",
1527 s->packet_sequence_number, packet_sequence_number);
1529 s->packet_sequence_number = packet_sequence_number;
1531 if (num_bits_prev_frame > 0) {
1532 /** append the previous frame data to the remaining data from the
1533 previous packet to create a full frame */
1534 save_bits(s, gb, num_bits_prev_frame, 1);
1535 DEBUGF("accumulated %x bits of frame data\n",
1536 s->num_saved_bits - s->frame_offset);
1538 /** decode the cross packet frame if it is valid */
1539 if (!s->packet_loss)
1540 decode_frame(s);
1541 } else if (s->num_saved_bits - s->frame_offset) {
1542 DEBUGF("ignoring %x previously saved bits\n",
1543 s->num_saved_bits - s->frame_offset);
1546 s->packet_loss = 0;
1548 } else {
1549 int frame_size;
1550 s->buf_bit_size = size << 3;
1551 init_get_bits(gb, pktdata, s->buf_bit_size);
1552 skip_bits(gb, s->packet_offset);
1553 if (remaining_bits(s, gb) > s->log2_frame_size &&
1554 (frame_size = show_bits(gb, s->log2_frame_size)) &&
1555 frame_size <= remaining_bits(s, gb)) {
1556 save_bits(s, gb, frame_size, 0);
1557 s->packet_done = !decode_frame(s);
1558 } else
1559 s->packet_done = 1;
1562 if (s->packet_done && !s->packet_loss &&
1563 remaining_bits(s, gb) > 0) {
1564 /** save the rest of the data so that it can be decoded
1565 with the next packet */
1566 save_bits(s, gb, remaining_bits(s, gb), 0);
1569 *data_size = (int8_t *)s->samples - (int8_t *)data;
1570 s->packet_offset = get_bits_count(gb) & 7;
1572 s->frame_num++;
1573 return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
1576 #if 0
1578 *@brief wmapro decoder
1580 AVCodec wmapro_decoder = {
1581 "wmapro",
1582 AVMEDIA_TYPE_AUDIO,
1583 CODEC_ID_WMAPRO,
1584 sizeof(WMAProDecodeCtx),
1585 decode_init,
1586 NULL,
1587 decode_end,
1588 decode_packet,
1589 .capabilities = CODEC_CAP_SUBFRAMES,
1590 .flush= flush,
1591 .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Professional"),
1593 #endif