xref: /aosp_15_r20/external/webrtc/rtc_base/bit_buffer.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
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 "absl/numeric/bits.h"
17 #include "rtc_base/checks.h"
18 
19 namespace {
20 
21 // Returns the highest byte of `val` in a uint8_t.
HighestByte(uint64_t val)22 uint8_t HighestByte(uint64_t val) {
23   return static_cast<uint8_t>(val >> 56);
24 }
25 
26 // Returns the result of writing partial data from `source`, of
27 // `source_bit_count` size in the highest bits, to `target` at
28 // `target_bit_offset` from the highest bit.
WritePartialByte(uint8_t source,size_t source_bit_count,uint8_t target,size_t target_bit_offset)29 uint8_t WritePartialByte(uint8_t source,
30                          size_t source_bit_count,
31                          uint8_t target,
32                          size_t target_bit_offset) {
33   RTC_DCHECK(target_bit_offset < 8);
34   RTC_DCHECK(source_bit_count < 9);
35   RTC_DCHECK(source_bit_count <= (8 - target_bit_offset));
36   // Generate a mask for just the bits we're going to overwrite, so:
37   uint8_t mask =
38       // The number of bits we want, in the most significant bits...
39       static_cast<uint8_t>(0xFF << (8 - source_bit_count))
40       // ...shifted over to the target offset from the most signficant bit.
41       >> target_bit_offset;
42 
43   // We want the target, with the bits we'll overwrite masked off, or'ed with
44   // the bits from the source we want.
45   return (target & ~mask) | (source >> target_bit_offset);
46 }
47 
48 }  // namespace
49 
50 namespace rtc {
51 
BitBufferWriter(uint8_t * bytes,size_t byte_count)52 BitBufferWriter::BitBufferWriter(uint8_t* bytes, size_t byte_count)
53     : writable_bytes_(bytes),
54       byte_count_(byte_count),
55       byte_offset_(),
56       bit_offset_() {
57   RTC_DCHECK(static_cast<uint64_t>(byte_count_) <=
58              std::numeric_limits<uint32_t>::max());
59 }
60 
RemainingBitCount() const61 uint64_t BitBufferWriter::RemainingBitCount() const {
62   return (static_cast<uint64_t>(byte_count_) - byte_offset_) * 8 - bit_offset_;
63 }
64 
ConsumeBytes(size_t byte_count)65 bool BitBufferWriter::ConsumeBytes(size_t byte_count) {
66   return ConsumeBits(byte_count * 8);
67 }
68 
ConsumeBits(size_t bit_count)69 bool BitBufferWriter::ConsumeBits(size_t bit_count) {
70   if (bit_count > RemainingBitCount()) {
71     return false;
72   }
73 
74   byte_offset_ += (bit_offset_ + bit_count) / 8;
75   bit_offset_ = (bit_offset_ + bit_count) % 8;
76   return true;
77 }
78 
GetCurrentOffset(size_t * out_byte_offset,size_t * out_bit_offset)79 void BitBufferWriter::GetCurrentOffset(size_t* out_byte_offset,
80                                        size_t* out_bit_offset) {
81   RTC_CHECK(out_byte_offset != nullptr);
82   RTC_CHECK(out_bit_offset != nullptr);
83   *out_byte_offset = byte_offset_;
84   *out_bit_offset = bit_offset_;
85 }
86 
Seek(size_t byte_offset,size_t bit_offset)87 bool BitBufferWriter::Seek(size_t byte_offset, size_t bit_offset) {
88   if (byte_offset > byte_count_ || bit_offset > 7 ||
89       (byte_offset == byte_count_ && bit_offset > 0)) {
90     return false;
91   }
92   byte_offset_ = byte_offset;
93   bit_offset_ = bit_offset;
94   return true;
95 }
96 
WriteUInt8(uint8_t val)97 bool BitBufferWriter::WriteUInt8(uint8_t val) {
98   return WriteBits(val, sizeof(uint8_t) * 8);
99 }
100 
WriteUInt16(uint16_t val)101 bool BitBufferWriter::WriteUInt16(uint16_t val) {
102   return WriteBits(val, sizeof(uint16_t) * 8);
103 }
104 
WriteUInt32(uint32_t val)105 bool BitBufferWriter::WriteUInt32(uint32_t val) {
106   return WriteBits(val, sizeof(uint32_t) * 8);
107 }
108 
WriteBits(uint64_t val,size_t bit_count)109 bool BitBufferWriter::WriteBits(uint64_t val, size_t bit_count) {
110   if (bit_count > RemainingBitCount()) {
111     return false;
112   }
113   size_t total_bits = bit_count;
114 
115   // For simplicity, push the bits we want to read from val to the highest bits.
116   val <<= (sizeof(uint64_t) * 8 - bit_count);
117 
118   uint8_t* bytes = writable_bytes_ + byte_offset_;
119 
120   // The first byte is relatively special; the bit offset to write to may put us
121   // in the middle of the byte, and the total bit count to write may require we
122   // save the bits at the end of the byte.
123   size_t remaining_bits_in_current_byte = 8 - bit_offset_;
124   size_t bits_in_first_byte =
125       std::min(bit_count, remaining_bits_in_current_byte);
126   *bytes = WritePartialByte(HighestByte(val), bits_in_first_byte, *bytes,
127                             bit_offset_);
128   if (bit_count <= remaining_bits_in_current_byte) {
129     // Nothing left to write, so quit early.
130     return ConsumeBits(total_bits);
131   }
132 
133   // Subtract what we've written from the bit count, shift it off the value, and
134   // write the remaining full bytes.
135   val <<= bits_in_first_byte;
136   bytes++;
137   bit_count -= bits_in_first_byte;
138   while (bit_count >= 8) {
139     *bytes++ = HighestByte(val);
140     val <<= 8;
141     bit_count -= 8;
142   }
143 
144   // Last byte may also be partial, so write the remaining bits from the top of
145   // val.
146   if (bit_count > 0) {
147     *bytes = WritePartialByte(HighestByte(val), bit_count, *bytes, 0);
148   }
149 
150   // All done! Consume the bits we've written.
151   return ConsumeBits(total_bits);
152 }
153 
WriteNonSymmetric(uint32_t val,uint32_t num_values)154 bool BitBufferWriter::WriteNonSymmetric(uint32_t val, uint32_t num_values) {
155   RTC_DCHECK_LT(val, num_values);
156   RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
157   if (num_values == 1) {
158     // When there is only one possible value, it requires zero bits to store it.
159     // But WriteBits doesn't support writing zero bits.
160     return true;
161   }
162   size_t count_bits = absl::bit_width(num_values);
163   uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
164 
165   return val < num_min_bits_values
166              ? WriteBits(val, count_bits - 1)
167              : WriteBits(val + num_min_bits_values, count_bits);
168 }
169 
SizeNonSymmetricBits(uint32_t val,uint32_t num_values)170 size_t BitBufferWriter::SizeNonSymmetricBits(uint32_t val,
171                                              uint32_t num_values) {
172   RTC_DCHECK_LT(val, num_values);
173   RTC_DCHECK_LE(num_values, uint32_t{1} << 31);
174   size_t count_bits = absl::bit_width(num_values);
175   uint32_t num_min_bits_values = (uint32_t{1} << count_bits) - num_values;
176 
177   return val < num_min_bits_values ? (count_bits - 1) : count_bits;
178 }
179 
WriteExponentialGolomb(uint32_t val)180 bool BitBufferWriter::WriteExponentialGolomb(uint32_t val) {
181   // We don't support reading UINT32_MAX, because it doesn't fit in a uint32_t
182   // when encoded, so don't support writing it either.
183   if (val == std::numeric_limits<uint32_t>::max()) {
184     return false;
185   }
186   uint64_t val_to_encode = static_cast<uint64_t>(val) + 1;
187 
188   // We need to write bit_width(val+1) 0s and then val+1. Since val (as a
189   // uint64_t) has leading zeros, we can just write the total golomb encoded
190   // size worth of bits, knowing the value will appear last.
191   return WriteBits(val_to_encode, absl::bit_width(val_to_encode) * 2 - 1);
192 }
193 
WriteSignedExponentialGolomb(int32_t val)194 bool BitBufferWriter::WriteSignedExponentialGolomb(int32_t val) {
195   if (val == 0) {
196     return WriteExponentialGolomb(0);
197   } else if (val > 0) {
198     uint32_t signed_val = val;
199     return WriteExponentialGolomb((signed_val * 2) - 1);
200   } else {
201     if (val == std::numeric_limits<int32_t>::min())
202       return false;  // Not supported, would cause overflow.
203     uint32_t signed_val = -val;
204     return WriteExponentialGolomb(signed_val * 2);
205   }
206 }
207 
208 }  // namespace rtc
209