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