18bb87b95e627be995eef459893c37cbc2ca65bb
[libav.git] / libavcodec / binkaudio.c
1 /*
2 * Bink Audio decoder
3 * Copyright (c) 2007-2011 Peter Ross (pross@xvid.org)
4 * Copyright (c) 2009 Daniel Verkamp (daniel@drv.nu)
5 *
6 * This file is part of Libav.
7 *
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 /**
24 * @file
25 * Bink Audio decoder
26 *
27 * Technical details here:
28 * http://wiki.multimedia.cx/index.php?title=Bink_Audio
29 */
30
31 #include "avcodec.h"
32 #define BITSTREAM_READER_LE
33 #include "get_bits.h"
34 #include "dsputil.h"
35 #include "dct.h"
36 #include "rdft.h"
37 #include "fmtconvert.h"
38 #include "libavutil/intfloat.h"
39
40 extern const uint16_t ff_wma_critical_freqs[25];
41
42 static float quant_table[96];
43
44 #define MAX_CHANNELS 2
45 #define BINK_BLOCK_MAX_SIZE (MAX_CHANNELS << 11)
46
47 typedef struct {
48 AVFrame frame;
49 GetBitContext gb;
50 DSPContext dsp;
51 FmtConvertContext fmt_conv;
52 int version_b; ///< Bink version 'b'
53 int first;
54 int channels;
55 int frame_len; ///< transform size (samples)
56 int overlap_len; ///< overlap size (samples)
57 int block_size;
58 int num_bands;
59 unsigned int *bands;
60 float root;
61 DECLARE_ALIGNED(32, FFTSample, coeffs)[BINK_BLOCK_MAX_SIZE];
62 DECLARE_ALIGNED(16, int16_t, previous)[BINK_BLOCK_MAX_SIZE / 16]; ///< coeffs from previous audio block
63 DECLARE_ALIGNED(16, int16_t, current)[BINK_BLOCK_MAX_SIZE / 16];
64 float *coeffs_ptr[MAX_CHANNELS]; ///< pointers to the coeffs arrays for float_to_int16_interleave
65 float *prev_ptr[MAX_CHANNELS]; ///< pointers to the overlap points in the coeffs array
66 uint8_t *packet_buffer;
67 union {
68 RDFTContext rdft;
69 DCTContext dct;
70 } trans;
71 } BinkAudioContext;
72
73
74 static av_cold int decode_init(AVCodecContext *avctx)
75 {
76 BinkAudioContext *s = avctx->priv_data;
77 int sample_rate = avctx->sample_rate;
78 int sample_rate_half;
79 int i;
80 int frame_len_bits;
81
82 ff_dsputil_init(&s->dsp, avctx);
83 ff_fmt_convert_init(&s->fmt_conv, avctx);
84
85 /* determine frame length */
86 if (avctx->sample_rate < 22050) {
87 frame_len_bits = 9;
88 } else if (avctx->sample_rate < 44100) {
89 frame_len_bits = 10;
90 } else {
91 frame_len_bits = 11;
92 }
93
94 if (avctx->channels > MAX_CHANNELS) {
95 av_log(avctx, AV_LOG_ERROR, "too many channels: %d\n", avctx->channels);
96 return -1;
97 }
98
99 s->version_b = avctx->extradata && avctx->extradata[3] == 'b';
100
101 if (avctx->codec->id == CODEC_ID_BINKAUDIO_RDFT) {
102 // audio is already interleaved for the RDFT format variant
103 sample_rate *= avctx->channels;
104 s->channels = 1;
105 if (!s->version_b)
106 frame_len_bits += av_log2(avctx->channels);
107 } else {
108 s->channels = avctx->channels;
109 }
110
111 s->frame_len = 1 << frame_len_bits;
112 s->overlap_len = s->frame_len / 16;
113 s->block_size = (s->frame_len - s->overlap_len) * s->channels;
114 sample_rate_half = (sample_rate + 1) / 2;
115 s->root = 2.0 / sqrt(s->frame_len);
116 for (i = 0; i < 96; i++) {
117 /* constant is result of 0.066399999/log10(M_E) */
118 quant_table[i] = expf(i * 0.15289164787221953823f) * s->root;
119 }
120
121 /* calculate number of bands */
122 for (s->num_bands = 1; s->num_bands < 25; s->num_bands++)
123 if (sample_rate_half <= ff_wma_critical_freqs[s->num_bands - 1])
124 break;
125
126 s->bands = av_malloc((s->num_bands + 1) * sizeof(*s->bands));
127 if (!s->bands)
128 return AVERROR(ENOMEM);
129
130 /* populate bands data */
131 s->bands[0] = 2;
132 for (i = 1; i < s->num_bands; i++)
133 s->bands[i] = (ff_wma_critical_freqs[i - 1] * s->frame_len / sample_rate_half) & ~1;
134 s->bands[s->num_bands] = s->frame_len;
135
136 s->first = 1;
137 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
138
139 for (i = 0; i < s->channels; i++) {
140 s->coeffs_ptr[i] = s->coeffs + i * s->frame_len;
141 s->prev_ptr[i] = s->coeffs_ptr[i] + s->frame_len - s->overlap_len;
142 }
143
144 if (CONFIG_BINKAUDIO_RDFT_DECODER && avctx->codec->id == CODEC_ID_BINKAUDIO_RDFT)
145 ff_rdft_init(&s->trans.rdft, frame_len_bits, DFT_C2R);
146 else if (CONFIG_BINKAUDIO_DCT_DECODER)
147 ff_dct_init(&s->trans.dct, frame_len_bits, DCT_III);
148 else
149 return -1;
150
151 avcodec_get_frame_defaults(&s->frame);
152 avctx->coded_frame = &s->frame;
153
154 return 0;
155 }
156
157 static float get_float(GetBitContext *gb)
158 {
159 int power = get_bits(gb, 5);
160 float f = ldexpf(get_bits_long(gb, 23), power - 23);
161 if (get_bits1(gb))
162 f = -f;
163 return f;
164 }
165
166 static const uint8_t rle_length_tab[16] = {
167 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 64
168 };
169
170 #define GET_BITS_SAFE(out, nbits) do { \
171 if (get_bits_left(gb) < nbits) \
172 return AVERROR_INVALIDDATA; \
173 out = get_bits(gb, nbits); \
174 } while (0)
175
176 /**
177 * Decode Bink Audio block
178 * @param[out] out Output buffer (must contain s->block_size elements)
179 * @return 0 on success, negative error code on failure
180 */
181 static int decode_block(BinkAudioContext *s, int16_t *out, int use_dct)
182 {
183 int ch, i, j, k;
184 float q, quant[25];
185 int width, coeff;
186 GetBitContext *gb = &s->gb;
187
188 if (use_dct)
189 skip_bits(gb, 2);
190
191 for (ch = 0; ch < s->channels; ch++) {
192 FFTSample *coeffs = s->coeffs_ptr[ch];
193 if (s->version_b) {
194 if (get_bits_left(gb) < 64)
195 return AVERROR_INVALIDDATA;
196 coeffs[0] = av_int2float(get_bits_long(gb, 32)) * s->root;
197 coeffs[1] = av_int2float(get_bits_long(gb, 32)) * s->root;
198 } else {
199 if (get_bits_left(gb) < 58)
200 return AVERROR_INVALIDDATA;
201 coeffs[0] = get_float(gb) * s->root;
202 coeffs[1] = get_float(gb) * s->root;
203 }
204
205 if (get_bits_left(gb) < s->num_bands * 8)
206 return AVERROR_INVALIDDATA;
207 for (i = 0; i < s->num_bands; i++) {
208 int value = get_bits(gb, 8);
209 quant[i] = quant_table[FFMIN(value, 95)];
210 }
211
212 k = 0;
213 q = quant[0];
214
215 // parse coefficients
216 i = 2;
217 while (i < s->frame_len) {
218 if (s->version_b) {
219 j = i + 16;
220 } else {
221 int v;
222 GET_BITS_SAFE(v, 1);
223 if (v) {
224 GET_BITS_SAFE(v, 4);
225 j = i + rle_length_tab[v] * 8;
226 } else {
227 j = i + 8;
228 }
229 }
230
231 j = FFMIN(j, s->frame_len);
232
233 GET_BITS_SAFE(width, 4);
234 if (width == 0) {
235 memset(coeffs + i, 0, (j - i) * sizeof(*coeffs));
236 i = j;
237 while (s->bands[k] < i)
238 q = quant[k++];
239 } else {
240 while (i < j) {
241 if (s->bands[k] == i)
242 q = quant[k++];
243 GET_BITS_SAFE(coeff, width);
244 if (coeff) {
245 int v;
246 GET_BITS_SAFE(v, 1);
247 if (v)
248 coeffs[i] = -q * coeff;
249 else
250 coeffs[i] = q * coeff;
251 } else {
252 coeffs[i] = 0.0f;
253 }
254 i++;
255 }
256 }
257 }
258
259 if (CONFIG_BINKAUDIO_DCT_DECODER && use_dct) {
260 coeffs[0] /= 0.5;
261 s->trans.dct.dct_calc(&s->trans.dct, coeffs);
262 s->dsp.vector_fmul_scalar(coeffs, coeffs, s->frame_len / 2, s->frame_len);
263 }
264 else if (CONFIG_BINKAUDIO_RDFT_DECODER)
265 s->trans.rdft.rdft_calc(&s->trans.rdft, coeffs);
266 }
267
268 s->fmt_conv.float_to_int16_interleave(s->current,
269 (const float **)s->prev_ptr,
270 s->overlap_len, s->channels);
271 s->fmt_conv.float_to_int16_interleave(out, (const float **)s->coeffs_ptr,
272 s->frame_len - s->overlap_len,
273 s->channels);
274
275 if (!s->first) {
276 int count = s->overlap_len * s->channels;
277 int shift = av_log2(count);
278 for (i = 0; i < count; i++) {
279 out[i] = (s->previous[i] * (count - i) + out[i] * i) >> shift;
280 }
281 }
282
283 memcpy(s->previous, s->current,
284 s->overlap_len * s->channels * sizeof(*s->previous));
285
286 s->first = 0;
287
288 return 0;
289 }
290
291 static av_cold int decode_end(AVCodecContext *avctx)
292 {
293 BinkAudioContext * s = avctx->priv_data;
294 av_freep(&s->bands);
295 av_freep(&s->packet_buffer);
296 if (CONFIG_BINKAUDIO_RDFT_DECODER && avctx->codec->id == CODEC_ID_BINKAUDIO_RDFT)
297 ff_rdft_end(&s->trans.rdft);
298 else if (CONFIG_BINKAUDIO_DCT_DECODER)
299 ff_dct_end(&s->trans.dct);
300
301 return 0;
302 }
303
304 static void get_bits_align32(GetBitContext *s)
305 {
306 int n = (-get_bits_count(s)) & 31;
307 if (n) skip_bits(s, n);
308 }
309
310 static int decode_frame(AVCodecContext *avctx, void *data,
311 int *got_frame_ptr, AVPacket *avpkt)
312 {
313 BinkAudioContext *s = avctx->priv_data;
314 int16_t *samples;
315 GetBitContext *gb = &s->gb;
316 int ret, consumed = 0;
317
318 if (!get_bits_left(gb)) {
319 uint8_t *buf;
320 /* handle end-of-stream */
321 if (!avpkt->size) {
322 *got_frame_ptr = 0;
323 return 0;
324 }
325 if (avpkt->size < 4) {
326 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
327 return AVERROR_INVALIDDATA;
328 }
329 buf = av_realloc(s->packet_buffer, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
330 if (!buf)
331 return AVERROR(ENOMEM);
332 s->packet_buffer = buf;
333 memcpy(s->packet_buffer, avpkt->data, avpkt->size);
334 init_get_bits(gb, s->packet_buffer, avpkt->size * 8);
335 consumed = avpkt->size;
336
337 /* skip reported size */
338 skip_bits_long(gb, 32);
339 }
340
341 /* get output buffer */
342 s->frame.nb_samples = s->block_size / avctx->channels;
343 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
344 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
345 return ret;
346 }
347 samples = (int16_t *)s->frame.data[0];
348
349 if (decode_block(s, samples, avctx->codec->id == CODEC_ID_BINKAUDIO_DCT)) {
350 av_log(avctx, AV_LOG_ERROR, "Incomplete packet\n");
351 return AVERROR_INVALIDDATA;
352 }
353 get_bits_align32(gb);
354
355 *got_frame_ptr = 1;
356 *(AVFrame *)data = s->frame;
357
358 return consumed;
359 }
360
361 AVCodec ff_binkaudio_rdft_decoder = {
362 .name = "binkaudio_rdft",
363 .type = AVMEDIA_TYPE_AUDIO,
364 .id = CODEC_ID_BINKAUDIO_RDFT,
365 .priv_data_size = sizeof(BinkAudioContext),
366 .init = decode_init,
367 .close = decode_end,
368 .decode = decode_frame,
369 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
370 .long_name = NULL_IF_CONFIG_SMALL("Bink Audio (RDFT)")
371 };
372
373 AVCodec ff_binkaudio_dct_decoder = {
374 .name = "binkaudio_dct",
375 .type = AVMEDIA_TYPE_AUDIO,
376 .id = CODEC_ID_BINKAUDIO_DCT,
377 .priv_data_size = sizeof(BinkAudioContext),
378 .init = decode_init,
379 .close = decode_end,
380 .decode = decode_frame,
381 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
382 .long_name = NULL_IF_CONFIG_SMALL("Bink Audio (DCT)")
383 };