1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//! MSB-first bit reader for AAC bitstreams.
// Untrusted input: narrowing casts are lint-enforced here (H-17).
#![warn(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_possible_wrap
)]
use crate::{Error, Result};
/// Reads bits most-significant-first from a byte slice (the order AAC uses).
pub struct BitReader<'a> {
data: &'a [u8],
/// Absolute bit position from the start of `data`.
pos: usize,
}
impl<'a> BitReader<'a> {
#[must_use]
pub fn new(data: &'a [u8]) -> Self {
BitReader { data, pos: 0 }
}
/// Total bits remaining.
#[must_use]
pub fn bits_left(&self) -> usize {
(self.data.len() * 8).saturating_sub(self.pos)
}
/// Read a single bit.
///
/// # Errors
///
/// Returns [`Error::InvalidData`] when no bits remain.
pub fn read_bit(&mut self) -> Result<u32> {
let byte = self.pos / 8;
if byte >= self.data.len() {
return Err(Error::invalid("aac: bit reader past end of data"));
}
let shift = 7 - (self.pos % 8);
let bit = (self.data[byte] >> shift) & 1;
self.pos += 1;
Ok(u32::from(bit))
}
/// Read `n` bits (0..=32) into a `u32`, MSB-first.
///
/// Word-at-a-time: one unaligned big-endian 64-bit window per call instead of
/// a loop over single bits. A read that would cross the end of the data is an
/// error, exactly as the bit loop it replaces (kept as `read_bits_slow`, the
/// test oracle).
///
/// # Errors
///
/// Returns [`Error::InvalidData`] if `n > 32` or fewer than `n` bits remain.
#[inline]
pub fn read_bits(&mut self, n: u32) -> Result<u32> {
if n > 32 {
return Err(Error::invalid("aac: read_bits > 32"));
}
if n == 0 {
return Ok(0);
}
if self.pos + n as usize > self.data.len() * 8 {
return Err(Error::invalid("aac: bit reader past end of data"));
}
let v = self.peek_window();
self.pos += n as usize;
#[allow(
clippy::cast_possible_truncation,
reason = "a 64-bit window shifted right by 64 - n (n <= 32) fits in u32"
)]
let out = (v >> (64 - n)) as u32;
Ok(out)
}
/// The 64 bits starting at the current position, left-aligned; bytes past the
/// end read as zero.
#[inline]
fn peek_window(&self) -> u64 {
let byte = self.pos / 8;
// A full window is one constant-length load; only the last seven bytes
// of the data take the zero-padded copy (a runtime-length copy is a real
// `memcpy` call, which every Huffman peek used to pay).
if let Some(w) = self.data.get(byte..byte + 8) {
// Cannot fail: `get(byte..byte + 8)` returned exactly eight bytes.
let w: [u8; 8] = w.try_into().expect("an 8-byte slice");
return u64::from_be_bytes(w) << (self.pos % 8);
}
let mut buf = [0u8; 8];
let end = (byte + 8).min(self.data.len());
if byte < end {
buf[..end - byte].copy_from_slice(&self.data[byte..end]);
}
u64::from_be_bytes(buf) << (self.pos % 8)
}
/// Look at the next `n` (<= 32) bits without consuming them; bits past the end
/// read as zero (for table-driven Huffman decoding).
#[inline]
#[must_use]
pub fn peek_bits(&self, n: u32) -> u32 {
if n == 0 {
return 0;
}
#[allow(
clippy::cast_possible_truncation,
reason = "a 64-bit window shifted right by 64 - n (n <= 32) fits in u32"
)]
let out = (self.peek_window() >> (64 - n)) as u32;
out
}
/// The whole byte slice being read (for decoders that keep their own bit
/// cache over it and hand the position back with `set_position`).
#[inline]
pub(crate) fn data(&self) -> &'a [u8] {
self.data
}
/// The 64 bits starting at bit `pos` of `data`, left-aligned; bytes past
/// the end read as zero (the free form of `peek_window`).
#[inline(always)]
pub(crate) fn window_at(data: &[u8], pos: usize) -> u64 {
let byte = pos / 8;
if let Some(w) = data.get(byte..byte + 8) {
// Cannot fail: `get(byte..byte + 8)` returned exactly eight bytes.
let w: [u8; 8] = w.try_into().expect("an 8-byte slice");
return u64::from_be_bytes(w) << (pos % 8);
}
let mut buf = [0u8; 8];
let end = (byte + 8).min(data.len());
if byte < end {
buf[..end - byte].copy_from_slice(&data[byte..end]);
}
u64::from_be_bytes(buf) << (pos % 8)
}
/// Absolute bit position from the start of the data.
#[must_use]
pub fn position(&self) -> usize {
self.pos
}
/// Seek to an absolute bit position (clamped to the end of the data).
pub fn set_position(&mut self, pos: usize) {
self.pos = pos.min(self.data.len() * 8);
}
#[cfg(test)]
fn read_bits_slow(&mut self, n: u32) -> Result<u32> {
let mut v = 0u32;
for _ in 0..n {
v = (v << 1) | self.read_bit()?;
}
Ok(v)
}
/// Read `n` (<= 8) bits as a `u8`: the value fits by construction.
///
/// # Errors
///
/// As [`read_bits`](Self::read_bits).
#[inline]
pub fn read_u8(&mut self, n: u32) -> Result<u8> {
debug_assert!(n <= 8);
// An `n`-bit read is below 2^n <= 256; the mask makes that local.
Ok((self.read_bits(n)? & 0xFF) as u8)
}
/// Read `n` (<= 16) bits as a `u16`: the value fits by construction.
///
/// # Errors
///
/// As [`read_bits`](Self::read_bits).
#[inline]
pub fn read_u16(&mut self, n: u32) -> Result<u16> {
debug_assert!(n <= 16);
// An `n`-bit read is below 2^n <= 65536; the mask makes that local.
Ok((self.read_bits(n)? & 0xFFFF) as u16)
}
/// Read `n` (<= 31) bits as a non-negative `i32`: the value fits by
/// construction.
///
/// # Errors
///
/// As [`read_bits`](Self::read_bits).
#[inline]
pub fn read_i32(&mut self, n: u32) -> Result<i32> {
debug_assert!(n <= 31);
// An `n`-bit read is below 2^n <= 2^31; the mask makes that local.
let v = self.read_bits(n)? & 0x7FFF_FFFF;
#[allow(
clippy::cast_possible_wrap,
reason = "masked to 31 bits, so the value is below 2^31"
)]
let out = v as i32;
Ok(out)
}
/// Read one bit as a bool.
///
/// # Errors
///
/// Returns [`Error::InvalidData`] when no bits remain.
pub fn read_bool(&mut self) -> Result<bool> {
Ok(self.read_bit()? != 0)
}
/// Skip `n` bits.
///
/// # Errors
///
/// Returns [`Error::InvalidData`] if fewer than `n` bits remain; the position is then unchanged.
pub fn skip(&mut self, n: usize) -> Result<()> {
if self.pos + n > self.data.len() * 8 {
return Err(Error::invalid("aac: skip past end of data"));
}
self.pos += n;
Ok(())
}
/// Advance to the next byte boundary.
pub fn byte_align(&mut self) {
if self.pos % 8 != 0 {
self.pos += 8 - (self.pos % 8);
}
}
}
#[cfg(test)]
#[allow(clippy::cast_possible_truncation, reason = "test data generators")]
mod tests {
use super::*;
#[test]
fn reads_bits_msb_first() {
// 0b1011_0010, 0b1100_0001
let mut r = BitReader::new(&[0xB2, 0xC1]);
assert_eq!(r.read_bits(4).unwrap(), 0b1011);
assert_eq!(r.read_bits(4).unwrap(), 0b0010);
assert_eq!(r.read_bits(3).unwrap(), 0b110);
assert_eq!(r.read_bit().unwrap(), 0);
assert_eq!(r.read_bits(4).unwrap(), 0b0001);
assert_eq!(r.bits_left(), 0);
}
#[test]
fn skip_and_align() {
let mut r = BitReader::new(&[0xFF, 0x0F]);
r.skip(4).unwrap();
r.byte_align(); // jump to bit 8
assert_eq!(r.read_bits(4).unwrap(), 0x0);
assert_eq!(r.read_bits(4).unwrap(), 0xF);
}
/// The word-at-a-time reader must agree with the bit loop on every width and
/// alignment, including reads that touch the last byte.
#[test]
fn fast_read_matches_bit_loop() {
let data: Vec<u8> = (0..37u32)
.map(|i| (i.wrapping_mul(97) ^ 0x5A) as u8)
.collect();
let mut seed = 12345u32;
let mut a = BitReader::new(&data);
let mut b = BitReader::new(&data);
loop {
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
let n = (seed >> 27) + 1; // 1..=32
let (x, y) = (a.read_bits(n), b.read_bits_slow(n));
match (x, y) {
(Ok(x), Ok(y)) => assert_eq!(x, y, "n={n} pos={}", a.position()),
(Err(_), Err(_)) => break,
(x, y) => panic!("disagree at end: {x:?} vs {y:?}"),
}
}
}
#[test]
fn errors_past_end() {
let mut r = BitReader::new(&[0x00]);
assert!(r.read_bits(8).is_ok());
assert!(r.read_bit().is_err());
}
}