Merge branch 't/gui_improvements'
[paraslash.git] / wmadec_filter.c
1 /*
2 * WMA compatible decoder
3 *
4 * Extracted 2009 from the mplayer source code 2009-02-10.
5 *
6 * Copyright (c) 2002 The FFmpeg Project
7 *
8 * Licensed under the GNU Lesser General Public License.
9 * For licencing details see COPYING.LIB.
10 */
11
12 /** \file wmadec_filter.c paraslash's WMA decoder. */
13
14 /*
15 * This decoder handles Microsoft Windows Media Audio data version 2.
16 */
17
18 #define _XOPEN_SOURCE 600
19
20 #include <inttypes.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <math.h>
24 #include <string.h>
25 #include <regex.h>
26 #include <sys/select.h>
27
28 #include "para.h"
29 #include "error.h"
30 #include "list.h"
31 #include "ggo.h"
32 #include "string.h"
33 #include "sched.h"
34 #include "buffer_tree.h"
35 #include "filter.h"
36 #include "bitstream.h"
37 #include "imdct.h"
38 #include "wma.h"
39 #include "wmadata.h"
40
41
42 /* size of blocks */
43 #define BLOCK_MIN_BITS 7
44 #define BLOCK_MAX_BITS 11
45 #define BLOCK_MAX_SIZE (1 << BLOCK_MAX_BITS)
46
47 #define BLOCK_NB_SIZES (BLOCK_MAX_BITS - BLOCK_MIN_BITS + 1)
48
49 /* XXX: find exact max size */
50 #define HIGH_BAND_MAX_SIZE 16
51
52 /* XXX: is it a suitable value ? */
53 #define MAX_CODED_SUPERFRAME_SIZE 16384
54
55 #define MAX_CHANNELS 2
56
57 #define NOISE_TAB_SIZE 8192
58
59 #define LSP_POW_BITS 7
60
61 struct private_wmadec_data {
62 /** Information contained in the audio file header. */
63 struct asf_header_info ahi;
64 struct getbit_context gb;
65 /** Whether to use the bit reservoir. */
66 int use_bit_reservoir;
67 /** Whether to use variable block length. */
68 int use_variable_block_len;
69 /** Whether to use exponent coding. */
70 int use_exp_vlc;
71 /** Whether perceptual noise is added. */
72 int use_noise_coding;
73 /** Depends on number of the bits per second and the frame length. */
74 int byte_offset_bits;
75 /** Only used if use_exp_vlc is true. */
76 struct vlc exp_vlc;
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 int exponent_size;
231
232 block_len = pwd->frame_len >> k;
233 table = NULL;
234 a = pwd->frame_len_bits - BLOCK_MIN_BITS - k;
235 if (a < 3) {
236 if (ahi->sample_rate >= 44100)
237 table = exponent_band_44100[a];
238 else if (ahi->sample_rate >= 32000)
239 table = exponent_band_32000[a];
240 else if (ahi->sample_rate >= 22050)
241 table = exponent_band_22050[a];
242 }
243 if (table) {
244 n = *table++;
245 for (i = 0; i < n; i++)
246 pwd->exponent_bands[k][i] = table[i];
247 exponent_size = n;
248 } else {
249 j = 0;
250 lpos = 0;
251 for (i = 0; i < 25; i++) {
252 a = wma_critical_freqs[i];
253 b = ahi->sample_rate;
254 pos = ((block_len * 2 * a) + (b << 1)) / (4 * b);
255 pos <<= 2;
256 if (pos > block_len)
257 pos = block_len;
258 if (pos > lpos)
259 pwd->exponent_bands[k][j++] = pos - lpos;
260 if (pos >= block_len)
261 break;
262 lpos = pos;
263 }
264 exponent_size = j;
265 }
266
267 /* max number of coefs */
268 pwd->coefs_end[k] = (pwd->frame_len - ((pwd->frame_len * 9) / 100)) >> k;
269 /* high freq computation */
270 pwd->high_band_start[k] = (int) ((block_len * 2 * high_freq)
271 / ahi->sample_rate + 0.5);
272 n = exponent_size;
273 j = 0;
274 pos = 0;
275 for (i = 0; i < n; i++) {
276 int start, end;
277 start = pos;
278 pos += pwd->exponent_bands[k][i];
279 end = pos;
280 if (start < pwd->high_band_start[k])
281 start = pwd->high_band_start[k];
282 if (end > pwd->coefs_end[k])
283 end = pwd->coefs_end[k];
284 if (end > start)
285 pwd->exponent_high_bands[k][j++] = end - start;
286 }
287 pwd->exponent_high_sizes[k] = j;
288 }
289 }
290
291 static int wma_init(struct private_wmadec_data *pwd)
292 {
293 int i;
294 float bps1, high_freq;
295 volatile float bps;
296 int sample_rate1;
297 int coef_vlc_table;
298 struct asf_header_info *ahi = &pwd->ahi;
299 int flags2 = ahi->flags2;
300
301 if (ahi->sample_rate <= 0 || ahi->sample_rate > 50000
302 || ahi->channels <= 0 || ahi->channels > 8
303 || ahi->bit_rate <= 0)
304 return -E_WMA_BAD_PARAMS;
305
306 /* compute MDCT block size */
307 if (ahi->sample_rate <= 16000)
308 pwd->frame_len_bits = 9;
309 else if (ahi->sample_rate <= 22050)
310 pwd->frame_len_bits = 10;
311 else
312 pwd->frame_len_bits = 11;
313 pwd->frame_len = 1 << pwd->frame_len_bits;
314 if (pwd->use_variable_block_len) {
315 int nb_max, nb;
316 nb = ((flags2 >> 3) & 3) + 1;
317 if ((ahi->bit_rate / ahi->channels) >= 32000)
318 nb += 2;
319 nb_max = pwd->frame_len_bits - BLOCK_MIN_BITS;
320 if (nb > nb_max)
321 nb = nb_max;
322 pwd->nb_block_sizes = nb + 1;
323 } else
324 pwd->nb_block_sizes = 1;
325
326 /* init rate dependent parameters */
327 pwd->use_noise_coding = 1;
328 high_freq = ahi->sample_rate * 0.5;
329
330 /* wma2 rates are normalized */
331 sample_rate1 = ahi->sample_rate;
332 if (sample_rate1 >= 44100)
333 sample_rate1 = 44100;
334 else if (sample_rate1 >= 22050)
335 sample_rate1 = 22050;
336 else if (sample_rate1 >= 16000)
337 sample_rate1 = 16000;
338 else if (sample_rate1 >= 11025)
339 sample_rate1 = 11025;
340 else if (sample_rate1 >= 8000)
341 sample_rate1 = 8000;
342
343 bps = (float) ahi->bit_rate / (float) (ahi->channels * ahi->sample_rate);
344 pwd->byte_offset_bits = wma_log2((int) (bps * pwd->frame_len / 8.0 + 0.5)) + 2;
345 /*
346 * Compute high frequency value and choose if noise coding should be
347 * activated.
348 */
349 bps1 = bps;
350 if (ahi->channels == 2)
351 bps1 = bps * 1.6;
352 if (sample_rate1 == 44100) {
353 if (bps1 >= 0.61)
354 pwd->use_noise_coding = 0;
355 else
356 high_freq = high_freq * 0.4;
357 } else if (sample_rate1 == 22050) {
358 if (bps1 >= 1.16)
359 pwd->use_noise_coding = 0;
360 else if (bps1 >= 0.72)
361 high_freq = high_freq * 0.7;
362 else
363 high_freq = high_freq * 0.6;
364 } else if (sample_rate1 == 16000) {
365 if (bps > 0.5)
366 high_freq = high_freq * 0.5;
367 else
368 high_freq = high_freq * 0.3;
369 } else if (sample_rate1 == 11025)
370 high_freq = high_freq * 0.7;
371 else if (sample_rate1 == 8000) {
372 if (bps <= 0.625)
373 high_freq = high_freq * 0.5;
374 else if (bps > 0.75)
375 pwd->use_noise_coding = 0;
376 else
377 high_freq = high_freq * 0.65;
378 } else {
379 if (bps >= 0.8)
380 high_freq = high_freq * 0.75;
381 else if (bps >= 0.6)
382 high_freq = high_freq * 0.6;
383 else
384 high_freq = high_freq * 0.5;
385 }
386 PARA_INFO_LOG("channels=%d sample_rate=%d "
387 "bitrate=%d block_align=%d\n",
388 ahi->channels, ahi->sample_rate,
389 ahi->bit_rate, ahi->block_align);
390 PARA_INFO_LOG("frame_len=%d, bps=%f bps1=%f "
391 "high_freq=%f bitoffset=%d\n",
392 pwd->frame_len, bps, bps1,
393 high_freq, pwd->byte_offset_bits);
394 PARA_INFO_LOG("use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",
395 pwd->use_noise_coding, pwd->use_exp_vlc, pwd->nb_block_sizes);
396
397 compute_scale_factor_band_sizes(pwd, high_freq);
398 /* init MDCT windows : simple sinus window */
399 for (i = 0; i < pwd->nb_block_sizes; i++) {
400 int n;
401 n = 1 << (pwd->frame_len_bits - i);
402 sine_window_init(sine_windows[pwd->frame_len_bits - i - 7], n);
403 pwd->windows[i] = sine_windows[pwd->frame_len_bits - i - 7];
404 }
405
406 pwd->reset_block_lengths = 1;
407
408 if (pwd->use_noise_coding) {
409 /* init the noise generator */
410 if (pwd->use_exp_vlc)
411 pwd->noise_mult = 0.02;
412 else
413 pwd->noise_mult = 0.04;
414
415 {
416 unsigned int seed;
417 float norm;
418 seed = 1;
419 norm = (1.0 / (float) (1LL << 31)) * sqrt(3) * pwd->noise_mult;
420 for (i = 0; i < NOISE_TAB_SIZE; i++) {
421 seed = seed * 314159 + 1;
422 pwd->noise_table[i] = (float) ((int) seed) * norm;
423 }
424 }
425 }
426
427 /* choose the VLC tables for the coefficients */
428 coef_vlc_table = 2;
429 if (ahi->sample_rate >= 32000) {
430 if (bps1 < 0.72)
431 coef_vlc_table = 0;
432 else if (bps1 < 1.16)
433 coef_vlc_table = 1;
434 }
435 pwd->coef_vlcs[0] = &coef_vlcs[coef_vlc_table * 2];
436 pwd->coef_vlcs[1] = &coef_vlcs[coef_vlc_table * 2 + 1];
437 init_coef_vlc(&pwd->coef_vlc[0], &pwd->run_table[0], &pwd->level_table[0],
438 pwd->coef_vlcs[0]);
439 init_coef_vlc(&pwd->coef_vlc[1], &pwd->run_table[1], &pwd->level_table[1],
440 pwd->coef_vlcs[1]);
441 return 0;
442 }
443
444 static void wma_lsp_to_curve_init(struct private_wmadec_data *pwd, int frame_len)
445 {
446 float wdel, a, b;
447 int i, e, m;
448
449 wdel = M_PI / frame_len;
450 for (i = 0; i < frame_len; i++)
451 pwd->lsp_cos_table[i] = 2.0f * cos(wdel * i);
452
453 /* tables for x^-0.25 computation */
454 for (i = 0; i < 256; i++) {
455 e = i - 126;
456 pwd->lsp_pow_e_table[i] = pow(2.0, e * -0.25);
457 }
458
459 /* These two tables are needed to avoid two operations in pow_m1_4. */
460 b = 1.0;
461 for (i = (1 << LSP_POW_BITS) - 1; i >= 0; i--) {
462 m = (1 << LSP_POW_BITS) + i;
463 a = (float) m *(0.5 / (1 << LSP_POW_BITS));
464 a = pow(a, -0.25);
465 pwd->lsp_pow_m_table1[i] = 2 * a - b;
466 pwd->lsp_pow_m_table2[i] = b - a;
467 b = a;
468 }
469 }
470
471 static int wma_decode_init(char *initial_buf, int len, struct private_wmadec_data **result)
472 {
473 struct private_wmadec_data *pwd;
474 int ret, i;
475
476 PARA_NOTICE_LOG("initial buf: %d bytes\n", len);
477 pwd = para_calloc(sizeof(*pwd));
478 ret = read_asf_header(initial_buf, len, &pwd->ahi);
479 if (ret <= 0) {
480 free(pwd);
481 return ret;
482 }
483
484 pwd->use_exp_vlc = pwd->ahi.flags2 & 0x0001;
485 pwd->use_bit_reservoir = pwd->ahi.flags2 & 0x0002;
486 pwd->use_variable_block_len = pwd->ahi.flags2 & 0x0004;
487
488 ret = wma_init(pwd);
489 if (ret < 0)
490 return ret;
491 /* init MDCT */
492 for (i = 0; i < pwd->nb_block_sizes; i++) {
493 ret = imdct_init(pwd->frame_len_bits - i + 1, &pwd->mdct_ctx[i]);
494 if (ret < 0)
495 return ret;
496 }
497 if (pwd->use_noise_coding) {
498 PARA_INFO_LOG("using noise coding\n");
499 init_vlc(&pwd->hgain_vlc, HGAINVLCBITS,
500 sizeof(wma_hgain_huffbits), wma_hgain_huffbits,
501 wma_hgain_huffcodes, 2);
502 }
503
504 if (pwd->use_exp_vlc) {
505 PARA_INFO_LOG("using exp_vlc\n");
506 init_vlc(&pwd->exp_vlc, EXPVLCBITS, sizeof(wma_scale_huffbits),
507 wma_scale_huffbits, 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 int 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, out_size;
1217 struct private_wmadec_data *pwd = fn->private_data;
1218 struct btr_node *btrn = fn->btrn;
1219 size_t len;
1220 char *in, *out;
1221
1222 next_buffer:
1223 converted = 0;
1224 ret = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
1225 if (ret < 0)
1226 goto err;
1227 if (ret == 0)
1228 return 0;
1229 btr_merge(btrn, fn->min_iqs);
1230 len = btr_next_buffer(btrn, (char **)&in);
1231 ret = -E_WMADEC_EOF;
1232 if (len < fn->min_iqs)
1233 goto err;
1234 if (!pwd) {
1235 ret = wma_decode_init(in, len, &pwd);
1236 if (ret < 0)
1237 goto err;
1238 if (ret == 0) {
1239 fn->min_iqs += 4096;
1240 goto next_buffer;
1241 }
1242 fn->min_iqs = 2 * (WMA_FRAME_SKIP + pwd->ahi.block_align);
1243 fn->private_data = pwd;
1244 converted = pwd->ahi.header_len;
1245 goto success;
1246 }
1247 fn->min_iqs = WMA_FRAME_SKIP + pwd->ahi.block_align;
1248 if (fn->min_iqs > len)
1249 goto success;
1250 out_size = WMA_OUTPUT_BUFFER_SIZE;
1251 out = para_malloc(out_size);
1252 ret = wma_decode_superframe(pwd, out, &out_size,
1253 (uint8_t *)in + WMA_FRAME_SKIP, len - WMA_FRAME_SKIP);
1254 if (ret < 0) {
1255 free(out);
1256 goto err;
1257 }
1258 out = para_realloc(out, out_size);
1259 if (out_size > 0)
1260 btr_add_output(out, out_size, btrn);
1261 converted += ret + WMA_FRAME_SKIP;
1262 success:
1263 btr_consume(btrn, converted);
1264 return 0;
1265 err:
1266 assert(ret < 0);
1267 btr_remove_node(&fn->btrn);
1268 return ret;
1269 }
1270
1271 static void wmadec_open(struct filter_node *fn)
1272 {
1273 fn->private_data = NULL;
1274 fn->min_iqs = 4096;
1275 }
1276
1277 /**
1278 * The init function of the wma decoder.
1279 *
1280 * \param f Its fields are filled in by the function.
1281 */
1282 void wmadec_filter_init(struct filter *f)
1283 {
1284 f->open = wmadec_open;
1285 f->close = wmadec_close;
1286 f->execute = wmadec_execute;
1287 f->pre_select = generic_filter_pre_select;
1288 f->post_select = wmadec_post_select;
1289 }