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