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