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