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