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