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