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