]> git.sesse.net Git - ffmpeg/blob - libavcodec/get_bits.h
libopusdec: fix out-of-bounds read
[ffmpeg] / libavcodec / get_bits.h
1 /*
2  * copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * bitstream reader API header.
24  */
25
26 #ifndef AVCODEC_GET_BITS_H
27 #define AVCODEC_GET_BITS_H
28
29 #include <stdint.h>
30
31 #include "libavutil/common.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/log.h"
34 #include "mathops.h"
35 #include "vlc.h"
36
37 /*
38  * Safe bitstream reading:
39  * optionally, the get_bits API can check to ensure that we
40  * don't read past input buffer boundaries. This is protected
41  * with CONFIG_SAFE_BITSTREAM_READER at the global level, and
42  * then below that with UNCHECKED_BITSTREAM_READER at the per-
43  * decoder level. This means that decoders that check internally
44  * can "#define UNCHECKED_BITSTREAM_READER 1" to disable
45  * overread checks.
46  * Boundary checking causes a minor performance penalty so for
47  * applications that won't want/need this, it can be disabled
48  * globally using "#define CONFIG_SAFE_BITSTREAM_READER 0".
49  */
50 #ifndef UNCHECKED_BITSTREAM_READER
51 #define UNCHECKED_BITSTREAM_READER !CONFIG_SAFE_BITSTREAM_READER
52 #endif
53
54 typedef struct GetBitContext {
55     const uint8_t *buffer, *buffer_end;
56     int index;
57     int size_in_bits;
58 #if !UNCHECKED_BITSTREAM_READER
59     int size_in_bits_plus8;
60 #endif
61 } GetBitContext;
62
63 /* Bitstream reader API docs:
64  * name
65  *   arbitrary name which is used as prefix for the internal variables
66  *
67  * gb
68  *   getbitcontext
69  *
70  * OPEN_READER(name, gb)
71  *   load gb into local variables
72  *
73  * CLOSE_READER(name, gb)
74  *   store local vars in gb
75  *
76  * UPDATE_CACHE(name, gb)
77  *   Refill the internal cache from the bitstream.
78  *   After this call at least MIN_CACHE_BITS will be available.
79  *
80  * GET_CACHE(name, gb)
81  *   Will output the contents of the internal cache,
82  *   next bit is MSB of 32 or 64 bits (FIXME 64 bits).
83  *
84  * SHOW_UBITS(name, gb, num)
85  *   Will return the next num bits.
86  *
87  * SHOW_SBITS(name, gb, num)
88  *   Will return the next num bits and do sign extension.
89  *
90  * SKIP_BITS(name, gb, num)
91  *   Will skip over the next num bits.
92  *   Note, this is equivalent to SKIP_CACHE; SKIP_COUNTER.
93  *
94  * SKIP_CACHE(name, gb, num)
95  *   Will remove the next num bits from the cache (note SKIP_COUNTER
96  *   MUST be called before UPDATE_CACHE / CLOSE_READER).
97  *
98  * SKIP_COUNTER(name, gb, num)
99  *   Will increment the internal bit counter (see SKIP_CACHE & SKIP_BITS).
100  *
101  * LAST_SKIP_BITS(name, gb, num)
102  *   Like SKIP_BITS, to be used if next call is UPDATE_CACHE or CLOSE_READER.
103  *
104  * For examples see get_bits, show_bits, skip_bits, get_vlc.
105  */
106
107 #ifdef LONG_BITSTREAM_READER
108 #   define MIN_CACHE_BITS 32
109 #else
110 #   define MIN_CACHE_BITS 25
111 #endif
112
113 #define OPEN_READER_NOSIZE(name, gb)            \
114     unsigned int name ## _index = (gb)->index;  \
115     unsigned int av_unused name ## _cache = 0
116
117 #if UNCHECKED_BITSTREAM_READER
118 #define OPEN_READER(name, gb) OPEN_READER_NOSIZE(name, gb)
119
120 #define BITS_AVAILABLE(name, gb) 1
121 #else
122 #define OPEN_READER(name, gb)                   \
123     OPEN_READER_NOSIZE(name, gb);               \
124     unsigned int name ## _size_plus8 = (gb)->size_in_bits_plus8
125
126 #define BITS_AVAILABLE(name, gb) name ## _index < name ## _size_plus8
127 #endif
128
129 #define CLOSE_READER(name, gb) (gb)->index = name ## _index
130
131 #ifdef BITSTREAM_READER_LE
132
133 # ifdef LONG_BITSTREAM_READER
134 #   define UPDATE_CACHE(name, gb) name ## _cache = \
135         AV_RL64((gb)->buffer + (name ## _index >> 3)) >> (name ## _index & 7)
136 # else
137 #   define UPDATE_CACHE(name, gb) name ## _cache = \
138         AV_RL32((gb)->buffer + (name ## _index >> 3)) >> (name ## _index & 7)
139 # endif
140
141 # define SKIP_CACHE(name, gb, num) name ## _cache >>= (num)
142
143 #else
144
145 # ifdef LONG_BITSTREAM_READER
146 #   define UPDATE_CACHE(name, gb) name ## _cache = \
147         AV_RB64((gb)->buffer + (name ## _index >> 3)) >> (32 - (name ## _index & 7))
148 # else
149 #   define UPDATE_CACHE(name, gb) name ## _cache = \
150         AV_RB32((gb)->buffer + (name ## _index >> 3)) << (name ## _index & 7)
151 # endif
152
153 # define SKIP_CACHE(name, gb, num) name ## _cache <<= (num)
154
155 #endif
156
157 #if UNCHECKED_BITSTREAM_READER
158 #   define SKIP_COUNTER(name, gb, num) name ## _index += (num)
159 #else
160 #   define SKIP_COUNTER(name, gb, num) \
161     name ## _index = FFMIN(name ## _size_plus8, name ## _index + (num))
162 #endif
163
164 #define SKIP_BITS(name, gb, num)                \
165     do {                                        \
166         SKIP_CACHE(name, gb, num);              \
167         SKIP_COUNTER(name, gb, num);            \
168     } while (0)
169
170 #define LAST_SKIP_BITS(name, gb, num) SKIP_COUNTER(name, gb, num)
171
172 #ifdef BITSTREAM_READER_LE
173 #   define SHOW_UBITS(name, gb, num) zero_extend(name ## _cache, num)
174 #   define SHOW_SBITS(name, gb, num) sign_extend(name ## _cache, num)
175 #else
176 #   define SHOW_UBITS(name, gb, num) NEG_USR32(name ## _cache, num)
177 #   define SHOW_SBITS(name, gb, num) NEG_SSR32(name ## _cache, num)
178 #endif
179
180 #define GET_CACHE(name, gb) ((uint32_t) name ## _cache)
181
182 static inline int get_bits_count(const GetBitContext *s)
183 {
184     return s->index;
185 }
186
187 static inline void skip_bits_long(GetBitContext *s, int n)
188 {
189 #if UNCHECKED_BITSTREAM_READER
190     s->index += n;
191 #else
192     s->index += av_clip(n, -s->index, s->size_in_bits_plus8 - s->index);
193 #endif
194 }
195
196 /**
197  * Read MPEG-1 dc-style VLC (sign bit + mantisse with no MSB).
198  * if MSB not set it is negative
199  * @param n length in bits
200  */
201 static inline int get_xbits(GetBitContext *s, int n)
202 {
203     register int sign;
204     register int32_t cache;
205     OPEN_READER(re, s);
206     UPDATE_CACHE(re, s);
207     cache = GET_CACHE(re, s);
208     sign  = ~cache >> 31;
209     LAST_SKIP_BITS(re, s, n);
210     CLOSE_READER(re, s);
211     return (NEG_USR32(sign ^ cache, n) ^ sign) - sign;
212 }
213
214 static inline int get_sbits(GetBitContext *s, int n)
215 {
216     register int tmp;
217     OPEN_READER(re, s);
218     UPDATE_CACHE(re, s);
219     tmp = SHOW_SBITS(re, s, n);
220     LAST_SKIP_BITS(re, s, n);
221     CLOSE_READER(re, s);
222     return tmp;
223 }
224
225 /**
226  * Read 1-25 bits.
227  */
228 static inline unsigned int get_bits(GetBitContext *s, int n)
229 {
230     register int tmp;
231     OPEN_READER(re, s);
232     UPDATE_CACHE(re, s);
233     tmp = SHOW_UBITS(re, s, n);
234     LAST_SKIP_BITS(re, s, n);
235     CLOSE_READER(re, s);
236     return tmp;
237 }
238
239 /**
240  * Read 0-25 bits.
241  */
242 static av_always_inline int get_bitsz(GetBitContext *s, int n)
243 {
244     return n ? get_bits(s, n) : 0;
245 }
246
247 /**
248  * Show 1-25 bits.
249  */
250 static inline unsigned int show_bits(GetBitContext *s, int n)
251 {
252     register int tmp;
253     OPEN_READER_NOSIZE(re, s);
254     UPDATE_CACHE(re, s);
255     tmp = SHOW_UBITS(re, s, n);
256     return tmp;
257 }
258
259 static inline void skip_bits(GetBitContext *s, int n)
260 {
261     OPEN_READER(re, s);
262     UPDATE_CACHE(re, s);
263     LAST_SKIP_BITS(re, s, n);
264     CLOSE_READER(re, s);
265 }
266
267 static inline unsigned int get_bits1(GetBitContext *s)
268 {
269     unsigned int index = s->index;
270     uint8_t result     = s->buffer[index >> 3];
271 #ifdef BITSTREAM_READER_LE
272     result >>= index & 7;
273     result  &= 1;
274 #else
275     result <<= index & 7;
276     result >>= 8 - 1;
277 #endif
278 #if !UNCHECKED_BITSTREAM_READER
279     if (s->index < s->size_in_bits_plus8)
280 #endif
281         index++;
282     s->index = index;
283
284     return result;
285 }
286
287 static inline unsigned int show_bits1(GetBitContext *s)
288 {
289     return show_bits(s, 1);
290 }
291
292 static inline void skip_bits1(GetBitContext *s)
293 {
294     skip_bits(s, 1);
295 }
296
297 /**
298  * Read 0-32 bits.
299  */
300 static inline unsigned int get_bits_long(GetBitContext *s, int n)
301 {
302     if (n <= MIN_CACHE_BITS) {
303         return get_bits(s, n);
304     } else {
305 #ifdef BITSTREAM_READER_LE
306         int ret = get_bits(s, 16);
307         return ret | (get_bits(s, n - 16) << 16);
308 #else
309         int ret = get_bits(s, 16) << (n - 16);
310         return ret | get_bits(s, n - 16);
311 #endif
312     }
313 }
314
315 /*
316  * Read 0-64 bits.
317  */
318 static inline uint64_t get_bits64(GetBitContext *s, int n)
319 {
320     if (n <= 32) {
321         return get_bits_long(s, n);
322     } else {
323 #ifdef BITSTREAM_READER_LE
324         uint64_t ret = get_bits_long(s, 32);
325         return ret | (uint64_t) get_bits_long(s, n - 32) << 32;
326 #else
327         uint64_t ret = (uint64_t) get_bits_long(s, n - 32) << 32;
328         return ret | get_bits_long(s, 32);
329 #endif
330     }
331 }
332
333 /**
334  * Read 0-32 bits as a signed integer.
335  */
336 static inline int get_sbits_long(GetBitContext *s, int n)
337 {
338     return sign_extend(get_bits_long(s, n), n);
339 }
340
341 /**
342  * Show 0-32 bits.
343  */
344 static inline unsigned int show_bits_long(GetBitContext *s, int n)
345 {
346     if (n <= MIN_CACHE_BITS) {
347         return show_bits(s, n);
348     } else {
349         GetBitContext gb = *s;
350         return get_bits_long(&gb, n);
351     }
352 }
353
354 /**
355  * Initialize GetBitContext.
356  * @param buffer bitstream buffer, must be AV_INPUT_BUFFER_PADDING_SIZE bytes
357  *        larger than the actual read bits because some optimized bitstream
358  *        readers read 32 or 64 bit at once and could read over the end
359  * @param bit_size the size of the buffer in bits
360  * @return 0 on success, AVERROR_INVALIDDATA if the buffer_size would overflow.
361  */
362 static inline int init_get_bits(GetBitContext *s, const uint8_t *buffer,
363                                 int bit_size)
364 {
365     int buffer_size;
366     int ret = 0;
367
368     if (bit_size > INT_MAX - 7 || bit_size < 0 || !buffer) {
369         bit_size    = 0;
370         buffer      = NULL;
371         ret         = AVERROR_INVALIDDATA;
372     }
373
374     buffer_size = (bit_size + 7) >> 3;
375
376     s->buffer             = buffer;
377     s->size_in_bits       = bit_size;
378 #if !UNCHECKED_BITSTREAM_READER
379     s->size_in_bits_plus8 = bit_size + 8;
380 #endif
381     s->buffer_end         = buffer + buffer_size;
382     s->index              = 0;
383
384     return ret;
385 }
386
387 /**
388  * Initialize GetBitContext.
389  * @param buffer bitstream buffer, must be AV_INPUT_BUFFER_PADDING_SIZE bytes
390  *        larger than the actual read bits because some optimized bitstream
391  *        readers read 32 or 64 bit at once and could read over the end
392  * @param byte_size the size of the buffer in bytes
393  * @return 0 on success, AVERROR_INVALIDDATA if the buffer_size would overflow.
394  */
395 static inline int init_get_bits8(GetBitContext *s, const uint8_t *buffer,
396                                  int byte_size)
397 {
398     if (byte_size > INT_MAX / 8)
399         return AVERROR_INVALIDDATA;
400     return init_get_bits(s, buffer, byte_size * 8);
401 }
402
403 static inline const uint8_t *align_get_bits(GetBitContext *s)
404 {
405     int n = -get_bits_count(s) & 7;
406     if (n)
407         skip_bits(s, n);
408     return s->buffer + (s->index >> 3);
409 }
410
411 /**
412  * If the vlc code is invalid and max_depth=1, then no bits will be removed.
413  * If the vlc code is invalid and max_depth>1, then the number of bits removed
414  * is undefined.
415  */
416 #define GET_VLC(code, name, gb, table, bits, max_depth)         \
417     do {                                                        \
418         int n, nb_bits;                                         \
419         unsigned int index;                                     \
420                                                                 \
421         index = SHOW_UBITS(name, gb, bits);                     \
422         code  = table[index][0];                                \
423         n     = table[index][1];                                \
424                                                                 \
425         if (max_depth > 1 && n < 0) {                           \
426             LAST_SKIP_BITS(name, gb, bits);                     \
427             UPDATE_CACHE(name, gb);                             \
428                                                                 \
429             nb_bits = -n;                                       \
430                                                                 \
431             index = SHOW_UBITS(name, gb, nb_bits) + code;       \
432             code  = table[index][0];                            \
433             n     = table[index][1];                            \
434             if (max_depth > 2 && n < 0) {                       \
435                 LAST_SKIP_BITS(name, gb, nb_bits);              \
436                 UPDATE_CACHE(name, gb);                         \
437                                                                 \
438                 nb_bits = -n;                                   \
439                                                                 \
440                 index = SHOW_UBITS(name, gb, nb_bits) + code;   \
441                 code  = table[index][0];                        \
442                 n     = table[index][1];                        \
443             }                                                   \
444         }                                                       \
445         SKIP_BITS(name, gb, n);                                 \
446     } while (0)
447
448 #define GET_RL_VLC(level, run, name, gb, table, bits,           \
449                    max_depth, need_update)                      \
450     do {                                                        \
451         int n, nb_bits;                                         \
452         unsigned int index;                                     \
453                                                                 \
454         index = SHOW_UBITS(name, gb, bits);                     \
455         level = table[index].level;                             \
456         n     = table[index].len;                               \
457                                                                 \
458         if (max_depth > 1 && n < 0) {                           \
459             SKIP_BITS(name, gb, bits);                          \
460             if (need_update) {                                  \
461                 UPDATE_CACHE(name, gb);                         \
462             }                                                   \
463                                                                 \
464             nb_bits = -n;                                       \
465                                                                 \
466             index = SHOW_UBITS(name, gb, nb_bits) + level;      \
467             level = table[index].level;                         \
468             n     = table[index].len;                           \
469             if (max_depth > 2 && n < 0) {                       \
470                 LAST_SKIP_BITS(name, gb, nb_bits);              \
471                 if (need_update) {                              \
472                     UPDATE_CACHE(name, gb);                     \
473                 }                                               \
474                 nb_bits = -n;                                   \
475                                                                 \
476                 index = SHOW_UBITS(name, gb, nb_bits) + level;  \
477                 level = table[index].level;                     \
478                 n     = table[index].len;                       \
479             }                                                   \
480         }                                                       \
481         run = table[index].run;                                 \
482         SKIP_BITS(name, gb, n);                                 \
483     } while (0)
484
485 /**
486  * Parse a vlc code.
487  * @param bits is the number of bits which will be read at once, must be
488  *             identical to nb_bits in init_vlc()
489  * @param max_depth is the number of times bits bits must be read to completely
490  *                  read the longest vlc code
491  *                  = (max_vlc_length + bits - 1) / bits
492  */
493 static av_always_inline int get_vlc2(GetBitContext *s, VLC_TYPE (*table)[2],
494                                      int bits, int max_depth)
495 {
496     int code;
497
498     OPEN_READER(re, s);
499     UPDATE_CACHE(re, s);
500
501     GET_VLC(code, re, s, table, bits, max_depth);
502
503     CLOSE_READER(re, s);
504
505     return code;
506 }
507
508 static inline int decode012(GetBitContext *gb)
509 {
510     int n;
511     n = get_bits1(gb);
512     if (n == 0)
513         return 0;
514     else
515         return get_bits1(gb) + 1;
516 }
517
518 static inline int decode210(GetBitContext *gb)
519 {
520     if (get_bits1(gb))
521         return 0;
522     else
523         return 2 - get_bits1(gb);
524 }
525
526 static inline int get_bits_left(GetBitContext *gb)
527 {
528     return gb->size_in_bits - get_bits_count(gb);
529 }
530
531 #endif /* AVCODEC_GET_BITS_H */