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