]> git.sesse.net Git - ffmpeg/blob - libavcodec/binkaudio.c
binkaudio: add some buffer overread checks.
[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 ALT_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_readwrite.h"
39
40 extern const uint16_t ff_wma_critical_freqs[25];
41
42 #define MAX_CHANNELS 2
43 #define BINK_BLOCK_MAX_SIZE (MAX_CHANNELS << 11)
44
45 typedef struct {
46     GetBitContext gb;
47     DSPContext dsp;
48     FmtConvertContext fmt_conv;
49     int version_b;          ///< Bink version 'b'
50     int first;
51     int channels;
52     int frame_len;          ///< transform size (samples)
53     int overlap_len;        ///< overlap size (samples)
54     int block_size;
55     int num_bands;
56     unsigned int *bands;
57     float root;
58     DECLARE_ALIGNED(32, FFTSample, coeffs)[BINK_BLOCK_MAX_SIZE];
59     DECLARE_ALIGNED(16, short, previous)[BINK_BLOCK_MAX_SIZE / 16];  ///< coeffs from previous audio block
60     float *coeffs_ptr[MAX_CHANNELS]; ///< pointers to the coeffs arrays for float_to_int16_interleave
61     union {
62         RDFTContext rdft;
63         DCTContext dct;
64     } trans;
65 } BinkAudioContext;
66
67
68 static av_cold int decode_init(AVCodecContext *avctx)
69 {
70     BinkAudioContext *s = avctx->priv_data;
71     int sample_rate = avctx->sample_rate;
72     int sample_rate_half;
73     int i;
74     int frame_len_bits;
75
76     dsputil_init(&s->dsp, avctx);
77     ff_fmt_convert_init(&s->fmt_conv, avctx);
78
79     /* determine frame length */
80     if (avctx->sample_rate < 22050) {
81         frame_len_bits = 9;
82     } else if (avctx->sample_rate < 44100) {
83         frame_len_bits = 10;
84     } else {
85         frame_len_bits = 11;
86     }
87
88     if (avctx->channels > MAX_CHANNELS) {
89         av_log(avctx, AV_LOG_ERROR, "too many channels: %d\n", avctx->channels);
90         return -1;
91     }
92
93     s->version_b = avctx->extradata && avctx->extradata[3] == 'b';
94
95     if (avctx->codec->id == CODEC_ID_BINKAUDIO_RDFT) {
96         // audio is already interleaved for the RDFT format variant
97         sample_rate  *= avctx->channels;
98         s->channels = 1;
99         if (!s->version_b)
100             frame_len_bits += av_log2(avctx->channels);
101     } else {
102         s->channels = avctx->channels;
103     }
104
105     s->frame_len     = 1 << frame_len_bits;
106     s->overlap_len   = s->frame_len / 16;
107     s->block_size    = (s->frame_len - s->overlap_len) * s->channels;
108     sample_rate_half = (sample_rate + 1) / 2;
109     s->root          = 2.0 / sqrt(s->frame_len);
110
111     /* calculate number of bands */
112     for (s->num_bands = 1; s->num_bands < 25; s->num_bands++)
113         if (sample_rate_half <= ff_wma_critical_freqs[s->num_bands - 1])
114             break;
115
116     s->bands = av_malloc((s->num_bands + 1) * sizeof(*s->bands));
117     if (!s->bands)
118         return AVERROR(ENOMEM);
119
120     /* populate bands data */
121     s->bands[0] = 2;
122     for (i = 1; i < s->num_bands; i++)
123         s->bands[i] = (ff_wma_critical_freqs[i - 1] * s->frame_len / sample_rate_half) & ~1;
124     s->bands[s->num_bands] = s->frame_len;
125
126     s->first = 1;
127     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
128
129     for (i = 0; i < s->channels; i++)
130         s->coeffs_ptr[i] = s->coeffs + i * s->frame_len;
131
132     if (CONFIG_BINKAUDIO_RDFT_DECODER && avctx->codec->id == CODEC_ID_BINKAUDIO_RDFT)
133         ff_rdft_init(&s->trans.rdft, frame_len_bits, DFT_C2R);
134     else if (CONFIG_BINKAUDIO_DCT_DECODER)
135         ff_dct_init(&s->trans.dct, frame_len_bits, DCT_III);
136     else
137         return -1;
138
139     return 0;
140 }
141
142 static float get_float(GetBitContext *gb)
143 {
144     int power = get_bits(gb, 5);
145     float f = ldexpf(get_bits_long(gb, 23), power - 23);
146     if (get_bits1(gb))
147         f = -f;
148     return f;
149 }
150
151 static const uint8_t rle_length_tab[16] = {
152     2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 64
153 };
154
155 #define GET_BITS_SAFE(out, nbits) do {  \
156     if (get_bits_left(gb) < nbits)      \
157         return AVERROR_INVALIDDATA;     \
158     out = get_bits(gb, nbits);          \
159 } while (0)
160
161 /**
162  * Decode Bink Audio block
163  * @param[out] out Output buffer (must contain s->block_size elements)
164  * @return 0 on success, negative error code on failure
165  */
166 static int decode_block(BinkAudioContext *s, short *out, int use_dct)
167 {
168     int ch, i, j, k;
169     float q, quant[25];
170     int width, coeff;
171     GetBitContext *gb = &s->gb;
172
173     if (use_dct)
174         skip_bits(gb, 2);
175
176     for (ch = 0; ch < s->channels; ch++) {
177         FFTSample *coeffs = s->coeffs_ptr[ch];
178         if (s->version_b) {
179             if (get_bits_left(gb) < 64)
180                 return AVERROR_INVALIDDATA;
181             coeffs[0] = av_int2flt(get_bits(gb, 32)) * s->root;
182             coeffs[1] = av_int2flt(get_bits(gb, 32)) * s->root;
183         } else {
184             if (get_bits_left(gb) < 58)
185                 return AVERROR_INVALIDDATA;
186             coeffs[0] = get_float(gb) * s->root;
187             coeffs[1] = get_float(gb) * s->root;
188         }
189
190         if (get_bits_left(gb) < s->num_bands * 8)
191             return AVERROR_INVALIDDATA;
192         for (i = 0; i < s->num_bands; i++) {
193             /* constant is result of 0.066399999/log10(M_E) */
194             int value = get_bits(gb, 8);
195             quant[i] = expf(FFMIN(value, 95) * 0.15289164787221953823f) * s->root;
196         }
197
198         k = 0;
199         q = quant[0];
200
201         // parse coefficients
202         i = 2;
203         while (i < s->frame_len) {
204             if (s->version_b) {
205                 j = i + 16;
206             } else {
207                 int v;
208                 GET_BITS_SAFE(v, 1);
209                 if (v) {
210                     GET_BITS_SAFE(v, 4);
211                     j = i + rle_length_tab[v] * 8;
212                 } else {
213                     j = i + 8;
214                 }
215             }
216
217             j = FFMIN(j, s->frame_len);
218
219             GET_BITS_SAFE(width, 4);
220             if (width == 0) {
221                 memset(coeffs + i, 0, (j - i) * sizeof(*coeffs));
222                 i = j;
223                 while (s->bands[k] < i)
224                     q = quant[k++];
225             } else {
226                 while (i < j) {
227                     if (s->bands[k] == i)
228                         q = quant[k++];
229                     GET_BITS_SAFE(coeff, width);
230                     if (coeff) {
231                         int v;
232                         GET_BITS_SAFE(v, 1);
233                         if (v)
234                             coeffs[i] = -q * coeff;
235                         else
236                             coeffs[i] =  q * coeff;
237                     } else {
238                         coeffs[i] = 0.0f;
239                     }
240                     i++;
241                 }
242             }
243         }
244
245         if (CONFIG_BINKAUDIO_DCT_DECODER && use_dct) {
246             coeffs[0] /= 0.5;
247             s->trans.dct.dct_calc(&s->trans.dct,  coeffs);
248             s->dsp.vector_fmul_scalar(coeffs, coeffs, s->frame_len / 2, s->frame_len);
249         }
250         else if (CONFIG_BINKAUDIO_RDFT_DECODER)
251             s->trans.rdft.rdft_calc(&s->trans.rdft, coeffs);
252     }
253
254     s->fmt_conv.float_to_int16_interleave(out, (const float **)s->coeffs_ptr,
255                                           s->frame_len, s->channels);
256
257     if (!s->first) {
258         int count = s->overlap_len * s->channels;
259         int shift = av_log2(count);
260         for (i = 0; i < count; i++) {
261             out[i] = (s->previous[i] * (count - i) + out[i] * i) >> shift;
262         }
263     }
264
265     memcpy(s->previous, out + s->block_size,
266            s->overlap_len * s->channels * sizeof(*out));
267
268     s->first = 0;
269
270     return 0;
271 }
272
273 static av_cold int decode_end(AVCodecContext *avctx)
274 {
275     BinkAudioContext * s = avctx->priv_data;
276     av_freep(&s->bands);
277     if (CONFIG_BINKAUDIO_RDFT_DECODER && avctx->codec->id == CODEC_ID_BINKAUDIO_RDFT)
278         ff_rdft_end(&s->trans.rdft);
279     else if (CONFIG_BINKAUDIO_DCT_DECODER)
280         ff_dct_end(&s->trans.dct);
281     return 0;
282 }
283
284 static void get_bits_align32(GetBitContext *s)
285 {
286     int n = (-get_bits_count(s)) & 31;
287     if (n) skip_bits(s, n);
288 }
289
290 static int decode_frame(AVCodecContext *avctx,
291                         void *data, int *data_size,
292                         AVPacket *avpkt)
293 {
294     BinkAudioContext *s = avctx->priv_data;
295     const uint8_t *buf  = avpkt->data;
296     int buf_size        = avpkt->size;
297     short *samples      = data;
298     short *samples_end  = (short*)((uint8_t*)data + *data_size);
299     int reported_size;
300     GetBitContext *gb = &s->gb;
301
302     if (buf_size < 4) {
303         av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
304         return AVERROR_INVALIDDATA;
305     }
306
307     init_get_bits(gb, buf, buf_size * 8);
308
309     reported_size = get_bits_long(gb, 32);
310     while (samples + s->block_size <= samples_end) {
311         if (decode_block(s, samples, avctx->codec->id == CODEC_ID_BINKAUDIO_DCT))
312             break;
313         samples += s->block_size;
314         get_bits_align32(gb);
315     }
316
317     *data_size = FFMIN(reported_size, (uint8_t*)samples - (uint8_t*)data);
318     return buf_size;
319 }
320
321 AVCodec ff_binkaudio_rdft_decoder = {
322     .name           = "binkaudio_rdft",
323     .type           = AVMEDIA_TYPE_AUDIO,
324     .id             = CODEC_ID_BINKAUDIO_RDFT,
325     .priv_data_size = sizeof(BinkAudioContext),
326     .init           = decode_init,
327     .close          = decode_end,
328     .decode         = decode_frame,
329     .long_name = NULL_IF_CONFIG_SMALL("Bink Audio (RDFT)")
330 };
331
332 AVCodec ff_binkaudio_dct_decoder = {
333     .name           = "binkaudio_dct",
334     .type           = AVMEDIA_TYPE_AUDIO,
335     .id             = CODEC_ID_BINKAUDIO_DCT,
336     .priv_data_size = sizeof(BinkAudioContext),
337     .init           = decode_init,
338     .close          = decode_end,
339     .decode         = decode_frame,
340     .long_name = NULL_IF_CONFIG_SMALL("Bink Audio (DCT)")
341 };