]> git.sesse.net Git - ffmpeg/blob - libavcodec/wmadec.c
support skiped blocks in SVQ1
[ffmpeg] / libavcodec / wmadec.c
1 /*
2  * WMA compatible decoder
3  * Copyright (c) 2002 The FFmpeg Project.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 /**
21  * @file wmadec.c
22  * WMA compatible decoder.
23  * This decoder handles Microsoft Windows Media Audio data, versions 1 & 2.
24  * WMA v1 is identified by audio format 0x160 in Microsoft media files 
25  * (ASF/AVI/WAV). WMA v2 is identified by audio format 0x161.
26  *
27  * To use this decoder, a calling application must supply the extra data
28  * bytes provided with the WMA data. These are the extra, codec-specific
29  * bytes at the end of a WAVEFORMATEX data structure. Transmit these bytes 
30  * to the decoder using the extradata[_size] fields in AVCodecContext. There 
31  * should be 4 extra bytes for v1 data and 6 extra bytes for v2 data.
32  */
33
34 #include "avcodec.h"
35 #include "dsputil.h"
36
37 /* size of blocks */
38 #define BLOCK_MIN_BITS 7
39 #define BLOCK_MAX_BITS 11
40 #define BLOCK_MAX_SIZE (1 << BLOCK_MAX_BITS)
41
42 #define BLOCK_NB_SIZES (BLOCK_MAX_BITS - BLOCK_MIN_BITS + 1)
43
44 /* XXX: find exact max size */
45 #define HIGH_BAND_MAX_SIZE 16
46
47 #define NB_LSP_COEFS 10
48
49 /* XXX: is it a suitable value ? */
50 #define MAX_CODED_SUPERFRAME_SIZE 4096
51
52 #define MAX_CHANNELS 2
53
54 #define NOISE_TAB_SIZE 8192
55
56 #define LSP_POW_BITS 7
57
58 typedef struct WMADecodeContext {
59     GetBitContext gb;
60     int sample_rate;
61     int nb_channels;
62     int bit_rate;
63     int version; /* 1 = 0x160 (WMAV1), 2 = 0x161 (WMAV2) */
64     int block_align;
65     int use_bit_reservoir;
66     int use_variable_block_len;
67     int use_exp_vlc;  /* exponent coding: 0 = lsp, 1 = vlc + delta */
68     int use_noise_coding; /* true if perceptual noise is added */
69     int byte_offset_bits;
70     VLC exp_vlc;
71     int exponent_sizes[BLOCK_NB_SIZES];
72     uint16_t exponent_bands[BLOCK_NB_SIZES][25];
73     int high_band_start[BLOCK_NB_SIZES]; /* index of first coef in high band */
74     int coefs_start;               /* first coded coef */
75     int coefs_end[BLOCK_NB_SIZES]; /* max number of coded coefficients */
76     int exponent_high_sizes[BLOCK_NB_SIZES];
77     int exponent_high_bands[BLOCK_NB_SIZES][HIGH_BAND_MAX_SIZE]; 
78     VLC hgain_vlc;
79     
80     /* coded values in high bands */
81     int high_band_coded[MAX_CHANNELS][HIGH_BAND_MAX_SIZE];
82     int high_band_values[MAX_CHANNELS][HIGH_BAND_MAX_SIZE];
83
84     /* there are two possible tables for spectral coefficients */
85     VLC coef_vlc[2];
86     uint16_t *run_table[2];
87     uint16_t *level_table[2];
88     /* frame info */
89     int frame_len;       /* frame length in samples */
90     int frame_len_bits;  /* frame_len = 1 << frame_len_bits */
91     int nb_block_sizes;  /* number of block sizes */
92     /* block info */
93     int reset_block_lengths;
94     int block_len_bits; /* log2 of current block length */
95     int next_block_len_bits; /* log2 of next block length */
96     int prev_block_len_bits; /* log2 of prev block length */
97     int block_len; /* block length in samples */
98     int block_num; /* block number in current frame */
99     int block_pos; /* current position in frame */
100     uint8_t ms_stereo; /* true if mid/side stereo mode */
101     uint8_t channel_coded[MAX_CHANNELS]; /* true if channel is coded */
102     float exponents[MAX_CHANNELS][BLOCK_MAX_SIZE] __attribute__((aligned(16)));
103     float max_exponent[MAX_CHANNELS];
104     int16_t coefs1[MAX_CHANNELS][BLOCK_MAX_SIZE];
105     float coefs[MAX_CHANNELS][BLOCK_MAX_SIZE] __attribute__((aligned(16)));
106     MDCTContext mdct_ctx[BLOCK_NB_SIZES];
107     float *windows[BLOCK_NB_SIZES];
108     FFTSample mdct_tmp[BLOCK_MAX_SIZE] __attribute__((aligned(16))); /* temporary storage for imdct */
109     /* output buffer for one frame and the last for IMDCT windowing */
110     float frame_out[MAX_CHANNELS][BLOCK_MAX_SIZE * 2] __attribute__((aligned(16)));
111     /* last frame info */
112     uint8_t last_superframe[MAX_CODED_SUPERFRAME_SIZE + 4]; /* padding added */
113     int last_bitoffset;
114     int last_superframe_len;
115     float noise_table[NOISE_TAB_SIZE];
116     int noise_index;
117     float noise_mult; /* XXX: suppress that and integrate it in the noise array */
118     /* lsp_to_curve tables */
119     float lsp_cos_table[BLOCK_MAX_SIZE];
120     float lsp_pow_e_table[256];
121     float lsp_pow_m_table1[(1 << LSP_POW_BITS)];
122     float lsp_pow_m_table2[(1 << LSP_POW_BITS)];
123
124 #ifdef TRACE
125     int frame_count;
126 #endif
127 } WMADecodeContext;
128
129 typedef struct CoefVLCTable {
130     int n; /* total number of codes */
131     const uint32_t *huffcodes; /* VLC bit values */
132     const uint8_t *huffbits;   /* VLC bit size */
133     const uint16_t *levels; /* table to build run/level tables */
134 } CoefVLCTable;
135
136 static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len);
137
138 #include "wmadata.h"
139
140 #ifdef TRACE
141 static void dump_shorts(const char *name, const short *tab, int n)
142 {
143     int i;
144
145     tprintf("%s[%d]:\n", name, n);
146     for(i=0;i<n;i++) {
147         if ((i & 7) == 0)
148             tprintf("%4d: ", i);
149         tprintf(" %5d.0", tab[i]);
150         if ((i & 7) == 7)
151             tprintf("\n");
152     }
153 }
154
155 static void dump_floats(const char *name, int prec, const float *tab, int n)
156 {
157     int i;
158
159     tprintf("%s[%d]:\n", name, n);
160     for(i=0;i<n;i++) {
161         if ((i & 7) == 0)
162             tprintf("%4d: ", i);
163         tprintf(" %8.*f", prec, tab[i]);
164         if ((i & 7) == 7)
165             tprintf("\n");
166     }
167     if ((i & 7) != 0)
168         tprintf("\n");
169 }
170 #endif
171
172 /* XXX: use same run/length optimization as mpeg decoders */
173 static void init_coef_vlc(VLC *vlc, 
174                           uint16_t **prun_table, uint16_t **plevel_table,
175                           const CoefVLCTable *vlc_table)
176 {
177     int n = vlc_table->n;
178     const uint8_t *table_bits = vlc_table->huffbits;
179     const uint32_t *table_codes = vlc_table->huffcodes;
180     const uint16_t *levels_table = vlc_table->levels;
181     uint16_t *run_table, *level_table;
182     const uint16_t *p;
183     int i, l, j, level;
184
185     init_vlc(vlc, 9, n, table_bits, 1, 1, table_codes, 4, 4);
186
187     run_table = av_malloc(n * sizeof(uint16_t));
188     level_table = av_malloc(n * sizeof(uint16_t));
189     p = levels_table;
190     i = 2;
191     level = 1;
192     while (i < n) {
193         l = *p++;
194         for(j=0;j<l;j++) {
195             run_table[i] = j;
196             level_table[i] = level;
197             i++;
198         }
199         level++;
200     }
201     *prun_table = run_table;
202     *plevel_table = level_table;
203 }
204
205 static int wma_decode_init(AVCodecContext * avctx)
206 {
207     WMADecodeContext *s = avctx->priv_data;
208     int i, flags1, flags2;
209     float *window;
210     uint8_t *extradata;
211     float bps1, high_freq, bps;
212     int sample_rate1;
213     int coef_vlc_table;
214     
215     s->sample_rate = avctx->sample_rate;
216     s->nb_channels = avctx->channels;
217     s->bit_rate = avctx->bit_rate;
218     s->block_align = avctx->block_align;
219
220     if (avctx->codec->id == CODEC_ID_WMAV1) {
221         s->version = 1;
222     } else {
223         s->version = 2;
224     }
225     
226     /* extract flag infos */
227     flags1 = 0;
228     flags2 = 0;
229     extradata = avctx->extradata;
230     if (s->version == 1 && avctx->extradata_size >= 4) {
231         flags1 = extradata[0] | (extradata[1] << 8);
232         flags2 = extradata[2] | (extradata[3] << 8);
233     } else if (s->version == 2 && avctx->extradata_size >= 6) {
234         flags1 = extradata[0] | (extradata[1] << 8) | 
235             (extradata[2] << 16) | (extradata[3] << 24);
236         flags2 = extradata[4] | (extradata[5] << 8);
237     }
238     s->use_exp_vlc = flags2 & 0x0001;
239     s->use_bit_reservoir = flags2 & 0x0002;
240     s->use_variable_block_len = flags2 & 0x0004;
241
242     /* compute MDCT block size */
243     if (s->sample_rate <= 16000) {
244         s->frame_len_bits = 9;
245     } else if (s->sample_rate <= 22050 || 
246                (s->sample_rate <= 32000 && s->version == 1)) {
247         s->frame_len_bits = 10;
248     } else {
249         s->frame_len_bits = 11;
250     }
251     s->frame_len = 1 << s->frame_len_bits;
252     if (s->use_variable_block_len) {
253         int nb_max, nb;
254         nb = ((flags2 >> 3) & 3) + 1;
255         if ((s->bit_rate / s->nb_channels) >= 32000)
256             nb += 2;
257         nb_max = s->frame_len_bits - BLOCK_MIN_BITS;
258         if (nb > nb_max)
259             nb = nb_max;
260         s->nb_block_sizes = nb + 1;
261     } else {
262         s->nb_block_sizes = 1;
263     }
264
265     /* init rate dependant parameters */
266     s->use_noise_coding = 1;
267     high_freq = s->sample_rate * 0.5;
268
269     /* if version 2, then the rates are normalized */
270     sample_rate1 = s->sample_rate;
271     if (s->version == 2) {
272         if (sample_rate1 >= 44100) 
273             sample_rate1 = 44100;
274         else if (sample_rate1 >= 22050) 
275             sample_rate1 = 22050;
276         else if (sample_rate1 >= 16000) 
277             sample_rate1 = 16000;
278         else if (sample_rate1 >= 11025) 
279             sample_rate1 = 11025;
280         else if (sample_rate1 >= 8000) 
281             sample_rate1 = 8000;
282     }
283
284     bps = (float)s->bit_rate / (float)(s->nb_channels * s->sample_rate);
285     s->byte_offset_bits = av_log2((int)(bps * s->frame_len / 8.0)) + 2;
286
287     /* compute high frequency value and choose if noise coding should
288        be activated */
289     bps1 = bps;
290     if (s->nb_channels == 2)
291         bps1 = bps * 1.6;
292     if (sample_rate1 == 44100) {
293         if (bps1 >= 0.61)
294             s->use_noise_coding = 0;
295         else
296             high_freq = high_freq * 0.4;
297     } else if (sample_rate1 == 22050) {
298         if (bps1 >= 1.16)
299             s->use_noise_coding = 0;
300         else if (bps1 >= 0.72) 
301             high_freq = high_freq * 0.7;
302         else
303             high_freq = high_freq * 0.6;
304     } else if (sample_rate1 == 16000) {
305         if (bps > 0.5)
306             high_freq = high_freq * 0.5;
307         else
308             high_freq = high_freq * 0.3;
309     } else if (sample_rate1 == 11025) {
310         high_freq = high_freq * 0.7;
311     } else if (sample_rate1 == 8000) {
312         if (bps <= 0.625) {
313             high_freq = high_freq * 0.5;
314         } else if (bps > 0.75) {
315             s->use_noise_coding = 0;
316         } else {
317             high_freq = high_freq * 0.65;
318         }
319     } else {
320         if (bps >= 0.8) {
321             high_freq = high_freq * 0.75;
322         } else if (bps >= 0.6) {
323             high_freq = high_freq * 0.6;
324         } else {
325             high_freq = high_freq * 0.5;
326         }
327     }
328     dprintf("flags1=0x%x flags2=0x%x\n", flags1, flags2);
329     dprintf("version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n",
330            s->version, s->nb_channels, s->sample_rate, s->bit_rate, 
331            s->block_align);
332     dprintf("bps=%f bps1=%f high_freq=%f bitoffset=%d\n", 
333            bps, bps1, high_freq, s->byte_offset_bits);
334     dprintf("use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",
335            s->use_noise_coding, s->use_exp_vlc, s->nb_block_sizes);
336
337     /* compute the scale factor band sizes for each MDCT block size */
338     {
339         int a, b, pos, lpos, k, block_len, i, j, n;
340         const uint8_t *table;
341         
342         if (s->version == 1) {
343             s->coefs_start = 3;
344         } else {
345             s->coefs_start = 0;
346         }
347         for(k = 0; k < s->nb_block_sizes; k++) {
348             block_len = s->frame_len >> k;
349
350             if (s->version == 1) {
351                 lpos = 0;
352                 for(i=0;i<25;i++) {
353                     a = wma_critical_freqs[i];
354                     b = s->sample_rate;
355                     pos = ((block_len * 2 * a)  + (b >> 1)) / b;
356                     if (pos > block_len) 
357                         pos = block_len;
358                     s->exponent_bands[0][i] = pos - lpos;
359                     if (pos >= block_len) {
360                         i++;
361                         break;
362                     }
363                     lpos = pos;
364                 }
365                 s->exponent_sizes[0] = i;
366             } else {
367                 /* hardcoded tables */
368                 table = NULL;
369                 a = s->frame_len_bits - BLOCK_MIN_BITS - k;
370                 if (a < 3) {
371                     if (s->sample_rate >= 44100)
372                         table = exponent_band_44100[a];
373                     else if (s->sample_rate >= 32000)
374                         table = exponent_band_32000[a];
375                     else if (s->sample_rate >= 22050)
376                         table = exponent_band_22050[a];
377                 }
378                 if (table) {
379                     n = *table++;
380                     for(i=0;i<n;i++)
381                         s->exponent_bands[k][i] = table[i];
382                     s->exponent_sizes[k] = n;
383                 } else {
384                     j = 0;
385                     lpos = 0;
386                     for(i=0;i<25;i++) {
387                         a = wma_critical_freqs[i];
388                         b = s->sample_rate;
389                         pos = ((block_len * 2 * a)  + (b << 1)) / (4 * b);
390                         pos <<= 2;
391                         if (pos > block_len) 
392                             pos = block_len;
393                         if (pos > lpos)
394                             s->exponent_bands[k][j++] = pos - lpos;
395                         if (pos >= block_len)
396                             break;
397                         lpos = pos;
398                     }
399                     s->exponent_sizes[k] = j;
400                 }
401             }
402
403             /* max number of coefs */
404             s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;
405             /* high freq computation */
406             s->high_band_start[k] = (int)((block_len * 2 * high_freq) / 
407                                           s->sample_rate + 0.5);
408             n = s->exponent_sizes[k];
409             j = 0;
410             pos = 0;
411             for(i=0;i<n;i++) {
412                 int start, end;
413                 start = pos;
414                 pos += s->exponent_bands[k][i];
415                 end = pos;
416                 if (start < s->high_band_start[k])
417                     start = s->high_band_start[k];
418                 if (end > s->coefs_end[k])
419                     end = s->coefs_end[k];
420                 if (end > start)
421                     s->exponent_high_bands[k][j++] = end - start;
422             }
423             s->exponent_high_sizes[k] = j;
424 #if 0
425             tprintf("%5d: coefs_end=%d high_band_start=%d nb_high_bands=%d: ",
426                   s->frame_len >> k, 
427                   s->coefs_end[k],
428                   s->high_band_start[k],
429                   s->exponent_high_sizes[k]);
430             for(j=0;j<s->exponent_high_sizes[k];j++)
431                 tprintf(" %d", s->exponent_high_bands[k][j]);
432             tprintf("\n");
433 #endif
434         }
435     }
436
437 #ifdef TRACE
438     {
439         int i, j;
440         for(i = 0; i < s->nb_block_sizes; i++) {
441             tprintf("%5d: n=%2d:", 
442                    s->frame_len >> i, 
443                    s->exponent_sizes[i]);
444             for(j=0;j<s->exponent_sizes[i];j++)
445                 tprintf(" %d", s->exponent_bands[i][j]);
446             tprintf("\n");
447         }
448     }
449 #endif
450
451     /* init MDCT */
452     for(i = 0; i < s->nb_block_sizes; i++)
453         ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 1);
454     
455     /* init MDCT windows : simple sinus window */
456     for(i = 0; i < s->nb_block_sizes; i++) {
457         int n, j;
458         float alpha;
459         n = 1 << (s->frame_len_bits - i);
460         window = av_malloc(sizeof(float) * n);
461         alpha = M_PI / (2.0 * n);
462         for(j=0;j<n;j++) {
463             window[n - j - 1] = sin((j + 0.5) * alpha);
464         }
465         s->windows[i] = window;
466     }
467
468     s->reset_block_lengths = 1;
469     
470     if (s->use_noise_coding) {
471
472         /* init the noise generator */
473         if (s->use_exp_vlc)
474             s->noise_mult = 0.02;
475         else
476             s->noise_mult = 0.04;
477                
478 #ifdef TRACE
479         for(i=0;i<NOISE_TAB_SIZE;i++)
480             s->noise_table[i] = 1.0 * s->noise_mult;
481 #else
482         {
483             unsigned int seed;
484             float norm;
485             seed = 1;
486             norm = (1.0 / (float)(1LL << 31)) * sqrt(3) * s->noise_mult;
487             for(i=0;i<NOISE_TAB_SIZE;i++) {
488                 seed = seed * 314159 + 1;
489                 s->noise_table[i] = (float)((int)seed) * norm;
490             }
491         }
492 #endif
493         init_vlc(&s->hgain_vlc, 9, sizeof(hgain_huffbits), 
494                  hgain_huffbits, 1, 1,
495                  hgain_huffcodes, 2, 2);
496     }
497
498     if (s->use_exp_vlc) {
499         init_vlc(&s->exp_vlc, 9, sizeof(scale_huffbits), 
500                  scale_huffbits, 1, 1,
501                  scale_huffcodes, 4, 4);
502     } else {
503         wma_lsp_to_curve_init(s, s->frame_len);
504     }
505
506     /* choose the VLC tables for the coefficients */
507     coef_vlc_table = 2;
508     if (s->sample_rate >= 32000) {
509         if (bps1 < 0.72)
510             coef_vlc_table = 0;
511         else if (bps1 < 1.16)
512             coef_vlc_table = 1;
513     }
514
515     init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0],
516                   &coef_vlcs[coef_vlc_table * 2]);
517     init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1],
518                   &coef_vlcs[coef_vlc_table * 2 + 1]);
519     return 0;
520 }
521
522 /* interpolate values for a bigger or smaller block. The block must
523    have multiple sizes */
524 static void interpolate_array(float *scale, int old_size, int new_size)
525 {
526     int i, j, jincr, k;
527     float v;
528
529     if (new_size > old_size) {
530         jincr = new_size / old_size;
531         j = new_size;
532         for(i = old_size - 1; i >=0; i--) {
533             v = scale[i];
534             k = jincr;
535             do {
536                 scale[--j] = v;
537             } while (--k);
538         }
539     } else if (new_size < old_size) {
540         j = 0;
541         jincr = old_size / new_size;
542         for(i = 0; i < new_size; i++) {
543             scale[i] = scale[j];
544             j += jincr;
545         }
546     }
547 }
548
549 /* compute x^-0.25 with an exponent and mantissa table. We use linear
550    interpolation to reduce the mantissa table size at a small speed
551    expense (linear interpolation approximately doubles the number of
552    bits of precision). */
553 static inline float pow_m1_4(WMADecodeContext *s, float x)
554 {
555     union {
556         float f;
557         unsigned int v;
558     } u, t;
559     unsigned int e, m;
560     float a, b;
561
562     u.f = x;
563     e = u.v >> 23;
564     m = (u.v >> (23 - LSP_POW_BITS)) & ((1 << LSP_POW_BITS) - 1);
565     /* build interpolation scale: 1 <= t < 2. */
566     t.v = ((u.v << LSP_POW_BITS) & ((1 << 23) - 1)) | (127 << 23);
567     a = s->lsp_pow_m_table1[m];
568     b = s->lsp_pow_m_table2[m];
569     return s->lsp_pow_e_table[e] * (a + b * t.f);
570 }
571
572 static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len)
573 {  
574     float wdel, a, b;
575     int i, e, m;
576
577     wdel = M_PI / frame_len;
578     for(i=0;i<frame_len;i++)
579         s->lsp_cos_table[i] = 2.0f * cos(wdel * i);
580
581     /* tables for x^-0.25 computation */
582     for(i=0;i<256;i++) {
583         e = i - 126;
584         s->lsp_pow_e_table[i] = pow(2.0, e * -0.25);
585     }
586
587     /* NOTE: these two tables are needed to avoid two operations in
588        pow_m1_4 */
589     b = 1.0;
590     for(i=(1 << LSP_POW_BITS) - 1;i>=0;i--) {
591         m = (1 << LSP_POW_BITS) + i;
592         a = (float)m * (0.5 / (1 << LSP_POW_BITS));
593         a = pow(a, -0.25);
594         s->lsp_pow_m_table1[i] = 2 * a - b;
595         s->lsp_pow_m_table2[i] = b - a;
596         b = a;
597     }
598 #if 0
599     for(i=1;i<20;i++) {
600         float v, r1, r2;
601         v = 5.0 / i;
602         r1 = pow_m1_4(s, v);
603         r2 = pow(v,-0.25);
604         printf("%f^-0.25=%f e=%f\n", v, r1, r2 - r1);
605     }
606 #endif
607 }
608
609 /* NOTE: We use the same code as Vorbis here */
610 /* XXX: optimize it further with SSE/3Dnow */
611 static void wma_lsp_to_curve(WMADecodeContext *s, 
612                              float *out, float *val_max_ptr, 
613                              int n, float *lsp)
614 {
615     int i, j;
616     float p, q, w, v, val_max;
617
618     val_max = 0;
619     for(i=0;i<n;i++) {
620         p = 0.5f;
621         q = 0.5f;
622         w = s->lsp_cos_table[i];
623         for(j=1;j<NB_LSP_COEFS;j+=2){
624             q *= w - lsp[j - 1];
625             p *= w - lsp[j];
626         }
627         p *= p * (2.0f - w);
628         q *= q * (2.0f + w);
629         v = p + q;
630         v = pow_m1_4(s, v);
631         if (v > val_max)
632             val_max = v;
633         out[i] = v;
634     }
635     *val_max_ptr = val_max;
636 }
637
638 /* decode exponents coded with LSP coefficients (same idea as Vorbis) */
639 static void decode_exp_lsp(WMADecodeContext *s, int ch)
640 {
641     float lsp_coefs[NB_LSP_COEFS];
642     int val, i;
643
644     for(i = 0; i < NB_LSP_COEFS; i++) {
645         if (i == 0 || i >= 8)
646             val = get_bits(&s->gb, 3);
647         else
648             val = get_bits(&s->gb, 4);
649         lsp_coefs[i] = lsp_codebook[i][val];
650     }
651
652     wma_lsp_to_curve(s, s->exponents[ch], &s->max_exponent[ch],
653                      s->block_len, lsp_coefs);
654 }
655
656 /* decode exponents coded with VLC codes */
657 static int decode_exp_vlc(WMADecodeContext *s, int ch)
658 {
659     int last_exp, n, code;
660     const uint16_t *ptr, *band_ptr;
661     float v, *q, max_scale, *q_end;
662     
663     band_ptr = s->exponent_bands[s->frame_len_bits - s->block_len_bits];
664     ptr = band_ptr;
665     q = s->exponents[ch];
666     q_end = q + s->block_len;
667     max_scale = 0;
668     if (s->version == 1) {
669         last_exp = get_bits(&s->gb, 5) + 10;
670         /* XXX: use a table */
671         v = pow(10, last_exp * (1.0 / 16.0));
672         max_scale = v;
673         n = *ptr++;
674         do {
675             *q++ = v;
676         } while (--n);
677     }
678     last_exp = 36;
679     while (q < q_end) {
680         code = get_vlc(&s->gb, &s->exp_vlc);
681         if (code < 0)
682             return -1;
683         /* NOTE: this offset is the same as MPEG4 AAC ! */
684         last_exp += code - 60;
685         /* XXX: use a table */
686         v = pow(10, last_exp * (1.0 / 16.0));
687         if (v > max_scale)
688             max_scale = v;
689         n = *ptr++;
690         do {
691             *q++ = v;
692         } while (--n);
693     }
694     s->max_exponent[ch] = max_scale;
695     return 0;
696 }
697
698 /* return 0 if OK. return 1 if last block of frame. return -1 if
699    unrecorrable error. */
700 static int wma_decode_block(WMADecodeContext *s)
701 {
702     int n, v, a, ch, code, bsize;
703     int coef_nb_bits, total_gain, parse_exponents;
704     float window[BLOCK_MAX_SIZE * 2];
705     int nb_coefs[MAX_CHANNELS];
706     float mdct_norm;
707
708 #ifdef TRACE
709     tprintf("***decode_block: %d:%d\n", s->frame_count - 1, s->block_num);
710 #endif
711
712     /* compute current block length */
713     if (s->use_variable_block_len) {
714         n = av_log2(s->nb_block_sizes - 1) + 1;
715     
716         if (s->reset_block_lengths) {
717             s->reset_block_lengths = 0;
718             v = get_bits(&s->gb, n);
719             if (v >= s->nb_block_sizes)
720                 return -1;
721             s->prev_block_len_bits = s->frame_len_bits - v;
722             v = get_bits(&s->gb, n);
723             if (v >= s->nb_block_sizes)
724                 return -1;
725             s->block_len_bits = s->frame_len_bits - v;
726         } else {
727             /* update block lengths */
728             s->prev_block_len_bits = s->block_len_bits;
729             s->block_len_bits = s->next_block_len_bits;
730         }
731         v = get_bits(&s->gb, n);
732         if (v >= s->nb_block_sizes)
733             return -1;
734         s->next_block_len_bits = s->frame_len_bits - v;
735     } else {
736         /* fixed block len */
737         s->next_block_len_bits = s->frame_len_bits;
738         s->prev_block_len_bits = s->frame_len_bits;
739         s->block_len_bits = s->frame_len_bits;
740     }
741
742     /* now check if the block length is coherent with the frame length */
743     s->block_len = 1 << s->block_len_bits;
744     if ((s->block_pos + s->block_len) > s->frame_len)
745         return -1;
746
747     if (s->nb_channels == 2) {
748         s->ms_stereo = get_bits(&s->gb, 1);
749     }
750     v = 0;
751     for(ch = 0; ch < s->nb_channels; ch++) {
752         a = get_bits(&s->gb, 1);
753         s->channel_coded[ch] = a;
754         v |= a;
755     }
756     /* if no channel coded, no need to go further */
757     /* XXX: fix potential framing problems */
758     if (!v)
759         goto next;
760
761     bsize = s->frame_len_bits - s->block_len_bits;
762
763     /* read total gain and extract corresponding number of bits for
764        coef escape coding */
765     total_gain = 1;
766     for(;;) {
767         a = get_bits(&s->gb, 7);
768         total_gain += a;
769         if (a != 127)
770             break;
771     }
772     
773     if (total_gain < 15)
774         coef_nb_bits = 13;
775     else if (total_gain < 32)
776         coef_nb_bits = 12;
777     else if (total_gain < 40)
778         coef_nb_bits = 11;
779     else if (total_gain < 45)
780         coef_nb_bits = 10;
781     else
782         coef_nb_bits = 9;
783
784     /* compute number of coefficients */
785     n = s->coefs_end[bsize] - s->coefs_start;
786     for(ch = 0; ch < s->nb_channels; ch++)
787         nb_coefs[ch] = n;
788
789     /* complex coding */
790     if (s->use_noise_coding) {
791
792         for(ch = 0; ch < s->nb_channels; ch++) {
793             if (s->channel_coded[ch]) {
794                 int i, n, a;
795                 n = s->exponent_high_sizes[bsize];
796                 for(i=0;i<n;i++) {
797                     a = get_bits(&s->gb, 1);
798                     s->high_band_coded[ch][i] = a;
799                     /* if noise coding, the coefficients are not transmitted */
800                     if (a)
801                         nb_coefs[ch] -= s->exponent_high_bands[bsize][i];
802                 }
803             }
804         }
805         for(ch = 0; ch < s->nb_channels; ch++) {
806             if (s->channel_coded[ch]) {
807                 int i, n, val, code;
808
809                 n = s->exponent_high_sizes[bsize];
810                 val = (int)0x80000000;
811                 for(i=0;i<n;i++) {
812                     if (s->high_band_coded[ch][i]) {
813                         if (val == (int)0x80000000) {
814                             val = get_bits(&s->gb, 7) - 19;
815                         } else {
816                             code = get_vlc(&s->gb, &s->hgain_vlc);
817                             if (code < 0)
818                                 return -1;
819                             val += code - 18;
820                         }
821                         s->high_band_values[ch][i] = val;
822                     }
823                 }
824             }
825         }
826     }
827            
828     /* exposant can be interpolated in short blocks. */
829     parse_exponents = 1;
830     if (s->block_len_bits != s->frame_len_bits) {
831         parse_exponents = get_bits(&s->gb, 1);
832     }
833     
834     if (parse_exponents) {
835         for(ch = 0; ch < s->nb_channels; ch++) {
836             if (s->channel_coded[ch]) {
837                 if (s->use_exp_vlc) {
838                     if (decode_exp_vlc(s, ch) < 0)
839                         return -1;
840                 } else {
841                     decode_exp_lsp(s, ch);
842                 }
843             }
844         }
845     } else {
846         for(ch = 0; ch < s->nb_channels; ch++) {
847             if (s->channel_coded[ch]) {
848                 interpolate_array(s->exponents[ch], 1 << s->prev_block_len_bits, 
849                                   s->block_len);
850             }
851         }
852     }
853
854     /* parse spectral coefficients : just RLE encoding */
855     for(ch = 0; ch < s->nb_channels; ch++) {
856         if (s->channel_coded[ch]) {
857             VLC *coef_vlc;
858             int level, run, sign, tindex;
859             int16_t *ptr, *eptr;
860             const int16_t *level_table, *run_table;
861
862             /* special VLC tables are used for ms stereo because
863                there is potentially less energy there */
864             tindex = (ch == 1 && s->ms_stereo);
865             coef_vlc = &s->coef_vlc[tindex];
866             run_table = s->run_table[tindex];
867             level_table = s->level_table[tindex];
868             /* XXX: optimize */
869             ptr = &s->coefs1[ch][0];
870             eptr = ptr + nb_coefs[ch];
871             memset(ptr, 0, s->block_len * sizeof(int16_t));
872             for(;;) {
873                 code = get_vlc(&s->gb, coef_vlc);
874                 if (code < 0)
875                     return -1;
876                 if (code == 1) {
877                     /* EOB */
878                     break;
879                 } else if (code == 0) {
880                     /* escape */
881                     level = get_bits(&s->gb, coef_nb_bits);
882                     /* NOTE: this is rather suboptimal. reading
883                        block_len_bits would be better */
884                     run = get_bits(&s->gb, s->frame_len_bits);
885                 } else {
886                     /* normal code */
887                     run = run_table[code];
888                     level = level_table[code];
889                 }
890                 sign = get_bits(&s->gb, 1);
891                 if (!sign)
892                     level = -level;
893                 ptr += run;
894                 if (ptr >= eptr)
895                     return -1;
896                 *ptr++ = level;
897                 /* NOTE: EOB can be omitted */
898                 if (ptr >= eptr)
899                     break;
900             }
901         }
902         if (s->version == 1 && s->nb_channels >= 2) {
903             align_get_bits(&s->gb);
904         }
905     }
906      
907     /* normalize */
908     {
909         int n4 = s->block_len / 2;
910         mdct_norm = 1.0 / (float)n4;
911         if (s->version == 1) {
912             mdct_norm *= sqrt(n4);
913         }
914     }
915
916     /* finally compute the MDCT coefficients */
917     for(ch = 0; ch < s->nb_channels; ch++) {
918         if (s->channel_coded[ch]) {
919             int16_t *coefs1;
920             float *coefs, *exponents, mult, mult1, noise, *exp_ptr;
921             int i, j, n, n1, last_high_band;
922             float exp_power[HIGH_BAND_MAX_SIZE];
923
924             coefs1 = s->coefs1[ch];
925             exponents = s->exponents[ch];
926             mult = pow(10, total_gain * 0.05) / s->max_exponent[ch];
927             mult *= mdct_norm;
928             coefs = s->coefs[ch];
929             if (s->use_noise_coding) {
930                 mult1 = mult;
931                 /* very low freqs : noise */
932                 for(i = 0;i < s->coefs_start; i++) {
933                     *coefs++ = s->noise_table[s->noise_index] * (*exponents++) * mult1;
934                     s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
935                 }
936                 
937                 n1 = s->exponent_high_sizes[bsize];
938
939                 /* compute power of high bands */
940                 exp_ptr = exponents + 
941                     s->high_band_start[bsize] - 
942                     s->coefs_start;
943                 last_high_band = 0; /* avoid warning */
944                 for(j=0;j<n1;j++) {
945                     n = s->exponent_high_bands[s->frame_len_bits - 
946                                               s->block_len_bits][j];
947                     if (s->high_band_coded[ch][j]) {
948                         float e2, v;
949                         e2 = 0;
950                         for(i = 0;i < n; i++) {
951                             v = exp_ptr[i];
952                             e2 += v * v;
953                         }
954                         exp_power[j] = e2 / n;
955                         last_high_band = j;
956                         tprintf("%d: power=%f (%d)\n", j, exp_power[j], n);
957                     }
958                     exp_ptr += n;
959                 }
960
961                 /* main freqs and high freqs */
962                 for(j=-1;j<n1;j++) {
963                     if (j < 0) {
964                         n = s->high_band_start[bsize] - 
965                             s->coefs_start;
966                     } else {
967                         n = s->exponent_high_bands[s->frame_len_bits - 
968                                                   s->block_len_bits][j];
969                     }
970                     if (j >= 0 && s->high_band_coded[ch][j]) {
971                         /* use noise with specified power */
972                         mult1 = sqrt(exp_power[j] / exp_power[last_high_band]);
973                         /* XXX: use a table */
974                         mult1 = mult1 * pow(10, s->high_band_values[ch][j] * 0.05);
975                         mult1 = mult1 / (s->max_exponent[ch] * s->noise_mult);
976                         mult1 *= mdct_norm;
977                         for(i = 0;i < n; i++) {
978                             noise = s->noise_table[s->noise_index];
979                             s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
980                             *coefs++ = (*exponents++) * noise * mult1;
981                         }
982                     } else {
983                         /* coded values + small noise */
984                         for(i = 0;i < n; i++) {
985                             noise = s->noise_table[s->noise_index];
986                             s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
987                             *coefs++ = ((*coefs1++) + noise) * (*exponents++) * mult;
988                         }
989                     }
990                 }
991
992                 /* very high freqs : noise */
993                 n = s->block_len - s->coefs_end[bsize];
994                 mult1 = mult * exponents[-1];
995                 for(i = 0; i < n; i++) {
996                     *coefs++ = s->noise_table[s->noise_index] * mult1;
997                     s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
998                 }
999             } else {
1000                 /* XXX: optimize more */
1001                 for(i = 0;i < s->coefs_start; i++)
1002                     *coefs++ = 0.0;
1003                 n = nb_coefs[ch];
1004                 for(i = 0;i < n; i++) {
1005                     *coefs++ = coefs1[i] * exponents[i] * mult;
1006                 }
1007                 n = s->block_len - s->coefs_end[bsize];
1008                 for(i = 0;i < n; i++)
1009                     *coefs++ = 0.0;
1010             }
1011         }
1012     }
1013
1014 #ifdef TRACE
1015     for(ch = 0; ch < s->nb_channels; ch++) {
1016         if (s->channel_coded[ch]) {
1017             dump_floats("exponents", 3, s->exponents[ch], s->block_len);
1018             dump_floats("coefs", 1, s->coefs[ch], s->block_len);
1019         }
1020     }
1021 #endif
1022     
1023     if (s->ms_stereo && s->channel_coded[1]) {
1024         float a, b;
1025         int i;
1026
1027         /* nominal case for ms stereo: we do it before mdct */
1028         /* no need to optimize this case because it should almost
1029            never happen */
1030         if (!s->channel_coded[0]) {
1031             tprintf("rare ms-stereo case happened\n");
1032             memset(s->coefs[0], 0, sizeof(float) * s->block_len);
1033             s->channel_coded[0] = 1;
1034         }
1035         
1036         for(i = 0; i < s->block_len; i++) {
1037             a = s->coefs[0][i];
1038             b = s->coefs[1][i];
1039             s->coefs[0][i] = a + b;
1040             s->coefs[1][i] = a - b;
1041         }
1042     }
1043
1044     /* build the window : we ensure that when the windows overlap
1045        their squared sum is always 1 (MDCT reconstruction rule) */
1046     /* XXX: merge with output */
1047     {
1048         int i, next_block_len, block_len, prev_block_len, n;
1049         float *wptr;
1050
1051         block_len = s->block_len;
1052         prev_block_len = 1 << s->prev_block_len_bits;
1053         next_block_len = 1 << s->next_block_len_bits;
1054
1055         /* right part */
1056         wptr = window + block_len;
1057         if (block_len <= next_block_len) {
1058             for(i=0;i<block_len;i++)
1059                 *wptr++ = s->windows[bsize][i];
1060         } else {
1061             /* overlap */
1062             n = (block_len / 2) - (next_block_len / 2);
1063             for(i=0;i<n;i++)
1064                 *wptr++ = 1.0;
1065             for(i=0;i<next_block_len;i++)
1066                 *wptr++ = s->windows[s->frame_len_bits - s->next_block_len_bits][i];
1067             for(i=0;i<n;i++)
1068                 *wptr++ = 0.0;
1069         }
1070
1071         /* left part */
1072         wptr = window + block_len;
1073         if (block_len <= prev_block_len) {
1074             for(i=0;i<block_len;i++)
1075                 *--wptr = s->windows[bsize][i];
1076         } else {
1077             /* overlap */
1078             n = (block_len / 2) - (prev_block_len / 2);
1079             for(i=0;i<n;i++)
1080                 *--wptr = 1.0;
1081             for(i=0;i<prev_block_len;i++)
1082                 *--wptr = s->windows[s->frame_len_bits - s->prev_block_len_bits][i];
1083             for(i=0;i<n;i++)
1084                 *--wptr = 0.0;
1085         }
1086     }
1087
1088     
1089     for(ch = 0; ch < s->nb_channels; ch++) {
1090         if (s->channel_coded[ch]) {
1091             FFTSample output[BLOCK_MAX_SIZE * 2] __attribute__((aligned(16)));
1092             float *ptr;
1093             int i, n4, index, n;
1094
1095             n = s->block_len;
1096             n4 = s->block_len / 2;
1097             ff_imdct_calc(&s->mdct_ctx[bsize], 
1098                           output, s->coefs[ch], s->mdct_tmp);
1099
1100             /* XXX: optimize all that by build the window and
1101                multipying/adding at the same time */
1102             /* multiply by the window */
1103             for(i=0;i<n * 2;i++) {
1104                 output[i] *= window[i];
1105             }
1106
1107             /* add in the frame */
1108             index = (s->frame_len / 2) + s->block_pos - n4;
1109             ptr = &s->frame_out[ch][index];
1110             for(i=0;i<n * 2;i++) {
1111                 *ptr += output[i];
1112                 ptr++;
1113             }
1114
1115             /* specific fast case for ms-stereo : add to second
1116                channel if it is not coded */
1117             if (s->ms_stereo && !s->channel_coded[1]) {
1118                 ptr = &s->frame_out[1][index];
1119                 for(i=0;i<n * 2;i++) {
1120                     *ptr += output[i];
1121                     ptr++;
1122                 }
1123             }
1124         }
1125     }
1126  next:
1127     /* update block number */
1128     s->block_num++;
1129     s->block_pos += s->block_len;
1130     if (s->block_pos >= s->frame_len)
1131         return 1;
1132     else
1133         return 0;
1134 }
1135
1136 /* decode a frame of frame_len samples */
1137 static int wma_decode_frame(WMADecodeContext *s, int16_t *samples)
1138 {
1139     int ret, i, n, a, ch, incr;
1140     int16_t *ptr;
1141     float *iptr;
1142
1143 #ifdef TRACE
1144     tprintf("***decode_frame: %d size=%d\n", s->frame_count++, s->frame_len);
1145 #endif
1146
1147     /* read each block */
1148     s->block_num = 0;
1149     s->block_pos = 0;
1150     for(;;) {
1151         ret = wma_decode_block(s);
1152         if (ret < 0) 
1153             return -1;
1154         if (ret)
1155             break;
1156     }
1157
1158     /* convert frame to integer */
1159     n = s->frame_len;
1160     incr = s->nb_channels;
1161     for(ch = 0; ch < s->nb_channels; ch++) {
1162         ptr = samples + ch;
1163         iptr = s->frame_out[ch];
1164
1165         for(i=0;i<n;i++) {
1166             a = lrintf(*iptr++);
1167             if (a > 32767)
1168                 a = 32767;
1169             else if (a < -32768)
1170                 a = -32768;
1171             *ptr = a;
1172             ptr += incr;
1173         }
1174         /* prepare for next block */
1175         memmove(&s->frame_out[ch][0], &s->frame_out[ch][s->frame_len],
1176                 s->frame_len * sizeof(float));
1177         /* XXX: suppress this */
1178         memset(&s->frame_out[ch][s->frame_len], 0, 
1179                s->frame_len * sizeof(float));
1180     }
1181
1182 #ifdef TRACE
1183     dump_shorts("samples", samples, n * s->nb_channels);
1184 #endif
1185     return 0;
1186 }
1187
1188 static int wma_decode_superframe(AVCodecContext *avctx, 
1189                                  void *data, int *data_size,
1190                                  uint8_t *buf, int buf_size)
1191 {
1192     WMADecodeContext *s = avctx->priv_data;
1193     int nb_frames, bit_offset, i, pos, len;
1194     uint8_t *q;
1195     int16_t *samples;
1196     
1197     tprintf("***decode_superframe:\n");
1198
1199     if(buf_size==0){
1200         s->last_superframe_len = 0;
1201         return 0;
1202     }
1203     
1204     samples = data;
1205
1206     init_get_bits(&s->gb, buf, buf_size*8);
1207     
1208     if (s->use_bit_reservoir) {
1209         /* read super frame header */
1210         get_bits(&s->gb, 4); /* super frame index */
1211         nb_frames = get_bits(&s->gb, 4) - 1;
1212
1213         bit_offset = get_bits(&s->gb, s->byte_offset_bits + 3);
1214
1215         if (s->last_superframe_len > 0) {
1216             //        printf("skip=%d\n", s->last_bitoffset);
1217             /* add bit_offset bits to last frame */
1218             if ((s->last_superframe_len + ((bit_offset + 7) >> 3)) > 
1219                 MAX_CODED_SUPERFRAME_SIZE)
1220                 goto fail;
1221             q = s->last_superframe + s->last_superframe_len;
1222             len = bit_offset;
1223             while (len > 0) {
1224                 *q++ = (get_bits)(&s->gb, 8);
1225                 len -= 8;
1226             }
1227             if (len > 0) {
1228                 *q++ = (get_bits)(&s->gb, len) << (8 - len);
1229             }
1230             
1231             /* XXX: bit_offset bits into last frame */
1232             init_get_bits(&s->gb, s->last_superframe, MAX_CODED_SUPERFRAME_SIZE*8);
1233             /* skip unused bits */
1234             if (s->last_bitoffset > 0)
1235                 skip_bits(&s->gb, s->last_bitoffset);
1236             /* this frame is stored in the last superframe and in the
1237                current one */
1238             if (wma_decode_frame(s, samples) < 0)
1239                 goto fail;
1240             samples += s->nb_channels * s->frame_len;
1241         }
1242
1243         /* read each frame starting from bit_offset */
1244         pos = bit_offset + 4 + 4 + s->byte_offset_bits + 3;
1245         init_get_bits(&s->gb, buf + (pos >> 3), (MAX_CODED_SUPERFRAME_SIZE - (pos >> 3))*8);
1246         len = pos & 7;
1247         if (len > 0)
1248             skip_bits(&s->gb, len);
1249     
1250         s->reset_block_lengths = 1;
1251         for(i=0;i<nb_frames;i++) {
1252             if (wma_decode_frame(s, samples) < 0)
1253                 goto fail;
1254             samples += s->nb_channels * s->frame_len;
1255         }
1256
1257         /* we copy the end of the frame in the last frame buffer */
1258         pos = get_bits_count(&s->gb) + ((bit_offset + 4 + 4 + s->byte_offset_bits + 3) & ~7);
1259         s->last_bitoffset = pos & 7;
1260         pos >>= 3;
1261         len = buf_size - pos;
1262         if (len > MAX_CODED_SUPERFRAME_SIZE || len < 0) {
1263             goto fail;
1264         }
1265         s->last_superframe_len = len;
1266         memcpy(s->last_superframe, buf + pos, len);
1267     } else {
1268         /* single frame decode */
1269         if (wma_decode_frame(s, samples) < 0)
1270             goto fail;
1271         samples += s->nb_channels * s->frame_len;
1272     }
1273     *data_size = (int8_t *)samples - (int8_t *)data;
1274     return s->block_align;
1275  fail:
1276     /* when error, we reset the bit reservoir */
1277     s->last_superframe_len = 0;
1278     return -1;
1279 }
1280
1281 static int wma_decode_end(AVCodecContext *avctx)
1282 {
1283     WMADecodeContext *s = avctx->priv_data;
1284     int i;
1285
1286     for(i = 0; i < s->nb_block_sizes; i++)
1287         ff_mdct_end(&s->mdct_ctx[i]);
1288     for(i = 0; i < s->nb_block_sizes; i++)
1289         av_free(s->windows[i]);
1290
1291     if (s->use_exp_vlc) {
1292         free_vlc(&s->exp_vlc);
1293     }
1294     if (s->use_noise_coding) {
1295         free_vlc(&s->hgain_vlc);
1296     }
1297     for(i = 0;i < 2; i++) {
1298         free_vlc(&s->coef_vlc[i]);
1299         av_free(s->run_table[i]);
1300         av_free(s->level_table[i]);
1301     }
1302     
1303     return 0;
1304 }
1305
1306 AVCodec wmav1_decoder =
1307 {
1308     "wmav1",
1309     CODEC_TYPE_AUDIO,
1310     CODEC_ID_WMAV1,
1311     sizeof(WMADecodeContext),
1312     wma_decode_init,
1313     NULL,
1314     wma_decode_end,
1315     wma_decode_superframe,
1316 };
1317
1318 AVCodec wmav2_decoder =
1319 {
1320     "wmav2",
1321     CODEC_TYPE_AUDIO,
1322     CODEC_ID_WMAV2,
1323     sizeof(WMADecodeContext),
1324     wma_decode_init,
1325     NULL,
1326     wma_decode_end,
1327     wma_decode_superframe,
1328 };