1 // Copyright 2010 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 // Boolean decoder
11 //
12 // Author: Skal (pascal.massimino@gmail.com)
13 //         Vikas Arora (vikaas.arora@gmail.com)
14 
15 #ifndef WEBP_UTILS_BIT_READER_UTILS_H_
16 #define WEBP_UTILS_BIT_READER_UTILS_H_
17 
18 #include <assert.h>
19 #ifdef _MSC_VER
20 #include <stdlib.h>  // _byteswap_ulong
21 #endif
22 #include "src/webp/types.h"
23 
24 // Warning! This macro triggers quite some MACRO wizardry around func signature!
25 #if !defined(BITTRACE)
26 #define BITTRACE 0    // 0 = off, 1 = print bits, 2 = print bytes
27 #endif
28 
29 #if (BITTRACE > 0)
30 struct VP8BitReader;
31 extern void BitTrace(const struct VP8BitReader* const br, const char label[]);
32 #define BT_TRACK(br) BitTrace(br, label)
33 #define VP8Get(BR, L) VP8GetValue(BR, 1, L)
34 #else
35 #define BT_TRACK(br)
36 // We'll REMOVE the 'const char label[]' from all signatures and calls (!!):
37 #define VP8GetValue(BR, N, L) VP8GetValue(BR, N)
38 #define VP8Get(BR, L) VP8GetValue(BR, 1, L)
39 #define VP8GetSignedValue(BR, N, L) VP8GetSignedValue(BR, N)
40 #define VP8GetBit(BR, P, L) VP8GetBit(BR, P)
41 #define VP8GetBitAlt(BR, P, L) VP8GetBitAlt(BR, P)
42 #define VP8GetSigned(BR, V, L) VP8GetSigned(BR, V)
43 #endif
44 
45 #ifdef __cplusplus
46 extern "C" {
47 #endif
48 
49 // The Boolean decoder needs to maintain infinite precision on the value_ field.
50 // However, since range_ is only 8bit, we only need an active window of 8 bits
51 // for value_. Left bits (MSB) gets zeroed and shifted away when value_ falls
52 // below 128, range_ is updated, and fresh bits read from the bitstream are
53 // brought in as LSB. To avoid reading the fresh bits one by one (slow), we
54 // cache BITS of them ahead. The total of (BITS + 8) bits must fit into a
55 // natural register (with type bit_t). To fetch BITS bits from bitstream we
56 // use a type lbit_t.
57 //
58 // BITS can be any multiple of 8 from 8 to 56 (inclusive).
59 // Pick values that fit natural register size.
60 
61 #if defined(__i386__) || defined(_M_IX86)      // x86 32bit
62 #define BITS 24
63 #elif defined(__x86_64__) || defined(_M_X64)   // x86 64bit
64 #define BITS 56
65 #elif defined(__arm__) || defined(_M_ARM)      // ARM
66 #define BITS 24
67 #elif defined(__aarch64__)                     // ARM 64bit
68 #define BITS 56
69 #elif defined(__mips__)                        // MIPS
70 #define BITS 24
71 #else                                          // reasonable default
72 #define BITS 24
73 #endif
74 
75 //------------------------------------------------------------------------------
76 // Derived types and constants:
77 //   bit_t = natural register type for storing 'value_' (which is BITS+8 bits)
78 //   range_t = register for 'range_' (which is 8bits only)
79 
80 #if (BITS > 24)
81 typedef uint64_t bit_t;
82 #else
83 typedef uint32_t bit_t;
84 #endif
85 
86 typedef uint32_t range_t;
87 
88 //------------------------------------------------------------------------------
89 // Bitreader
90 
91 typedef struct VP8BitReader VP8BitReader;
92 struct VP8BitReader {
93   // boolean decoder  (keep the field ordering as is!)
94   bit_t value_;               // current value
95   range_t range_;             // current range minus 1. In [127, 254] interval.
96   int bits_;                  // number of valid bits left
97   // read buffer
98   const uint8_t* buf_;        // next byte to be read
99   const uint8_t* buf_end_;    // end of read buffer
100   const uint8_t* buf_max_;    // max packed-read position on buffer
101   int eof_;                   // true if input is exhausted
102 };
103 
104 // Initialize the bit reader and the boolean decoder.
105 void VP8InitBitReader(VP8BitReader* const br,
106                       const uint8_t* const start, size_t size);
107 // Sets the working read buffer.
108 void VP8BitReaderSetBuffer(VP8BitReader* const br,
109                            const uint8_t* const start, size_t size);
110 
111 // Update internal pointers to displace the byte buffer by the
112 // relative offset 'offset'.
113 void VP8RemapBitReader(VP8BitReader* const br, ptrdiff_t offset);
114 
115 // return the next value made of 'num_bits' bits
116 uint32_t VP8GetValue(VP8BitReader* const br, int num_bits, const char label[]);
117 
118 // return the next value with sign-extension.
119 int32_t VP8GetSignedValue(VP8BitReader* const br, int num_bits,
120                           const char label[]);
121 
122 // bit_reader_inl.h will implement the following methods:
123 //   static WEBP_INLINE int VP8GetBit(VP8BitReader* const br, int prob, ...)
124 //   static WEBP_INLINE int VP8GetSigned(VP8BitReader* const br, int v, ...)
125 // and should be included by the .c files that actually need them.
126 // This is to avoid recompiling the whole library whenever this file is touched,
127 // and also allowing platform-specific ad-hoc hacks.
128 
129 // -----------------------------------------------------------------------------
130 // Bitreader for lossless format
131 
132 // maximum number of bits (inclusive) the bit-reader can handle:
133 #define VP8L_MAX_NUM_BIT_READ 24
134 
135 #define VP8L_LBITS 64  // Number of bits prefetched (= bit-size of vp8l_val_t).
136 #define VP8L_WBITS 32  // Minimum number of bytes ready after VP8LFillBitWindow.
137 
138 typedef uint64_t vp8l_val_t;  // right now, this bit-reader can only use 64bit.
139 
140 typedef struct {
141   vp8l_val_t     val_;        // pre-fetched bits
142   const uint8_t* buf_;        // input byte buffer
143   size_t         len_;        // buffer length
144   size_t         pos_;        // byte position in buf_
145   int            bit_pos_;    // current bit-reading position in val_
146   int            eos_;        // true if a bit was read past the end of buffer
147 } VP8LBitReader;
148 
149 void VP8LInitBitReader(VP8LBitReader* const br,
150                        const uint8_t* const start,
151                        size_t length);
152 
153 //  Sets a new data buffer.
154 void VP8LBitReaderSetBuffer(VP8LBitReader* const br,
155                             const uint8_t* const buffer, size_t length);
156 
157 // Reads the specified number of bits from read buffer.
158 // Flags an error in case end_of_stream or n_bits is more than the allowed limit
159 // of VP8L_MAX_NUM_BIT_READ (inclusive).
160 // Flags eos_ if this read attempt is going to cross the read buffer.
161 uint32_t VP8LReadBits(VP8LBitReader* const br, int n_bits);
162 
163 // Return the prefetched bits, so they can be looked up.
VP8LPrefetchBits(VP8LBitReader * const br)164 static WEBP_INLINE uint32_t VP8LPrefetchBits(VP8LBitReader* const br) {
165   return (uint32_t)(br->val_ >> (br->bit_pos_ & (VP8L_LBITS - 1)));
166 }
167 
168 // Returns true if there was an attempt at reading bit past the end of
169 // the buffer. Doesn't set br->eos_ flag.
VP8LIsEndOfStream(const VP8LBitReader * const br)170 static WEBP_INLINE int VP8LIsEndOfStream(const VP8LBitReader* const br) {
171   assert(br->pos_ <= br->len_);
172   return br->eos_ || ((br->pos_ == br->len_) && (br->bit_pos_ > VP8L_LBITS));
173 }
174 
175 // For jumping over a number of bits in the bit stream when accessed with
176 // VP8LPrefetchBits and VP8LFillBitWindow.
177 // This function does *not* set br->eos_, since it's speed-critical.
178 // Use with extreme care!
VP8LSetBitPos(VP8LBitReader * const br,int val)179 static WEBP_INLINE void VP8LSetBitPos(VP8LBitReader* const br, int val) {
180   br->bit_pos_ = val;
181 }
182 
183 // Advances the read buffer by 4 bytes to make room for reading next 32 bits.
184 // Speed critical, but infrequent part of the code can be non-inlined.
185 extern void VP8LDoFillBitWindow(VP8LBitReader* const br);
VP8LFillBitWindow(VP8LBitReader * const br)186 static WEBP_INLINE void VP8LFillBitWindow(VP8LBitReader* const br) {
187   if (br->bit_pos_ >= VP8L_WBITS) VP8LDoFillBitWindow(br);
188 }
189 
190 #ifdef __cplusplus
191 }    // extern "C"
192 #endif
193 
194 #endif  // WEBP_UTILS_BIT_READER_UTILS_H_
195