]> git.sesse.net Git - ffmpeg/blob - libavcodec/get_bits.h
33ddb4b89f2d77fe66599c022860af8c9a49de59
[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 #include <stdlib.h>
31 #include <assert.h>
32 #include "libavutil/bswap.h"
33 #include "libavutil/common.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/log.h"
36 #include "mathops.h"
37
38 /*
39  * Safe bitstream reading:
40  * optionally, the get_bits API can check to ensure that we
41  * don't read past input buffer boundaries. This is protected
42  * with CONFIG_SAFE_BITSTREAM_READER at the global level, and
43  * then below that with UNCHECKED_BITSTREAM_READER at the per-
44  * decoder level. This means that decoders that check internally
45  * can "#define UNCHECKED_BITSTREAM_READER 1" to disable
46  * overread checks.
47  * Boundary checking causes a minor performance penalty so for
48  * applications that won't want/need this, it can be disabled
49  * globally using "#define CONFIG_SAFE_BITSTREAM_READER 0".
50  */
51 #ifndef UNCHECKED_BITSTREAM_READER
52 #define UNCHECKED_BITSTREAM_READER !CONFIG_SAFE_BITSTREAM_READER
53 #endif
54
55 /* bit input */
56 /* buffer, buffer_end and size_in_bits must be present and used by every reader */
57 typedef struct GetBitContext {
58     const uint8_t *buffer, *buffer_end;
59     int index;
60     int size_in_bits;
61 #if !UNCHECKED_BITSTREAM_READER
62     int size_in_bits_plus8;
63 #endif
64 } GetBitContext;
65
66 #define VLC_TYPE int16_t
67
68 typedef struct VLC {
69     int bits;
70     VLC_TYPE (*table)[2]; ///< code, bits
71     int table_size, table_allocated;
72 } VLC;
73
74 typedef struct RL_VLC_ELEM {
75     int16_t level;
76     int8_t len;
77     uint8_t run;
78 } RL_VLC_ELEM;
79
80 /* Bitstream reader API docs:
81 name
82     arbitrary name which is used as prefix for the internal variables
83
84 gb
85     getbitcontext
86
87 OPEN_READER(name, gb)
88     load gb into local variables
89
90 CLOSE_READER(name, gb)
91     store local vars in gb
92
93 UPDATE_CACHE(name, gb)
94     refill the internal cache from the bitstream
95     after this call at least MIN_CACHE_BITS will be available,
96
97 GET_CACHE(name, gb)
98     will output the contents of the internal cache, next bit is MSB of 32 or 64 bit (FIXME 64bit)
99
100 SHOW_UBITS(name, gb, num)
101     will return the next num bits
102
103 SHOW_SBITS(name, gb, num)
104     will return the next num bits and do sign extension
105
106 SKIP_BITS(name, gb, num)
107     will skip over the next num bits
108     note, this is equivalent to SKIP_CACHE; SKIP_COUNTER
109
110 SKIP_CACHE(name, gb, num)
111     will remove the next num bits from the cache (note SKIP_COUNTER MUST be called before UPDATE_CACHE / CLOSE_READER)
112
113 SKIP_COUNTER(name, gb, num)
114     will increment the internal bit counter (see SKIP_CACHE & SKIP_BITS)
115
116 LAST_SKIP_CACHE(name, gb, num)
117     will remove the next num bits from the cache if it is needed for UPDATE_CACHE otherwise it will do nothing
118
119 LAST_SKIP_BITS(name, gb, num)
120     is equivalent to LAST_SKIP_CACHE; SKIP_COUNTER
121
122 for examples see get_bits, show_bits, skip_bits, get_vlc
123 */
124
125 #ifdef LONG_BITSTREAM_READER
126 #   define MIN_CACHE_BITS 32
127 #else
128 #   define MIN_CACHE_BITS 25
129 #endif
130
131 #   define OPEN_READER(name, gb)                \
132     unsigned int name##_index = (gb)->index;    \
133     unsigned int av_unused name##_cache = 0
134
135 #   define CLOSE_READER(name, gb) (gb)->index = name##_index
136
137 # ifdef ALT_BITSTREAM_READER_LE
138 # ifdef LONG_BITSTREAM_READER
139 #   define UPDATE_CACHE(name, gb) \
140     name##_cache = AV_RL64((gb)->buffer+(name##_index>>3)) >> (name##_index&0x07)
141 # else
142 #   define UPDATE_CACHE(name, gb) \
143     name##_cache = AV_RL32((gb)->buffer+(name##_index>>3)) >> (name##_index&0x07)
144 # endif
145
146 #   define SKIP_CACHE(name, gb, num) name##_cache >>= (num)
147 # else
148 # ifdef LONG_BITSTREAM_READER
149 #   define UPDATE_CACHE(name, gb) \
150     name##_cache = AV_RB64((gb)->buffer+(name##_index >> 3)) >> (32 - (name##_index & 0x07))
151 # else
152 #   define UPDATE_CACHE(name, gb) \
153     name##_cache = AV_RB32((gb)->buffer+(name##_index>>3)) << (name##_index&0x07)
154 # endif
155
156 #   define SKIP_CACHE(name, gb, num) name##_cache <<= (num)
157 # endif
158
159 // FIXME name?
160 #if UNCHECKED_BITSTREAM_READER
161 #   define SKIP_COUNTER(name, gb, num) name##_index += (num)
162 #else
163 #   define SKIP_COUNTER(name, gb, num) \
164     name##_index = FFMIN((gb)->size_in_bits_plus8, name##_index + (num))
165 #endif
166
167 #   define SKIP_BITS(name, gb, num) do {        \
168         SKIP_CACHE(name, gb, num);              \
169         SKIP_COUNTER(name, gb, num);            \
170     } while (0)
171
172 #   define LAST_SKIP_BITS(name, gb, num) SKIP_COUNTER(name, gb, num)
173 #   define LAST_SKIP_CACHE(name, gb, num)
174
175 # ifdef ALT_BITSTREAM_READER_LE
176 #   define SHOW_UBITS(name, gb, num) zero_extend(name##_cache, num)
177
178 #   define SHOW_SBITS(name, gb, num) sign_extend(name##_cache, num)
179 # else
180 #   define SHOW_UBITS(name, gb, num) NEG_USR32(name##_cache, num)
181
182 #   define SHOW_SBITS(name, gb, num) NEG_SSR32(name##_cache, num)
183 # endif
184
185 #   define GET_CACHE(name, gb) ((uint32_t)name##_cache)
186
187 static inline int get_bits_count(const GetBitContext *s){
188     return s->index;
189 }
190
191 static inline void skip_bits_long(GetBitContext *s, int n){
192 #if UNCHECKED_BITSTREAM_READER
193     s->index += n;
194 #else
195     s->index += av_clip(n, -s->index, s->size_in_bits_plus8 - s->index);
196 #endif
197 }
198
199 /**
200  * read mpeg1 dc style vlc (sign bit + mantisse with no MSB).
201  * if MSB not set it is negative
202  * @param n length in bits
203  * @author BERO
204  */
205 static inline int get_xbits(GetBitContext *s, int n){
206     register int sign;
207     register int32_t cache;
208     OPEN_READER(re, s);
209     UPDATE_CACHE(re, s);
210     cache = GET_CACHE(re, s);
211     sign = ~cache >> 31;
212     LAST_SKIP_BITS(re, s, n);
213     CLOSE_READER(re, s);
214     return (NEG_USR32(sign ^ cache, n) ^ sign) - sign;
215 }
216
217 static inline int get_sbits(GetBitContext *s, int n){
218     register int tmp;
219     OPEN_READER(re, s);
220     UPDATE_CACHE(re, s);
221     tmp = SHOW_SBITS(re, s, n);
222     LAST_SKIP_BITS(re, s, n);
223     CLOSE_READER(re, s);
224     return tmp;
225 }
226
227 /**
228  * Read 1-25 bits.
229  */
230 static inline unsigned int get_bits(GetBitContext *s, int n){
231     register int tmp;
232     OPEN_READER(re, s);
233     UPDATE_CACHE(re, s);
234     tmp = SHOW_UBITS(re, s, n);
235     LAST_SKIP_BITS(re, s, n);
236     CLOSE_READER(re, s);
237     return tmp;
238 }
239
240 /**
241  * Show 1-25 bits.
242  */
243 static inline unsigned int show_bits(GetBitContext *s, int n){
244     register int tmp;
245     OPEN_READER(re, s);
246     UPDATE_CACHE(re, s);
247     tmp = SHOW_UBITS(re, s, n);
248     return tmp;
249 }
250
251 static inline void skip_bits(GetBitContext *s, int n){
252  //Note gcc seems to optimize this to s->index+=n for the ALT_READER :))
253     OPEN_READER(re, s);
254     UPDATE_CACHE(re, s);
255     LAST_SKIP_BITS(re, s, n);
256     CLOSE_READER(re, s);
257 }
258
259 static inline unsigned int get_bits1(GetBitContext *s){
260     unsigned int index = s->index;
261     uint8_t result = s->buffer[index>>3];
262 #ifdef ALT_BITSTREAM_READER_LE
263     result >>= index & 7;
264     result &= 1;
265 #else
266     result <<= index & 7;
267     result >>= 8 - 1;
268 #endif
269 #if !UNCHECKED_BITSTREAM_READER
270     if (s->index < s->size_in_bits_plus8)
271 #endif
272         index++;
273     s->index = index;
274
275     return result;
276 }
277
278 static inline unsigned int show_bits1(GetBitContext *s){
279     return show_bits(s, 1);
280 }
281
282 static inline void skip_bits1(GetBitContext *s){
283     skip_bits(s, 1);
284 }
285
286 /**
287  * Read 0-32 bits.
288  */
289 static inline unsigned int get_bits_long(GetBitContext *s, int n){
290     if (n <= MIN_CACHE_BITS) return get_bits(s, n);
291     else {
292 #ifdef ALT_BITSTREAM_READER_LE
293         int ret = get_bits(s, 16);
294         return ret | (get_bits(s, n-16) << 16);
295 #else
296         int ret = get_bits(s, 16) << (n-16);
297         return ret | get_bits(s, n-16);
298 #endif
299     }
300 }
301
302 /**
303  * Read 0-32 bits as a signed integer.
304  */
305 static inline int get_sbits_long(GetBitContext *s, int n) {
306     return sign_extend(get_bits_long(s, n), n);
307 }
308
309 /**
310  * Show 0-32 bits.
311  */
312 static inline unsigned int show_bits_long(GetBitContext *s, int n){
313     if (n <= MIN_CACHE_BITS) return show_bits(s, n);
314     else {
315         GetBitContext gb = *s;
316         return get_bits_long(&gb, n);
317     }
318 }
319
320 static inline int check_marker(GetBitContext *s, const char *msg)
321 {
322     int bit = get_bits1(s);
323     if (!bit)
324         av_log(NULL, AV_LOG_INFO, "Marker bit missing %s\n", msg);
325
326     return bit;
327 }
328
329 /**
330  * Inititalize GetBitContext.
331  * @param buffer bitstream buffer, must be FF_INPUT_BUFFER_PADDING_SIZE bytes larger than the actual read bits
332  * because some optimized bitstream readers read 32 or 64 bit at once and could read over the end
333  * @param bit_size the size of the buffer in bits
334  *
335  * While GetBitContext stores the buffer size, for performance reasons you are
336  * responsible for checking for the buffer end yourself (take advantage of the padding)!
337  */
338 static inline void init_get_bits(GetBitContext *s,
339                    const uint8_t *buffer, int bit_size)
340 {
341     int buffer_size = (bit_size+7)>>3;
342     if (buffer_size < 0 || bit_size < 0) {
343         buffer_size = bit_size = 0;
344         buffer = NULL;
345     }
346
347     s->buffer       = buffer;
348     s->size_in_bits = bit_size;
349 #if !UNCHECKED_BITSTREAM_READER
350     s->size_in_bits_plus8 = bit_size + 8;
351 #endif
352     s->buffer_end   = buffer + buffer_size;
353     s->index        = 0;
354 }
355
356 static inline void align_get_bits(GetBitContext *s)
357 {
358     int n = -get_bits_count(s) & 7;
359     if (n) skip_bits(s, n);
360 }
361
362 #define init_vlc(vlc, nb_bits, nb_codes,                \
363                  bits, bits_wrap, bits_size,            \
364                  codes, codes_wrap, codes_size,         \
365                  flags)                                 \
366         init_vlc_sparse(vlc, nb_bits, nb_codes,         \
367                         bits, bits_wrap, bits_size,     \
368                         codes, codes_wrap, codes_size,  \
369                         NULL, 0, 0, flags)
370
371 int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
372              const void *bits, int bits_wrap, int bits_size,
373              const void *codes, int codes_wrap, int codes_size,
374              const void *symbols, int symbols_wrap, int symbols_size,
375              int flags);
376 #define INIT_VLC_LE         2
377 #define INIT_VLC_USE_NEW_STATIC 4
378 void free_vlc(VLC *vlc);
379
380 #define INIT_VLC_STATIC(vlc, bits, a,b,c,d,e,f,g, static_size) do {     \
381         static VLC_TYPE table[static_size][2];                          \
382         (vlc)->table = table;                                           \
383         (vlc)->table_allocated = static_size;                           \
384         init_vlc(vlc, bits, a,b,c,d,e,f,g, INIT_VLC_USE_NEW_STATIC);    \
385     } while (0)
386
387
388 /**
389  * If the vlc code is invalid and max_depth=1, then no bits will be removed.
390  * If the vlc code is invalid and max_depth>1, then the number of bits removed
391  * is undefined.
392  */
393 #define GET_VLC(code, name, gb, table, bits, max_depth) do {    \
394         int n, nb_bits;                                         \
395         unsigned int index;                                     \
396                                                                 \
397         index = SHOW_UBITS(name, gb, bits);                     \
398         code  = table[index][0];                                \
399         n     = table[index][1];                                \
400                                                                 \
401         if (max_depth > 1 && n < 0) {                           \
402             LAST_SKIP_BITS(name, gb, bits);                     \
403             UPDATE_CACHE(name, gb);                             \
404                                                                 \
405             nb_bits = -n;                                       \
406                                                                 \
407             index = SHOW_UBITS(name, gb, nb_bits) + code;       \
408             code  = table[index][0];                            \
409             n     = table[index][1];                            \
410             if (max_depth > 2 && n < 0) {                       \
411                 LAST_SKIP_BITS(name, gb, nb_bits);              \
412                 UPDATE_CACHE(name, gb);                         \
413                                                                 \
414                 nb_bits = -n;                                   \
415                                                                 \
416                 index = SHOW_UBITS(name, gb, nb_bits) + code;   \
417                 code  = table[index][0];                        \
418                 n     = table[index][1];                        \
419             }                                                   \
420         }                                                       \
421         SKIP_BITS(name, gb, n);                                 \
422     } while (0)
423
424 #define GET_RL_VLC(level, run, name, gb, table, bits, max_depth, need_update) do { \
425         int n, nb_bits;                                                 \
426         unsigned int index;                                             \
427                                                                         \
428         index = SHOW_UBITS(name, gb, bits);                             \
429         level = table[index].level;                                     \
430         n     = table[index].len;                                       \
431                                                                         \
432         if (max_depth > 1 && n < 0) {                                   \
433             SKIP_BITS(name, gb, bits);                                  \
434             if (need_update) {                                          \
435                 UPDATE_CACHE(name, gb);                                 \
436             }                                                           \
437                                                                         \
438             nb_bits = -n;                                               \
439                                                                         \
440             index = SHOW_UBITS(name, gb, nb_bits) + level;              \
441             level = table[index].level;                                 \
442             n     = table[index].len;                                   \
443         }                                                               \
444         run = table[index].run;                                         \
445         SKIP_BITS(name, gb, n);                                         \
446     } while (0)
447
448
449 /**
450  * Parse a vlc code, faster than get_vlc().
451  * @param bits is the number of bits which will be read at once, must be
452  *             identical to nb_bits in init_vlc()
453  * @param max_depth is the number of times bits bits must be read to completely
454  *                  read the longest vlc code
455  *                  = (max_vlc_length + bits - 1) / bits
456  */
457 static av_always_inline int get_vlc2(GetBitContext *s, VLC_TYPE (*table)[2],
458                                   int bits, int max_depth)
459 {
460     int code;
461
462     OPEN_READER(re, s);
463     UPDATE_CACHE(re, s);
464
465     GET_VLC(code, re, s, table, bits, max_depth);
466
467     CLOSE_READER(re, s);
468     return code;
469 }
470
471 static inline int decode012(GetBitContext *gb){
472     int n;
473     n = get_bits1(gb);
474     if (n == 0)
475         return 0;
476     else
477         return get_bits1(gb) + 1;
478 }
479
480 static inline int decode210(GetBitContext *gb){
481     if (get_bits1(gb))
482         return 0;
483     else
484         return 2 - get_bits1(gb);
485 }
486
487 static inline int get_bits_left(GetBitContext *gb)
488 {
489     return gb->size_in_bits - get_bits_count(gb);
490 }
491
492 //#define TRACE
493
494 #ifdef TRACE
495 static inline void print_bin(int bits, int n){
496     int i;
497
498     for (i = n-1; i >= 0; i--) {
499         av_log(NULL, AV_LOG_DEBUG, "%d", (bits>>i)&1);
500     }
501     for (i = n; i < 24; i++)
502         av_log(NULL, AV_LOG_DEBUG, " ");
503 }
504
505 static inline int get_bits_trace(GetBitContext *s, int n, char *file,
506                                  const char *func, int line){
507     int r = get_bits(s, n);
508
509     print_bin(r, n);
510     av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d bit @%5d in %s %s:%d\n",
511            r, n, r, get_bits_count(s)-n, file, func, line);
512     return r;
513 }
514 static inline int get_vlc_trace(GetBitContext *s, VLC_TYPE (*table)[2],
515                                 int bits, int max_depth, char *file,
516                                 const char *func, int line){
517     int show  = show_bits(s, 24);
518     int pos   = get_bits_count(s);
519     int r     = get_vlc2(s, table, bits, max_depth);
520     int len   = get_bits_count(s) - pos;
521     int bits2 = show >> (24-len);
522
523     print_bin(bits2, len);
524
525     av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d vlc @%5d in %s %s:%d\n",
526            bits2, len, r, pos, file, func, line);
527     return r;
528 }
529 static inline int get_xbits_trace(GetBitContext *s, int n, char *file,
530                                   const char *func, int line){
531     int show = show_bits(s, n);
532     int r    = get_xbits(s, n);
533
534     print_bin(show, n);
535     av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d xbt @%5d in %s %s:%d\n",
536            show, n, r, get_bits_count(s)-n, file, func, line);
537     return r;
538 }
539
540 #define get_bits(s, n)  get_bits_trace(s, n, __FILE__, __PRETTY_FUNCTION__, __LINE__)
541 #define get_bits1(s)    get_bits_trace(s, 1, __FILE__, __PRETTY_FUNCTION__, __LINE__)
542 #define get_xbits(s, n) get_xbits_trace(s, n, __FILE__, __PRETTY_FUNCTION__, __LINE__)
543 #define get_vlc(s, vlc)            get_vlc_trace(s, (vlc)->table, (vlc)->bits, 3, __FILE__, __PRETTY_FUNCTION__, __LINE__)
544 #define get_vlc2(s, tab, bits, max) get_vlc_trace(s, tab, bits, max, __FILE__, __PRETTY_FUNCTION__, __LINE__)
545
546 #define tprintf(p, ...) av_log(p, AV_LOG_DEBUG, __VA_ARGS__)
547
548 #else //TRACE
549 #define tprintf(p, ...) {}
550 #endif
551
552 #endif /* AVCODEC_GET_BITS_H */