afh: Implement --human option.
[paraslash.git] / bitstream.h
1 /*
2  * Extracted 2009 from mplayer 2009-02-10 libavcodec/bitstream.h.
3  *
4  * copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * Licensed under the GNU Lesser General Public License.
7  * For licencing details see COPYING.LIB.
8  */
9
10 /** \file bitstream.h Bitstream structures and inline functions. */
11
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;
18         /** Bit counter. */
19         int index;
20 };
21
22 #define VLC_TYPE int16_t
23
24 struct vlc {
25         int bits;
26         VLC_TYPE(*table)[2];    ///< code, bits
27         int table_size, table_allocated;
28 };
29
30 static inline uint32_t show_bits(struct getbit_context *gbc, int num)
31 {
32         int idx = gbc->index;
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);
36 }
37
38 static inline int get_bits_count(struct getbit_context *gbc)
39 {
40         return gbc->index;
41 }
42
43 static inline void skip_bits(struct getbit_context *gbc, int n)
44 {
45         gbc->index += n;
46 }
47
48 static inline unsigned int get_bits(struct getbit_context *gbc, int n)
49 {
50         unsigned int ret = show_bits(gbc, n);
51         skip_bits(gbc, n);
52         return ret;
53 }
54
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)
57 {
58         int idx = gbc->index++;
59         uint8_t tmp = gbc->buffer[idx >> 3], mask = (1 << (7 - (idx & 7)));
60         return !!(tmp & mask);
61 }
62
63 /**
64  * Initialize a getbit_context structure.
65  *
66  * \param buffer The bitstream buffer. It must be 4 bytes larger then the
67  * actual read bits because the bitstream reader might read 32 bits at once and
68  * could read over the end.
69  *
70  * \param bit_size The size of the buffer in bytes.
71  */
72 static inline void init_get_bits(struct getbit_context *gbc,
73                 const uint8_t *buffer, int size)
74 {
75         gbc->buffer = buffer;
76         gbc->buffer_end = buffer + size;
77         gbc->index = 0;
78 }
79
80 void init_vlc(struct vlc *vlc, int nb_bits, int nb_codes, const void *bits,
81                 const void *codes, int codes_size);
82 void free_vlc(struct vlc *vlc);
83 int get_vlc(struct getbit_context *gbc, VLC_TYPE(*table)[2], int bits,
84                 int max_depth);
85