blob: 222d30ca0b2b262b9411df2a4b168d0d7208d624 [file] [log] [blame]
Noah Richardsbbf7c862015-04-21 16:30:13 -07001/*
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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "rtc_base/bit_buffer.h"
Noah Richardsbbf7c862015-04-21 16:30:13 -070012
Noah Richards86153c22015-04-28 15:13:44 -070013#include <algorithm>
Noah Richardsbbf7c862015-04-21 16:30:13 -070014#include <limits>
15
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "rtc_base/checks.h"
Noah Richardsbbf7c862015-04-21 16:30:13 -070017
18namespace {
19
20// Returns the lowest (right-most) |bit_count| bits in |byte|.
Noah Richards9b9f1c42015-05-12 12:20:47 -070021uint8_t LowestBits(uint8_t byte, size_t bit_count) {
kwibergaf476c72016-11-28 15:21:39 -080022 RTC_DCHECK_LE(bit_count, 8);
Noah Richards86153c22015-04-28 15:13:44 -070023 return byte & ((1 << bit_count) - 1);
Noah Richardsbbf7c862015-04-21 16:30:13 -070024}
25
26// Returns the highest (left-most) |bit_count| bits in |byte|, shifted to the
27// lowest bits (to the right).
Noah Richards9b9f1c42015-05-12 12:20:47 -070028uint8_t HighestBits(uint8_t byte, size_t bit_count) {
kwibergaf476c72016-11-28 15:21:39 -080029 RTC_DCHECK_LE(bit_count, 8);
Noah Richards9b9f1c42015-05-12 12:20:47 -070030 uint8_t shift = 8 - static_cast<uint8_t>(bit_count);
31 uint8_t mask = 0xFF << shift;
Noah Richardsbbf7c862015-04-21 16:30:13 -070032 return (byte & mask) >> shift;
33}
34
Noah Richards9b9f1c42015-05-12 12:20:47 -070035// Returns the highest byte of |val| in a uint8_t.
36uint8_t HighestByte(uint64_t val) {
37 return static_cast<uint8_t>(val >> 56);
Noah Richards86153c22015-04-28 15:13:44 -070038}
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.
Noah Richards9b9f1c42015-05-12 12:20:47 -070043uint8_t WritePartialByte(uint8_t source,
44 size_t source_bit_count,
45 uint8_t target,
46 size_t target_bit_offset) {
henrikg91d6ede2015-09-17 00:24:34 -070047 RTC_DCHECK(target_bit_offset < 8);
48 RTC_DCHECK(source_bit_count < 9);
49 RTC_DCHECK(source_bit_count <= (8 - target_bit_offset));
Noah Richards86153c22015-04-28 15:13:44 -070050 // Generate a mask for just the bits we're going to overwrite, so:
Noah Richards9b9f1c42015-05-12 12:20:47 -070051 uint8_t mask =
Noah Richards86153c22015-04-28 15:13:44 -070052 // The number of bits we want, in the most significant bits...
Noah Richards9b9f1c42015-05-12 12:20:47 -070053 static_cast<uint8_t>(0xFF << (8 - source_bit_count))
Noah Richards86153c22015-04-28 15:13:44 -070054 // ...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.
Noah Richards9b9f1c42015-05-12 12:20:47 -070063size_t CountBits(uint64_t val) {
Noah Richards86153c22015-04-28 15:13:44 -070064 size_t bit_count = 0;
65 while (val != 0) {
66 bit_count++;
67 val >>= 1;
68 }
69 return bit_count;
70}
71
Noah Richardsbbf7c862015-04-21 16:30:13 -070072} // namespace
73
74namespace rtc {
75
Noah Richards9b9f1c42015-05-12 12:20:47 -070076BitBuffer::BitBuffer(const uint8_t* bytes, size_t byte_count)
Noah Richardsbbf7c862015-04-21 16:30:13 -070077 : bytes_(bytes), byte_count_(byte_count), byte_offset_(), bit_offset_() {
henrikg91d6ede2015-09-17 00:24:34 -070078 RTC_DCHECK(static_cast<uint64_t>(byte_count_) <=
79 std::numeric_limits<uint32_t>::max());
Noah Richardsbbf7c862015-04-21 16:30:13 -070080}
81
Noah Richards9b9f1c42015-05-12 12:20:47 -070082uint64_t BitBuffer::RemainingBitCount() const {
83 return (static_cast<uint64_t>(byte_count_) - byte_offset_) * 8 - bit_offset_;
Noah Richardsbbf7c862015-04-21 16:30:13 -070084}
85
Noah Richards9b9f1c42015-05-12 12:20:47 -070086bool BitBuffer::ReadUInt8(uint8_t* val) {
87 uint32_t bit_val;
88 if (!ReadBits(&bit_val, sizeof(uint8_t) * 8)) {
Noah Richardsbbf7c862015-04-21 16:30:13 -070089 return false;
90 }
henrikg91d6ede2015-09-17 00:24:34 -070091 RTC_DCHECK(bit_val <= std::numeric_limits<uint8_t>::max());
Noah Richards9b9f1c42015-05-12 12:20:47 -070092 *val = static_cast<uint8_t>(bit_val);
Noah Richardsbbf7c862015-04-21 16:30:13 -070093 return true;
94}
95
Noah Richards9b9f1c42015-05-12 12:20:47 -070096bool BitBuffer::ReadUInt16(uint16_t* val) {
97 uint32_t bit_val;
98 if (!ReadBits(&bit_val, sizeof(uint16_t) * 8)) {
Noah Richardsbbf7c862015-04-21 16:30:13 -070099 return false;
100 }
henrikg91d6ede2015-09-17 00:24:34 -0700101 RTC_DCHECK(bit_val <= std::numeric_limits<uint16_t>::max());
Noah Richards9b9f1c42015-05-12 12:20:47 -0700102 *val = static_cast<uint16_t>(bit_val);
Noah Richardsbbf7c862015-04-21 16:30:13 -0700103 return true;
104}
105
Noah Richards9b9f1c42015-05-12 12:20:47 -0700106bool BitBuffer::ReadUInt32(uint32_t* val) {
107 return ReadBits(val, sizeof(uint32_t) * 8);
Noah Richardsbbf7c862015-04-21 16:30:13 -0700108}
109
Noah Richards9b9f1c42015-05-12 12:20:47 -0700110bool BitBuffer::PeekBits(uint32_t* val, size_t bit_count) {
Niels Möller827cf3c2018-09-27 11:02:08 +0200111 // 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);
Noah Richardsbbf7c862015-04-21 16:30:13 -0700115 if (!val || bit_count > RemainingBitCount() || bit_count > 32) {
116 return false;
117 }
Noah Richards9b9f1c42015-05-12 12:20:47 -0700118 const uint8_t* bytes = bytes_ + byte_offset_;
Noah Richardsbbf7c862015-04-21 16:30:13 -0700119 size_t remaining_bits_in_current_byte = 8 - bit_offset_;
Noah Richards9b9f1c42015-05-12 12:20:47 -0700120 uint32_t bits = LowestBits(*bytes++, remaining_bits_in_current_byte);
Noah Richardsbbf7c862015-04-21 16:30:13 -0700121 // 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
Björn Terelius39284362021-05-11 15:30:12 +0200144bool BitBuffer::PeekBits(uint64_t* val, size_t bit_count) {
145 // TODO(nisse): Could allow bit_count == 0 and always return success. But
146 // current code reads one byte beyond end of buffer in the case that
147 // RemainingBitCount() == 0 and bit_count == 0.
148 RTC_DCHECK(bit_count > 0);
149 if (!val || bit_count > RemainingBitCount() || bit_count > 64) {
150 return false;
151 }
152 const uint8_t* bytes = bytes_ + byte_offset_;
153 size_t remaining_bits_in_current_byte = 8 - bit_offset_;
154 uint64_t bits = LowestBits(*bytes++, remaining_bits_in_current_byte);
155 // If we're reading fewer bits than what's left in the current byte, just
156 // return the portion of this byte that we need.
157 if (bit_count < remaining_bits_in_current_byte) {
158 *val = HighestBits(bits, bit_offset_ + bit_count);
159 return true;
160 }
161 // Otherwise, subtract what we've read from the bit count and read as many
162 // full bytes as we can into bits.
163 bit_count -= remaining_bits_in_current_byte;
164 while (bit_count >= 8) {
165 bits = (bits << 8) | *bytes++;
166 bit_count -= 8;
167 }
168 // Whatever we have left is smaller than a byte, so grab just the bits we need
169 // and shift them into the lowest bits.
170 if (bit_count > 0) {
171 bits <<= bit_count;
172 bits |= HighestBits(*bytes, bit_count);
173 }
174 *val = bits;
175 return true;
176}
177
Noah Richards9b9f1c42015-05-12 12:20:47 -0700178bool BitBuffer::ReadBits(uint32_t* val, size_t bit_count) {
Noah Richardsbbf7c862015-04-21 16:30:13 -0700179 return PeekBits(val, bit_count) && ConsumeBits(bit_count);
180}
181
Björn Terelius39284362021-05-11 15:30:12 +0200182bool BitBuffer::ReadBits(uint64_t* val, size_t bit_count) {
183 return PeekBits(val, bit_count) && ConsumeBits(bit_count);
184}
185
Noah Richardsbbf7c862015-04-21 16:30:13 -0700186bool BitBuffer::ConsumeBytes(size_t byte_count) {
187 return ConsumeBits(byte_count * 8);
188}
189
190bool BitBuffer::ConsumeBits(size_t bit_count) {
191 if (bit_count > RemainingBitCount()) {
192 return false;
193 }
194
195 byte_offset_ += (bit_offset_ + bit_count) / 8;
196 bit_offset_ = (bit_offset_ + bit_count) % 8;
197 return true;
198}
199
Danil Chapovalova2b30d82019-07-03 14:41:50 +0200200bool BitBuffer::ReadNonSymmetric(uint32_t* val, uint32_t num_values) {
201 RTC_DCHECK_GT(num_values, 0);
202 RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
Danil Chapovalova9e1b492020-07-08 11:24:19 +0200203 if (num_values == 1) {
204 // When there is only one possible value, it requires zero bits to store it.
205 // But ReadBits doesn't support reading zero bits.
206 *val = 0;
207 return true;
208 }
Danil Chapovalova2b30d82019-07-03 14:41:50 +0200209 size_t count_bits = CountBits(num_values);
210 uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
211
212 if (!ReadBits(val, count_bits - 1)) {
213 return false;
214 }
215
216 if (*val < num_min_bits_values) {
217 return true;
218 }
219
220 uint32_t extra_bit;
221 if (!ReadBits(&extra_bit, /*bit_count=*/1)) {
222 return false;
223 }
224
225 *val = (*val << 1) + extra_bit - num_min_bits_values;
226 return true;
227}
228
Noah Richards9b9f1c42015-05-12 12:20:47 -0700229bool BitBuffer::ReadExponentialGolomb(uint32_t* val) {
Noah Richardsbbf7c862015-04-21 16:30:13 -0700230 if (!val) {
231 return false;
232 }
233 // Store off the current byte/bit offset, in case we want to restore them due
234 // to a failed parse.
235 size_t original_byte_offset = byte_offset_;
236 size_t original_bit_offset = bit_offset_;
237
238 // Count the number of leading 0 bits by peeking/consuming them one at a time.
239 size_t zero_bit_count = 0;
Noah Richards9b9f1c42015-05-12 12:20:47 -0700240 uint32_t peeked_bit;
Noah Richardsbbf7c862015-04-21 16:30:13 -0700241 while (PeekBits(&peeked_bit, 1) && peeked_bit == 0) {
242 zero_bit_count++;
243 ConsumeBits(1);
244 }
245
246 // We should either be at the end of the stream, or the next bit should be 1.
henrikg91d6ede2015-09-17 00:24:34 -0700247 RTC_DCHECK(!PeekBits(&peeked_bit, 1) || peeked_bit == 1);
Noah Richardsbbf7c862015-04-21 16:30:13 -0700248
249 // The bit count of the value is the number of zeros + 1. Make sure that many
Noah Richards9b9f1c42015-05-12 12:20:47 -0700250 // bits fits in a uint32_t and that we have enough bits left for it, and then
Noah Richardsbbf7c862015-04-21 16:30:13 -0700251 // read the value.
252 size_t value_bit_count = zero_bit_count + 1;
253 if (value_bit_count > 32 || !ReadBits(val, value_bit_count)) {
henrikg91d6ede2015-09-17 00:24:34 -0700254 RTC_CHECK(Seek(original_byte_offset, original_bit_offset));
Noah Richardsbbf7c862015-04-21 16:30:13 -0700255 return false;
256 }
257 *val -= 1;
258 return true;
259}
260
Peter Boström8c266e62015-09-24 15:06:50 +0200261bool BitBuffer::ReadSignedExponentialGolomb(int32_t* val) {
262 uint32_t unsigned_val;
263 if (!ReadExponentialGolomb(&unsigned_val)) {
264 return false;
265 }
266 if ((unsigned_val & 1) == 0) {
267 *val = -static_cast<int32_t>(unsigned_val / 2);
268 } else {
269 *val = (unsigned_val + 1) / 2;
270 }
271 return true;
272}
273
Yves Gerey665174f2018-06-19 15:03:05 +0200274void BitBuffer::GetCurrentOffset(size_t* out_byte_offset,
275 size_t* out_bit_offset) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800276 RTC_CHECK(out_byte_offset != nullptr);
277 RTC_CHECK(out_bit_offset != nullptr);
Noah Richards86153c22015-04-28 15:13:44 -0700278 *out_byte_offset = byte_offset_;
279 *out_bit_offset = bit_offset_;
280}
281
282bool BitBuffer::Seek(size_t byte_offset, size_t bit_offset) {
283 if (byte_offset > byte_count_ || bit_offset > 7 ||
284 (byte_offset == byte_count_ && bit_offset > 0)) {
285 return false;
286 }
287 byte_offset_ = byte_offset;
288 bit_offset_ = bit_offset;
289 return true;
290}
291
Noah Richards9b9f1c42015-05-12 12:20:47 -0700292BitBufferWriter::BitBufferWriter(uint8_t* bytes, size_t byte_count)
Yves Gerey665174f2018-06-19 15:03:05 +0200293 : BitBuffer(bytes, byte_count), writable_bytes_(bytes) {}
Noah Richards86153c22015-04-28 15:13:44 -0700294
Noah Richards9b9f1c42015-05-12 12:20:47 -0700295bool BitBufferWriter::WriteUInt8(uint8_t val) {
296 return WriteBits(val, sizeof(uint8_t) * 8);
Noah Richards86153c22015-04-28 15:13:44 -0700297}
298
Noah Richards9b9f1c42015-05-12 12:20:47 -0700299bool BitBufferWriter::WriteUInt16(uint16_t val) {
300 return WriteBits(val, sizeof(uint16_t) * 8);
Noah Richards86153c22015-04-28 15:13:44 -0700301}
302
Noah Richards9b9f1c42015-05-12 12:20:47 -0700303bool BitBufferWriter::WriteUInt32(uint32_t val) {
304 return WriteBits(val, sizeof(uint32_t) * 8);
Noah Richards86153c22015-04-28 15:13:44 -0700305}
306
Noah Richards9b9f1c42015-05-12 12:20:47 -0700307bool BitBufferWriter::WriteBits(uint64_t val, size_t bit_count) {
Noah Richards86153c22015-04-28 15:13:44 -0700308 if (bit_count > RemainingBitCount()) {
309 return false;
310 }
311 size_t total_bits = bit_count;
312
313 // For simplicity, push the bits we want to read from val to the highest bits.
Noah Richards9b9f1c42015-05-12 12:20:47 -0700314 val <<= (sizeof(uint64_t) * 8 - bit_count);
Noah Richards86153c22015-04-28 15:13:44 -0700315
Noah Richards9b9f1c42015-05-12 12:20:47 -0700316 uint8_t* bytes = writable_bytes_ + byte_offset_;
Noah Richards86153c22015-04-28 15:13:44 -0700317
318 // The first byte is relatively special; the bit offset to write to may put us
319 // in the middle of the byte, and the total bit count to write may require we
320 // save the bits at the end of the byte.
321 size_t remaining_bits_in_current_byte = 8 - bit_offset_;
322 size_t bits_in_first_byte =
323 std::min(bit_count, remaining_bits_in_current_byte);
Yves Gerey665174f2018-06-19 15:03:05 +0200324 *bytes = WritePartialByte(HighestByte(val), bits_in_first_byte, *bytes,
325 bit_offset_);
Noah Richards86153c22015-04-28 15:13:44 -0700326 if (bit_count <= remaining_bits_in_current_byte) {
327 // Nothing left to write, so quit early.
328 return ConsumeBits(total_bits);
329 }
330
331 // Subtract what we've written from the bit count, shift it off the value, and
332 // write the remaining full bytes.
333 val <<= bits_in_first_byte;
334 bytes++;
335 bit_count -= bits_in_first_byte;
336 while (bit_count >= 8) {
337 *bytes++ = HighestByte(val);
338 val <<= 8;
339 bit_count -= 8;
340 }
341
342 // Last byte may also be partial, so write the remaining bits from the top of
343 // val.
344 if (bit_count > 0) {
345 *bytes = WritePartialByte(HighestByte(val), bit_count, *bytes, 0);
346 }
347
348 // All done! Consume the bits we've written.
349 return ConsumeBits(total_bits);
350}
351
Danil Chapovalova2b30d82019-07-03 14:41:50 +0200352bool BitBufferWriter::WriteNonSymmetric(uint32_t val, uint32_t num_values) {
353 RTC_DCHECK_LT(val, num_values);
354 RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
Danil Chapovalova9e1b492020-07-08 11:24:19 +0200355 if (num_values == 1) {
356 // When there is only one possible value, it requires zero bits to store it.
357 // But WriteBits doesn't support writing zero bits.
358 return true;
359 }
Danil Chapovalova2b30d82019-07-03 14:41:50 +0200360 size_t count_bits = CountBits(num_values);
361 uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
362
363 return val < num_min_bits_values
364 ? WriteBits(val, count_bits - 1)
365 : WriteBits(val + num_min_bits_values, count_bits);
366}
367
368size_t BitBufferWriter::SizeNonSymmetricBits(uint32_t val,
369 uint32_t num_values) {
370 RTC_DCHECK_LT(val, num_values);
371 RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
372 size_t count_bits = CountBits(num_values);
373 uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
374
375 return val < num_min_bits_values ? (count_bits - 1) : count_bits;
376}
377
Noah Richards9b9f1c42015-05-12 12:20:47 -0700378bool BitBufferWriter::WriteExponentialGolomb(uint32_t val) {
379 // We don't support reading UINT32_MAX, because it doesn't fit in a uint32_t
Noah Richards86153c22015-04-28 15:13:44 -0700380 // when encoded, so don't support writing it either.
Noah Richards9b9f1c42015-05-12 12:20:47 -0700381 if (val == std::numeric_limits<uint32_t>::max()) {
Noah Richards86153c22015-04-28 15:13:44 -0700382 return false;
383 }
Noah Richards9b9f1c42015-05-12 12:20:47 -0700384 uint64_t val_to_encode = static_cast<uint64_t>(val) + 1;
Noah Richards86153c22015-04-28 15:13:44 -0700385
386 // We need to write CountBits(val+1) 0s and then val+1. Since val (as a
Noah Richards9b9f1c42015-05-12 12:20:47 -0700387 // uint64_t) has leading zeros, we can just write the total golomb encoded
388 // size worth of bits, knowing the value will appear last.
Noah Richards86153c22015-04-28 15:13:44 -0700389 return WriteBits(val_to_encode, CountBits(val_to_encode) * 2 - 1);
390}
391
sprang52033d62016-06-02 02:43:32 -0700392bool BitBufferWriter::WriteSignedExponentialGolomb(int32_t val) {
393 if (val == 0) {
394 return WriteExponentialGolomb(0);
395 } else if (val > 0) {
396 uint32_t signed_val = val;
397 return WriteExponentialGolomb((signed_val * 2) - 1);
398 } else {
399 if (val == std::numeric_limits<int32_t>::min())
400 return false; // Not supported, would cause overflow.
401 uint32_t signed_val = -val;
402 return WriteExponentialGolomb(signed_val * 2);
403 }
404}
405
Noah Richardsbbf7c862015-04-21 16:30:13 -0700406} // namespace rtc