]> git.sesse.net Git - ffmpeg/blob - libavcodec/binkaudio.c
915e7aa1717ef3024f3de3a3c7707a76f05d8005
[ffmpeg] / 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     FmtConvertContext fmt_conv;
51     int version_b;          ///< Bink version 'b'
52     int first;
53     int channels;
54     int frame_len;          ///< transform size (samples)
55     int overlap_len;        ///< overlap size (samples)
56     int block_size;
57     int num_bands;
58     unsigned int *bands;
59     float root;
60     DECLARE_ALIGNED(32, FFTSample, coeffs)[BINK_BLOCK_MAX_SIZE];
61     DECLARE_ALIGNED(16, int16_t, previous)[BINK_BLOCK_MAX_SIZE / 16];  ///< coeffs from previous audio block
62     DECLARE_ALIGNED(16, int16_t, current)[BINK_BLOCK_MAX_SIZE / 16];
63     float *coeffs_ptr[MAX_CHANNELS]; ///< pointers to the coeffs arrays for float_to_int16_interleave
64     float *prev_ptr[MAX_CHANNELS];   ///< pointers to the overlap points in the coeffs array
65     uint8_t *packet_buffer;
66     union {
67         RDFTContext rdft;
68         DCTContext dct;
69     } trans;
70 } BinkAudioContext;
71
72
73 static av_cold int decode_init(AVCodecContext *avctx)
74 {
75     BinkAudioContext *s = avctx->priv_data;
76     int sample_rate = avctx->sample_rate;
77     int sample_rate_half;
78     int i;
79     int frame_len_bits;
80
81     ff_fmt_convert_init(&s->fmt_conv, avctx);
82
83     /* determine frame length */
84     if (avctx->sample_rate < 22050) {
85         frame_len_bits = 9;
86     } else if (avctx->sample_rate < 44100) {
87         frame_len_bits = 10;
88     } else {
89         frame_len_bits = 11;
90     }
91
92     if (avctx->channels > MAX_CHANNELS) {
93         av_log(avctx, AV_LOG_ERROR, "too many channels: %d\n", avctx->channels);
94         return -1;
95     }
96
97     s->version_b = avctx->extradata && avctx->extradata[3] == 'b';
98
99     if (avctx->codec->id == AV_CODEC_ID_BINKAUDIO_RDFT) {
100         // audio is already interleaved for the RDFT format variant
101         sample_rate  *= avctx->channels;
102         s->channels = 1;
103         if (!s->version_b)
104             frame_len_bits += av_log2(avctx->channels);
105     } else {
106         s->channels = avctx->channels;
107     }
108
109     s->frame_len     = 1 << frame_len_bits;
110     s->overlap_len   = s->frame_len / 16;
111     s->block_size    = (s->frame_len - s->overlap_len) * s->channels;
112     sample_rate_half = (sample_rate + 1) / 2;
113     if (avctx->codec->id == AV_CODEC_ID_BINKAUDIO_RDFT)
114         s->root = 2.0 / sqrt(s->frame_len);
115     else
116         s->root = s->frame_len / sqrt(s->frame_len);
117     for (i = 0; i < 96; i++) {
118         /* constant is result of 0.066399999/log10(M_E) */
119         quant_table[i] = expf(i * 0.15289164787221953823f) * s->root;
120     }
121
122     /* calculate number of bands */
123     for (s->num_bands = 1; s->num_bands < 25; s->num_bands++)
124         if (sample_rate_half <= ff_wma_critical_freqs[s->num_bands - 1])
125             break;
126
127     s->bands = av_malloc((s->num_bands + 1) * sizeof(*s->bands));
128     if (!s->bands)
129         return AVERROR(ENOMEM);
130
131     /* populate bands data */
132     s->bands[0] = 2;
133     for (i = 1; i < s->num_bands; i++)
134         s->bands[i] = (ff_wma_critical_freqs[i - 1] * s->frame_len / sample_rate_half) & ~1;
135     s->bands[s->num_bands] = s->frame_len;
136
137     s->first = 1;
138     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
139
140     for (i = 0; i < s->channels; i++) {
141         s->coeffs_ptr[i] = s->coeffs + i * s->frame_len;
142         s->prev_ptr[i]   = s->coeffs_ptr[i] + s->frame_len - s->overlap_len;
143     }
144
145     if (CONFIG_BINKAUDIO_RDFT_DECODER && avctx->codec->id == AV_CODEC_ID_BINKAUDIO_RDFT)
146         ff_rdft_init(&s->trans.rdft, frame_len_bits, DFT_C2R);
147     else if (CONFIG_BINKAUDIO_DCT_DECODER)
148         ff_dct_init(&s->trans.dct, frame_len_bits, DCT_III);
149     else
150         return -1;
151
152     avcodec_get_frame_defaults(&s->frame);
153     avctx->coded_frame = &s->frame;
154
155     return 0;
156 }
157
158 static float get_float(GetBitContext *gb)
159 {
160     int power = get_bits(gb, 5);
161     float f = ldexpf(get_bits_long(gb, 23), power - 23);
162     if (get_bits1(gb))
163         f = -f;
164     return f;
165 }
166
167 static const uint8_t rle_length_tab[16] = {
168     2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 64
169 };
170
171 #define GET_BITS_SAFE(out, nbits) do {  \
172     if (get_bits_left(gb) < nbits)      \
173         return AVERROR_INVALIDDATA;     \
174     out = get_bits(gb, nbits);          \
175 } while (0)
176
177 /**
178  * Decode Bink Audio block
179  * @param[out] out Output buffer (must contain s->block_size elements)
180  * @return 0 on success, negative error code on failure
181  */
182 static int decode_block(BinkAudioContext *s, int16_t *out, int use_dct)
183 {
184     int ch, i, j, k;
185     float q, quant[25];
186     int width, coeff;
187     GetBitContext *gb = &s->gb;
188
189     if (use_dct)
190         skip_bits(gb, 2);
191
192     for (ch = 0; ch < s->channels; ch++) {
193         FFTSample *coeffs = s->coeffs_ptr[ch];
194         if (s->version_b) {
195             if (get_bits_left(gb) < 64)
196                 return AVERROR_INVALIDDATA;
197             coeffs[0] = av_int2float(get_bits_long(gb, 32)) * s->root;
198             coeffs[1] = av_int2float(get_bits_long(gb, 32)) * s->root;
199         } else {
200             if (get_bits_left(gb) < 58)
201                 return AVERROR_INVALIDDATA;
202             coeffs[0] = get_float(gb) * s->root;
203             coeffs[1] = get_float(gb) * s->root;
204         }
205
206         if (get_bits_left(gb) < s->num_bands * 8)
207             return AVERROR_INVALIDDATA;
208         for (i = 0; i < s->num_bands; i++) {
209             int value = get_bits(gb, 8);
210             quant[i]  = quant_table[FFMIN(value, 95)];
211         }
212
213         k = 0;
214         q = quant[0];
215
216         // parse coefficients
217         i = 2;
218         while (i < s->frame_len) {
219             if (s->version_b) {
220                 j = i + 16;
221             } else {
222                 int v;
223                 GET_BITS_SAFE(v, 1);
224                 if (v) {
225                     GET_BITS_SAFE(v, 4);
226                     j = i + rle_length_tab[v] * 8;
227                 } else {
228                     j = i + 8;
229                 }
230             }
231
232             j = FFMIN(j, s->frame_len);
233
234             GET_BITS_SAFE(width, 4);
235             if (width == 0) {
236                 memset(coeffs + i, 0, (j - i) * sizeof(*coeffs));
237                 i = j;
238                 while (s->bands[k] < i)
239                     q = quant[k++];
240             } else {
241                 while (i < j) {
242                     if (s->bands[k] == i)
243                         q = quant[k++];
244                     GET_BITS_SAFE(coeff, width);
245                     if (coeff) {
246                         int v;
247                         GET_BITS_SAFE(v, 1);
248                         if (v)
249                             coeffs[i] = -q * coeff;
250                         else
251                             coeffs[i] =  q * coeff;
252                     } else {
253                         coeffs[i] = 0.0f;
254                     }
255                     i++;
256                 }
257             }
258         }
259
260         if (CONFIG_BINKAUDIO_DCT_DECODER && use_dct) {
261             coeffs[0] /= 0.5;
262             s->trans.dct.dct_calc(&s->trans.dct,  coeffs);
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 == AV_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 == AV_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             = AV_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             = AV_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 };