move structures around in the header files
[Rockbox.git] / apps / codecs / libwma / wmadeci.c
blob8b4c698ebc8bd7c396b10da990aa0b2c8efbcbe1
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"
33 #define VLCBITS 7 /*7 is the lowest without glitching*/
34 #define VLCMAX ((22+VLCBITS-1)/VLCBITS)
36 #define EXPVLCBITS 7
37 #define EXPMAX ((19+EXPVLCBITS-1)/EXPVLCBITS)
39 #define HGAINVLCBITS 9
40 #define HGAINMAX ((13+HGAINVLCBITS-1)/HGAINVLCBITS)
43 typedef struct CoefVLCTable
45 int n; /* total number of codes */
46 const uint32_t *huffcodes; /* VLC bit values */
47 const uint8_t *huffbits; /* VLC bit size */
48 const uint16_t *levels; /* table to build run/level tables */
50 CoefVLCTable;
52 static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len);
54 fixed32 coefsarray[MAX_CHANNELS][BLOCK_MAX_SIZE] IBSS_ATTR;
56 //static variables that replace malloced stuff
57 fixed32 stat0[2048], stat1[1024], stat2[512], stat3[256], stat4[128]; //these are the MDCT reconstruction windows
59 uint16_t *runtabarray[2], *levtabarray[2]; //these are VLC lookup tables
61 uint16_t runtab0[1336], runtab1[1336], levtab0[1336], levtab1[1336]; //these could be made smaller since only one can be 1336
63 /*putting these in IRAM actually makes PP slower*/
64 VLC_TYPE vlcbuf1[2550][2];
65 VLC_TYPE vlcbuf2[2550][2];
66 VLC_TYPE vlcbuf3[360][2];
67 VLC_TYPE vlcbuf4[540][2];
71 #include "wmadata.h" // PJJ
76 * Helper functions for wma_window.
81 #ifdef CPU_ARM
82 static inline
83 void vector_fmul_add_add(fixed32 *dst, const fixed32 *data, const fixed32 *window, int n)
85 while (n>=2) {
86 asm volatile ("ldmia %[d]!, {r0, r1};"
87 "ldmia %[w]!, {r4, r5};"
89 /*consume the first data and window value so we can use those registers again */
90 "smull r8, r9, r0, r4;"
92 "ldmia %[dst], {r0, r4};"
93 "add r0, r0, r9, lsl #1;" /* *dst=*dst+(r9<<1)*/
94 "smull r8, r9, r1, r5;"
95 "add r1, r4, r9, lsl #1;"
96 "stmia %[dst]!, {r0, r1};"
97 : [d] "+r" (data), [w] "+r" (window), [dst] "+r" (dst)
98 : : "r0", "r1",
99 "r4", "r5", "r8", "r9",
100 "memory", "cc");
101 n -= 2;
103 while(n>0) {
104 *dst = fixmul32b(*data, *window);
105 data++;
106 window++;
107 n--;
111 #else
113 static inline void vector_fmul_add_add(fixed32 *dst, const fixed32 *src0, const fixed32 *src1, int len){
114 int i;
115 for(i=0; i<len; i++)
116 dst[i] = fixmul32b(src0[i], src1[i]) + dst[i];
119 #endif
121 /* TODO: Adapt the above to work with this */
122 static inline void vector_fmul_reverse(fixed32 *dst, const fixed32 *src0, const fixed32 *src1, int len){
123 int i;
124 src1 += len-1;
125 for(i=0; i<len; i++)
126 dst[i] = fixmul32b(src0[i], src1[-i]);
131 * Apply MDCT window and add into output.
133 * We ensure that when the windows overlap their squared sum
134 * is always 1 (MDCT reconstruction rule).
136 * The Vorbis I spec has a great diagram explaining this process.
137 * See section 1.3.2.3 of http://xiph.org/vorbis/doc/Vorbis_I_spec.html
139 static void wma_window(WMADecodeContext *s, fixed32 *in, fixed32 *out)
141 //float *in = s->output;
142 int block_len, bsize, n;
144 /* left part */
145 /*previous block was larger, so we'll use the size of the current block to set the window size*/
146 if (s->block_len_bits <= s->prev_block_len_bits) {
147 block_len = s->block_len;
148 bsize = s->frame_len_bits - s->block_len_bits;
150 vector_fmul_add_add(out, in, s->windows[bsize], block_len);
152 } else {
153 /*previous block was smaller or the same size, so use it's size to set the window length*/
154 block_len = 1 << s->prev_block_len_bits;
155 /*find the middle of the two overlapped blocks, this will be the first overlapped sample*/
156 n = (s->block_len - block_len) / 2;
157 bsize = s->frame_len_bits - s->prev_block_len_bits;
159 vector_fmul_add_add(out+n, in+n, s->windows[bsize], block_len);
161 memcpy(out+n+block_len, in+n+block_len, n*sizeof(fixed32));
163 /* Advance to the end of the current block and prepare to window it for the next block.
164 * Since the window function needs to be reversed, we do it backwards starting with the
165 * last sample and moving towards the first
167 out += s->block_len;
168 in += s->block_len;
170 /* right part */
171 if (s->block_len_bits <= s->next_block_len_bits) {
172 block_len = s->block_len;
173 bsize = s->frame_len_bits - s->block_len_bits;
175 vector_fmul_reverse(out, in, s->windows[bsize], block_len);
177 } else {
178 block_len = 1 << s->next_block_len_bits;
179 n = (s->block_len - block_len) / 2;
180 bsize = s->frame_len_bits - s->next_block_len_bits;
182 memcpy(out, in, n*sizeof(fixed32));
184 vector_fmul_reverse(out+n, in+n, s->windows[bsize], block_len);
186 memset(out+n+block_len, 0, n*sizeof(fixed32));
193 /* XXX: use same run/length optimization as mpeg decoders */
194 static void init_coef_vlc(VLC *vlc,
195 uint16_t **prun_table, uint16_t **plevel_table,
196 const CoefVLCTable *vlc_table, int tab)
198 int n = vlc_table->n;
199 const uint8_t *table_bits = vlc_table->huffbits;
200 const uint32_t *table_codes = vlc_table->huffcodes;
201 const uint16_t *levels_table = vlc_table->levels;
202 uint16_t *run_table, *level_table;
203 const uint16_t *p;
204 int i, l, j, level;
207 init_vlc(vlc, VLCBITS, n, table_bits, 1, 1, table_codes, 4, 4, 0);
209 run_table = runtabarray[tab];
210 level_table= levtabarray[tab];
212 p = levels_table;
213 i = 2;
214 level = 1;
215 while (i < n)
217 l = *p++;
218 for(j=0;j<l;++j)
220 run_table[i] = j;
221 level_table[i] = level;
222 ++i;
224 ++level;
226 *prun_table = run_table;
227 *plevel_table = level_table;
230 int wma_decode_init(WMADecodeContext* s, asf_waveformatex_t *wfx)
232 //WMADecodeContext *s = avctx->priv_data;
233 int i, flags1, flags2;
234 fixed32 *window;
235 uint8_t *extradata;
236 fixed64 bps1;
237 fixed32 high_freq;
238 fixed64 bps;
239 int sample_rate1;
240 int coef_vlc_table;
241 // int filehandle;
242 #ifdef CPU_COLDFIRE
243 coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
244 #endif
246 s->sample_rate = wfx->rate;
247 s->nb_channels = wfx->channels;
248 s->bit_rate = wfx->bitrate;
249 s->block_align = wfx->blockalign;
251 s->coefs = &coefsarray;
253 if (wfx->codec_id == ASF_CODEC_ID_WMAV1) {
254 s->version = 1;
255 } else if (wfx->codec_id == ASF_CODEC_ID_WMAV2 ) {
256 s->version = 2;
257 } else {
258 /*one of those other wma flavors that don't have GPLed decoders */
259 return -1;
262 /* extract flag infos */
263 flags1 = 0;
264 flags2 = 0;
265 extradata = wfx->data;
266 if (s->version == 1 && wfx->datalen >= 4) {
267 flags1 = extradata[0] | (extradata[1] << 8);
268 flags2 = extradata[2] | (extradata[3] << 8);
269 }else if (s->version == 2 && wfx->datalen >= 6){
270 flags1 = extradata[0] | (extradata[1] << 8) |
271 (extradata[2] << 16) | (extradata[3] << 24);
272 flags2 = extradata[4] | (extradata[5] << 8);
274 s->use_exp_vlc = flags2 & 0x0001;
275 s->use_bit_reservoir = flags2 & 0x0002;
276 s->use_variable_block_len = flags2 & 0x0004;
278 /* compute MDCT block size */
279 if (s->sample_rate <= 16000){
280 s->frame_len_bits = 9;
281 }else if (s->sample_rate <= 22050 ||
282 (s->sample_rate <= 32000 && s->version == 1)){
283 s->frame_len_bits = 10;
284 }else{
285 s->frame_len_bits = 11;
287 s->frame_len = 1 << s->frame_len_bits;
288 if (s-> use_variable_block_len)
290 int nb_max, nb;
291 nb = ((flags2 >> 3) & 3) + 1;
292 if ((s->bit_rate / s->nb_channels) >= 32000)
294 nb += 2;
296 nb_max = s->frame_len_bits - BLOCK_MIN_BITS; //max is 11-7
297 if (nb > nb_max)
298 nb = nb_max;
299 s->nb_block_sizes = nb + 1;
301 else
303 s->nb_block_sizes = 1;
306 /* init rate dependant parameters */
307 s->use_noise_coding = 1;
308 high_freq = itofix64(s->sample_rate) >> 1;
311 /* if version 2, then the rates are normalized */
312 sample_rate1 = s->sample_rate;
313 if (s->version == 2)
315 if (sample_rate1 >= 44100)
316 sample_rate1 = 44100;
317 else if (sample_rate1 >= 22050)
318 sample_rate1 = 22050;
319 else if (sample_rate1 >= 16000)
320 sample_rate1 = 16000;
321 else if (sample_rate1 >= 11025)
322 sample_rate1 = 11025;
323 else if (sample_rate1 >= 8000)
324 sample_rate1 = 8000;
327 fixed64 tmp = itofix64(s->bit_rate);
328 fixed64 tmp2 = itofix64(s->nb_channels * s->sample_rate);
329 bps = fixdiv64(tmp, tmp2);
330 fixed64 tim = bps * s->frame_len;
331 fixed64 tmpi = fixdiv64(tim,itofix64(8));
332 s->byte_offset_bits = av_log2(fixtoi64(tmpi+0x8000)) + 2;
334 /* compute high frequency value and choose if noise coding should
335 be activated */
336 bps1 = bps;
337 if (s->nb_channels == 2)
338 bps1 = fixmul32(bps,0x1999a);
339 if (sample_rate1 == 44100)
341 if (bps1 >= 0x9c29)
342 s->use_noise_coding = 0;
343 else
344 high_freq = fixmul32(high_freq,0x6666);
346 else if (sample_rate1 == 22050)
348 if (bps1 >= 0x128f6)
349 s->use_noise_coding = 0;
350 else if (bps1 >= 0xb852)
351 high_freq = fixmul32(high_freq,0xb333);
352 else
353 high_freq = fixmul32(high_freq,0x999a);
355 else if (sample_rate1 == 16000)
357 if (bps > 0x8000)
358 high_freq = fixmul32(high_freq,0x8000);
359 else
360 high_freq = fixmul32(high_freq,0x4ccd);
362 else if (sample_rate1 == 11025)
364 high_freq = fixmul32(high_freq,0xb333);
366 else if (sample_rate1 == 8000)
368 if (bps <= 0xa000)
370 high_freq = fixmul32(high_freq,0x8000);
372 else if (bps > 0xc000)
374 s->use_noise_coding = 0;
376 else
378 high_freq = fixmul32(high_freq,0xa666);
381 else
383 if (bps >= 0xcccd)
385 high_freq = fixmul32(high_freq,0xc000);
387 else if (bps >= 0x999a)
389 high_freq = fixmul32(high_freq,0x999a);
391 else
393 high_freq = fixmul32(high_freq,0x8000);
397 /* compute the scale factor band sizes for each MDCT block size */
399 int a, b, pos, lpos, k, block_len, i, j, n;
400 const uint8_t *table;
402 if (s->version == 1)
404 s->coefs_start = 3;
406 else
408 s->coefs_start = 0;
410 for(k = 0; k < s->nb_block_sizes; ++k)
412 block_len = s->frame_len >> k;
414 if (s->version == 1)
416 lpos = 0;
417 for(i=0;i<25;++i)
419 a = wma_critical_freqs[i];
420 b = s->sample_rate;
421 pos = ((block_len * 2 * a) + (b >> 1)) / b;
422 if (pos > block_len)
423 pos = block_len;
424 s->exponent_bands[0][i] = pos - lpos;
425 if (pos >= block_len)
427 ++i;
428 break;
430 lpos = pos;
432 s->exponent_sizes[0] = i;
434 else
436 /* hardcoded tables */
437 table = NULL;
438 a = s->frame_len_bits - BLOCK_MIN_BITS - k;
439 if (a < 3)
441 if (s->sample_rate >= 44100)
442 table = exponent_band_44100[a];
443 else if (s->sample_rate >= 32000)
444 table = exponent_band_32000[a];
445 else if (s->sample_rate >= 22050)
446 table = exponent_band_22050[a];
448 if (table)
450 n = *table++;
451 for(i=0;i<n;++i)
452 s->exponent_bands[k][i] = table[i];
453 s->exponent_sizes[k] = n;
455 else
457 j = 0;
458 lpos = 0;
459 for(i=0;i<25;++i)
461 a = wma_critical_freqs[i];
462 b = s->sample_rate;
463 pos = ((block_len * 2 * a) + (b << 1)) / (4 * b);
464 pos <<= 2;
465 if (pos > block_len)
466 pos = block_len;
467 if (pos > lpos)
468 s->exponent_bands[k][j++] = pos - lpos;
469 if (pos >= block_len)
470 break;
471 lpos = pos;
473 s->exponent_sizes[k] = j;
477 /* max number of coefs */
478 s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;
479 /* high freq computation */
481 fixed32 tmp1 = high_freq*2; /* high_freq is a fixed32!*/
482 fixed32 tmp2=itofix32(s->sample_rate>>1);
483 s->high_band_start[k] = fixtoi32( fixdiv32(tmp1, tmp2) * (block_len>>1) +0x8000);
486 s->high_band_start[k] = (int)((block_len * 2 * high_freq) /
487 s->sample_rate + 0.5);*/
489 n = s->exponent_sizes[k];
490 j = 0;
491 pos = 0;
492 for(i=0;i<n;++i)
494 int start, end;
495 start = pos;
496 pos += s->exponent_bands[k][i];
497 end = pos;
498 if (start < s->high_band_start[k])
499 start = s->high_band_start[k];
500 if (end > s->coefs_end[k])
501 end = s->coefs_end[k];
502 if (end > start)
503 s->exponent_high_bands[k][j++] = end - start;
505 s->exponent_high_sizes[k] = j;
509 mdct_init_global();
511 for(i = 0; i < s->nb_block_sizes; ++i)
513 ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 1);
516 /*ffmpeg uses malloc to only allocate as many window sizes as needed. However, we're really only interested in the worst case memory usage.
517 * In the worst case you can have 5 window sizes, 128 doubling up 2048
518 * Smaller windows are handled differently.
519 * Since we don't have malloc, just statically allocate this
521 fixed32 *temp[5];
522 temp[0] = stat0;
523 temp[1] = stat1;
524 temp[2] = stat2;
525 temp[3] = stat3;
526 temp[4] = stat4;
528 /* init MDCT windows : simple sinus window */
529 for(i = 0; i < s->nb_block_sizes; i++)
531 int n, j;
532 fixed32 alpha;
533 n = 1 << (s->frame_len_bits - i);
534 //window = av_malloc(sizeof(fixed32) * n);
535 window = temp[i];
537 //fixed32 n2 = itofix32(n<<1); //2x the window length
538 //alpha = fixdiv32(M_PI_F, n2); //PI / (2x Window length) == PI<<(s->frame_len_bits - i+1)
540 //alpha = M_PI_F>>(s->frame_len_bits - i+1);
541 alpha = (1<<15)>>(s->frame_len_bits - i+1); /* this calculates 0.5/(2*n) */
542 for(j=0;j<n;++j)
544 fixed32 j2 = itofix32(j) + 0x8000;
545 window[j] = fsincos(fixmul32(j2,alpha)<<16, 0); //alpha between 0 and pi/2
548 //printf("created window\n");
549 s->windows[i] = window;
550 //printf("assigned window\n");
553 s->reset_block_lengths = 1;
555 if (s->use_noise_coding)
557 /* init the noise generator */
558 if (s->use_exp_vlc)
560 s->noise_mult = 0x51f;
561 s->noise_table = noisetable_exp;
563 else
565 s->noise_mult = 0xa3d;
566 /* LSP values are simply 2x the EXP values */
567 for (i=0;i<NOISE_TAB_SIZE;++i)
568 noisetable_exp[i] = noisetable_exp[i]<< 1;
569 s->noise_table = noisetable_exp;
571 #if 0
573 unsigned int seed;
574 fixed32 norm;
575 seed = 1;
576 norm = 0; // PJJ: near as makes any diff to 0!
577 for (i=0;i<NOISE_TAB_SIZE;++i)
579 seed = seed * 314159 + 1;
580 s->noise_table[i] = itofix32((int)seed) * norm;
583 #endif
585 s->hgain_vlc.table = vlcbuf4;
586 init_vlc(&s->hgain_vlc, HGAINVLCBITS, sizeof(hgain_huffbits),
587 hgain_huffbits, 1, 1,
588 hgain_huffcodes, 2, 2, 0);
591 if (s->use_exp_vlc)
594 s->exp_vlc.table = vlcbuf3;
596 init_vlc(&s->exp_vlc, EXPVLCBITS, sizeof(scale_huffbits),
597 scale_huffbits, 1, 1,
598 scale_huffcodes, 4, 4, 0);
600 else
602 wma_lsp_to_curve_init(s, s->frame_len);
605 /* choose the VLC tables for the coefficients */
606 coef_vlc_table = 2;
607 if (s->sample_rate >= 32000)
609 if (bps1 < 0xb852)
610 coef_vlc_table = 0;
611 else if (bps1 < 0x128f6)
612 coef_vlc_table = 1;
615 runtabarray[0] = runtab0; runtabarray[1] = runtab1;
616 levtabarray[0] = levtab0; levtabarray[1] = levtab1;
618 s->coef_vlc[0].table = vlcbuf1;
619 s->coef_vlc[0].table_allocated = 24576/4;
620 s->coef_vlc[1].table = vlcbuf2;
621 s->coef_vlc[1].table_allocated = 14336/4;
624 init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0],
625 &coef_vlcs[coef_vlc_table * 2], 0);
626 init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1],
627 &coef_vlcs[coef_vlc_table * 2 + 1], 1);
629 s->last_superframe_len = 0;
630 s->last_bitoffset = 0;
632 return 0;
636 /* compute x^-0.25 with an exponent and mantissa table. We use linear
637 interpolation to reduce the mantissa table size at a small speed
638 expense (linear interpolation approximately doubles the number of
639 bits of precision). */
640 static inline fixed32 pow_m1_4(WMADecodeContext *s, fixed32 x)
642 union {
643 float f;
644 unsigned int v;
645 } u, t;
646 unsigned int e, m;
647 fixed32 a, b;
649 u.f = fixtof64(x);
650 e = u.v >> 23;
651 m = (u.v >> (23 - LSP_POW_BITS)) & ((1 << LSP_POW_BITS) - 1);
652 /* build interpolation scale: 1 <= t < 2. */
653 t.v = ((u.v << LSP_POW_BITS) & ((1 << 23) - 1)) | (127 << 23);
654 a = s->lsp_pow_m_table1[m];
655 b = s->lsp_pow_m_table2[m];
657 /* lsp_pow_e_table contains 32.32 format */
658 /* TODO: Since we're unlikely have value that cover the whole
659 * IEEE754 range, we probably don't need to have all possible exponents */
661 return (lsp_pow_e_table[e] * (a + fixmul32(b, ftofix32(t.f))) >>32);
664 static void wma_lsp_to_curve_init(WMADecodeContext *s, int frame_len)
666 fixed32 wdel, a, b, temp, temp2;
667 int i, m;
669 wdel = fixdiv32(M_PI_F, itofix32(frame_len));
670 temp = fixdiv32(itofix32(1), itofix32(frame_len));
671 for (i=0; i<frame_len; ++i)
673 /* TODO: can probably reuse the trig_init values here */
674 fsincos((temp*i)<<15, &temp2);
675 /* get 3 bits headroom + 1 bit from not doubleing the values */
676 s->lsp_cos_table[i] = temp2>>3;
679 /* NOTE: these two tables are needed to avoid two operations in
680 pow_m1_4 */
681 b = itofix32(1);
682 int ix = 0;
684 /*double check this later*/
685 for(i=(1 << LSP_POW_BITS) - 1;i>=0;i--)
687 m = (1 << LSP_POW_BITS) + i;
688 a = pow_a_table[ix++]<<4;
689 s->lsp_pow_m_table1[i] = 2 * a - b;
690 s->lsp_pow_m_table2[i] = b - a;
691 b = a;
696 /* NOTE: We use the same code as Vorbis here */
697 /* XXX: optimize it further with SSE/3Dnow */
698 static void wma_lsp_to_curve(WMADecodeContext *s,
699 fixed32 *out,
700 fixed32 *val_max_ptr,
701 int n,
702 fixed32 *lsp)
704 int i, j;
705 fixed32 p, q, w, v, val_max, temp, temp2;
707 val_max = 0;
708 for(i=0;i<n;++i)
710 /* shift by 2 now to reduce rounding error,
711 * we can renormalize right before pow_m1_4
714 p = 0x8000<<5;
715 q = 0x8000<<5;
716 w = s->lsp_cos_table[i];
718 for (j=1;j<NB_LSP_COEFS;j+=2)
720 /* w is 5.27 format, lsp is in 16.16, temp2 becomes 5.27 format */
721 temp2 = ((w - (lsp[j - 1]<<11)));
722 temp = q;
724 /* q is 16.16 format, temp2 is 5.27, q becomes 16.16 */
725 q = fixmul32b(q, temp2 )<<4;
726 p = fixmul32b(p, (w - (lsp[j]<<11)))<<4;
729 /* 2 in 5.27 format is 0x10000000 */
730 p = fixmul32(p, fixmul32b(p, (0x10000000 - w)))<<3;
731 q = fixmul32(q, fixmul32b(q, (0x10000000 + w)))<<3;
733 v = (p + q) >>9; /* p/q end up as 16.16 */
734 v = pow_m1_4(s, v);
735 if (v > val_max)
736 val_max = v;
737 out[i] = v;
740 *val_max_ptr = val_max;
743 /* decode exponents coded with LSP coefficients (same idea as Vorbis) */
744 static void decode_exp_lsp(WMADecodeContext *s, int ch)
746 fixed32 lsp_coefs[NB_LSP_COEFS];
747 int val, i;
749 for (i = 0; i < NB_LSP_COEFS; ++i)
751 if (i == 0 || i >= 8)
752 val = get_bits(&s->gb, 3);
753 else
754 val = get_bits(&s->gb, 4);
755 lsp_coefs[i] = lsp_codebook[i][val];
758 wma_lsp_to_curve(s,
759 s->exponents[ch],
760 &s->max_exponent[ch],
761 s->block_len,
762 lsp_coefs);
765 /* decode exponents coded with VLC codes */
766 static int decode_exp_vlc(WMADecodeContext *s, int ch)
768 int last_exp, n, code;
769 const uint16_t *ptr, *band_ptr;
770 fixed32 v, max_scale;
771 fixed32 *q,*q_end;
773 /*accommodate the 16 negative indices */
774 const fixed32 *pow_10_to_yover16_ptr = &pow_10_to_yover16[16];
776 band_ptr = s->exponent_bands[s->frame_len_bits - s->block_len_bits];
777 ptr = band_ptr;
778 q = s->exponents[ch];
779 q_end = q + s->block_len;
780 max_scale = 0;
783 if (s->version == 1) //wmav1 only
785 last_exp = get_bits(&s->gb, 5) + 10;
786 /* XXX: use a table */
787 v = pow_10_to_yover16[last_exp];
788 max_scale = v;
789 n = *ptr++;
792 *q++ = v;
794 while (--n);
796 last_exp = 36;
798 while (q < q_end)
800 code = get_vlc2(&s->gb, s->exp_vlc.table, EXPVLCBITS, EXPMAX);
801 if (code < 0)
803 return -1;
805 /* NOTE: this offset is the same as MPEG4 AAC ! */
806 last_exp += code - 60;
807 /* XXX: use a table */
808 v = pow_10_to_yover16_ptr[last_exp];
809 if (v > max_scale)
811 max_scale = v;
813 n = *ptr++;
816 *q++ = v;
819 while (--n);
822 s->max_exponent[ch] = max_scale;
823 return 0;
826 /* return 0 if OK. return 1 if last block of frame. return -1 if
827 unrecorrable error. */
828 static int wma_decode_block(WMADecodeContext *s)
830 int n, v, a, ch, code, bsize;
831 int coef_nb_bits, total_gain;
832 int nb_coefs[MAX_CHANNELS];
833 fixed32 mdct_norm;
835 DEBUGF("***decode_block: %d of (%d samples) (%d)\n", s->block_num, s->frame_len, s->block_len);
837 /* compute current block length */
838 if (s->use_variable_block_len)
840 n = av_log2(s->nb_block_sizes - 1) + 1;
842 if (s->reset_block_lengths)
844 s->reset_block_lengths = 0;
845 v = get_bits(&s->gb, n);
846 if (v >= s->nb_block_sizes)
848 return -2;
850 s->prev_block_len_bits = s->frame_len_bits - v;
851 v = get_bits(&s->gb, n);
852 if (v >= s->nb_block_sizes)
854 return -3;
856 s->block_len_bits = s->frame_len_bits - v;
858 else
860 /* update block lengths */
861 s->prev_block_len_bits = s->block_len_bits;
862 s->block_len_bits = s->next_block_len_bits;
864 v = get_bits(&s->gb, n);
866 if (v >= s->nb_block_sizes)
868 // rb->splash(HZ*4, "v was %d", v); //5, 7
869 return -4; //this is it
871 else{
872 //rb->splash(HZ, "passed v block (%d)!", v);
874 s->next_block_len_bits = s->frame_len_bits - v;
876 else
878 /* fixed block len */
879 s->next_block_len_bits = s->frame_len_bits;
880 s->prev_block_len_bits = s->frame_len_bits;
881 s->block_len_bits = s->frame_len_bits;
883 /* now check if the block length is coherent with the frame length */
884 s->block_len = 1 << s->block_len_bits;
886 if ((s->block_pos + s->block_len) > s->frame_len)
888 return -5;
891 if (s->nb_channels == 2)
893 s->ms_stereo = get_bits(&s->gb, 1);
895 v = 0;
896 for (ch = 0; ch < s->nb_channels; ++ch)
898 a = get_bits(&s->gb, 1);
899 s->channel_coded[ch] = a;
900 v |= a;
902 /* if no channel coded, no need to go further */
903 /* XXX: fix potential framing problems */
904 if (!v)
906 goto next;
909 bsize = s->frame_len_bits - s->block_len_bits;
911 /* read total gain and extract corresponding number of bits for
912 coef escape coding */
913 total_gain = 1;
914 for(;;)
916 a = get_bits(&s->gb, 7);
917 total_gain += a;
918 if (a != 127)
920 break;
924 if (total_gain < 15)
925 coef_nb_bits = 13;
926 else if (total_gain < 32)
927 coef_nb_bits = 12;
928 else if (total_gain < 40)
929 coef_nb_bits = 11;
930 else if (total_gain < 45)
931 coef_nb_bits = 10;
932 else
933 coef_nb_bits = 9;
935 /* compute number of coefficients */
936 n = s->coefs_end[bsize] - s->coefs_start;
938 for(ch = 0; ch < s->nb_channels; ++ch)
940 nb_coefs[ch] = n;
942 /* complex coding */
943 if (s->use_noise_coding)
946 for(ch = 0; ch < s->nb_channels; ++ch)
948 if (s->channel_coded[ch])
950 int i, n, a;
951 n = s->exponent_high_sizes[bsize];
952 for(i=0;i<n;++i)
954 a = get_bits(&s->gb, 1);
955 s->high_band_coded[ch][i] = a;
956 /* if noise coding, the coefficients are not transmitted */
957 if (a)
958 nb_coefs[ch] -= s->exponent_high_bands[bsize][i];
962 for(ch = 0; ch < s->nb_channels; ++ch)
964 if (s->channel_coded[ch])
966 int i, n, val, code;
968 n = s->exponent_high_sizes[bsize];
969 val = (int)0x80000000;
970 for(i=0;i<n;++i)
972 if (s->high_band_coded[ch][i])
974 if (val == (int)0x80000000)
976 val = get_bits(&s->gb, 7) - 19;
978 else
980 //code = get_vlc(&s->gb, &s->hgain_vlc);
981 code = get_vlc2(&s->gb, s->hgain_vlc.table, HGAINVLCBITS, HGAINMAX);
982 if (code < 0)
984 return -6;
986 val += code - 18;
988 s->high_band_values[ch][i] = val;
995 /* exponents can be reused in short blocks. */
996 if ((s->block_len_bits == s->frame_len_bits) || get_bits(&s->gb, 1))
998 for(ch = 0; ch < s->nb_channels; ++ch)
1000 if (s->channel_coded[ch])
1002 if (s->use_exp_vlc)
1004 if (decode_exp_vlc(s, ch) < 0)
1006 return -7;
1009 else
1011 decode_exp_lsp(s, ch);
1013 s->exponents_bsize[ch] = bsize;
1018 /* parse spectral coefficients : just RLE encoding */
1019 for(ch = 0; ch < s->nb_channels; ++ch)
1021 if (s->channel_coded[ch])
1023 VLC *coef_vlc;
1024 int level, run, sign, tindex;
1025 int16_t *ptr, *eptr;
1026 const int16_t *level_table, *run_table;
1028 /* special VLC tables are used for ms stereo because
1029 there is potentially less energy there */
1030 tindex = (ch == 1 && s->ms_stereo);
1031 coef_vlc = &s->coef_vlc[tindex];
1032 run_table = s->run_table[tindex];
1033 level_table = s->level_table[tindex];
1034 /* XXX: optimize */
1035 ptr = &s->coefs1[ch][0];
1036 eptr = ptr + nb_coefs[ch];
1037 memset(ptr, 0, s->block_len * sizeof(int16_t));
1039 for(;;)
1041 code = get_vlc2(&s->gb, coef_vlc->table, VLCBITS, VLCMAX);
1042 //code = get_vlc(&s->gb, coef_vlc);
1043 if (code < 0)
1045 return -8;
1047 if (code == 1)
1049 /* EOB */
1050 break;
1052 else if (code == 0)
1054 /* escape */
1055 level = get_bits(&s->gb, coef_nb_bits);
1056 /* NOTE: this is rather suboptimal. reading
1057 block_len_bits would be better */
1058 run = get_bits(&s->gb, s->frame_len_bits);
1060 else
1062 /* normal code */
1063 run = run_table[code];
1064 level = level_table[code];
1066 sign = get_bits(&s->gb, 1);
1067 if (!sign)
1068 level = -level;
1069 ptr += run;
1070 if (ptr >= eptr)
1072 return -9;
1074 *ptr++ = level;
1077 /* NOTE: EOB can be omitted */
1078 if (ptr >= eptr)
1079 break;
1082 if (s->version == 1 && s->nb_channels >= 2)
1084 align_get_bits(&s->gb);
1089 int n4 = s->block_len >> 1;
1090 //mdct_norm = 0x10000;
1091 //mdct_norm = fixdiv32(mdct_norm,itofix32(n4));
1093 mdct_norm = 0x10000>>(s->block_len_bits-1); //theres no reason to do a divide by two in fixed precision ...
1095 if (s->version == 1)
1097 fixed32 tmp = fixsqrt32(itofix32(n4));
1098 mdct_norm *= tmp; // PJJ : exercise this path
1103 /* finally compute the MDCT coefficients */
1104 for(ch = 0; ch < s->nb_channels; ++ch)
1106 if (s->channel_coded[ch])
1108 int16_t *coefs1;
1109 fixed32 *exponents, *exp_ptr;
1110 fixed32 *coefs, atemp;
1111 fixed64 mult;
1112 fixed64 mult1;
1113 fixed32 noise, temp1, temp2, mult2;
1114 int i, j, n, n1, last_high_band, esize;
1115 fixed32 exp_power[HIGH_BAND_MAX_SIZE];
1117 //total_gain, coefs1, mdctnorm are lossless
1119 coefs1 = s->coefs1[ch];
1120 exponents = s->exponents[ch];
1121 esize = s->exponents_bsize[ch];
1122 coefs = (*(s->coefs))[ch];
1124 n=0;
1127 * Previously the IMDCT was run in 17.15 precision to avoid overflow. However rare files could
1128 * overflow here as well, so switch to 17.15 during coefs calculation.
1132 if (s->use_noise_coding)
1134 /*TODO: mult should be converted to 32 bit to speed up noise coding*/
1136 mult = fixdiv64(pow_table[total_gain+20],Fixed32To64(s->max_exponent[ch]));
1137 mult = mult* mdct_norm; //what the hell? This is actually fixed64*2^16!
1138 mult1 = mult;
1140 /* very low freqs : noise */
1141 for(i = 0;i < s->coefs_start; ++i)
1143 *coefs++ = fixmul32( (fixmul32(s->noise_table[s->noise_index],(*exponents++))>>4),Fixed32From64(mult1)) >>1;
1144 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1147 n1 = s->exponent_high_sizes[bsize];
1149 /* compute power of high bands */
1150 exp_ptr = exponents +
1151 s->high_band_start[bsize] -
1152 s->coefs_start;
1153 last_high_band = 0; /* avoid warning */
1154 for (j=0;j<n1;++j)
1156 n = s->exponent_high_bands[s->frame_len_bits -
1157 s->block_len_bits][j];
1158 if (s->high_band_coded[ch][j])
1160 fixed32 e2, v;
1161 e2 = 0;
1162 for(i = 0;i < n; ++i)
1164 /*v is noramlized later on so its fixed format is irrelevant*/
1165 v = exp_ptr[i]>>4;
1166 e2 += fixmul32(v, v)>>3;
1168 exp_power[j] = e2/n; /*n is an int...*/
1169 last_high_band = j;
1171 exp_ptr += n;
1174 /* main freqs and high freqs */
1175 for(j=-1;j<n1;++j)
1177 if (j < 0)
1179 n = s->high_band_start[bsize] -
1180 s->coefs_start;
1182 else
1184 n = s->exponent_high_bands[s->frame_len_bits -
1185 s->block_len_bits][j];
1187 if (j >= 0 && s->high_band_coded[ch][j])
1189 /* use noise with specified power */
1190 fixed32 tmp = fixdiv32(exp_power[j],exp_power[last_high_band]);
1191 mult1 = (fixed64)fixsqrt32(tmp);
1192 /* XXX: use a table */
1193 /*mult1 is 48.16, pow_table is 48.16*/
1194 mult1 = mult1 * pow_table[s->high_band_values[ch][j]+20] >> PRECISION;
1196 /*this step has a fairly high degree of error for some reason*/
1197 mult1 = fixdiv64(mult1,fixmul32(s->max_exponent[ch],s->noise_mult));
1199 mult1 = mult1*mdct_norm>>PRECISION;
1200 for(i = 0;i < n; ++i)
1202 noise = s->noise_table[s->noise_index];
1203 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1204 *coefs++ = fixmul32((fixmul32(*exponents,noise)>>4),Fixed32From64(mult1)) >>1;
1205 ++exponents;
1208 else
1210 /* coded values + small noise */
1211 for(i = 0;i < n; ++i)
1213 // PJJ: check code path
1214 noise = s->noise_table[s->noise_index];
1215 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1217 /*don't forget to renormalize the noise*/
1218 temp1 = (((int32_t)*coefs1++)<<16) + (noise>>4);
1219 temp2 = fixmul32(*exponents, mult>>17);
1220 *coefs++ = fixmul32(temp1, temp2);
1221 ++exponents;
1226 /* very high freqs : noise */
1227 n = s->block_len - s->coefs_end[bsize];
1228 mult2 = fixmul32(mult>>16,exponents[-1]) ; /*the work around for 32.32 vars are getting stupid*/
1229 for (i = 0; i < n; ++i)
1231 /*renormalize the noise product and then reduce to 17.15 precison*/
1232 *coefs++ = fixmul32(s->noise_table[s->noise_index],mult2) >>5;
1234 s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
1237 else
1239 /*Noise coding not used, simply convert from exp to fixed representation*/
1242 fixed32 mult3 = (fixed32)(fixdiv64(pow_table[total_gain+20],Fixed32To64(s->max_exponent[ch])));
1243 mult3 = fixmul32(mult3, mdct_norm);
1245 n = nb_coefs[ch];
1247 /* XXX: optimize more, unrolling this loop in asm might be a good idea */
1249 for(i = 0;i < n; ++i)
1251 atemp = (coefs1[i] * mult3)>>1;
1252 *coefs++=fixmul32(atemp,exponents[i<<bsize>>esize]);
1254 n = s->block_len - s->coefs_end[bsize];
1255 memset(coefs, 0, n*sizeof(fixed32));
1262 if (s->ms_stereo && s->channel_coded[1])
1264 fixed32 a, b;
1265 int i;
1266 fixed32 (*coefs)[MAX_CHANNELS][BLOCK_MAX_SIZE] = (s->coefs);
1268 /* nominal case for ms stereo: we do it before mdct */
1269 /* no need to optimize this case because it should almost
1270 never happen */
1271 if (!s->channel_coded[0])
1273 memset((*(s->coefs))[0], 0, sizeof(fixed32) * s->block_len);
1274 s->channel_coded[0] = 1;
1277 for(i = 0; i < s->block_len; ++i)
1279 a = (*coefs)[0][i];
1280 b = (*coefs)[1][i];
1281 (*coefs)[0][i] = a + b;
1282 (*coefs)[1][i] = a - b;
1286 for(ch = 0; ch < s->nb_channels; ++ch)
1288 if (s->channel_coded[ch])
1290 static fixed32 output[BLOCK_MAX_SIZE * 2] IBSS_ATTR;
1292 int n4, index, n;
1294 n = s->block_len;
1295 n4 = s->block_len >>1;
1297 ff_imdct_calc(&s->mdct_ctx[bsize],
1298 output,
1299 (*(s->coefs))[ch]);
1302 /* add in the frame */
1303 index = (s->frame_len / 2) + s->block_pos - n4;
1305 wma_window(s, output, &s->frame_out[ch][index]);
1309 /* specific fast case for ms-stereo : add to second
1310 channel if it is not coded */
1311 if (s->ms_stereo && !s->channel_coded[1])
1313 wma_window(s, output, &s->frame_out[1][index]);
1317 next:
1318 /* update block number */
1319 ++s->block_num;
1320 s->block_pos += s->block_len;
1321 if (s->block_pos >= s->frame_len)
1323 return 1;
1325 else
1327 return 0;
1331 /* decode a frame of frame_len samples */
1332 static int wma_decode_frame(WMADecodeContext *s, int32_t *samples)
1334 int ret, i, n, ch, incr;
1335 int32_t *ptr;
1336 fixed32 *iptr;
1337 // rb->splash(HZ, "in wma_decode_frame");
1339 /* read each block */
1340 s->block_num = 0;
1341 s->block_pos = 0;
1344 for(;;)
1346 ret = wma_decode_block(s);
1347 if (ret < 0)
1350 //rb->splash(HZ*4, "wma_decode_block failed with ret %d", ret);
1351 return -1;
1353 if (ret)
1355 break;
1359 /* return frame with full 30-bit precision */
1360 n = s->frame_len;
1361 incr = s->nb_channels;
1362 for(ch = 0; ch < s->nb_channels; ++ch)
1364 ptr = samples + ch;
1365 iptr = s->frame_out[ch];
1367 for (i=0;i<n;++i)
1369 *ptr = (*iptr++);
1370 ptr += incr;
1372 /* prepare for next block */
1373 memmove(&s->frame_out[ch][0], &s->frame_out[ch][s->frame_len],
1374 s->frame_len * sizeof(fixed32));
1378 return 0;
1381 /* Initialise the superframe decoding */
1383 int wma_decode_superframe_init(WMADecodeContext* s,
1384 uint8_t *buf, /*input*/
1385 int buf_size)
1387 if (buf_size==0)
1389 s->last_superframe_len = 0;
1390 return 0;
1393 s->current_frame = 0;
1395 init_get_bits(&s->gb, buf, buf_size*8);
1397 if (s->use_bit_reservoir)
1399 /* read super frame header */
1400 get_bits(&s->gb, 4); /* super frame index */
1401 s->nb_frames = get_bits(&s->gb, 4);
1403 if (s->last_superframe_len == 0)
1404 s->nb_frames --;
1405 else if (s->nb_frames == 0)
1406 s->nb_frames++;
1408 s->bit_offset = get_bits(&s->gb, s->byte_offset_bits + 3);
1409 } else {
1410 s->nb_frames = 1;
1413 return 1;
1417 /* Decode a single frame in the current superframe - return -1 if
1418 there was a decoding error, or the number of samples decoded.
1421 int wma_decode_superframe_frame(WMADecodeContext* s,
1422 int32_t* samples, /*output*/
1423 uint8_t *buf, /*input*/
1424 int buf_size)
1426 int pos, len;
1427 uint8_t *q;
1428 int done = 0;
1430 if ((s->use_bit_reservoir) && (s->current_frame == 0))
1432 if (s->last_superframe_len > 0)
1434 /* add s->bit_offset bits to last frame */
1435 if ((s->last_superframe_len + ((s->bit_offset + 7) >> 3)) >
1436 MAX_CODED_SUPERFRAME_SIZE)
1438 goto fail;
1440 q = s->last_superframe + s->last_superframe_len;
1441 len = s->bit_offset;
1442 while (len > 0)
1444 *q++ = (get_bits)(&s->gb, 8);
1445 len -= 8;
1447 if (len > 0)
1449 *q++ = (get_bits)(&s->gb, len) << (8 - len);
1452 /* XXX: s->bit_offset bits into last frame */
1453 init_get_bits(&s->gb, s->last_superframe, MAX_CODED_SUPERFRAME_SIZE*8);
1454 /* skip unused bits */
1455 if (s->last_bitoffset > 0)
1456 skip_bits(&s->gb, s->last_bitoffset);
1458 /* this frame is stored in the last superframe and in the
1459 current one */
1460 if (wma_decode_frame(s, samples) < 0)
1462 goto fail;
1464 done = 1;
1467 /* read each frame starting from s->bit_offset */
1468 pos = s->bit_offset + 4 + 4 + s->byte_offset_bits + 3;
1469 init_get_bits(&s->gb, buf + (pos >> 3), (MAX_CODED_SUPERFRAME_SIZE - (pos >> 3))*8);
1470 len = pos & 7;
1471 if (len > 0)
1472 skip_bits(&s->gb, len);
1474 s->reset_block_lengths = 1;
1477 /* If we haven't decoded a frame yet, do it now */
1478 if (!done)
1480 if (wma_decode_frame(s, samples) < 0)
1482 goto fail;
1486 s->current_frame++;
1488 if ((s->use_bit_reservoir) && (s->current_frame == s->nb_frames))
1490 /* we copy the end of the frame in the last frame buffer */
1491 pos = get_bits_count(&s->gb) + ((s->bit_offset + 4 + 4 + s->byte_offset_bits + 3) & ~7);
1492 s->last_bitoffset = pos & 7;
1493 pos >>= 3;
1494 len = buf_size - pos;
1495 if (len > MAX_CODED_SUPERFRAME_SIZE || len < 0)
1497 goto fail;
1499 s->last_superframe_len = len;
1500 memcpy(s->last_superframe, buf + pos, len);
1503 return s->frame_len;
1505 fail:
1506 /* when error, we reset the bit reservoir */
1507 s->last_superframe_len = 0;
1508 return -1;