Merge branch 'refs/heads/t/para_play' into next
[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, see file COPYING.LIB.
7 */
8
9 /** \file bitstream.h Bitstream structures and inline functions. */
10
11 /** Structure for bistream I/O. */
12 struct getbit_context {
13 /** Start of the internal buffer. */
14 const uint8_t *buffer;
15 /** Length of buffer in bits (always a multiple of 8). */
16 uint32_t num_bits;
17 /** Bit counter. */
18 int index;
19 };
20
21 /** A variable length code table. */
22 struct vlc {
23 /** Number of bits of the table. */
24 int bits;
25 /** The code and the bits table. */
26 int16_t (*table)[2];
27 /** The size of the table. */
28 int table_size;
29 /** Amount of memory allocated so far. */
30 int table_allocated;
31 };
32
33 static inline uint32_t show_bits(struct getbit_context *gbc, int num)
34 {
35 int idx = gbc->index;
36 const char *p;
37 uint32_t x;
38
39 assert(idx + num <= gbc->num_bits);
40 p = (const char *)gbc->buffer + (idx >> 3);
41 x = read_u32_be(p);
42 return (x << (idx & 7)) >> (32 - num);
43 }
44
45 static inline int get_bits_count(struct getbit_context *gbc)
46 {
47 return gbc->index;
48 }
49
50 static inline void skip_bits(struct getbit_context *gbc, int n)
51 {
52 assert(gbc->index + n <= gbc->num_bits);
53 gbc->index += n;
54 }
55
56 static inline unsigned int get_bits(struct getbit_context *gbc, int n)
57 {
58 unsigned int ret = show_bits(gbc, n); /* checks n */
59 skip_bits(gbc, n);
60 return ret;
61 }
62
63 /* This is rather hot, we can do better than get_bits(gbc, 1). */
64 static inline unsigned int get_bit(struct getbit_context *gbc)
65 {
66 int idx;
67 uint8_t tmp, mask;
68
69 assert(gbc->index < gbc->num_bits);
70 idx = gbc->index++;
71 tmp = gbc->buffer[idx >> 3];
72 mask = 1 << (7 - (idx & 7));
73 return !!(tmp & mask);
74 }
75
76 /**
77 * Initialize a getbit_context structure.
78 *
79 * \param gbc The structure to initialize.
80 * \param buffer The bitstream buffer.
81 * \param size The size of the buffer in bytes.
82 *
83 * The bitstream buffer must be 4 bytes larger then the actual read bits
84 * because the bitstream reader might read 32 bits at once and could read over
85 * the end.
86 */
87 static inline void init_get_bits(struct getbit_context *gbc,
88 const uint8_t *buffer, int size)
89 {
90 gbc->buffer = buffer;
91 gbc->num_bits = size * 8;
92 gbc->index = 0;
93 }
94
95 void init_vlc(struct vlc *vlc, int nb_bits, int nb_codes, const void *bits,
96 const void *codes, int codes_size);
97 void free_vlc(struct vlc *vlc);
98 int get_vlc(struct getbit_context *gbc, const struct vlc *vlc);