forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

bits.rs323 lines, 10.0 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 /// Read `n` bits (`n <= 32`) MSB-first, zero-filled past the end of the
136 /// stream — the CABAC engine's supply contract (see the module note in
137 /// `cabac.rs`): a conformant stream never depends on those bits, and the
138 /// phantom reads do not advance `bit_position` beyond the real ones.
139 #[inline]
140 pub fn bits_zero_fill(&mut self, n: u32) -> u32 {
141 debug_assert!(n <= 32);
142 if n == 0 {
143 return 0;
144 }
145 if self.cached < n {
146 self.refill();
147 }
148 if self.cached >= n {
149 let v = (self.cache >> (64 - n)) as u32;
150 self.cache <<= n;
151 self.cached -= n;
152 return v;
153 }
154 // Genuinely past the end: consume what is cached, zero-fill the rest.
155 let have = self.cached;
156 let v = if have == 0 {
157 0
158 } else {
159 ((self.cache >> (64 - have)) as u32) << (n - have)
160 };
161 self.cache <<= have;
162 self.cached = 0;
163 v
164 }
165
166 /// One bit, zero-filled past the end (see [`bits_zero_fill`]).
167 #[inline]
168 pub fn bit_zero_fill(&mut self) -> u32 {
169 self.bits_zero_fill(1)
170 }
171
172 /// Count leading zero bits up to and including the terminating one bit
173 /// (level_prefix / exp-Golomb prefix). Capped at `cap` zeros.
174 #[inline]
175 pub fn read_prefix_zeros(&mut self, cap: u32) -> Result<u32> {
176 let mut zeros = 0u32;
177 loop {
178 if self.cached == 0 {
179 self.refill();
180 if self.cached == 0 {
181 return Err(Error::NeedMore);
182 }
183 }
184 let lz = (self.cache.leading_zeros()).min(self.cached);
185 if lz < self.cached {
186 // Found the 1 bit within the cache.
187 zeros += lz;
188 if zeros > cap {
189 return Err(Error::corrupt("prefix run of zeros too long"));
190 }
191 self.cache <<= lz + 1;
192 self.cached -= lz + 1;
193 return Ok(zeros);
194 }
195 zeros += lz;
196 if zeros > cap {
197 return Err(Error::corrupt("prefix run of zeros too long"));
198 }
199 self.cache = 0;
200 self.cached = 0;
201 self.refill();
202 if self.cached == 0 && self.bits_remaining() == 0 {
203 return Err(Error::NeedMore);
204 }
205 }
206 }
207
208 /// Unsigned exp-Golomb `ue(v)` (prefix capped at 31 zeros, as in
209 /// `ec_core::BitReader::read_ue`).
210 #[inline]
211 pub fn read_ue(&mut self) -> Result<u32> {
212 let zeros = self.read_prefix_zeros(31)?;
213 if zeros == 0 {
214 return Ok(0);
215 }
216 let suffix = self.read_bits(zeros)?;
217 Ok((1u32 << zeros) - 1 + suffix)
218 }
219
220 /// Signed exp-Golomb `se(v)`.
221 #[inline]
222 pub fn read_se(&mut self) -> Result<i32> {
223 let k = self.read_ue()? as i64;
224 let v = if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) };
225 i32::try_from(v).map_err(|_| Error::corrupt("se(v) out of i32 range"))
226 }
227
228 /// Skip to the next byte boundary (I_PCM alignment).
229 #[inline]
230 pub fn align_to_byte(&mut self) {
231 let sub = (self.bit_position() % 8) as u32;
232 if sub != 0 {
233 let n = 8 - sub;
234 self.cache <<= n;
235 self.cached -= n.min(self.cached);
236 }
237 }
238
239 /// Borrow `n` whole bytes at the current (byte-aligned) position.
240 pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> {
241 if !self.bit_position().is_multiple_of(8) {
242 return Err(Error::corrupt("read_bytes at a non-byte-aligned position"));
243 }
244 let start = (self.bit_position() / 8) as usize;
245 let end = start.checked_add(n).ok_or(Error::NeedMore)?;
246 let slice = self.data.get(start..end).ok_or(Error::NeedMore)?;
247 // Drop the cache and reposition after the bytes.
248 self.cache = 0;
249 self.cached = 0;
250 self.next_byte = end;
251 self.refill();
252 Ok(slice)
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259 use ec_core::BitWriter;
260
261 #[test]
262 fn agrees_with_core_bitreader() {
263 let mut w = BitWriter::new();
264 for v in [0u32, 1, 5, 127, 4096] {
265 w.write_ue(v);
266 }
267 for v in [0i32, -3, 7, -128] {
268 w.write_se(v);
269 }
270 w.write_bits(0b1011, 4);
271 w.write_bit(true); // stop bit
272 w.align_to_byte();
273 let bytes = w.into_bytes();
274 let mut c = BitCursor::new(&bytes, 0);
275 for v in [0u32, 1, 5, 127, 4096] {
276 assert_eq!(c.read_ue().unwrap(), v);
277 }
278 for v in [0i32, -3, 7, -128] {
279 assert_eq!(c.read_se().unwrap(), v);
280 }
281 assert_eq!(c.read_bits(4).unwrap(), 0b1011);
282 assert!(!c.more_rbsp_data());
283 }
284
285 #[test]
286 fn peek16_pads_and_skip_tracks_position() {
287 let data = [0xAB, 0xCD];
288 let mut c = BitCursor::new(&data, 4);
289 assert_eq!(c.bit_position(), 4);
290 assert_eq!(c.peek16(), 0xBCD0);
291 c.skip(8).unwrap();
292 assert_eq!(c.bit_position(), 12);
293 assert_eq!(c.peek16(), 0xD000);
294 assert_eq!(c.read_bits(4).unwrap(), 0xD);
295 assert!(c.read_bit().is_err());
296 }
297
298 #[test]
299 fn pcm_bytes_and_alignment() {
300 let data = [0b1000_0000, 0x11, 0x22, 0x33];
301 let mut c = BitCursor::new(&data, 0);
302 assert!(c.read_bit().unwrap());
303 c.align_to_byte();
304 assert_eq!(c.read_bytes(2).unwrap(), &[0x11, 0x22]);
305 assert_eq!(c.read_bits(8).unwrap(), 0x33);
306 assert!(c.read_bytes(1).is_err());
307 }
308
309 #[test]
310 fn long_zero_runs_are_corrupt_or_need_more() {
311 // 33 zero bits then a 1: exp-Golomb prefix over the cap.
312 let data = [0, 0, 0, 0, 0b0100_0000];
313 let mut c = BitCursor::new(&data, 0);
314 assert!(matches!(c.read_ue(), Err(Error::Corrupt { .. })));
315 // All zeros: NeedMore (no stop bit at all).
316 let zeros = [0u8; 4];
317 let mut c = BitCursor::new(&zeros, 0);
318 assert!(matches!(
319 c.read_ue(),
320 Err(Error::NeedMore | Error::Corrupt { .. })
321 ));
322 }
323}