Move bitstream.[ch] to codecs/lib/ffmpeg_bitstream.[ch] to avoid duplicate copies...
[kugel-rb.git] / apps / codecs / libwma / wmadeci.c
blobf01ffefc13c54ec4fc21f6b267f3924b17a27b35
1 /*
2 * WMA compatible decoder
3 * Copyright (c) 2002 The FFmpeg Project.
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.
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.
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
20 /**
21 * @file wmadec.c
22 * WMA compatible decoder.
25 #include <codecs.h>
26 #include <codecs/lib/codeclib.h>
27 #include "asf.h"
28 #include "wmadec.h"
29 #include "wmafixed.h"
30 #include "bitstream.h"
31 #include "wmadata.h"
33 static const uint8_t ff_log2_tab[256]={
34 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
35 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
36 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
37 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
38 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
39 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
40 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
41 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
44 static inline int av_log2(unsigned int v)
46 int n;
48 n = 0;
49 if (v & 0xffff0000) {
50 v >>= 16;
51 n += 16;
53 if (v & 0xff00) {
54 v >>= 8;
55 n += 8;
57 n += ff_log2_tab[v];
59 return n;
62 static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len);
63 inline void vector_fmul_add_add(fixed32 *dst, const fixed32 *data,
64 const fixed32 *window, int n);
65 inline void vector_fmul_reverse(fixed32 *dst, const fixed32 *src0,
66 const fixed32 *src1, int len);
68 /*declarations of statically allocated variables used to remove malloc calls*/
70 fixed32 coefsarray[MAX_CHANNELS][BLOCK_MAX_SIZE] IBSS_ATTR;
71 /*decode and window into IRAM on targets with at least 80KB of codec IRAM*/
72 fixed32 frame_out_buf[MAX_CHANNELS][BLOCK_MAX_SIZE * 2] IBSS_ATTR_WMA_LARGE_IRAM;
74 /*MDCT reconstruction windows*/
75 fixed32 stat0[2048], stat1[1024], stat2[512], stat3[256], stat4[128];
77 /*VLC lookup tables*/
78 uint16_t *runtabarray[2], *levtabarray[2];
80 /*these could be made smaller since only one can be 1336*/
81 uint16_t runtab0[1336], runtab1[1336], levtab0[1336], levtab1[1336];
83 #define VLCBUF1SIZE 4598
84 #define VLCBUF2SIZE 3574
85 #define VLCBUF3SIZE 360
86 #define VLCBUF4SIZE 540
88 /*putting these in IRAM actually makes PP slower*/
90 VLC_TYPE vlcbuf1[VLCBUF1SIZE][2];
91 VLC_TYPE vlcbuf2[VLCBUF2SIZE][2];
92 VLC_TYPE vlcbuf3[VLCBUF3SIZE][2];
93 VLC_TYPE vlcbuf4[VLCBUF4SIZE][2];
98 /**
99 * Apply MDCT window and add into output.
101 * We ensure that when the windows overlap their squared sum
102 * is always 1 (MDCT reconstruction rule).
104 * The Vorbis I spec has a great diagram explaining this process.
105 * See section 1.3.2.3 of http://xiph.org/vorbis/doc/Vorbis_I_spec.html
107 static void wma_window(WMADecodeContext *s, fixed32 *in, fixed32 *out)
109 //float *in = s->output;
110 int block_len, bsize, n;
112 /* left part */
114 /* previous block was larger, so we'll use the size of the current
115 * block to set the window size*/
116 if (s->block_len_bits <= s->prev_block_len_bits) {
117 block_len = s->block_len;
118 bsize = s->frame_len_bits - s->block_len_bits;
120 vector_fmul_add_add(out, in, s->windows[bsize], block_len);
122 } else {
123 /*previous block was smaller or the same size, so use it's size to set the window length*/
124 block_len = 1 << s->prev_block_len_bits;
125 /*find the middle of the two overlapped blocks, this will be the first overlapped sample*/
126 n = (s->block_len - block_len) / 2;
127 bsize = s->frame_len_bits - s->prev_block_len_bits;
129 vector_fmul_add_add(out+n, in+n, s->windows[bsize], block_len);
131 memcpy(out+n+block_len, in+n+block_len, n*sizeof(fixed32));
133 /* Advance to the end of the current block and prepare to window it for the next block.
134 * Since the window function needs to be reversed, we do it backwards starting with the
135 * last sample and moving towards the first
137 out += s->block_len;
138 in += s->block_len;
140 /* right part */
141 if (s->block_len_bits <= s->next_block_len_bits) {
142 block_len = s->block_len;
143 bsize = s->frame_len_bits - s->block_len_bits;
145 vector_fmul_reverse(out, in, s->windows[bsize], block_len);
147 } else {
148 block_len = 1 << s->next_block_len_bits;
149 n = (s->block_len - block_len) / 2;
150 bsize = s->frame_len_bits - s->next_block_len_bits;
152 memcpy(out, in, n*sizeof(fixed32));
154 vector_fmul_reverse(out+n, in+n, s->windows[bsize], block_len);
156 memset(out+n+block_len, 0, n*sizeof(fixed32));
163 /* XXX: use same run/length optimization as mpeg decoders */
164 static void init_coef_vlc(VLC *vlc,
165 uint16_t **prun_table, uint16_t **plevel_table,
166 const CoefVLCTable *vlc_table, int tab)
168 int n = vlc_table->n;
169 const uint8_t *table_bits = vlc_table->huffbits;
170 const uint32_t *table_codes = vlc_table->huffcodes;
171 const uint16_t *levels_table = vlc_table->levels;
172 uint16_t *run_table, *level_table;
173 const uint16_t *p;
174 int i, l, j, level;
177 init_vlc(vlc, VLCBITS, n, table_bits, 1, 1, table_codes, 4, 4, 0);
179 run_table = runtabarray[tab];
180 level_table= levtabarray[tab];
182 p = levels_table;
183 i = 2;
184 level = 1;
185 while (i < n)
187 l = *p++;
188 for(j=0;j<l;++j)
190 run_table[i] = j;
191 level_table[i] = level;
192 ++i;
194 ++level;
196 *prun_table = run_table;
197 *plevel_table = level_table;
200 int wma_decode_init(WMADecodeContext* s, asf_waveformatex_t *wfx)
203 int i, flags1, flags2;
204 fixed32 *window;
205 uint8_t *extradata;
206 fixed64 bps1;
207 fixed32 high_freq;
208 fixed64 bps;
209 int sample_rate1;
210 int coef_vlc_table;
211 // int filehandle;
212 #ifdef CPU_COLDFIRE
213 coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
214 #endif
216 /*clear stereo setting to avoid glitches when switching stereo->mono*/
217 s->channel_coded[0]=0;
218 s->channel_coded[1]=0;
219 s->ms_stereo=0;
221 s->sample_rate = wfx->rate;
222 s->nb_channels = wfx->channels;
223 s->bit_rate = wfx->bitrate;
224 s->block_align = wfx->blockalign;
226 s->coefs = &coefsarray;
227 s->frame_out = &frame_out_buf;
229 if (wfx->codec_id == ASF_CODEC_ID_WMAV1) {
230 s->version = 1;
231 } else if (wfx->codec_id == ASF_CODEC_ID_WMAV2 ) {
232 s->version = 2;
233 } else {
234 /*one of those other wma flavors that don't have GPLed decoders */
235 return -1;
238 /* extract flag infos */
239 flags1 = 0;
240 flags2 = 0;
241 extradata = wfx->data;
242 if (s->version == 1 && wfx->datalen >= 4) {
243 flags1 = extradata[0] | (extradata[1] << 8);
244 flags2 = extradata[2] | (extradata[3] << 8);
245 }else if (s->version == 2 && wfx->datalen >= 6){
246 flags1 = extradata[0] | (extradata[1] << 8) |
247 (extradata[2] << 16) | (extradata[3] << 24);
248 flags2 = extradata[4] | (extradata[5] << 8);
250 s->use_exp_vlc = flags2 & 0x0001;
251 s->use_bit_reservoir = flags2 & 0x0002;
252 s->use_variable_block_len = flags2 & 0x0004;
254 /* compute MDCT block size */
255 if (s->sample_rate <= 16000){
256 s->frame_len_bits = 9;
257 }else if (s->sample_rate <= 22050 ||
258 (s->sample_rate <= 32000 && s->version == 1)){
259 s->frame_len_bits = 10;
260 }else{
261 s->frame_len_bits = 11;
263 s->frame_len = 1 << s->frame_len_bits;
264 if (s-> use_variable_block_len)
266 int nb_max, nb;
267 nb = ((flags2 >> 3) & 3) + 1;
268 if ((s->bit_rate / s->nb_channels) >= 32000)
270 nb += 2;
272 nb_max = s->frame_len_bits - BLOCK_MIN_BITS; //max is 11-7
273 if (nb > nb_max)
274 nb = nb_max;
275 s->nb_block_sizes = nb + 1;
277 else
279 s->nb_block_sizes = 1;
282 /* init rate dependant parameters */
283 s->use_noise_coding = 1;
284 high_freq = itofix64(s->sample_rate) >> 1;
287 /* if version 2, then the rates are normalized */
288 sample_rate1 = s->sample_rate;
289 if (s->version == 2)
291 if (sample_rate1 >= 44100)
292 sample_rate1 = 44100;
293 else if (sample_rate1 >= 22050)
294 sample_rate1 = 22050;
295 else if (sample_rate1 >= 16000)
296 sample_rate1 = 16000;
297 else if (sample_rate1 >= 11025)
298 sample_rate1 = 11025;
299 else if (sample_rate1 >= 8000)
300 sample_rate1 = 8000;
303 fixed64 tmp = itofix64(s->bit_rate);
304 fixed64 tmp2 = itofix64(s->nb_channels * s->sample_rate);
305 bps = fixdiv64(tmp, tmp2);
306 fixed64 tim = bps * s->frame_len;
307 fixed64 tmpi = fixdiv64(tim,itofix64(8));
308 s->byte_offset_bits = av_log2(fixtoi64(tmpi+0x8000)) + 2;
310 /* compute high frequency value and choose if noise coding should
311 be activated */
312 bps1 = bps;
313 if (s->nb_channels == 2)
314 bps1 = fixmul32(bps,0x1999a);
315 if (sample_rate1 == 44100)
317 if (bps1 >= 0x9c29)
318 s->use_noise_coding = 0;
319 else
320 high_freq = fixmul32(high_freq,0x6666);
322 else if (sample_rate1 == 22050)
324 if (bps1 >= 0x128f6)
325 s->use_noise_coding = 0;
326 else if (bps1 >= 0xb852)
327 high_freq = fixmul32(high_freq,0xb333);
328 else
329 high_freq = fixmul32(high_freq,0x999a);
331 else if (sample_rate1 == 16000)
333 if (bps > 0x8000)
334 high_freq = fixmul32(high_freq,0x8000);
335 else
336 high_freq = fixmul32(high_freq,0x4ccd);
338 else if (sample_rate1 == 11025)
340 high_freq = fixmul32(high_freq,0xb333);
342 else if (sample_rate1 == 8000)
344 if (bps <= 0xa000)
346 high_freq = fixmul32(high_freq,0x8000);
348 else if (bps > 0xc000)
350 s->use_noise_coding = 0;
352 else
354 high_freq = fixmul32(high_freq,0xa666);
357 else
359 if (bps >= 0xcccd)
361 high_freq = fixmul32(high_freq,0xc000);
363 else if (bps >= 0x999a)
365 high_freq = fixmul32(high_freq,0x999a);
367 else
369 high_freq = fixmul32(high_freq,0x8000);
373 /* compute the scale factor band sizes for each MDCT block size */
375 int a, b, pos, lpos, k, block_len, i, j, n;
376 const uint8_t *table;
378 if (s->version == 1)
380 s->coefs_start = 3;
382 else
384 s->coefs_start = 0;
386 for(k = 0; k < s->nb_block_sizes; ++k)
388 block_len = s->frame_len >> k;
390 if (s->version == 1)
392 lpos = 0;
393 for(i=0;i<25;++i)
395 a = wma_critical_freqs[i];
396 b = s->sample_rate;
397 pos = ((block_len * 2 * a) + (b >> 1)) / b;
398 if (pos > block_len)
399 pos = block_len;
400 s->exponent_bands[0][i] = pos - lpos;
401 if (pos >= block_len)
403 ++i;
404 break;
406 lpos = pos;
408 s->exponent_sizes[0] = i;
410 else
412 /* hardcoded tables */
413 table = NULL;
414 a = s->frame_len_bits - BLOCK_MIN_BITS - k;
415 if (a < 3)
417 if (s->sample_rate >= 44100)
418 table = exponent_band_44100[a];
419 else if (s->sample_rate >= 32000)
420 table = exponent_band_32000[a];
421 else if (s->sample_rate >= 22050)
422 table = exponent_band_22050[a];
424 if (table)
426 n = *table++;
427 for(i=0;i<n;++i)
428 s->exponent_bands[k][i] = table[i];
429 s->exponent_sizes[k] = n;
431 else
433 j = 0;
434 lpos = 0;
435 for(i=0;i<25;++i)
437 a = wma_critical_freqs[i];
438 b = s->sample_rate;
439 pos = ((block_len * 2 * a) + (b << 1)) / (4 * b);
440 pos <<= 2;
441 if (pos > block_len)
442 pos = block_len;
443 if (pos > lpos)
444 s->exponent_bands[k][j++] = pos - lpos;
445 if (pos >= block_len)
446 break;
447 lpos = pos;
449 s->exponent_sizes[k] = j;
453 /* max number of coefs */
454 s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;
455 /* high freq computation */
457 fixed32 tmp1 = high_freq*2; /* high_freq is a fixed32!*/
458 fixed32 tmp2=itofix32(s->sample_rate>>1);
459 s->high_band_start[k] = fixtoi32( fixdiv32(tmp1, tmp2) * (block_len>>1) +0x8000);
462 s->high_band_start[k] = (int)((block_len * 2 * high_freq) /
463 s->sample_rate + 0.5);*/
465 n = s->exponent_sizes[k];
466 j = 0;
467 pos = 0;
468 for(i=0;i<n;++i)
470 int start, end;
471 start = pos;
472 pos += s->exponent_bands[k][i];
473 end = pos;
474 if (start < s->high_band_start[k])
475 start = s->high_band_start[k];
476 if (end > s->coefs_end[k])
477 end = s->coefs_end[k];
478 if (end > start)
479 s->exponent_high_bands[k][j++] = end - start;
481 s->exponent_high_sizes[k] = j;
485 /*Not using the ffmpeg IMDCT anymore*/
487 /* mdct_init_global();
489 for(i = 0; i < s->nb_block_sizes; ++i)
491 ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 1);
496 /* ffmpeg uses malloc to only allocate as many window sizes as needed.
497 * However, we're really only interested in the worst case memory usage.
498 * In the worst case you can have 5 window sizes, 128 doubling up 2048
499 * Smaller windows are handled differently.
500 * Since we don't have malloc, just statically allocate this
502 fixed32 *temp[5];
503 temp[0] = stat0;
504 temp[1] = stat1;
505 temp[2] = stat2;
506 temp[3] = stat3;
507 temp[4] = stat4;
509 /* init MDCT windows : simple sinus window */
510 for(i = 0; i < s->nb_block_sizes; i++)
512 int n, j;
513 fixed32 alpha;
514 n = 1 << (s->frame_len_bits - i);
515 window = temp[i];
517 /* this calculates 0.5/(2*n) */
518 alpha = (1<<15)>>(s->frame_len_bits - i+1);
519 for(j=0;j<n;++j)
521 fixed32 j2 = itofix32(j) + 0x8000;
522 /*alpha between 0 and pi/2*/
523 window[j] = fsincos(fixmul32(j2,alpha)<<16, 0);
525 s->windows[i] = window;
529 s->reset_block_lengths = 1;
531 if (s->use_noise_coding)
533 /* init the noise generator */
534 if (s->use_exp_vlc)
536 s->noise_mult = 0x51f;
537 s->noise_table = noisetable_exp;
539 else
541 s->noise_mult = 0xa3d;
542 /* LSP values are simply 2x the EXP values */
543 for (i=0;i<NOISE_TAB_SIZE;++i)
544 noisetable_exp[i] = noisetable_exp[i]<< 1;
545 s->noise_table = noisetable_exp;
547 #if 0
548 /* We use a lookup table computered in advance, so no need to do this*/
550 unsigned int seed;
551 fixed32 norm;
552 seed = 1;
553 norm = 0; // PJJ: near as makes any diff to 0!
554 for (i=0;i<NOISE_TAB_SIZE;++i)
556 seed = seed * 314159 + 1;
557 s->noise_table[i] = itofix32((int)seed) * norm;
560 #endif
562 s->hgain_vlc.table = vlcbuf4;
563 s->hgain_vlc.table_allocated = VLCBUF4SIZE;
564 init_vlc(&s->hgain_vlc, HGAINVLCBITS, sizeof(hgain_huffbits),
565 hgain_huffbits, 1, 1,
566 hgain_huffcodes, 2, 2, 0);
569 if (s->use_exp_vlc)
572 s->exp_vlc.table = vlcbuf3;
573 s->exp_vlc.table_allocated = VLCBUF3SIZE;
575 init_vlc(&s->exp_vlc, EXPVLCBITS, sizeof(scale_huffbits),
576 scale_huffbits, 1, 1,
577 scale_huffcodes, 4, 4, 0);
579 else
581 wma_lsp_to_curve_init(s, s->frame_len);
584 /* choose the VLC tables for the coefficients */
585 coef_vlc_table = 2;
586 if (s->sample_rate >= 32000)
588 if (bps1 < 0xb852)
589 coef_vlc_table = 0;
590 else if (bps1 < 0x128f6)
591 coef_vlc_table = 1;
594 runtabarray[0] = runtab0; runtabarray[1] = runtab1;
595 levtabarray[0] = levtab0; levtabarray[1] = levtab1;
597 s->coef_vlc[0].table = vlcbuf1;
598 s->coef_vlc[0].table_allocated = VLCBUF1SIZE;
599 s->coef_vlc[1].table = vlcbuf2;
600 s->coef_vlc[1].table_allocated = VLCBUF2SIZE;
603 init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0],
604 &coef_vlcs[coef_vlc_table * 2], 0);
605 init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1],
606 &coef_vlcs[coef_vlc_table * 2 + 1], 1);
608 s->last_superframe_len = 0;
609 s->last_bitoffset = 0;
611 return 0;
615 /* compute x^-0.25 with an exponent and mantissa table. We use linear
616 interpolation to reduce the mantissa table size at a small speed
617 expense (linear interpolation approximately doubles the number of
618 bits of precision). */
619 static inline fixed32 pow_m1_4(WMADecodeContext *s, fixed32 x)
621 union {
622 float f;
623 unsigned int v;
624 } u, t;
625 unsigned int e, m;
626 fixed32 a, b;
628 u.f = fixtof64(x);
629 e = u.v >> 23;
630 m = (u.v >> (23 - LSP_POW_BITS)) & ((1 << LSP_POW_BITS) - 1);
631 /* build interpolation scale: 1 <= t < 2. */
632 t.v = ((u.v << LSP_POW_BITS) & ((1 << 23) - 1)) | (127 << 23);
633 a = s->lsp_pow_m_table1[m];
634 b = s->lsp_pow_m_table2[m];
636 /* lsp_pow_e_table contains 32.32 format */
637 /* TODO: Since we're unlikely have value that cover the whole
638 * IEEE754 range, we probably don't need to have all possible exponents */
640 return (lsp_pow_e_table[e] * (a + fixmul32(b, ftofix32(t.f))) >>32);
643 static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len)
645 fixed32 wdel, a, b, temp, temp2;
646 int i, m;
648 wdel = fixdiv32(M_PI_F, itofix32(frame_len));
649 temp = fixdiv32(itofix32(1), itofix32(frame_len));
650 for (i=0; i<frame_len; ++i)
652 /* TODO: can probably reuse the trig_init values here */
653 fsincos((temp*i)<<15, &temp2);
654 /* get 3 bits headroom + 1 bit from not doubleing the values */
655 s->lsp_cos_table[i] = temp2>>3;
658 /* NOTE: these two tables are needed to avoid two operations in
659 pow_m1_4 */
660 b = itofix32(1);
661 int ix = 0;
663 /*double check this later*/
664 for(i=(1 << LSP_POW_BITS) - 1;i>=0;i--)
666 m = (1 << LSP_POW_BITS) + i;
667 a = pow_a_table[ix++]<<4;
668 s->lsp_pow_m_table1[i] = 2 * a - b;
669 s->lsp_pow_m_table2[i] = b - a;
670 b = a;
675 /* NOTE: We use the same code as Vorbis here */
676 /* XXX: optimize it further with SSE/3Dnow */
677 static void wma_lsp_to_curve(WMADecodeContext *s,
678 fixed32 *out,
679 fixed32 *val_max_ptr,
680 int n,
681 fixed32 *lsp)
683 int i, j;
684 fixed32 p, q, w, v, val_max, temp, temp2;
686 val_max = 0;
687 for(i=0;i<n;++i)
689 /* shift by 2 now to reduce rounding error,
690 * we can renormalize right before pow_m1_4
693 p = 0x8000<<5;
694 q = 0x8000<<5;
695 w = s->lsp_cos_table[i];
697 for (j=1;j<NB_LSP_COEFS;j+=2)
699 /* w is 5.27 format, lsp is in 16.16, temp2 becomes 5.27 format */
700 temp2 = ((w - (lsp[j - 1]<<11)));
701 temp = q;
703 /* q is 16.16 format, temp2 is 5.27, q becomes 16.16 */
704 q = fixmul32b(q, temp2 )<<4;
705 p = fixmul32b(p, (w - (lsp[j]<<11)))<<4;
708 /* 2 in 5.27 format is 0x10000000 */
709 p = fixmul32(p, fixmul32b(p, (0x10000000 - w)))<<3;
710 q = fixmul32(q, fixmul32b(q, (0x10000000 + w)))<<3;
712 v = (p + q) >>9; /* p/q end up as 16.16 */
713 v = pow_m1_4(s, v);
714 if (v > val_max)
715 val_max = v;
716 out[i] = v;
719 *val_max_ptr = val_max;
722 /* decode exponents coded with LSP coefficients (same idea as Vorbis)
723 * only used for low bitrate (< 16kbps) files
725 static void decode_exp_lsp(WMADecodeContext *s, int ch)
727 fixed32 lsp_coefs[NB_LSP_COEFS];
728 int val, i;
730 for (i = 0; i < NB_LSP_COEFS; ++i)
732 if (i == 0 || i >= 8)
733 val = get_bits(&s->gb, 3);
734 else
735 val = get_bits(&s->gb, 4);
736 lsp_coefs[i] = lsp_codebook[i][val];
739 wma_lsp_to_curve(s,
740 s->exponents[ch],
741 &s->max_exponent[ch],
742 s->block_len,
743 lsp_coefs);
746 /* decode exponents coded with VLC codes - used for bitrate >= 32kbps*/
747 static int decode_exp_vlc(WMADecodeContext *s, int ch)
749 int last_exp, n, code;
750 const uint16_t *ptr, *band_ptr;
751 fixed32 v, max_scale;
752 fixed32 *q,*q_end;
754 /*accommodate the 60 negative indices */
755 const fixed32 *pow_10_to_yover16_ptr = &pow_10_to_yover16[61];
757 band_ptr = s->exponent_bands[s->frame_len_bits - s->block_len_bits];
758 ptr = band_ptr;
759 q = s->exponents[ch];
760 q_end = q + s->block_len;
761 max_scale = 0;
764 if (s->version == 1) //wmav1 only
766 last_exp = get_bits(&s->gb, 5) + 10;
768 v = pow_10_to_yover16_ptr[last_exp];
769 max_scale = v;
770 n = *ptr++;
773 *q++ = v;
775 while (--n);
776 } else {
777 last_exp = 36;
780 while (q < q_end)
782 code = get_vlc2(&s->gb, s->exp_vlc.table, EXPVLCBITS, EXPMAX);
783 if (code < 0)
785 return -1;
787 /* NOTE: this offset is the same as MPEG4 AAC ! */
788 last_exp += code - 60;
790 v = pow_10_to_yover16_ptr[last_exp];
791 if (v > max_scale)
793 max_scale = v;
795 n = *ptr++;
798 *q++ = v;
801 while (--n);
804 s->max_exponent[ch] = max_scale;
805 return 0;
808 /* return 0 if OK. return 1 if last block of frame. return -1 if
809 unrecorrable error. */
810 static int wma_decode_block(WMADecodeContext *s, int32_t *scratch_buffer)
812 int n, v, a, ch, code, bsize;
813 int coef_nb_bits, total_gain;
814 int nb_coefs[MAX_CHANNELS];
815 fixed32 mdct_norm;
817 /*DEBUGF("***decode_block: %d (%d samples of %d in frame)\n", s->block_num, s->block_len, s->frame_len);*/
819 /* compute current block length */
820 if (s->use_variable_block_len)
822 n = av_log2(s->nb_block_sizes - 1) + 1;
824 if (s->reset_block_lengths)
826 s->reset_block_lengths = 0;
827 v = get_bits(&s->gb, n);
828 if (v >= s->nb_block_sizes)
830 return -2;
832 s->prev_block_len_bits = s->frame_len_bits - v;
833 v = get_bits(&s->gb, n);
834 if (v >= s->nb_block_sizes)
836 return -3;
838 s->block_len_bits = s->frame_len_bits - v;
840 else
842 /* update block lengths */
843 s->prev_block_len_bits = s->block_len_bits;
844 s->block_len_bits = s->next_block_len_bits;
846 v = get_bits(&s->gb, n);
848 if (v >= s->nb_block_sizes)
850 // rb->splash(HZ*4, "v was %d", v); //5, 7
851 return -4; //this is it
853 else{
854 //rb->splash(HZ, "passed v block (%d)!", v);
856 s->next_block_len_bits = s->frame_len_bits - v;
858 else
860 /* fixed block len */
861 s->next_block_len_bits = s->frame_len_bits;
862 s->prev_block_len_bits = s->frame_len_bits;
863 s->block_len_bits = s->frame_len_bits;
865 /* now check if the block length is coherent with the frame length */
866 s->block_len = 1 << s->block_len_bits;
868 if ((s->block_pos + s->block_len) > s->frame_len)
870 return -5; //oddly 32k sample from tracker fails here
873 if (s->nb_channels == 2)
875 s->ms_stereo = get_bits1(&s->gb);
877 v = 0;
878 for (ch = 0; ch < s->nb_channels; ++ch)
880 a = get_bits1(&s->gb);
881 s->channel_coded[ch] = a;
882 v |= a;
884 /* if no channel coded, no need to go further */
885 /* XXX: fix potential framing problems */
886 if (!v)
888 goto next;
891 bsize = s->frame_len_bits - s->block_len_bits;
893 /* read total gain and extract corresponding number of bits for
894 coef escape coding */
895 total_gain = 1;
896 for(;;)
898 a = get_bits(&s->gb, 7);
899 total_gain += a;
900 if (a != 127)
902 break;
906 if (total_gain < 15)
907 coef_nb_bits = 13;
908 else if (total_gain < 32)
909 coef_nb_bits = 12;
910 else if (total_gain < 40)
911 coef_nb_bits = 11;
912 else if (total_gain < 45)
913 coef_nb_bits = 10;
914 else
915 coef_nb_bits = 9;
917 /* compute number of coefficients */
918 n = s->coefs_end[bsize] - s->coefs_start;
920 for(ch = 0; ch < s->nb_channels; ++ch)
922 nb_coefs[ch] = n;
924 /* complex coding */
925 if (s->use_noise_coding)
928 for(ch = 0; ch < s->nb_channels; ++ch)
930 if (s->channel_coded[ch])
932 int i, n, a;
933 n = s->exponent_high_sizes[bsize];
934 for(i=0;i<n;++i)
936 a = get_bits1(&s->gb);
937 s->high_band_coded[ch][i] = a;
938 /* if noise coding, the coefficients are not transmitted */
939 if (a)
940 nb_coefs[ch] -= s->exponent_high_bands[bsize][i];
944 for(ch = 0; ch < s->nb_channels; ++ch)
946 if (s->channel_coded[ch])
948 int i, n, val, code;
950 n = s->exponent_high_sizes[bsize];
951 val = (int)0x80000000;
952 for(i=0;i<n;++i)
954 if (s->high_band_coded[ch][i])
956 if (val == (int)0x80000000)
958 val = get_bits(&s->gb, 7) - 19;
960 else
962 //code = get_vlc(&s->gb, &s->hgain_vlc);
963 code = get_vlc2(&s->gb, s->hgain_vlc.table, HGAINVLCBITS, HGAINMAX);
964 if (code < 0)
966 return -6;
968 val += code - 18;
970 s->high_band_values[ch][i] = val;
977 /* exponents can be reused in short blocks. */
978 if ((s->block_len_bits == s->frame_len_bits) || get_bits1(&s->gb))
980 for(ch = 0; ch < s->nb_channels; ++ch)
982 if (s->channel_coded[ch])
984 if (s->use_exp_vlc)
986 if (decode_exp_vlc(s, ch) < 0)
988 return -7;
991 else
993 decode_exp_lsp(s, ch);
995 s->exponents_bsize[ch] = bsize;
1000 /* parse spectral coefficients : just RLE encoding */
1001 for(ch = 0; ch < s->nb_channels; ++ch)
1003 if (s->channel_coded[ch])
1005 VLC *coef_vlc;
1006 int level, run, sign, tindex;
1007 int16_t *ptr, *eptr;
1008 const int16_t *level_table, *run_table;
1010 /* special VLC tables are used for ms stereo because
1011 there is potentially less energy there */
1012 tindex = (ch == 1 && s->ms_stereo);
1013 coef_vlc = &s->coef_vlc[tindex];
1014 run_table = s->run_table[tindex];
1015 level_table = s->level_table[tindex];
1016 /* XXX: optimize */
1017 ptr = &s->coefs1[ch][0];
1018 eptr = ptr + nb_coefs[ch];
1019 memset(ptr, 0, s->block_len * sizeof(int16_t));
1021 for(;;)
1023 code = get_vlc2(&s->gb, coef_vlc->table, VLCBITS, VLCMAX);
1025 if (code < 0)
1027 return -8;
1029 if (code == 1)
1031 /* EOB */
1032 break;
1034 else if (code == 0)
1036 /* escape */
1037 level = get_bits(&s->gb, coef_nb_bits);
1038 /* NOTE: this is rather suboptimal. reading
1039 block_len_bits would be better */
1040 run = get_bits(&s->gb, s->frame_len_bits);
1042 else
1044 /* normal code */
1045 run = run_table[code];
1046 level = level_table[code];
1048 sign = get_bits1(&s->gb);
1049 if (!sign)
1050 level = -level;
1051 ptr += run;
1052 if (ptr >= eptr)
1054 break;
1056 *ptr++ = level;
1059 /* NOTE: EOB can be omitted */
1060 if (ptr >= eptr)
1061 break;
1064 if (s->version == 1 && s->nb_channels >= 2)
1066 align_get_bits(&s->gb);
1071 int n4 = s->block_len >> 1;
1074 mdct_norm = 0x10000>>(s->block_len_bits-1);
1076 if (s->version == 1)
1078 mdct_norm *= fixtoi32(fixsqrt32(itofix32(n4)));
1083 /* finally compute the MDCT coefficients */
1084 for(ch = 0; ch < s->nb_channels; ++ch)
1086 if (s->channel_coded[ch])
1088 int16_t *coefs1;
1089 fixed32 *exponents;
1090 fixed32 *coefs, atemp;
1091 fixed64 mult;
1092 fixed64 mult1;
1093 fixed32 noise, temp1, temp2, mult2;
1094 int i, j, n, n1, last_high_band, esize;
1095 fixed32 exp_power[HIGH_BAND_MAX_SIZE];
1097 //total_gain, coefs1, mdctnorm are lossless
1099 coefs1 = s->coefs1[ch];
1100 exponents = s->exponents[ch];
1101 esize = s->exponents_bsize[ch];
1102 coefs = (*(s->coefs))[ch];
1103 n=0;
1106 * The calculation of coefs has a shift right by 2 built in. This
1107 * prepares samples for the Tremor IMDCT which uses a slightly
1108 * different fixed format then the ffmpeg one. If the old ffmpeg
1109 * imdct is used, each shift storing into coefs should be reduced
1110 * by 1.
1111 * See SVN logs for details.
1115 if (s->use_noise_coding)
1117 /*This case is only used for low bitrates (typically less then 32kbps)*/
1119 /*TODO: mult should be converted to 32 bit to speed up noise coding*/
1121 mult = fixdiv64(pow_table[total_gain+20],Fixed32To64(s->max_exponent[ch]));
1122 mult = mult* mdct_norm;
1123 mult1 = mult;
1125 /* very low freqs : noise */
1126 for(i = 0;i < s->coefs_start; ++i)
1128 *coefs++ = fixmul32( (fixmul32(s->noise_table[s->noise_index],
1129 exponents[i<<bsize>>esize])>>4),Fixed32From64(mult1)) >>2;
1130 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1133 n1 = s->exponent_high_sizes[bsize];
1135 /* compute power of high bands */
1136 exponents = s->exponents[ch] +(s->high_band_start[bsize]<<bsize);
1137 last_high_band = 0; /* avoid warning */
1138 for (j=0;j<n1;++j)
1140 n = s->exponent_high_bands[s->frame_len_bits -
1141 s->block_len_bits][j];
1142 if (s->high_band_coded[ch][j])
1144 fixed32 e2, v;
1145 e2 = 0;
1146 for(i = 0;i < n; ++i)
1148 /*v is normalized later on so its fixed format is irrelevant*/
1149 v = exponents[i<<bsize>>esize]>>4;
1150 e2 += fixmul32(v, v)>>3;
1152 exp_power[j] = e2/n; /*n is an int...*/
1153 last_high_band = j;
1155 exponents += n<<bsize;
1158 /* main freqs and high freqs */
1159 exponents = s->exponents[ch] + (s->coefs_start<<bsize);
1160 for(j=-1;j<n1;++j)
1162 if (j < 0)
1164 n = s->high_band_start[bsize] -
1165 s->coefs_start;
1167 else
1169 n = s->exponent_high_bands[s->frame_len_bits -
1170 s->block_len_bits][j];
1172 if (j >= 0 && s->high_band_coded[ch][j])
1174 /* use noise with specified power */
1175 fixed32 tmp = fixdiv32(exp_power[j],exp_power[last_high_band]);
1177 /*mult1 is 48.16, pow_table is 48.16*/
1178 mult1 = fixmul32(fixsqrt32(tmp),
1179 pow_table[s->high_band_values[ch][j]+20]) >> 16;
1181 /*this step has a fairly high degree of error for some reason*/
1182 mult1 = fixdiv64(mult1,fixmul32(s->max_exponent[ch],s->noise_mult));
1183 mult1 = mult1*mdct_norm>>PRECISION;
1184 for(i = 0;i < n; ++i)
1186 noise = s->noise_table[s->noise_index];
1187 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1188 *coefs++ = fixmul32((fixmul32(exponents[i<<bsize>>esize],noise)>>4),
1189 Fixed32From64(mult1)) >>2;
1192 exponents += n<<bsize;
1194 else
1196 /* coded values + small noise */
1197 for(i = 0;i < n; ++i)
1199 noise = s->noise_table[s->noise_index];
1200 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1202 /*don't forget to renormalize the noise*/
1203 temp1 = (((int32_t)*coefs1++)<<16) + (noise>>4);
1204 temp2 = fixmul32(exponents[i<<bsize>>esize], mult>>18);
1205 *coefs++ = fixmul32(temp1, temp2);
1207 exponents += n<<bsize;
1211 /* very high freqs : noise */
1212 n = s->block_len - s->coefs_end[bsize];
1213 mult2 = fixmul32(mult>>16,exponents[((-1<<bsize))>>esize]) ;
1214 for (i = 0; i < n; ++i)
1216 /*renormalize the noise product and then reduce to 14.18 precison*/
1217 *coefs++ = fixmul32(s->noise_table[s->noise_index],mult2) >>6;
1219 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1222 else
1224 /*Noise coding not used, simply convert from exp to fixed representation*/
1226 fixed32 mult3 = (fixed32)(fixdiv64(pow_table[total_gain+20],
1227 Fixed32To64(s->max_exponent[ch])));
1228 mult3 = fixmul32(mult3, mdct_norm);
1230 /*zero the first 3 coefficients for WMA V1, does nothing otherwise*/
1231 for(i=0; i<s->coefs_start; i++)
1232 *coefs++=0;
1234 n = nb_coefs[ch];
1236 /* XXX: optimize more, unrolling this loop in asm
1237 might be a good idea */
1239 for(i = 0;i < n; ++i)
1241 /*ffmpeg imdct needs 15.17, while tremor 14.18*/
1242 atemp = (coefs1[i] * mult3)>>2;
1243 *coefs++=fixmul32(atemp,exponents[i<<bsize>>esize]);
1245 n = s->block_len - s->coefs_end[bsize];
1246 memset(coefs, 0, n*sizeof(fixed32));
1253 if (s->ms_stereo && s->channel_coded[1])
1255 fixed32 a, b;
1256 int i;
1257 fixed32 (*coefs)[MAX_CHANNELS][BLOCK_MAX_SIZE] = (s->coefs);
1259 /* nominal case for ms stereo: we do it before mdct */
1260 /* no need to optimize this case because it should almost
1261 never happen */
1262 if (!s->channel_coded[0])
1264 memset((*(s->coefs))[0], 0, sizeof(fixed32) * s->block_len);
1265 s->channel_coded[0] = 1;
1268 for(i = 0; i < s->block_len; ++i)
1270 a = (*coefs)[0][i];
1271 b = (*coefs)[1][i];
1272 (*coefs)[0][i] = a + b;
1273 (*coefs)[1][i] = a - b;
1277 for(ch = 0; ch < s->nb_channels; ++ch)
1279 if (s->channel_coded[ch])
1281 int n4, index;
1283 n4 = s->block_len >>1;
1285 /*faster IMDCT from Vorbis*/
1286 mdct_backward( (1 << (s->block_len_bits+1)), (int32_t*)(*(s->coefs))[ch], (int32_t*)scratch_buffer);
1288 /*slower but more easily understood IMDCT from FFMPEG*/
1289 //ff_imdct_calc(&s->mdct_ctx[bsize],
1290 // output,
1291 // (*(s->coefs))[ch]);
1294 /* add in the frame */
1295 index = (s->frame_len / 2) + s->block_pos - n4;
1296 wma_window(s, scratch_buffer, &((*s->frame_out)[ch][index]));
1300 /* specific fast case for ms-stereo : add to second
1301 channel if it is not coded */
1302 if (s->ms_stereo && !s->channel_coded[1])
1304 wma_window(s, scratch_buffer, &((*s->frame_out)[1][index]));
1308 next:
1309 /* update block number */
1310 ++s->block_num;
1311 s->block_pos += s->block_len;
1312 if (s->block_pos >= s->frame_len)
1314 return 1;
1316 else
1318 return 0;
1322 /* decode a frame of frame_len samples */
1323 static int wma_decode_frame(WMADecodeContext *s, int32_t *samples)
1325 int ret, i, n, ch, incr;
1326 int32_t *ptr;
1327 fixed32 *iptr;
1329 /* read each block */
1330 s->block_num = 0;
1331 s->block_pos = 0;
1334 for(;;)
1336 ret = wma_decode_block(s, samples);
1337 if (ret < 0)
1340 DEBUGF("wma_decode_block failed with code %d\n", ret);
1341 return -1;
1343 if (ret)
1345 break;
1349 /* return frame with full 30-bit precision */
1350 n = s->frame_len;
1351 incr = s->nb_channels;
1352 for(ch = 0; ch < s->nb_channels; ++ch)
1354 ptr = samples + ch;
1355 iptr = &((*s->frame_out)[ch][0]);
1357 for (i=0;i<n;++i)
1359 *ptr = (*iptr++);
1360 ptr += incr;
1363 memmove(&((*s->frame_out)[ch][0]), &((*s->frame_out)[ch][s->frame_len]),
1364 s->frame_len * sizeof(fixed32));
1367 return 0;
1370 /* Initialise the superframe decoding */
1372 int wma_decode_superframe_init(WMADecodeContext* s,
1373 const uint8_t *buf, /*input*/
1374 int buf_size)
1376 if (buf_size==0)
1378 s->last_superframe_len = 0;
1379 return 0;
1382 s->current_frame = 0;
1384 init_get_bits(&s->gb, buf, buf_size*8);
1386 if (s->use_bit_reservoir)
1388 /* read super frame header */
1389 skip_bits(&s->gb, 4); /* super frame index */
1390 s->nb_frames = get_bits(&s->gb, 4);
1392 if (s->last_superframe_len == 0)
1393 s->nb_frames --;
1394 else if (s->nb_frames == 0)
1395 s->nb_frames++;
1397 s->bit_offset = get_bits(&s->gb, s->byte_offset_bits + 3);
1398 } else {
1399 s->nb_frames = 1;
1402 return 1;
1406 /* Decode a single frame in the current superframe - return -1 if
1407 there was a decoding error, or the number of samples decoded.
1410 int wma_decode_superframe_frame(WMADecodeContext* s,
1411 int32_t* samples, /*output*/
1412 const uint8_t *buf, /*input*/
1413 int buf_size)
1415 int pos, len;
1416 uint8_t *q;
1417 int done = 0;
1418 if ((s->use_bit_reservoir) && (s->current_frame == 0))
1420 if (s->last_superframe_len > 0)
1422 /* add s->bit_offset bits to last frame */
1423 if ((s->last_superframe_len + ((s->bit_offset + 7) >> 3)) >
1424 MAX_CODED_SUPERFRAME_SIZE)
1426 DEBUGF("superframe size too large error\n");
1427 goto fail;
1429 q = s->last_superframe + s->last_superframe_len;
1430 len = s->bit_offset;
1431 while (len > 7)
1433 *q++ = (get_bits)(&s->gb, 8);
1434 len -= 8;
1436 if (len > 0)
1438 *q++ = (get_bits)(&s->gb, len) << (8 - len);
1441 /* XXX: s->bit_offset bits into last frame */
1442 init_get_bits(&s->gb, s->last_superframe, MAX_CODED_SUPERFRAME_SIZE*8);
1443 /* skip unused bits */
1444 if (s->last_bitoffset > 0)
1445 skip_bits(&s->gb, s->last_bitoffset);
1447 /* this frame is stored in the last superframe and in the
1448 current one */
1449 if (wma_decode_frame(s, samples) < 0)
1451 goto fail;
1453 done = 1;
1456 /* read each frame starting from s->bit_offset */
1457 pos = s->bit_offset + 4 + 4 + s->byte_offset_bits + 3;
1458 init_get_bits(&s->gb, buf + (pos >> 3), (MAX_CODED_SUPERFRAME_SIZE - (pos >> 3))*8);
1459 len = pos & 7;
1460 if (len > 0)
1461 skip_bits(&s->gb, len);
1463 s->reset_block_lengths = 1;
1466 /* If we haven't decoded a frame yet, do it now */
1467 if (!done)
1469 if (wma_decode_frame(s, samples) < 0)
1471 goto fail;
1475 s->current_frame++;
1477 if ((s->use_bit_reservoir) && (s->current_frame == s->nb_frames))
1479 /* we copy the end of the frame in the last frame buffer */
1480 pos = get_bits_count(&s->gb) + ((s->bit_offset + 4 + 4 + s->byte_offset_bits + 3) & ~7);
1481 s->last_bitoffset = pos & 7;
1482 pos >>= 3;
1483 len = buf_size - pos;
1484 if (len > MAX_CODED_SUPERFRAME_SIZE || len < 0)
1486 DEBUGF("superframe size too large error after decoding\n");
1487 goto fail;
1489 s->last_superframe_len = len;
1490 memcpy(s->last_superframe, buf + pos, len);
1493 return s->frame_len;
1495 fail:
1496 /* when error, we reset the bit reservoir */
1498 s->last_superframe_len = 0;
1499 return -1;