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