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