forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2a2adbaTahinli2 months ago2117 commits

bits.rs286 lines, 8.8 KiBHistoryRawDownload
1//! Slice-data bit cursor: a 64-bit-cached reader for the CAVLC hot loop.
2//!
3//! `ec_core::BitReader` is the family-wide, allocation-free contract type and
4//! stays the parser for headers. Slice data is different: it is read one to
5//! three bits at a time, millions of times per picture, so this cursor keeps
6//! the next 32..64 bits left-aligned in a register and refills by whole
7//! words. Truncation still surfaces as [`Error::NeedMore`]; the exp-Golomb
8//! prefix cap still turns runaway zeros into [`Error::Corrupt`].
9
10use ec_core::error::{Error, Result};
11
12/// Register-cached MSB-first bit reader over a byte slice.
13pub struct BitCursor<'a> {
14 data: &'a [u8],
15 /// Upcoming bits, left-aligned.
16 cache: u64,
17 /// Valid bit count in `cache`.
18 cached: u32,
19 /// Next byte of `data` to load into the cache.
20 next_byte: usize,
21 /// Index of the bit just past the `rbsp_stop_one_bit`, for
22 /// `more_rbsp_data()`; `data.len() * 8` when no stop bit exists.
23 stop_bit: u64,
24}
25
26impl<'a> BitCursor<'a> {
27 /// A cursor over `data`, positioned `bit_pos` bits in.
28 pub fn new(data: &'a [u8], bit_pos: u64) -> BitCursor<'a> {
29 let stop_bit = match data.iter().rposition(|&b| b != 0) {
30 Some(i) => i as u64 * 8 + (7 - data[i].trailing_zeros() as u64),
31 None => data.len() as u64 * 8,
32 };
33 let mut c = BitCursor {
34 data,
35 cache: 0,
36 cached: 0,
37 next_byte: (bit_pos / 8) as usize,
38 stop_bit,
39 };
40 c.refill();
41 let sub = (bit_pos % 8) as u32;
42 c.cache <<= sub;
43 c.cached = c.cached.saturating_sub(sub);
44 c
45 }
46
47 /// Bits consumed so far.
48 #[inline]
49 pub fn bit_position(&self) -> u64 {
50 self.next_byte as u64 * 8 - u64::from(self.cached)
51 }
52
53 /// True while syntax elements remain before the RBSP stop bit
54 /// (spec 7.2 `more_rbsp_data()`).
55 #[inline]
56 pub fn more_rbsp_data(&self) -> bool {
57 self.bit_position() < self.stop_bit
58 }
59
60 #[inline]
61 fn refill(&mut self) {
62 while self.cached <= 56 {
63 let Some(&b) = self.data.get(self.next_byte) else {
64 break;
65 };
66 self.cache |= u64::from(b) << (56 - self.cached);
67 self.cached += 8;
68 self.next_byte += 1;
69 }
70 }
71
72 /// Bits left in the stream.
73 #[inline]
74 pub fn bits_remaining(&self) -> u64 {
75 (self.data.len() - self.next_byte) as u64 * 8 + u64::from(self.cached)
76 }
77
78 /// The next 16 bits left-aligned in a u32, zero-padded past the end.
79 #[inline]
80 pub fn peek16(&mut self) -> u32 {
81 if self.cached < 16 {
82 self.refill();
83 }
84 (self.cache >> 48) as u32 & 0xFFFF
85 }
86
87 /// Consume `n` bits (`n <= 16` after a `peek16`; general `n <= 32`).
88 #[inline]
89 pub fn skip(&mut self, n: u32) -> Result<()> {
90 if self.cached < n {
91 self.refill();
92 if self.cached < n {
93 return Err(Error::NeedMore);
94 }
95 }
96 self.cache <<= n;
97 self.cached -= n;
98 Ok(())
99 }
100
101 /// Read one bit.
102 #[inline]
103 pub fn read_bit(&mut self) -> Result<bool> {
104 if self.cached == 0 {
105 self.refill();
106 if self.cached == 0 {
107 return Err(Error::NeedMore);
108 }
109 }
110 let bit = self.cache >> 63 != 0;
111 self.cache <<= 1;
112 self.cached -= 1;
113 Ok(bit)
114 }
115
116 /// Read `n` bits (`n <= 32`) MSB-first.
117 #[inline]
118 pub fn read_bits(&mut self, n: u32) -> Result<u32> {
119 debug_assert!(n <= 32);
120 if n == 0 {
121 return Ok(0);
122 }
123 if self.cached < n {
124 self.refill();
125 if self.cached < n {
126 return Err(Error::NeedMore);
127 }
128 }
129 let v = (self.cache >> (64 - n)) as u32;
130 self.cache <<= n;
131 self.cached -= n;
132 Ok(v)
133 }
134
135 /// Count leading zero bits up to and including the terminating one bit
136 /// (level_prefix / exp-Golomb prefix). Capped at `cap` zeros.
137 #[inline]
138 pub fn read_prefix_zeros(&mut self, cap: u32) -> Result<u32> {
139 let mut zeros = 0u32;
140 loop {
141 if self.cached == 0 {
142 self.refill();
143 if self.cached == 0 {
144 return Err(Error::NeedMore);
145 }
146 }
147 let lz = (self.cache.leading_zeros()).min(self.cached);
148 if lz < self.cached {
149 // Found the 1 bit within the cache.
150 zeros += lz;
151 if zeros > cap {
152 return Err(Error::corrupt("prefix run of zeros too long"));
153 }
154 self.cache <<= lz + 1;
155 self.cached -= lz + 1;
156 return Ok(zeros);
157 }
158 zeros += lz;
159 if zeros > cap {
160 return Err(Error::corrupt("prefix run of zeros too long"));
161 }
162 self.cache = 0;
163 self.cached = 0;
164 self.refill();
165 if self.cached == 0 && self.bits_remaining() == 0 {
166 return Err(Error::NeedMore);
167 }
168 }
169 }
170
171 /// Unsigned exp-Golomb `ue(v)` (prefix capped at 31 zeros, as in
172 /// `ec_core::BitReader::read_ue`).
173 #[inline]
174 pub fn read_ue(&mut self) -> Result<u32> {
175 let zeros = self.read_prefix_zeros(31)?;
176 if zeros == 0 {
177 return Ok(0);
178 }
179 let suffix = self.read_bits(zeros)?;
180 Ok((1u32 << zeros) - 1 + suffix)
181 }
182
183 /// Signed exp-Golomb `se(v)`.
184 #[inline]
185 pub fn read_se(&mut self) -> Result<i32> {
186 let k = self.read_ue()? as i64;
187 let v = if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) };
188 i32::try_from(v).map_err(|_| Error::corrupt("se(v) out of i32 range"))
189 }
190
191 /// Skip to the next byte boundary (I_PCM alignment).
192 #[inline]
193 pub fn align_to_byte(&mut self) {
194 let sub = (self.bit_position() % 8) as u32;
195 if sub != 0 {
196 let n = 8 - sub;
197 self.cache <<= n;
198 self.cached -= n.min(self.cached);
199 }
200 }
201
202 /// Borrow `n` whole bytes at the current (byte-aligned) position.
203 pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> {
204 if !self.bit_position().is_multiple_of(8) {
205 return Err(Error::corrupt("read_bytes at a non-byte-aligned position"));
206 }
207 let start = (self.bit_position() / 8) as usize;
208 let end = start.checked_add(n).ok_or(Error::NeedMore)?;
209 let slice = self.data.get(start..end).ok_or(Error::NeedMore)?;
210 // Drop the cache and reposition after the bytes.
211 self.cache = 0;
212 self.cached = 0;
213 self.next_byte = end;
214 self.refill();
215 Ok(slice)
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use ec_core::BitWriter;
223
224 #[test]
225 fn agrees_with_core_bitreader() {
226 let mut w = BitWriter::new();
227 for v in [0u32, 1, 5, 127, 4096] {
228 w.write_ue(v);
229 }
230 for v in [0i32, -3, 7, -128] {
231 w.write_se(v);
232 }
233 w.write_bits(0b1011, 4);
234 w.write_bit(true); // stop bit
235 w.align_to_byte();
236 let bytes = w.into_bytes();
237 let mut c = BitCursor::new(&bytes, 0);
238 for v in [0u32, 1, 5, 127, 4096] {
239 assert_eq!(c.read_ue().unwrap(), v);
240 }
241 for v in [0i32, -3, 7, -128] {
242 assert_eq!(c.read_se().unwrap(), v);
243 }
244 assert_eq!(c.read_bits(4).unwrap(), 0b1011);
245 assert!(!c.more_rbsp_data());
246 }
247
248 #[test]
249 fn peek16_pads_and_skip_tracks_position() {
250 let data = [0xAB, 0xCD];
251 let mut c = BitCursor::new(&data, 4);
252 assert_eq!(c.bit_position(), 4);
253 assert_eq!(c.peek16(), 0xBCD0);
254 c.skip(8).unwrap();
255 assert_eq!(c.bit_position(), 12);
256 assert_eq!(c.peek16(), 0xD000);
257 assert_eq!(c.read_bits(4).unwrap(), 0xD);
258 assert!(c.read_bit().is_err());
259 }
260
261 #[test]
262 fn pcm_bytes_and_alignment() {
263 let data = [0b1000_0000, 0x11, 0x22, 0x33];
264 let mut c = BitCursor::new(&data, 0);
265 assert!(c.read_bit().unwrap());
266 c.align_to_byte();
267 assert_eq!(c.read_bytes(2).unwrap(), &[0x11, 0x22]);
268 assert_eq!(c.read_bits(8).unwrap(), 0x33);
269 assert!(c.read_bytes(1).is_err());
270 }
271
272 #[test]
273 fn long_zero_runs_are_corrupt_or_need_more() {
274 // 33 zero bits then a 1: exp-Golomb prefix over the cap.
275 let data = [0, 0, 0, 0, 0b0100_0000];
276 let mut c = BitCursor::new(&data, 0);
277 assert!(matches!(c.read_ue(), Err(Error::Corrupt { .. })));
278 // All zeros: NeedMore (no stop bit at all).
279 let zeros = [0u8; 4];
280 let mut c = BitCursor::new(&zeros, 0);
281 assert!(matches!(
282 c.read_ue(),
283 Err(Error::NeedMore | Error::Corrupt { .. })
284 ));
285 }
286}