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