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