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