forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB682c080Tahinli2 months ago2434 commits

bits.rs268 lines, 8.2 KiBHistoryRawDownload
1//! AV1 bit-primitive writers — bit-exact inverses of the readers in
2//! [`ec_av1_syntax::obu`], built on the family [`ec_core::BitWriter`].
3//!
4//! Every function here is the inverse of a named AV1 bit-reading descriptor
5//! (spec section 4.10 / 5.9); the parser function it mirrors is named in its
6//! docs and roundtripped in the tests below.
7
8use ec_av1_syntax::obu::floor_log2;
9use ec_core::BitWriter;
10
11/// `leb128()` writer (spec 4.10.5); inverts [`ec_av1_syntax::obu::read_leb128`].
12///
13/// Little-endian base-128: each byte carries 7 payload bits and a high
14/// continuation bit, set on every byte but the last. A 32-bit value needs at
15/// most 5 bytes (the parser accepts up to 8 and rejects anything that does not
16/// fit in 32 bits).
17pub fn write_leb128(w: &mut BitWriter, value: u32) {
18 let mut v = value;
19 loop {
20 let byte = v & 0x7f;
21 v >>= 7;
22 let more = v != 0;
23 w.write_bits(if more { byte | 0x80 } else { byte }, 8);
24 if !more {
25 return;
26 }
27 }
28}
29
30/// `uvlc()` writer (spec 4.10.3); inverts [`ec_av1_syntax::obu::read_uvlc`].
31///
32/// `0` is a single `1` bit; `u32::MAX` is the 32-leading-zero escape the
33/// parser returns verbatim; otherwise `lz` zero bits, a `1` bit, then the
34/// `lz`-bit suffix, where `lz = floor_log2(value + 1)` and the suffix is
35/// `value - (1 << lz) + 1` (so the decoded value is `suffix + (1 << lz) - 1`).
36pub fn write_uvlc(w: &mut BitWriter, value: u32) {
37 if value == u32::MAX {
38 // The spec escape: 32 leading zeros read back as u32::MAX, with no
39 // terminating 1 bit.
40 w.write_bits64(0, 32);
41 return;
42 }
43 let lz = floor_log2(value + 1);
44 w.write_bits64(0, lz);
45 w.write_bit(true);
46 if lz > 0 {
47 let suffix = value - ((1u32 << lz) - 1);
48 w.write_bits(suffix, lz);
49 }
50}
51
52/// `le(n)` writer (spec 4.10.4); inverts [`ec_av1_syntax::obu::read_le`].
53///
54/// `n`-byte little-endian, least-significant byte first. AV1 reads `le(n)`
55/// only at a byte boundary; the writer should be byte aligned when called.
56pub fn write_le(w: &mut BitWriter, n: u32, value: u32) {
57 for i in 0..n {
58 w.write_bits((value >> (i * 8)) & 0xff, 8);
59 }
60}
61
62/// `su(n)` writer (spec 4.10.6); inverts [`ec_av1_syntax::obu::read_su`].
63///
64/// `n`-bit two's complement, delegated to [`BitWriter::write_signed`].
65pub fn write_su(w: &mut BitWriter, n: u32, value: i32) {
66 w.write_signed(value, n);
67}
68
69/// `ns(n)` writer (spec 4.10.7); inverts [`ec_av1_syntax::obu::read_ns`].
70///
71/// Non-symmetric unsigned below `n`: `w = floor_log2(n) + 1` bits, split into a
72/// `w - 1`-bit leading part and, for the high range, one extra bit. Values
73/// `[0, m)` (with `m = (1 << w) - n`) carry themselves in `w - 1` bits; values
74/// `[m, n)` carry `(value + m) >> 1` in `w - 1` bits plus the low bit of
75/// `value + m`.
76pub fn write_ns(w: &mut BitWriter, n: u32, value: u32) {
77 assert!(value < n, "write_ns: value {value} >= n {n}");
78 if n <= 1 {
79 return;
80 }
81 let width = floor_log2(n) + 1;
82 let m = (1u32 << width) - n;
83 if value < m {
84 w.write_bits(value, width - 1);
85 } else {
86 let combined = value + m;
87 w.write_bits(combined >> 1, width - 1);
88 w.write_bit(combined & 1 != 0);
89 }
90}
91
92/// `delta_q()` writer (spec 5.9.13); inverts
93/// `ec_av1_syntax::frame::read_delta_q`.
94///
95/// One `delta_coded` bit: `0` when the delta is zero, otherwise `1` followed by
96/// `su(7)` holding the signed delta. (The frame module is private, so the test
97/// reconstructs the read side from [`ec_av1_syntax::obu::read_su`] plus a bit.)
98pub fn write_delta_q(w: &mut BitWriter, delta_q: i32) {
99 if delta_q == 0 {
100 w.write_bit(false);
101 } else {
102 w.write_bit(true);
103 w.write_signed(delta_q, 7);
104 }
105}
106
107/// `trailing_bits()` writer (spec 4.8.4).
108///
109/// A required `1` bit followed by zero bits up to the next byte boundary. AV1
110/// ends every OBU that is not a whole number of bytes with this.
111pub fn write_trailing_bits(w: &mut BitWriter) {
112 w.write_bit(true);
113 w.align_to_byte();
114}
115
116/// `byte_alignment()` writer (spec 4.8.5).
117///
118/// Zero bits up to the next byte boundary — [`BitWriter::align_to_byte`] is the
119/// exact inverse of the parser's `while !byte_aligned: read_bit()` loop.
120pub fn write_byte_alignment(w: &mut BitWriter) {
121 w.align_to_byte();
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use ec_av1_syntax::obu::{read_le, read_leb128, read_ns, read_su, read_uvlc};
128 use ec_core::{BitReader, BitWriter};
129
130 /// Write `f` into a fresh writer, then read it back with `g`.
131 fn roundtrip<T, F, G>(f: F, g: G) -> T
132 where
133 F: FnOnce(&mut BitWriter),
134 G: FnOnce(&mut BitReader<'_>) -> ec_core::Result<T>,
135 {
136 let mut w = BitWriter::new();
137 f(&mut w);
138 let bytes = w.into_bytes();
139 let mut r = BitReader::new(&bytes);
140 g(&mut r).expect("parser readback failed")
141 }
142
143 #[test]
144 fn uvlc_roundtrip() {
145 for v in 0..4096u32 {
146 assert_eq!(roundtrip(|w| write_uvlc(w, v), read_uvlc), v, "uvlc {v}");
147 }
148 assert_eq!(
149 roundtrip(|w| write_uvlc(w, u32::MAX), read_uvlc),
150 u32::MAX,
151 "uvlc escape"
152 );
153 }
154 #[test]
155 fn leb128_roundtrip() {
156 // One value at each LEB128 byte-length boundary (1 through 5 bytes),
157 // plus the all-ones and zero corners.
158 let spread = [
159 0u32,
160 1,
161 127,
162 128,
163 255,
164 256,
165 16_383,
166 16_384,
167 65_535,
168 65_536,
169 2_097_151,
170 2_097_152,
171 134_217_727,
172 134_217_728,
173 268_435_455,
174 268_435_456,
175 u32::MAX,
176 ];
177 for v in spread {
178 assert_eq!(
179 roundtrip(|w| write_leb128(w, v), read_leb128),
180 v,
181 "leb128 {v}"
182 );
183 }
184 }
185
186 #[test]
187 fn ns_roundtrip() {
188 for n in 1u32..256 {
189 if n <= 64 {
190 for v in 0..n {
191 assert_eq!(
192 roundtrip(|w| write_ns(w, n, v), |r| read_ns(r, n)),
193 v,
194 "ns n={n} v={v}"
195 );
196 }
197 } else {
198 for &v in &[0u32, 1, n / 2, n - 2, n - 1] {
199 assert_eq!(
200 roundtrip(|w| write_ns(w, n, v), |r| read_ns(r, n)),
201 v,
202 "ns n={n} v={v}"
203 );
204 }
205 }
206 }
207 }
208
209 #[test]
210 fn su_roundtrip() {
211 for v in -64..64i32 {
212 assert_eq!(
213 roundtrip(|w| write_su(w, 8, v), |r| read_su(r, 8)),
214 v,
215 "su {v}"
216 );
217 }
218 }
219
220 #[test]
221 fn le_roundtrip() {
222 for n in 1u32..=4 {
223 let max = u32::MAX >> (32 - 8 * n);
224 for &v in &[0u32, 1, 0xAB, 0x1234, 0x123456, 0xDEADBEEF, max] {
225 let v = v & max;
226 assert_eq!(
227 roundtrip(|w| write_le(w, n, v), |r| read_le(r, n)),
228 v,
229 "le n={n} v={v}"
230 );
231 }
232 }
233 }
234
235 #[test]
236 fn delta_q_roundtrip() {
237 // Mirrors ec_av1_syntax::frame::read_delta_q exactly: a `delta_coded`
238 // bit, then su(7) when set. That function is private, so the read side
239 // is rebuilt from BitReader::read_bit + obu::read_su.
240 for v in -63..=63i32 {
241 let got = roundtrip(
242 |w| write_delta_q(w, v),
243 |r| -> ec_core::Result<i32> {
244 if r.read_bit()? {
245 Ok(read_su(r, 7)?)
246 } else {
247 Ok(0)
248 }
249 },
250 );
251 assert_eq!(got, v, "delta_q {v}");
252 }
253 }
254
255 #[test]
256 fn trailing_bits_and_byte_alignment_are_byte_aligned() {
257 let mut w = BitWriter::new();
258 w.write_bits(0b101, 3);
259 assert!(!w.is_byte_aligned());
260 write_trailing_bits(&mut w);
261 assert!(w.is_byte_aligned());
262
263 let mut w = BitWriter::new();
264 w.write_bits(0b101, 3);
265 write_byte_alignment(&mut w);
266 assert!(w.is_byte_aligned());
267 }
268}