1#[derive(Clone, Debug, Default)]
19pub struct BitWriter {
20 bytes: Vec<u8>,
21 cur: u8,
23 nbits: u8,
25}
26
27impl BitWriter {
28 pub fn new() -> Self {
30 Self::default()
31 }
32
33 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 #[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 #[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 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 #[inline]
73 pub fn flag(&mut self, b: bool) {
74 self.write_bit(b as u32);
75 }
76
77 #[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 pub fn write_ue(&mut self, value: u32) {
92 let v1 = value as u64 + 1;
94 let len = 64 - v1.leading_zeros(); for _ in 0..(len - 1) {
96 self.write_bit(0);
97 }
98 self.write_bits64(v1, len);
99 }
100
101 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 pub fn bit_len(&self) -> usize {
114 self.bytes.len() * 8 + self.nbits as usize
115 }
116
117 pub fn is_byte_aligned(&self) -> bool {
119 self.nbits == 0
120 }
121
122 pub fn align_zero(&mut self) {
124 while self.nbits != 0 {
125 self.write_bit(0);
126 }
127 }
128
129 pub fn finish(mut self) -> Vec<u8> {
132 self.align_zero();
133 self.bytes
134 }
135
136 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
147pub fn rbsp_trailing_bits(w: &mut BitWriter) {
150 w.write_bit(1);
151 w.align_zero();
152}
153
154pub 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 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); rbsp_trailing_bits(&mut w);
254 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 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 assert_eq!(
287 emulation_prevention(&[0x00, 0x00, 0x00, 0x00]),
288 vec![0x00, 0x00, 0x03, 0x00, 0x00]
289 );
290 }
291}