Skip to main content

threers_codec/
bitstream.rs

1//! Bit-level output primitives shared by the native codecs.
2//!
3//! [`BitWriter`] packs bits MSB-first into a byte buffer and knows the two
4//! variable-length codes the HEVC high-level syntax needs: unsigned/signed
5//! Exp-Golomb (`ue(v)` / `se(v)`). [`rbsp_trailing_bits`] and
6//! [`emulation_prevention`] turn a raw bit payload into the byte-stuffed form a
7//! NAL unit carries.
8//!
9//! Pure `core`/`alloc` + `std::Vec` — no OS, threads, or time — so it builds and
10//! runs identically on native and `wasm32`.
11
12/// Packs bits MSB-first into a growable byte buffer.
13///
14/// The first bit written lands in bit 7 (the most-significant bit) of byte 0,
15/// matching the bit order every video/image bitstream uses. Partial trailing
16/// bits stay in an internal accumulator until a byte fills or the writer is
17/// byte-aligned.
18#[derive(Clone, Debug, Default)]
19pub struct BitWriter {
20    bytes: Vec<u8>,
21    /// Accumulator for the current, not-yet-complete byte (bits left-aligned).
22    cur: u8,
23    /// Number of valid bits currently held in `cur` (0..=7).
24    nbits: u8,
25}
26
27impl BitWriter {
28    /// A new, empty writer.
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    /// A writer preallocated for roughly `bytes` bytes of output.
34    pub fn with_capacity(bytes: usize) -> Self {
35        Self {
36            bytes: Vec::with_capacity(bytes),
37            cur: 0,
38            nbits: 0,
39        }
40    }
41
42    /// Append a single bit (only the low bit of `bit` is used).
43    #[inline]
44    pub fn write_bit(&mut self, bit: u32) {
45        self.cur |= ((bit & 1) as u8) << (7 - self.nbits);
46        self.nbits += 1;
47        if self.nbits == 8 {
48            self.bytes.push(self.cur);
49            self.cur = 0;
50            self.nbits = 0;
51        }
52    }
53
54    /// Append the low `n` bits of `value`, MSB-first. `n` must be `<= 32`.
55    #[inline]
56    pub fn write_bits(&mut self, value: u32, n: u32) {
57        debug_assert!(n <= 32);
58        for i in (0..n).rev() {
59            self.write_bit((value >> i) & 1);
60        }
61    }
62
63    /// Append the low `n` bits of a 64-bit `value`, MSB-first. `n` must be `<= 64`.
64    pub fn write_bits64(&mut self, value: u64, n: u32) {
65        debug_assert!(n <= 64);
66        for i in (0..n).rev() {
67            self.write_bit(((value >> i) & 1) as u32);
68        }
69    }
70
71    /// Append a boolean as a `u(1)` flag.
72    #[inline]
73    pub fn flag(&mut self, b: bool) {
74        self.write_bit(b as u32);
75    }
76
77    /// Append a whole byte. Fast when byte-aligned (the common case for raw PCM
78    /// samples); falls back to bit-by-bit otherwise.
79    #[inline]
80    pub fn write_byte(&mut self, b: u8) {
81        if self.nbits == 0 {
82            self.bytes.push(b);
83        } else {
84            self.write_bits(b as u32, 8);
85        }
86    }
87
88    /// Unsigned Exp-Golomb, `ue(v)` (H.265 §9.2). Encodes `value` as
89    /// `leadingZeros` `0`s, a `1`, then the `leadingZeros`-bit suffix of
90    /// `value + 1`.
91    pub fn write_ue(&mut self, value: u32) {
92        // codeNum + 1; its bit length is the total code length.
93        let v1 = value as u64 + 1;
94        let len = 64 - v1.leading_zeros(); // bits in v1
95        for _ in 0..(len - 1) {
96            self.write_bit(0);
97        }
98        self.write_bits64(v1, len);
99    }
100
101    /// Signed Exp-Golomb, `se(v)` (H.265 §9.2). Maps `value` to a `ue(v)`
102    /// codeNum via the standard zig-zag (`0→0, 1→1, -1→2, 2→3, -2→4, …`).
103    pub fn write_se(&mut self, value: i32) {
104        let code = if value <= 0 {
105            (-(value as i64) as u64) * 2
106        } else {
107            (value as u64) * 2 - 1
108        };
109        self.write_ue(code as u32);
110    }
111
112    /// Total number of bits written so far.
113    pub fn bit_len(&self) -> usize {
114        self.bytes.len() * 8 + self.nbits as usize
115    }
116
117    /// Whether the next bit would start a fresh byte.
118    pub fn is_byte_aligned(&self) -> bool {
119        self.nbits == 0
120    }
121
122    /// Pad to the next byte boundary with `0` bits (no-op if already aligned).
123    pub fn align_zero(&mut self) {
124        while self.nbits != 0 {
125            self.write_bit(0);
126        }
127    }
128
129    /// Consume the writer, padding any partial final byte with zeros, and return
130    /// the bytes.
131    pub fn finish(mut self) -> Vec<u8> {
132        self.align_zero();
133        self.bytes
134    }
135
136    /// Borrow the completed bytes; panics unless byte-aligned. Prefer
137    /// [`finish`](Self::finish) unless you must keep writing.
138    pub fn as_bytes(&self) -> &[u8] {
139        debug_assert!(
140            self.is_byte_aligned(),
141            "as_bytes on a non-byte-aligned writer"
142        );
143        &self.bytes
144    }
145}
146
147/// Append RBSP trailing bits: a single `1` stop bit followed by `0`s to the next
148/// byte boundary (H.265 §7.3.2.11). Every RBSP ends with this.
149pub fn rbsp_trailing_bits(w: &mut BitWriter) {
150    w.write_bit(1);
151    w.align_zero();
152}
153
154/// Insert emulation-prevention bytes, turning a raw byte-aligned RBSP into the
155/// EBSP a NAL unit carries (H.265 §7.3.1.1).
156///
157/// Any run `00 00 00`, `00 00 01`, `00 00 02`, or `00 00 03` in the RBSP would
158/// collide with a start code, so a `0x03` byte is spliced in after the two
159/// zeros: `00 00 XX` → `00 00 03 XX` (for `XX <= 03`).
160pub fn emulation_prevention(rbsp: &[u8]) -> Vec<u8> {
161    let mut out = Vec::with_capacity(rbsp.len() + rbsp.len() / 128 + 4);
162    let mut zeros = 0u32;
163    for &b in rbsp {
164        if zeros >= 2 && b <= 0x03 {
165            out.push(0x03);
166            zeros = 0;
167        }
168        out.push(b);
169        if b == 0 {
170            zeros += 1;
171        } else {
172            zeros = 0;
173        }
174    }
175    out
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    fn bits_of(w: &BitWriter) -> String {
183        let mut s = String::new();
184        let full = w.bytes.len();
185        for &byte in &w.bytes {
186            for i in (0..8).rev() {
187                s.push(if (byte >> i) & 1 == 1 { '1' } else { '0' });
188            }
189        }
190        let _ = full;
191        for i in (0..w.nbits).rev() {
192            s.push(if (w.cur >> (7 - (w.nbits - 1 - i))) & 1 == 1 {
193                '1'
194            } else {
195                '0'
196            });
197        }
198        s
199    }
200
201    #[test]
202    fn ue_known_vectors() {
203        // H.265 Table: codeNum → bit string.
204        let cases: &[(u32, &str)] = &[
205            (0, "1"),
206            (1, "010"),
207            (2, "011"),
208            (3, "00100"),
209            (4, "00101"),
210            (5, "00110"),
211            (6, "00111"),
212            (7, "0001000"),
213            (8, "0001001"),
214        ];
215        for &(v, expect) in cases {
216            let mut w = BitWriter::new();
217            w.write_ue(v);
218            assert_eq!(bits_of(&w), expect, "ue({v})");
219        }
220    }
221
222    #[test]
223    fn se_known_vectors() {
224        let cases: &[(i32, &str)] = &[
225            (0, "1"),
226            (1, "010"),
227            (-1, "011"),
228            (2, "00100"),
229            (-2, "00101"),
230            (3, "00110"),
231            (-3, "00111"),
232        ];
233        for &(v, expect) in cases {
234            let mut w = BitWriter::new();
235            w.write_se(v);
236            assert_eq!(bits_of(&w), expect, "se({v})");
237        }
238    }
239
240    #[test]
241    fn write_bits_msb_first() {
242        let mut w = BitWriter::new();
243        w.write_bits(0b101, 3);
244        w.write_bits(0b1, 1);
245        w.write_bits(0b0000, 4);
246        assert_eq!(w.finish(), vec![0b1011_0000]);
247    }
248
249    #[test]
250    fn rbsp_trailing_aligns_with_stop_bit() {
251        let mut w = BitWriter::new();
252        w.write_bits(0b101, 3); // 3 bits used
253        rbsp_trailing_bits(&mut w);
254        // 101 + stop 1 + pad 0000 = 1011_0000
255        assert_eq!(w.finish(), vec![0b1011_0000]);
256    }
257
258    #[test]
259    fn emulation_prevention_inserts_03() {
260        assert_eq!(
261            emulation_prevention(&[0x00, 0x00, 0x00]),
262            vec![0x00, 0x00, 0x03, 0x00]
263        );
264        assert_eq!(
265            emulation_prevention(&[0x00, 0x00, 0x01]),
266            vec![0x00, 0x00, 0x03, 0x01]
267        );
268        assert_eq!(
269            emulation_prevention(&[0x00, 0x00, 0x02]),
270            vec![0x00, 0x00, 0x03, 0x02]
271        );
272        assert_eq!(
273            emulation_prevention(&[0x00, 0x00, 0x03]),
274            vec![0x00, 0x00, 0x03, 0x03]
275        );
276        // No collision → untouched.
277        assert_eq!(
278            emulation_prevention(&[0x00, 0x00, 0x04]),
279            vec![0x00, 0x00, 0x04]
280        );
281        assert_eq!(
282            emulation_prevention(&[0x12, 0x34, 0x56]),
283            vec![0x12, 0x34, 0x56]
284        );
285        // Long zero run: 00 00 00 00 → 00 00 03 00 00 (the extra 03 resets the count).
286        assert_eq!(
287            emulation_prevention(&[0x00, 0x00, 0x00, 0x00]),
288            vec![0x00, 0x00, 0x03, 0x00, 0x00]
289        );
290    }
291}