VS2008 project files.
[xiph/unicode.git] / w3d / golomb.h
blobfa66d750b2590da2a78a8fe8f08ca82e92ee37ab
1 #ifndef __GOLOMB_H
2 #define __GOLOMB_H
5 #include "bitcoder.h"
8 static inline
9 unsigned int required_bits (unsigned int x)
11 int bits = 31;
13 while ((x & (1 << bits)) == 0 && bits)
14 bits--;
16 return bits;
20 static inline
21 void write_number_binary (BitCoderState *b, unsigned int x, int bits, int u)
23 //printf ("wrote %i with %i bits (%i+%i)\n", x, u+bits, u, bits);
24 while (bits) {
25 bits--;
26 bitcoder_write_bit (b, (x >> bits) & 1);
31 static inline
32 unsigned int read_number_binary (BitCoderState *b, int bits)
34 unsigned int x = 0;
36 while (bits) {
37 bits--;
38 x |= bitcoder_read_bit (b) << bits;
41 return x;
45 static inline
46 void golomb_write_number (BitCoderState *b, unsigned int x, int bits)
48 unsigned int q, r;
49 int i = 0;
51 assert (x > 0);
53 while ((q = (x - 1) >> bits) > 0) {
54 bitcoder_write_bit (b, 1); /* fast temporary adaption, write */
55 bits++; /* unary representation of q */
56 i++;
59 bitcoder_write_bit (b, 0);
61 r = x - 1 - (q << bits);
63 write_number_binary (b, r, bits, i+1);
67 static inline
68 unsigned int golomb_read_number (BitCoderState *b, int bits)
70 unsigned int q = 0, r, x;
72 while (bitcoder_read_bit (b) != 0) {
73 bits++;
76 r = read_number_binary (b, bits);
77 x = (q << bits) + r + 1;
79 return x;
83 typedef struct {
84 uint8_t count;
85 uint8_t bits; /* a 5.3 fixed point integer */
86 } GolombAdaptiveCoderState;
88 #define GOLOMB_ADAPTIVE_CODER_STATE_INITIALIZER { 8<<3, 0 }
91 static const int golomb_w_tab [] = { 256, 128, 64 };
96 static inline
97 void golombcoder_encode_number (GolombAdaptiveCoderState *g,
98 BitCoderState *b,
99 unsigned int x)
101 golomb_write_number (b, x, g->bits >> 3);
103 g->bits = ((256 - golomb_w_tab[g->count]) * (int) g->bits +
104 golomb_w_tab[g->count] * (required_bits(x)<<3)) / 256;
105 g->count++;
107 if (g->count > 2)
108 g->count = 2;
112 static inline
113 unsigned int golombcoder_decode_number (GolombAdaptiveCoderState *g,
114 BitCoderState *b)
116 unsigned int x;
118 x = golomb_read_number (b, g->bits >> 3);
120 g->bits = ((256 - golomb_w_tab[g->count]) * g->bits +
121 golomb_w_tab[g->count] * (required_bits(x)<<3)) / 256;
122 g->count++;
124 if (g->count > 2)
125 g->count = 2;
127 return x;
131 #endif