Kill afhi->header_offset.
[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 #include <stdbool.h>
29
30 #include "para.h"
31 #include "error.h"
32 #include "list.h"
33 #include "ggo.h"
34 #include "string.h"
35 #include "sched.h"
36 #include "buffer_tree.h"
37 #include "filter.h"
38 #include "bitstream.h"
39 #include "imdct.h"
40 #include "wma.h"
41 #include "wmadata.h"
42
43
44 /* size of blocks */
45 #define BLOCK_MIN_BITS 7
46 #define BLOCK_MAX_BITS 11
47 #define BLOCK_MAX_SIZE (1 << BLOCK_MAX_BITS)
48
49 #define BLOCK_NB_SIZES (BLOCK_MAX_BITS - BLOCK_MIN_BITS + 1)
50
51 /* XXX: find exact max size */
52 #define HIGH_BAND_MAX_SIZE 16
53
54 /* XXX: is it a suitable value ? */
55 #define MAX_CODED_SUPERFRAME_SIZE 16384
56
57 #define MAX_CHANNELS 2
58
59 #define NOISE_TAB_SIZE 8192
60
61 #define LSP_POW_BITS 7
62
63 struct private_wmadec_data {
64 /** Information contained in the audio file header. */
65 struct asf_header_info ahi;
66 struct getbit_context gb;
67 /** Whether to use the bit reservoir. */
68 int use_bit_reservoir;
69 /** Whether to use variable block length. */
70 int use_variable_block_len;
71 /** Whether to use exponent coding. */
72 int use_exp_vlc;
73 /** Whether perceptual noise is added. */
74 int use_noise_coding;
75 int byte_offset_bits;
76 struct vlc exp_vlc;
77 int exponent_sizes[BLOCK_NB_SIZES];
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) 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 block_len = pwd->frame_len >> k;
232
233 table = NULL;
234 a = pwd->frame_len_bits - BLOCK_MIN_BITS - k;
235 if (a < 3) {
236 if (ahi->sample_rate >= 44100)
237 table = exponent_band_44100[a];
238 else if (ahi->sample_rate >= 32000)
239 table = exponent_band_32000[a];
240 else if (ahi->sample_rate >= 22050)
241 table = exponent_band_22050[a];
242 }
243 if (table) {
244 n = *table++;
245 for (i = 0; i < n; i++)
246 pwd->exponent_bands[k][i] = table[i];
247 pwd->exponent_sizes[k] = n;
248 } else {
249 j = 0;
250 lpos = 0;
251 for (i = 0; i < 25; i++) {
252 a = wma_critical_freqs[i];
253 b = ahi->sample_rate;
254 pos = ((block_len * 2 * a) + (b << 1)) / (4 * b);
255 pos <<= 2;
256 if (pos > block_len)
257 pos = block_len;
258 if (pos > lpos)
259 pwd->exponent_bands[k][j++] = pos - lpos;
260 if (pos >= block_len)
261 break;
262 lpos = pos;
263 }
264 pwd->exponent_sizes[k] = j;
265 }
266
267 /* max number of coefs */
268 pwd->coefs_end[k] = (pwd->frame_len - ((pwd->frame_len * 9) / 100)) >> k;
269 /* high freq computation */
270 pwd->high_band_start[k] = (int) ((block_len * 2 * high_freq)
271 / ahi->sample_rate + 0.5);
272 n = pwd->exponent_sizes[k];
273 j = 0;
274 pos = 0;
275 for (i = 0; i < n; i++) {
276 int start, end;
277 start = pos;
278 pos += pwd->exponent_bands[k][i];
279 end = pos;
280 if (start < pwd->high_band_start[k])
281 start = pwd->high_band_start[k];
282 if (end > pwd->coefs_end[k])
283 end = pwd->coefs_end[k];
284 if (end > start)
285 pwd->exponent_high_bands[k][j++] = end - start;
286 }
287 pwd->exponent_high_sizes[k] = j;
288 }
289 }
290
291 static int wma_init(struct private_wmadec_data *pwd)
292 {
293 int i;
294 float bps1, high_freq;
295 volatile float bps;
296 int sample_rate1;
297 int coef_vlc_table;
298 struct asf_header_info *ahi = &pwd->ahi;
299 int flags2 = ahi->flags2;
300
301 if (ahi->sample_rate <= 0 || ahi->sample_rate > 50000
302 || ahi->channels <= 0 || ahi->channels > 8
303 || ahi->bit_rate <= 0)
304 return -E_WMA_BAD_PARAMS;
305
306 /* compute MDCT block size */
307 if (ahi->sample_rate <= 16000)
308 pwd->frame_len_bits = 9;
309 else if (ahi->sample_rate <= 22050)
310 pwd->frame_len_bits = 10;
311 else
312 pwd->frame_len_bits = 11;
313 pwd->frame_len = 1 << pwd->frame_len_bits;
314 if (pwd->use_variable_block_len) {
315 int nb_max, nb;
316 nb = ((flags2 >> 3) & 3) + 1;
317 if ((ahi->bit_rate / ahi->channels) >= 32000)
318 nb += 2;
319 nb_max = pwd->frame_len_bits - BLOCK_MIN_BITS;
320 if (nb > nb_max)
321 nb = nb_max;
322 pwd->nb_block_sizes = nb + 1;
323 } else
324 pwd->nb_block_sizes = 1;
325
326 /* init rate dependent parameters */
327 pwd->use_noise_coding = 1;
328 high_freq = ahi->sample_rate * 0.5;
329
330 /* wma2 rates are normalized */
331 sample_rate1 = ahi->sample_rate;
332 if (sample_rate1 >= 44100)
333 sample_rate1 = 44100;
334 else if (sample_rate1 >= 22050)
335 sample_rate1 = 22050;
336 else if (sample_rate1 >= 16000)
337 sample_rate1 = 16000;
338 else if (sample_rate1 >= 11025)
339 sample_rate1 = 11025;
340 else if (sample_rate1 >= 8000)
341 sample_rate1 = 8000;
342
343 bps = (float) ahi->bit_rate / (float) (ahi->channels * ahi->sample_rate);
344 pwd->byte_offset_bits = wma_log2((int) (bps * pwd->frame_len / 8.0 + 0.5)) + 2;
345 /*
346 * Compute high frequency value and choose if noise coding should be
347 * activated.
348 */
349 bps1 = bps;
350 if (ahi->channels == 2)
351 bps1 = bps * 1.6;
352 if (sample_rate1 == 44100) {
353 if (bps1 >= 0.61)
354 pwd->use_noise_coding = 0;
355 else
356 high_freq = high_freq * 0.4;
357 } else if (sample_rate1 == 22050) {
358 if (bps1 >= 1.16)
359 pwd->use_noise_coding = 0;
360 else if (bps1 >= 0.72)
361 high_freq = high_freq * 0.7;
362 else
363 high_freq = high_freq * 0.6;
364 } else if (sample_rate1 == 16000) {
365 if (bps > 0.5)
366 high_freq = high_freq * 0.5;
367 else
368 high_freq = high_freq * 0.3;
369 } else if (sample_rate1 == 11025)
370 high_freq = high_freq * 0.7;
371 else if (sample_rate1 == 8000) {
372 if (bps <= 0.625)
373 high_freq = high_freq * 0.5;
374 else if (bps > 0.75)
375 pwd->use_noise_coding = 0;
376 else
377 high_freq = high_freq * 0.65;
378 } else {
379 if (bps >= 0.8)
380 high_freq = high_freq * 0.75;
381 else if (bps >= 0.6)
382 high_freq = high_freq * 0.6;
383 else
384 high_freq = high_freq * 0.5;
385 }
386 PARA_INFO_LOG("channels=%d sample_rate=%d "
387 "bitrate=%d block_align=%d\n",
388 ahi->channels, ahi->sample_rate,
389 ahi->bit_rate, ahi->block_align);
390 PARA_INFO_LOG("frame_len=%d, bps=%f bps1=%f "
391 "high_freq=%f bitoffset=%d\n",
392 pwd->frame_len, bps, bps1,
393 high_freq, pwd->byte_offset_bits);
394 PARA_INFO_LOG("use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",
395 pwd->use_noise_coding, pwd->use_exp_vlc, pwd->nb_block_sizes);
396
397 compute_scale_factor_band_sizes(pwd, high_freq);
398 /* init MDCT windows : simple sinus window */
399 for (i = 0; i < pwd->nb_block_sizes; i++) {
400 int n;
401 n = 1 << (pwd->frame_len_bits - i);
402 sine_window_init(sine_windows[pwd->frame_len_bits - i - 7], n);
403 pwd->windows[i] = sine_windows[pwd->frame_len_bits - i - 7];
404 }
405
406 pwd->reset_block_lengths = 1;
407
408 if (pwd->use_noise_coding) {
409 /* init the noise generator */
410 if (pwd->use_exp_vlc)
411 pwd->noise_mult = 0.02;
412 else
413 pwd->noise_mult = 0.04;
414
415 {
416 unsigned int seed;
417 float norm;
418 seed = 1;
419 norm = (1.0 / (float) (1LL << 31)) * sqrt(3) * pwd->noise_mult;
420 for (i = 0; i < NOISE_TAB_SIZE; i++) {
421 seed = seed * 314159 + 1;
422 pwd->noise_table[i] = (float) ((int) seed) * norm;
423 }
424 }
425 }
426
427 /* choose the VLC tables for the coefficients */
428 coef_vlc_table = 2;
429 if (ahi->sample_rate >= 32000) {
430 if (bps1 < 0.72)
431 coef_vlc_table = 0;
432 else if (bps1 < 1.16)
433 coef_vlc_table = 1;
434 }
435 pwd->coef_vlcs[0] = &coef_vlcs[coef_vlc_table * 2];
436 pwd->coef_vlcs[1] = &coef_vlcs[coef_vlc_table * 2 + 1];
437 init_coef_vlc(&pwd->coef_vlc[0], &pwd->run_table[0], &pwd->level_table[0],
438 pwd->coef_vlcs[0]);
439 init_coef_vlc(&pwd->coef_vlc[1], &pwd->run_table[1], &pwd->level_table[1],
440 pwd->coef_vlcs[1]);
441 return 0;
442 }
443
444 static void wma_lsp_to_curve_init(struct private_wmadec_data *pwd, int frame_len)
445 {
446 float wdel, a, b;
447 int i, e, m;
448
449 wdel = M_PI / frame_len;
450 for (i = 0; i < frame_len; i++)
451 pwd->lsp_cos_table[i] = 2.0f * cos(wdel * i);
452
453 /* tables for x^-0.25 computation */
454 for (i = 0; i < 256; i++) {
455 e = i - 126;
456 pwd->lsp_pow_e_table[i] = pow(2.0, e * -0.25);
457 }
458
459 /* These two tables are needed to avoid two operations in pow_m1_4. */
460 b = 1.0;
461 for (i = (1 << LSP_POW_BITS) - 1; i >= 0; i--) {
462 m = (1 << LSP_POW_BITS) + i;
463 a = (float) m *(0.5 / (1 << LSP_POW_BITS));
464 a = pow(a, -0.25);
465 pwd->lsp_pow_m_table1[i] = 2 * a - b;
466 pwd->lsp_pow_m_table2[i] = b - a;
467 b = a;
468 }
469 }
470
471 static int wma_decode_init(char *initial_buf, int len, struct private_wmadec_data **result)
472 {
473 struct private_wmadec_data *pwd;
474 int ret, i;
475
476 PARA_NOTICE_LOG("initial buf: %d bytes\n", len);
477 pwd = para_calloc(sizeof(*pwd));
478 ret = read_asf_header(initial_buf, len, &pwd->ahi);
479 if (ret <= 0) {
480 free(pwd);
481 return ret;
482 }
483
484 pwd->use_exp_vlc = pwd->ahi.flags2 & 0x0001;
485 pwd->use_bit_reservoir = pwd->ahi.flags2 & 0x0002;
486 pwd->use_variable_block_len = pwd->ahi.flags2 & 0x0004;
487
488 ret = wma_init(pwd);
489 if (ret < 0)
490 return ret;
491 /* init MDCT */
492 for (i = 0; i < pwd->nb_block_sizes; i++) {
493 ret = imdct_init(pwd->frame_len_bits - i + 1, &pwd->mdct_ctx[i]);
494 if (ret < 0)
495 return ret;
496 }
497 if (pwd->use_noise_coding) {
498 PARA_INFO_LOG("using noise coding\n");
499 init_vlc(&pwd->hgain_vlc, HGAINVLCBITS,
500 sizeof(wma_hgain_huffbits), wma_hgain_huffbits,
501 wma_hgain_huffcodes, 2);
502 }
503
504 if (pwd->use_exp_vlc) {
505 PARA_INFO_LOG("using exp_vlc\n");
506 init_vlc(&pwd->exp_vlc, EXPVLCBITS,
507 sizeof(wma_scale_huffbits), wma_scale_huffbits,
508 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 mult1 = mult;
773 n1 = pwd->exponent_high_sizes[bsize];
774 /* compute power of high bands */
775 exponents = pwd->exponents[ch] +
776 (pwd->high_band_start[bsize] << bsize);
777 last_high_band = 0; /* avoid warning */
778 for (j = 0; j < n1; j++) {
779 n = pwd->exponent_high_bands[
780 pwd->frame_len_bits - pwd->block_len_bits][j];
781 if (pwd->high_band_coded[ch][j]) {
782 float e2, val;
783 e2 = 0;
784 for (i = 0; i < n; i++) {
785 val = exponents[i << bsize >> esize];
786 e2 += val * val;
787 }
788 exp_power[j] = e2 / n;
789 last_high_band = j;
790 }
791 exponents += n << bsize;
792 }
793 /* main freqs and high freqs */
794 exponents = pwd->exponents[ch];
795 for (j = -1; j < n1; j++) {
796 if (j < 0)
797 n = pwd->high_band_start[bsize];
798 else
799 n = pwd->exponent_high_bands[pwd->frame_len_bits
800 - pwd->block_len_bits][j];
801 if (j >= 0 && pwd->high_band_coded[ch][j]) {
802 /* use noise with specified power */
803 mult1 = sqrt(exp_power[j]
804 / exp_power[last_high_band]);
805 /* XXX: use a table */
806 mult1 = mult1 * pow(10,
807 pwd->high_band_values[ch][j] * 0.05);
808 mult1 /= (pwd->max_exponent[ch] * pwd->noise_mult);
809 mult1 *= mdct_norm;
810 for (i = 0; i < n; i++) {
811 noise = pwd->noise_table[pwd->noise_index];
812 pwd->noise_index = (pwd->noise_index + 1)
813 & (NOISE_TAB_SIZE - 1);
814 *coefs++ = noise * exponents[
815 i << bsize >> esize] * mult1;
816 }
817 exponents += n << bsize;
818 } else {
819 /* coded values + small noise */
820 for (i = 0; i < n; i++) {
821 noise = pwd->noise_table[pwd->noise_index];
822 pwd->noise_index = (pwd->noise_index + 1)
823 & (NOISE_TAB_SIZE - 1);
824 *coefs++ = ((*coefs1++) + noise) *
825 exponents[i << bsize >> esize]
826 * mult;
827 }
828 exponents += n << bsize;
829 }
830 }
831 /* very high freqs: noise */
832 n = pwd->block_len - pwd->coefs_end[bsize];
833 mult1 = mult * exponents[((-1 << bsize)) >> esize];
834 for (i = 0; i < n; i++) {
835 *coefs++ = pwd->noise_table[pwd->noise_index] * mult1;
836 pwd->noise_index = (pwd->noise_index + 1)
837 & (NOISE_TAB_SIZE - 1);
838 }
839 }
840 }
841
842 /**
843 * Returns 0 if OK, 1 if last block of frame, negative on uncorrectable
844 * errors.
845 */
846 static int wma_decode_block(struct private_wmadec_data *pwd)
847 {
848 int ret, n, v, ch, code, bsize;
849 int coef_nb_bits, total_gain;
850 int nb_coefs[MAX_CHANNELS];
851
852 /* compute current block length */
853 if (pwd->use_variable_block_len) {
854 n = wma_log2(pwd->nb_block_sizes - 1) + 1;
855
856 if (pwd->reset_block_lengths) {
857 pwd->reset_block_lengths = 0;
858 v = get_bits(&pwd->gb, n);
859 if (v >= pwd->nb_block_sizes)
860 return -E_WMA_BLOCK_SIZE;
861 pwd->prev_block_len_bits = pwd->frame_len_bits - v;
862 v = get_bits(&pwd->gb, n);
863 if (v >= pwd->nb_block_sizes)
864 return -E_WMA_BLOCK_SIZE;
865 pwd->block_len_bits = pwd->frame_len_bits - v;
866 } else {
867 /* update block lengths */
868 pwd->prev_block_len_bits = pwd->block_len_bits;
869 pwd->block_len_bits = pwd->next_block_len_bits;
870 }
871 v = get_bits(&pwd->gb, n);
872 if (v >= pwd->nb_block_sizes)
873 return -E_WMA_BLOCK_SIZE;
874 pwd->next_block_len_bits = pwd->frame_len_bits - v;
875 } else {
876 /* fixed block len */
877 pwd->next_block_len_bits = pwd->frame_len_bits;
878 pwd->prev_block_len_bits = pwd->frame_len_bits;
879 pwd->block_len_bits = pwd->frame_len_bits;
880 }
881
882 /* now check if the block length is coherent with the frame length */
883 pwd->block_len = 1 << pwd->block_len_bits;
884 if ((pwd->block_pos + pwd->block_len) > pwd->frame_len)
885 return -E_INCOHERENT_BLOCK_LEN;
886
887 if (pwd->ahi.channels == 2)
888 pwd->ms_stereo = get_bit(&pwd->gb);
889 v = 0;
890 for (ch = 0; ch < pwd->ahi.channels; ch++) {
891 int a = get_bit(&pwd->gb);
892 pwd->channel_coded[ch] = a;
893 v |= a;
894 }
895
896 bsize = pwd->frame_len_bits - pwd->block_len_bits;
897
898 /* if no channel coded, no need to go further */
899 /* XXX: fix potential framing problems */
900 if (!v)
901 goto next;
902
903 /*
904 * Read total gain and extract corresponding number of bits for coef
905 * escape coding.
906 */
907 total_gain = 1;
908 for (;;) {
909 int a = get_bits(&pwd->gb, 7);
910 total_gain += a;
911 if (a != 127)
912 break;
913 }
914
915 coef_nb_bits = wma_total_gain_to_bits(total_gain);
916
917 /* compute number of coefficients */
918 n = pwd->coefs_end[bsize];
919 for (ch = 0; ch < pwd->ahi.channels; ch++)
920 nb_coefs[ch] = n;
921
922 ret = compute_high_band_values(pwd, bsize, nb_coefs);
923 if (ret < 0)
924 return ret;
925
926 /* exponents can be reused in short blocks. */
927 if ((pwd->block_len_bits == pwd->frame_len_bits) || get_bit(&pwd->gb)) {
928 for (ch = 0; ch < pwd->ahi.channels; ch++) {
929 if (pwd->channel_coded[ch]) {
930 if (pwd->use_exp_vlc) {
931 ret = decode_exp_vlc(pwd, ch);
932 if (ret < 0)
933 return ret;
934 } else
935 decode_exp_lsp(pwd, ch);
936 pwd->exponents_bsize[ch] = bsize;
937 }
938 }
939 }
940
941 /* parse spectral coefficients : just RLE encoding */
942 for (ch = 0; ch < pwd->ahi.channels; ch++) {
943 struct vlc *coef_vlc;
944 int level, run, tindex;
945 int16_t *ptr, *eptr;
946 const uint16_t *level_table, *run_table;
947
948 if (!pwd->channel_coded[ch])
949 continue;
950 /*
951 * special VLC tables are used for ms stereo because there is
952 * potentially less energy there
953 */
954 tindex = (ch == 1 && pwd->ms_stereo);
955 coef_vlc = &pwd->coef_vlc[tindex];
956 run_table = pwd->run_table[tindex];
957 level_table = pwd->level_table[tindex];
958 /* XXX: optimize */
959 ptr = &pwd->coefs1[ch][0];
960 eptr = ptr + nb_coefs[ch];
961 memset(ptr, 0, pwd->block_len * sizeof(int16_t));
962 for (;;) {
963 code = get_vlc(&pwd->gb, coef_vlc->table,
964 VLCBITS, VLCMAX);
965 if (code < 0)
966 return code;
967 if (code == 1) /* EOB */
968 break;
969 if (code == 0) { /* escape */
970 level = get_bits(&pwd->gb, coef_nb_bits);
971 /* reading block_len_bits would be better */
972 run = get_bits(&pwd->gb, pwd->frame_len_bits);
973 } else { /* normal code */
974 run = run_table[code];
975 level = level_table[code];
976 }
977 if (!get_bit(&pwd->gb))
978 level = -level;
979 ptr += run;
980 if (ptr >= eptr) {
981 PARA_ERROR_LOG("overflow in spectral RLE, ignoring\n");
982 break;
983 }
984 *ptr++ = level;
985 if (ptr >= eptr) /* EOB can be omitted */
986 break;
987 }
988 }
989 compute_mdct_coefficients(pwd, bsize, total_gain, nb_coefs);
990 if (pwd->ms_stereo && pwd->channel_coded[1]) {
991 float a, b;
992 int i;
993 /*
994 * Nominal case for ms stereo: we do it before mdct.
995 *
996 * No need to optimize this case because it should almost never
997 * happen.
998 */
999 if (!pwd->channel_coded[0]) {
1000 PARA_NOTICE_LOG("rare ms-stereo\n");
1001 memset(pwd->coefs[0], 0, sizeof(float) * pwd->block_len);
1002 pwd->channel_coded[0] = 1;
1003 }
1004 for (i = 0; i < pwd->block_len; i++) {
1005 a = pwd->coefs[0][i];
1006 b = pwd->coefs[1][i];
1007 pwd->coefs[0][i] = a + b;
1008 pwd->coefs[1][i] = a - b;
1009 }
1010 }
1011 next:
1012 for (ch = 0; ch < pwd->ahi.channels; ch++) {
1013 int n4, idx;
1014
1015 n = pwd->block_len;
1016 n4 = pwd->block_len / 2;
1017 if (pwd->channel_coded[ch])
1018 imdct(pwd->mdct_ctx[bsize], pwd->output, pwd->coefs[ch]);
1019 else if (!(pwd->ms_stereo && ch == 1))
1020 memset(pwd->output, 0, sizeof(pwd->output));
1021
1022 /* multiply by the window and add in the frame */
1023 idx = (pwd->frame_len / 2) + pwd->block_pos - n4;
1024 wma_window(pwd, &pwd->frame_out[ch][idx]);
1025 }
1026
1027 /* update block number */
1028 pwd->block_pos += pwd->block_len;
1029 if (pwd->block_pos >= pwd->frame_len)
1030 return 1;
1031 else
1032 return 0;
1033 }
1034
1035 /*
1036 * Clip a signed integer value into the -32768,32767 range.
1037 *
1038 * \param a The value to clip.
1039 *
1040 * \return The clipped value.
1041 */
1042 static inline int16_t av_clip_int16(int a)
1043 {
1044 if ((a + 32768) & ~65535)
1045 return (a >> 31) ^ 32767;
1046 else
1047 return a;
1048 }
1049
1050 /* Decode a frame of frame_len samples. */
1051 static int wma_decode_frame(struct private_wmadec_data *pwd, int16_t *samples)
1052 {
1053 int ret, i, n, ch, incr;
1054 int16_t *ptr;
1055 float *iptr;
1056
1057 /* read each block */
1058 pwd->block_pos = 0;
1059 for (;;) {
1060 ret = wma_decode_block(pwd);
1061 if (ret < 0)
1062 return ret;
1063 if (ret)
1064 break;
1065 }
1066
1067 /* convert frame to integer */
1068 n = pwd->frame_len;
1069 incr = pwd->ahi.channels;
1070 for (ch = 0; ch < pwd->ahi.channels; ch++) {
1071 ptr = samples + ch;
1072 iptr = pwd->frame_out[ch];
1073
1074 for (i = 0; i < n; i++) {
1075 *ptr = av_clip_int16(lrintf(*iptr++));
1076 ptr += incr;
1077 }
1078 /* prepare for next block */
1079 memmove(&pwd->frame_out[ch][0], &pwd->frame_out[ch][pwd->frame_len],
1080 pwd->frame_len * sizeof(float));
1081 }
1082 return 0;
1083 }
1084
1085 static int wma_decode_superframe(struct private_wmadec_data *pwd, void *data,
1086 int *data_size, const uint8_t *buf, int buf_size)
1087 {
1088 int ret;
1089 int16_t *samples;
1090
1091 if (buf_size == 0) {
1092 pwd->last_superframe_len = 0;
1093 return 0;
1094 }
1095 if (buf_size < pwd->ahi.block_align)
1096 return 0;
1097 buf_size = pwd->ahi.block_align;
1098 samples = data;
1099 init_get_bits(&pwd->gb, buf, buf_size);
1100 if (pwd->use_bit_reservoir) {
1101 int i, nb_frames, bit_offset, pos, len;
1102 uint8_t *q;
1103
1104 /* read super frame header */
1105 skip_bits(&pwd->gb, 4); /* super frame index */
1106 nb_frames = get_bits(&pwd->gb, 4) - 1;
1107 // PARA_DEBUG_LOG("have %d frames\n", nb_frames);
1108 ret = -E_WMA_OUTPUT_SPACE;
1109 if ((nb_frames + 1) * pwd->ahi.channels * pwd->frame_len
1110 * sizeof(int16_t) > *data_size)
1111 goto fail;
1112
1113 bit_offset = get_bits(&pwd->gb, pwd->byte_offset_bits + 3);
1114
1115 if (pwd->last_superframe_len > 0) {
1116 /* add bit_offset bits to last frame */
1117 ret = -E_WMA_BAD_SUPERFRAME;
1118 if ((pwd->last_superframe_len + ((bit_offset + 7) >> 3)) >
1119 MAX_CODED_SUPERFRAME_SIZE)
1120 goto fail;
1121 q = pwd->last_superframe + pwd->last_superframe_len;
1122 len = bit_offset;
1123 while (len > 7) {
1124 *q++ = get_bits(&pwd->gb, 8);
1125 len -= 8;
1126 }
1127 if (len > 0)
1128 *q++ = get_bits(&pwd->gb, len) << (8 - len);
1129
1130 /* XXX: bit_offset bits into last frame */
1131 init_get_bits(&pwd->gb, pwd->last_superframe,
1132 MAX_CODED_SUPERFRAME_SIZE);
1133 /* skip unused bits */
1134 if (pwd->last_bitoffset > 0)
1135 skip_bits(&pwd->gb, pwd->last_bitoffset);
1136 /*
1137 * This frame is stored in the last superframe and in
1138 * the current one.
1139 */
1140 ret = wma_decode_frame(pwd, samples);
1141 if (ret < 0)
1142 goto fail;
1143 samples += pwd->ahi.channels * pwd->frame_len;
1144 }
1145
1146 /* read each frame starting from bit_offset */
1147 pos = bit_offset + 4 + 4 + pwd->byte_offset_bits + 3;
1148 init_get_bits(&pwd->gb, buf + (pos >> 3),
1149 (MAX_CODED_SUPERFRAME_SIZE - (pos >> 3)));
1150 len = pos & 7;
1151 if (len > 0)
1152 skip_bits(&pwd->gb, len);
1153
1154 pwd->reset_block_lengths = 1;
1155 for (i = 0; i < nb_frames; i++) {
1156 ret = wma_decode_frame(pwd, samples);
1157 if (ret < 0)
1158 goto fail;
1159 samples += pwd->ahi.channels * pwd->frame_len;
1160 }
1161
1162 /* we copy the end of the frame in the last frame buffer */
1163 pos = get_bits_count(&pwd->gb) +
1164 ((bit_offset + 4 + 4 + pwd->byte_offset_bits + 3) & ~7);
1165 pwd->last_bitoffset = pos & 7;
1166 pos >>= 3;
1167 len = buf_size - pos;
1168 ret = -E_WMA_BAD_SUPERFRAME;
1169 if (len > MAX_CODED_SUPERFRAME_SIZE || len < 0)
1170 goto fail;
1171 pwd->last_superframe_len = len;
1172 memcpy(pwd->last_superframe, buf + pos, len);
1173 } else {
1174 PARA_DEBUG_LOG("not using bit reservoir\n");
1175 ret = -E_WMA_OUTPUT_SPACE;
1176 if (pwd->ahi.channels * pwd->frame_len * sizeof(int16_t) > *data_size)
1177 goto fail;
1178 /* single frame decode */
1179 ret = wma_decode_frame(pwd, samples);
1180 if (ret < 0)
1181 goto fail;
1182 samples += pwd->ahi.channels * pwd->frame_len;
1183 }
1184 PARA_DEBUG_LOG("frame_len: %d, block_len: %d, outbytes: %d, eaten: %d\n",
1185 pwd->frame_len, pwd->block_len,
1186 (int)((int8_t *)samples - (int8_t *)data), pwd->ahi.block_align);
1187 *data_size = (int8_t *)samples - (int8_t *)data;
1188 return pwd->ahi.block_align;
1189 fail:
1190 /* reset the bit reservoir on errors */
1191 pwd->last_superframe_len = 0;
1192 return ret;
1193 }
1194
1195 static void wmadec_close(struct filter_node *fn)
1196 {
1197 struct private_wmadec_data *pwd = fn->private_data;
1198
1199 if (!pwd)
1200 return;
1201 wmadec_cleanup(pwd);
1202 free(fn->private_data);
1203 fn->private_data = NULL;
1204 }
1205
1206 static int wmadec_execute(struct btr_node *btrn, const char *cmd, char **result)
1207 {
1208 struct filter_node *fn = btr_context(btrn);
1209 struct private_wmadec_data *pwd = fn->private_data;
1210
1211 return decoder_execute(cmd, pwd->ahi.sample_rate, pwd->ahi.channels,
1212 result);
1213 }
1214
1215 #define WMA_OUTPUT_BUFFER_SIZE (128 * 1024)
1216
1217 static void wmadec_post_select(__a_unused struct sched *s, struct task *t)
1218 {
1219 struct filter_node *fn = container_of(t, struct filter_node, task);
1220 int ret, converted;
1221 struct private_wmadec_data *pwd = fn->private_data;
1222 struct btr_node *btrn = fn->btrn;
1223 size_t len;
1224 char *in;
1225
1226 next_buffer:
1227 converted = 0;
1228 t->error = 0;
1229 ret = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
1230 if (ret < 0)
1231 goto err;
1232 if (ret == 0)
1233 return;
1234 btr_merge(btrn, fn->min_iqs);
1235 len = btr_next_buffer(btrn, (char **)&in);
1236 ret = -E_WMADEC_EOF;
1237 if (len < fn->min_iqs)
1238 goto err;
1239 if (!pwd) {
1240 ret = wma_decode_init(in, len, &pwd);
1241 if (ret < 0)
1242 goto err;
1243 if (ret == 0) {
1244 fn->min_iqs += 4096;
1245 goto next_buffer;
1246 }
1247 fn->min_iqs = 2 * (WMA_FRAME_SKIP + pwd->ahi.block_align);
1248 fn->private_data = pwd;
1249 converted = pwd->ahi.header_len;
1250 goto success;
1251 }
1252 fn->min_iqs = WMA_FRAME_SKIP + pwd->ahi.block_align;
1253 for (;;) {
1254 char *out;
1255 int out_size = WMA_OUTPUT_BUFFER_SIZE;
1256 if (converted + fn->min_iqs > len)
1257 break;
1258 out = para_malloc(WMA_OUTPUT_BUFFER_SIZE);
1259 ret = wma_decode_superframe(pwd, out,
1260 &out_size, (uint8_t *)in + converted + WMA_FRAME_SKIP,
1261 len - WMA_FRAME_SKIP);
1262 if (ret < 0) {
1263 free(out);
1264 goto err;
1265 }
1266 btr_add_output(out, out_size, btrn);
1267 converted += ret + WMA_FRAME_SKIP;
1268 }
1269 success:
1270 btr_consume(btrn, converted);
1271 return;
1272 err:
1273 assert(ret < 0);
1274 t->error = ret;
1275 btr_remove_node(btrn);
1276 }
1277
1278 static void wmadec_open(struct filter_node *fn)
1279 {
1280 fn->private_data = NULL;
1281 fn->min_iqs = 4096;
1282 }
1283
1284 /**
1285 * The init function of the wma decoder.
1286 *
1287 * \param f Its fields are filled in by the function.
1288 */
1289 void wmadec_filter_init(struct filter *f)
1290 {
1291 f->open = wmadec_open;
1292 f->close = wmadec_close;
1293 f->execute = wmadec_execute;
1294 f->pre_select = generic_filter_pre_select;
1295 f->post_select = wmadec_post_select;
1296 }