2 * Extracted 2009 from mplayer 2009-02-10 libavcodec/bitstream.h.
4 * copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
6 * Licensed under the GNU Lesser General Public License.
7 * For licencing details see COPYING.LIB.
10 /** \file bitstream.h Bitstream structures and inline functions. */
12 /** Structure for bistream I/O. */
13 struct getbit_context {
14 /* Start of the internal buffer. */
15 const uint8_t *buffer;
16 /* End of the internal buffer. */
17 const uint8_t *buffer_end;
22 #define VLC_TYPE int16_t
26 VLC_TYPE(*table)[2]; ///< code, bits
27 int table_size, table_allocated;
30 static inline uint32_t show_bits(struct getbit_context *gbc, int num)
33 const uint8_t *p = gbc->buffer + (idx >> 3);
34 uint32_t x = ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
35 return (x << (idx & 7)) >> (32 - num);
38 static inline int get_bits_count(struct getbit_context *gbc)
43 static inline void skip_bits(struct getbit_context *gbc, int n)
48 static inline unsigned int get_bits(struct getbit_context *gbc, int n)
50 unsigned int ret = show_bits(gbc, n);
55 /* This is rather hot, we can do better than get_bits(gbc, 1). */
56 static inline unsigned int get_bit(struct getbit_context *gbc)
58 int idx = gbc->index++;
59 uint8_t tmp = gbc->buffer[idx >> 3], mask = (1 << (7 - (idx & 7)));
60 return !!(tmp & mask);
64 * Initialize a getbit_context structure.
66 * \param buffer The bitstream buffer. It must be FF_INPUT_BUFFER_PADDING_SIZE
67 * bytes larger then the actual read bits * because some optimized bitstream
68 * readers read 32 or 64 bit at once and could read over the end.
70 * \param bit_size The size of the buffer in bytes.
72 static inline void init_get_bits(struct getbit_context *gbc,
73 const uint8_t *buffer, int size)
76 gbc->buffer_end = buffer + size;
80 void init_vlc(struct vlc *vlc, int nb_bits, int nb_codes, const void *bits,
81 const void *codes, int codes_size);
83 void free_vlc(struct vlc *vlc);
88 * \param bits The number of bits which will be read at once, must be
89 * identical to nb_bits in init_vlc()
91 * \param max_depth The number of times bits bits must be read to completely
92 * read the longest vlc code = (max_vlc_length + bits - 1) / bits.
94 static inline int get_vlc(struct getbit_context *gbc, VLC_TYPE(*table)[2],
95 int bits, int max_depth)
97 int n, idx, nb_bits, code;
99 idx = show_bits(gbc, bits);
100 code = table[idx][0];
102 if (max_depth > 1 && n < 0) {
103 skip_bits(gbc, bits);
105 idx = show_bits(gbc, nb_bits) + code;
106 code = table[idx][0];
108 if (max_depth > 2 && n < 0) {
109 skip_bits(gbc, nb_bits);
111 idx = show_bits(gbc, nb_bits) + code;
112 code = table[idx][0];