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