1 /*
2  *  Copyright 2015 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "rtc_base/bit_buffer.h"
12 
13 #include <algorithm>
14 #include <limits>
15 
16 #include "rtc_base/checks.h"
17 
18 namespace {
19 
20 // Returns the lowest (right-most) |bit_count| bits in |byte|.
LowestBits(uint8_t byte,size_t bit_count)21 uint8_t LowestBits(uint8_t byte, size_t bit_count) {
22   RTC_DCHECK_LE(bit_count, 8);
23   return byte & ((1 << bit_count) - 1);
24 }
25 
26 // Returns the highest (left-most) |bit_count| bits in |byte|, shifted to the
27 // lowest bits (to the right).
HighestBits(uint8_t byte,size_t bit_count)28 uint8_t HighestBits(uint8_t byte, size_t bit_count) {
29   RTC_DCHECK_LE(bit_count, 8);
30   uint8_t shift = 8 - static_cast<uint8_t>(bit_count);
31   uint8_t mask = 0xFF << shift;
32   return (byte & mask) >> shift;
33 }
34 
35 // Returns the highest byte of |val| in a uint8_t.
HighestByte(uint64_t val)36 uint8_t HighestByte(uint64_t val) {
37   return static_cast<uint8_t>(val >> 56);
38 }
39 
40 // Returns the result of writing partial data from |source|, of
41 // |source_bit_count| size in the highest bits, to |target| at
42 // |target_bit_offset| from the highest bit.
WritePartialByte(uint8_t source,size_t source_bit_count,uint8_t target,size_t target_bit_offset)43 uint8_t WritePartialByte(uint8_t source,
44                          size_t source_bit_count,
45                          uint8_t target,
46                          size_t target_bit_offset) {
47   RTC_DCHECK(target_bit_offset < 8);
48   RTC_DCHECK(source_bit_count < 9);
49   RTC_DCHECK(source_bit_count <= (8 - target_bit_offset));
50   // Generate a mask for just the bits we're going to overwrite, so:
51   uint8_t mask =
52       // The number of bits we want, in the most significant bits...
53       static_cast<uint8_t>(0xFF << (8 - source_bit_count))
54       // ...shifted over to the target offset from the most signficant bit.
55       >> target_bit_offset;
56 
57   // We want the target, with the bits we'll overwrite masked off, or'ed with
58   // the bits from the source we want.
59   return (target & ~mask) | (source >> target_bit_offset);
60 }
61 
62 // Counts the number of bits used in the binary representation of val.
CountBits(uint64_t val)63 size_t CountBits(uint64_t val) {
64   size_t bit_count = 0;
65   while (val != 0) {
66     bit_count++;
67     val >>= 1;
68   }
69   return bit_count;
70 }
71 
72 }  // namespace
73 
74 namespace rtc {
75 
BitBuffer(const uint8_t * bytes,size_t byte_count)76 BitBuffer::BitBuffer(const uint8_t* bytes, size_t byte_count)
77     : bytes_(bytes), byte_count_(byte_count), byte_offset_(), bit_offset_() {
78   RTC_DCHECK(static_cast<uint64_t>(byte_count_) <=
79              std::numeric_limits<uint32_t>::max());
80 }
81 
RemainingBitCount() const82 uint64_t BitBuffer::RemainingBitCount() const {
83   return (static_cast<uint64_t>(byte_count_) - byte_offset_) * 8 - bit_offset_;
84 }
85 
ReadUInt8(uint8_t * val)86 bool BitBuffer::ReadUInt8(uint8_t* val) {
87   uint32_t bit_val;
88   if (!ReadBits(&bit_val, sizeof(uint8_t) * 8)) {
89     return false;
90   }
91   RTC_DCHECK(bit_val <= std::numeric_limits<uint8_t>::max());
92   *val = static_cast<uint8_t>(bit_val);
93   return true;
94 }
95 
ReadUInt16(uint16_t * val)96 bool BitBuffer::ReadUInt16(uint16_t* val) {
97   uint32_t bit_val;
98   if (!ReadBits(&bit_val, sizeof(uint16_t) * 8)) {
99     return false;
100   }
101   RTC_DCHECK(bit_val <= std::numeric_limits<uint16_t>::max());
102   *val = static_cast<uint16_t>(bit_val);
103   return true;
104 }
105 
ReadUInt32(uint32_t * val)106 bool BitBuffer::ReadUInt32(uint32_t* val) {
107   return ReadBits(val, sizeof(uint32_t) * 8);
108 }
109 
PeekBits(uint32_t * val,size_t bit_count)110 bool BitBuffer::PeekBits(uint32_t* val, size_t bit_count) {
111   // TODO(nisse): Could allow bit_count == 0 and always return success. But
112   // current code reads one byte beyond end of buffer in the case that
113   // RemainingBitCount() == 0 and bit_count == 0.
114   RTC_DCHECK(bit_count > 0);
115   if (!val || bit_count > RemainingBitCount() || bit_count > 32) {
116     return false;
117   }
118   const uint8_t* bytes = bytes_ + byte_offset_;
119   size_t remaining_bits_in_current_byte = 8 - bit_offset_;
120   uint32_t bits = LowestBits(*bytes++, remaining_bits_in_current_byte);
121   // If we're reading fewer bits than what's left in the current byte, just
122   // return the portion of this byte that we need.
123   if (bit_count < remaining_bits_in_current_byte) {
124     *val = HighestBits(bits, bit_offset_ + bit_count);
125     return true;
126   }
127   // Otherwise, subtract what we've read from the bit count and read as many
128   // full bytes as we can into bits.
129   bit_count -= remaining_bits_in_current_byte;
130   while (bit_count >= 8) {
131     bits = (bits << 8) | *bytes++;
132     bit_count -= 8;
133   }
134   // Whatever we have left is smaller than a byte, so grab just the bits we need
135   // and shift them into the lowest bits.
136   if (bit_count > 0) {
137     bits <<= bit_count;
138     bits |= HighestBits(*bytes, bit_count);
139   }
140   *val = bits;
141   return true;
142 }
143 
ReadBits(uint32_t * val,size_t bit_count)144 bool BitBuffer::ReadBits(uint32_t* val, size_t bit_count) {
145   return PeekBits(val, bit_count) && ConsumeBits(bit_count);
146 }
147 
ConsumeBytes(size_t byte_count)148 bool BitBuffer::ConsumeBytes(size_t byte_count) {
149   return ConsumeBits(byte_count * 8);
150 }
151 
ConsumeBits(size_t bit_count)152 bool BitBuffer::ConsumeBits(size_t bit_count) {
153   if (bit_count > RemainingBitCount()) {
154     return false;
155   }
156 
157   byte_offset_ += (bit_offset_ + bit_count) / 8;
158   bit_offset_ = (bit_offset_ + bit_count) % 8;
159   return true;
160 }
161 
ReadNonSymmetric(uint32_t * val,uint32_t num_values)162 bool BitBuffer::ReadNonSymmetric(uint32_t* val, uint32_t num_values) {
163   RTC_DCHECK_GT(num_values, 0);
164   RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
165   if (num_values == 1) {
166     // When there is only one possible value, it requires zero bits to store it.
167     // But ReadBits doesn't support reading zero bits.
168     *val = 0;
169     return true;
170   }
171   size_t count_bits = CountBits(num_values);
172   uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
173 
174   if (!ReadBits(val, count_bits - 1)) {
175     return false;
176   }
177 
178   if (*val < num_min_bits_values) {
179     return true;
180   }
181 
182   uint32_t extra_bit;
183   if (!ReadBits(&extra_bit, /*bit_count=*/1)) {
184     return false;
185   }
186 
187   *val = (*val << 1) + extra_bit - num_min_bits_values;
188   return true;
189 }
190 
ReadExponentialGolomb(uint32_t * val)191 bool BitBuffer::ReadExponentialGolomb(uint32_t* val) {
192   if (!val) {
193     return false;
194   }
195   // Store off the current byte/bit offset, in case we want to restore them due
196   // to a failed parse.
197   size_t original_byte_offset = byte_offset_;
198   size_t original_bit_offset = bit_offset_;
199 
200   // Count the number of leading 0 bits by peeking/consuming them one at a time.
201   size_t zero_bit_count = 0;
202   uint32_t peeked_bit;
203   while (PeekBits(&peeked_bit, 1) && peeked_bit == 0) {
204     zero_bit_count++;
205     ConsumeBits(1);
206   }
207 
208   // We should either be at the end of the stream, or the next bit should be 1.
209   RTC_DCHECK(!PeekBits(&peeked_bit, 1) || peeked_bit == 1);
210 
211   // The bit count of the value is the number of zeros + 1. Make sure that many
212   // bits fits in a uint32_t and that we have enough bits left for it, and then
213   // read the value.
214   size_t value_bit_count = zero_bit_count + 1;
215   if (value_bit_count > 32 || !ReadBits(val, value_bit_count)) {
216     RTC_CHECK(Seek(original_byte_offset, original_bit_offset));
217     return false;
218   }
219   *val -= 1;
220   return true;
221 }
222 
ReadSignedExponentialGolomb(int32_t * val)223 bool BitBuffer::ReadSignedExponentialGolomb(int32_t* val) {
224   uint32_t unsigned_val;
225   if (!ReadExponentialGolomb(&unsigned_val)) {
226     return false;
227   }
228   if ((unsigned_val & 1) == 0) {
229     *val = -static_cast<int32_t>(unsigned_val / 2);
230   } else {
231     *val = (unsigned_val + 1) / 2;
232   }
233   return true;
234 }
235 
GetCurrentOffset(size_t * out_byte_offset,size_t * out_bit_offset)236 void BitBuffer::GetCurrentOffset(size_t* out_byte_offset,
237                                  size_t* out_bit_offset) {
238   RTC_CHECK(out_byte_offset != nullptr);
239   RTC_CHECK(out_bit_offset != nullptr);
240   *out_byte_offset = byte_offset_;
241   *out_bit_offset = bit_offset_;
242 }
243 
Seek(size_t byte_offset,size_t bit_offset)244 bool BitBuffer::Seek(size_t byte_offset, size_t bit_offset) {
245   if (byte_offset > byte_count_ || bit_offset > 7 ||
246       (byte_offset == byte_count_ && bit_offset > 0)) {
247     return false;
248   }
249   byte_offset_ = byte_offset;
250   bit_offset_ = bit_offset;
251   return true;
252 }
253 
BitBufferWriter(uint8_t * bytes,size_t byte_count)254 BitBufferWriter::BitBufferWriter(uint8_t* bytes, size_t byte_count)
255     : BitBuffer(bytes, byte_count), writable_bytes_(bytes) {}
256 
WriteUInt8(uint8_t val)257 bool BitBufferWriter::WriteUInt8(uint8_t val) {
258   return WriteBits(val, sizeof(uint8_t) * 8);
259 }
260 
WriteUInt16(uint16_t val)261 bool BitBufferWriter::WriteUInt16(uint16_t val) {
262   return WriteBits(val, sizeof(uint16_t) * 8);
263 }
264 
WriteUInt32(uint32_t val)265 bool BitBufferWriter::WriteUInt32(uint32_t val) {
266   return WriteBits(val, sizeof(uint32_t) * 8);
267 }
268 
WriteBits(uint64_t val,size_t bit_count)269 bool BitBufferWriter::WriteBits(uint64_t val, size_t bit_count) {
270   if (bit_count > RemainingBitCount()) {
271     return false;
272   }
273   size_t total_bits = bit_count;
274 
275   // For simplicity, push the bits we want to read from val to the highest bits.
276   val <<= (sizeof(uint64_t) * 8 - bit_count);
277 
278   uint8_t* bytes = writable_bytes_ + byte_offset_;
279 
280   // The first byte is relatively special; the bit offset to write to may put us
281   // in the middle of the byte, and the total bit count to write may require we
282   // save the bits at the end of the byte.
283   size_t remaining_bits_in_current_byte = 8 - bit_offset_;
284   size_t bits_in_first_byte =
285       std::min(bit_count, remaining_bits_in_current_byte);
286   *bytes = WritePartialByte(HighestByte(val), bits_in_first_byte, *bytes,
287                             bit_offset_);
288   if (bit_count <= remaining_bits_in_current_byte) {
289     // Nothing left to write, so quit early.
290     return ConsumeBits(total_bits);
291   }
292 
293   // Subtract what we've written from the bit count, shift it off the value, and
294   // write the remaining full bytes.
295   val <<= bits_in_first_byte;
296   bytes++;
297   bit_count -= bits_in_first_byte;
298   while (bit_count >= 8) {
299     *bytes++ = HighestByte(val);
300     val <<= 8;
301     bit_count -= 8;
302   }
303 
304   // Last byte may also be partial, so write the remaining bits from the top of
305   // val.
306   if (bit_count > 0) {
307     *bytes = WritePartialByte(HighestByte(val), bit_count, *bytes, 0);
308   }
309 
310   // All done! Consume the bits we've written.
311   return ConsumeBits(total_bits);
312 }
313 
WriteNonSymmetric(uint32_t val,uint32_t num_values)314 bool BitBufferWriter::WriteNonSymmetric(uint32_t val, uint32_t num_values) {
315   RTC_DCHECK_LT(val, num_values);
316   RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
317   if (num_values == 1) {
318     // When there is only one possible value, it requires zero bits to store it.
319     // But WriteBits doesn't support writing zero bits.
320     return true;
321   }
322   size_t count_bits = CountBits(num_values);
323   uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
324 
325   return val < num_min_bits_values
326              ? WriteBits(val, count_bits - 1)
327              : WriteBits(val + num_min_bits_values, count_bits);
328 }
329 
SizeNonSymmetricBits(uint32_t val,uint32_t num_values)330 size_t BitBufferWriter::SizeNonSymmetricBits(uint32_t val,
331                                              uint32_t num_values) {
332   RTC_DCHECK_LT(val, num_values);
333   RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
334   size_t count_bits = CountBits(num_values);
335   uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
336 
337   return val < num_min_bits_values ? (count_bits - 1) : count_bits;
338 }
339 
WriteExponentialGolomb(uint32_t val)340 bool BitBufferWriter::WriteExponentialGolomb(uint32_t val) {
341   // We don't support reading UINT32_MAX, because it doesn't fit in a uint32_t
342   // when encoded, so don't support writing it either.
343   if (val == std::numeric_limits<uint32_t>::max()) {
344     return false;
345   }
346   uint64_t val_to_encode = static_cast<uint64_t>(val) + 1;
347 
348   // We need to write CountBits(val+1) 0s and then val+1. Since val (as a
349   // uint64_t) has leading zeros, we can just write the total golomb encoded
350   // size worth of bits, knowing the value will appear last.
351   return WriteBits(val_to_encode, CountBits(val_to_encode) * 2 - 1);
352 }
353 
WriteSignedExponentialGolomb(int32_t val)354 bool BitBufferWriter::WriteSignedExponentialGolomb(int32_t val) {
355   if (val == 0) {
356     return WriteExponentialGolomb(0);
357   } else if (val > 0) {
358     uint32_t signed_val = val;
359     return WriteExponentialGolomb((signed_val * 2) - 1);
360   } else {
361     if (val == std::numeric_limits<int32_t>::min())
362       return false;  // Not supported, would cause overflow.
363     uint32_t signed_val = -val;
364     return WriteExponentialGolomb(signed_val * 2);
365   }
366 }
367 
368 }  // namespace rtc
369