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