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