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