forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-msac': AV1 symbol coder

Browse files at this commit

3c7b63f87739cae034431bee0c872762e10517e7Ahmet Kaan GümüşParent: d951540a580965
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -14,5 +14,6 @@
14 14
15 pub mod bits;15 pub mod bits;
16 pub mod frame;16 pub mod frame;
17+pub mod msac;
17 pub mod obu;18 pub mod obu;
18 pub mod sequence;19 pub mod sequence;
crates/ec-av1/src/msac.rsadded+438 -0
@@ -0,0 +1,438 @@
1+//! AV1 multi-symbol arithmetic coder (spec section 8.2) — the writer side of
2+//! the decoder the specification defines, plus the probability adaptation of
3+//! spec section 8.3.
4+//!
5+//! AV1 specifies only the decoder: every tile payload is a range-coded string
6+//! whose meaning is whatever the decoding process in section 8.2 recovers from
7+//! it. [`SymbolEncoder`] is the inverse of that process — it narrows the same
8+//! `[low, low + range)` interval the decoder tracks and flushes the shortest
9+//! prefix that pins the interval down, so the decoder's `decode_symbol` returns
10+//! the symbols in the order they were written whatever bytes follow.
11+//!
12+//! CDFs are held in the specification's own orientation: for an `n`-symbol
13+//! alphabet the slice has `n + 1` entries, `cdf[i]` is the cumulative
14+//! probability of symbols `0..=i` scaled to `1 << 15` (so `cdf[n - 1]` is
15+//! always `1 << 15`), and `cdf[n]` is the adaptation counter of section 8.3.2.
16+//! Decoders that store the complement (`(1 << 15) - cdf[i]`) compute the same
17+//! intervals; the arithmetic below takes the complement where the spec does.
18+
19+/// Probability precision dropped before the range multiply (spec `EC_PROB_SHIFT`).
20+const EC_PROB_SHIFT: u32 = 6;
21+/// Minimum interval width reserved for every symbol (spec `EC_MIN_PROB`).
22+const EC_MIN_PROB: u32 = 4;
23+/// Total probability mass of a CDF (spec `1 << 15`).
24+const CDF_TOP: u16 = 1 << 15;
25+
26+/// A CDF for a two-symbol alphabet with fixed, equal probabilities — the
27+/// `L(n)` literal coder of spec 4.10.4 reads its bits through one of these.
28+const EQUIPROBABLE: [u16; 3] = [1 << 14, CDF_TOP, 0];
29+
30+/// Writer for one AV1 symbol-coded string (one tile payload).
31+///
32+/// Symbols are written with [`SymbolEncoder::symbol`] (adapting the CDF as the
33+/// decoder will) or [`SymbolEncoder::symbol_fixed`]; raw bits go through
34+/// [`SymbolEncoder::literal`]. [`SymbolEncoder::finish`] flushes and returns
35+/// the payload bytes.
36+#[derive(Debug, Clone)]
37+pub struct SymbolEncoder {
38+ /// Low end of the current interval, kept shifted up so that the top of the
39+ /// active window sits at bit `cnt + 16`.
40+ low: u64,
41+ /// Width of the current interval, always renormalised into `[2^15, 2^16)`.
42+ rng: u32,
43+ /// Bits of headroom left in `low` before a byte has to be flushed; starts
44+ /// at `-9` so that the first flush happens once 9 bits have accumulated.
45+ cnt: i32,
46+ /// Flushed bytes before carry propagation: each entry can exceed `0xff` by
47+ /// the carry it owes the byte before it, which [`Self::finish`] adds in.
48+ precarry: Vec<u16>,
49+}
50+
51+impl Default for SymbolEncoder {
52+ fn default() -> SymbolEncoder {
53+ SymbolEncoder::new()
54+ }
55+}
56+
57+impl SymbolEncoder {
58+ /// A new encoder holding the full interval, as the decoder's
59+ /// `init_symbol` process assumes.
60+ pub fn new() -> SymbolEncoder {
61+ SymbolEncoder {
62+ low: 0,
63+ rng: 0x8000,
64+ cnt: -9,
65+ precarry: Vec::new(),
66+ }
67+ }
68+
69+ /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder
70+ /// will after reading it (spec 8.3.2).
71+ ///
72+ /// # Panics
73+ /// Panics if `symbol` is not a symbol of `cdf`'s alphabet, or if `cdf` is
74+ /// shorter than a two-symbol alphabet's three entries.
75+ pub fn symbol(&mut self, symbol: usize, cdf: &mut [u16]) {
76+ self.symbol_fixed(symbol, cdf);
77+ update_cdf(cdf, symbol);
78+ }
79+
80+ /// Writes `symbol` against a CDF that does not adapt — the form the spec
81+ /// uses for the literal and equiprobable reads.
82+ ///
83+ /// # Panics
84+ /// Panics if `symbol` is not a symbol of `cdf`'s alphabet, or if `cdf` is
85+ /// shorter than a two-symbol alphabet's three entries.
86+ pub fn symbol_fixed(&mut self, symbol: usize, cdf: &[u16]) {
87+ assert!(cdf.len() >= 3, "a CDF covers at least two symbols");
88+ let nsyms = cdf.len() - 1;
89+ assert!(symbol < nsyms, "symbol {symbol} is outside the alphabet");
90+
91+ // The decoder walks the alphabet computing the same two boundaries and
92+ // stops at the first symbol whose lower boundary the coded value has
93+ // fallen below, so the encoder only has to narrow to that symbol's
94+ // slice of the interval.
95+ let r = self.rng;
96+ let fh = u32::from(CDF_TOP - cdf[symbol]);
97+ let v = (((r >> 8) * (fh >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
98+ + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
99+ let mut low = self.low;
100+ let rng = if symbol > 0 {
101+ let fl = u32::from(CDF_TOP - cdf[symbol - 1]);
102+ let u = (((r >> 8) * (fl >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
103+ + EC_MIN_PROB * (nsyms - symbol) as u32;
104+ low += u64::from(r - u);
105+ u - v
106+ } else {
107+ // Symbol 0 owns the top of the interval, so only its width moves.
108+ r - v
109+ };
110+ self.normalize(low, rng);
111+ }
112+
113+ /// Writes `bits` raw bits of `value`, most significant first — the `L(n)`
114+ /// descriptor of spec 4.10.4, which is `bits` equiprobable symbols.
115+ ///
116+ /// # Panics
117+ /// Panics if `bits` exceeds 32.
118+ pub fn literal(&mut self, value: u32, bits: u32) {
119+ assert!(bits <= 32, "a literal is at most 32 bits");
120+ for i in (0..bits).rev() {
121+ let bit = (value >> i) & 1;
122+ self.symbol_fixed(bit as usize, &EQUIPROBABLE);
123+ }
124+ }
125+
126+ /// Flushes the coder and returns the payload bytes.
127+ ///
128+ /// The flush writes the shortest value inside the final interval that stays
129+ /// inside it however the decoder pads the string, which is what lets a tile
130+ /// payload end on a byte boundary with no terminator.
131+ pub fn finish(mut self) -> Vec<u8> {
132+ // Round the interval's low end up to a value with 14 low zero bits,
133+ // then set bit 14: the result is inside the interval (the interval is
134+ // at least 2^15 wide before normalisation) and its tail bits are all
135+ // zero, so they need not be written at all.
136+ let m: u64 = 0x3fff;
137+ let mut e = ((self.low + m) & !m) | (m + 1);
138+ let mut c = self.cnt;
139+ let mut s = 10 + c;
140+ while s > 0 {
141+ self.precarry.push((e >> (c + 16)) as u16);
142+ e &= (1u64 << (c + 16)) - 1;
143+ s -= 8;
144+ c -= 8;
145+ }
146+
147+ // Each flushed entry may have overflowed a byte; the overflow is a
148+ // carry into the byte written before it.
149+ let mut out = vec![0u8; self.precarry.len()];
150+ let mut carry = 0u32;
151+ for (byte, &pre) in out.iter_mut().zip(self.precarry.iter()).rev() {
152+ let v = u32::from(pre) + carry;
153+ *byte = v as u8;
154+ carry = v >> 8;
155+ }
156+ out
157+ }
158+
159+ /// Renormalises the interval back into `[2^15, 2^16)`, flushing whole bytes
160+ /// of `low` once they can no longer change.
161+ fn normalize(&mut self, low: u64, rng: u32) {
162+ debug_assert!(rng > 0 && rng <= 0xffff);
163+ let d = 16 - (32 - rng.leading_zeros()) as i32;
164+ let mut c = self.cnt;
165+ let mut s = c + d;
166+ let mut low = low;
167+ if s >= 0 {
168+ // At least one byte at the top of `low` is settled: a later carry
169+ // can still reach it, which is why it is kept in the precarry
170+ // buffer as a `u16` rather than truncated to a byte here.
171+ c += 16;
172+ let mut m = (1u64 << c) - 1;
173+ if s >= 8 {
174+ self.precarry.push((low >> c) as u16);
175+ low &= m;
176+ c -= 8;
177+ m >>= 8;
178+ }
179+ self.precarry.push((low >> c) as u16);
180+ s = c + d - 24;
181+ low &= m;
182+ }
183+ self.low = low << d;
184+ self.rng = rng << d;
185+ self.cnt = s;
186+ }
187+}
188+
189+/// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent
190+/// fraction of the way towards the extreme the observed symbol implies, and the
191+/// counter in the last entry slows the rate down for the first 32 symbols.
192+fn update_cdf(cdf: &mut [u16], symbol: usize) {
193+ let nsyms = cdf.len() - 1;
194+ let count = cdf[nsyms];
195+ let rate = 3 + (nsyms >> 1).min(2) + (count >> 4) as usize;
196+ for (i, p) in cdf[..nsyms - 1].iter_mut().enumerate() {
197+ if i < symbol {
198+ *p -= *p >> rate;
199+ } else {
200+ *p += (CDF_TOP - *p) >> rate;
201+ }
202+ }
203+ cdf[nsyms] = count + 1 - (count >> 5);
204+}
205+
206+#[cfg(test)]
207+mod tests {
208+ use super::*;
209+
210+ /// The decoding process of spec 8.2, written from the specification's
211+ /// pseudocode so that the roundtrip tests measure the encoder against the
212+ /// decoder AV1 defines rather than against the encoder's own arithmetic.
213+ struct SymbolDecoder<'a> {
214+ data: &'a [u8],
215+ /// Next bit to read, as a bit offset into `data`.
216+ bit: usize,
217+ value: u32,
218+ range: u32,
219+ /// Bits left before the decoder starts padding with zeros (spec
220+ /// `SymbolMaxBits`), which goes negative at the end of the string.
221+ max_bits: i32,
222+ }
223+
224+ impl<'a> SymbolDecoder<'a> {
225+ /// `init_symbol` (spec 8.2.2).
226+ fn new(data: &'a [u8]) -> SymbolDecoder<'a> {
227+ let mut d = SymbolDecoder {
228+ data,
229+ bit: 0,
230+ value: 0,
231+ range: 1 << 15,
232+ max_bits: 8 * data.len() as i32 - 15,
233+ };
234+ let num_bits = usize::min(data.len() * 8, 15) as u32;
235+ let buf = d.f(num_bits);
236+ d.value = ((1 << 15) - 1) ^ (buf << (15 - num_bits));
237+ d
238+ }
239+
240+ /// `f(n)`: the next `n` bits, most significant first, zero past the end.
241+ fn f(&mut self, n: u32) -> u32 {
242+ let mut v = 0;
243+ for _ in 0..n {
244+ let byte = self.data.get(self.bit >> 3).copied().unwrap_or(0);
245+ v = (v << 1) | u32::from((byte >> (7 - (self.bit & 7))) & 1);
246+ self.bit += 1;
247+ }
248+ v
249+ }
250+
251+ /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
252+ fn symbol(&mut self, cdf: &mut [u16]) -> usize {
253+ let s = self.symbol_fixed(cdf);
254+ update_cdf(cdf, s);
255+ s
256+ }
257+
258+ fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
259+ let nsyms = cdf.len() - 1;
260+ let mut cur = self.range;
261+ let mut prev;
262+ let mut symbol = 0;
263+ loop {
264+ prev = cur;
265+ let f = u32::from(CDF_TOP - cdf[symbol]);
266+ cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
267+ + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
268+ if self.value >= cur {
269+ break;
270+ }
271+ symbol += 1;
272+ }
273+ self.range = prev - cur;
274+ self.value -= cur;
275+
276+ // Renormalise back into `[2^15, 2^16)`, the same shift the encoder
277+ // applied when it narrowed to this symbol.
278+ let bits = 16 - (32 - self.range.leading_zeros());
279+ self.range <<= bits;
280+ let num_bits = u32::min(bits, self.max_bits.max(0) as u32);
281+ let new_data = self.f(num_bits);
282+ let padded = new_data << (bits - num_bits);
283+ self.value = padded ^ (((self.value + 1) << bits) - 1);
284+ self.max_bits -= bits as i32;
285+ symbol
286+ }
287+
288+ fn literal(&mut self, bits: u32) -> u32 {
289+ let mut v = 0;
290+ for _ in 0..bits {
291+ v = (v << 1) | self.symbol_fixed(&EQUIPROBABLE) as u32;
292+ }
293+ v
294+ }
295+ }
296+
297+ /// A reproducible symbol stream: xorshift, so a failure names one seed.
298+ fn rng(state: &mut u64) -> u64 {
299+ *state ^= *state << 13;
300+ *state ^= *state >> 7;
301+ *state ^= *state << 17;
302+ *state
303+ }
304+
305+ fn flat_cdf(nsyms: usize) -> Vec<u16> {
306+ let mut cdf = vec![0u16; nsyms + 1];
307+ for (i, p) in cdf[..nsyms].iter_mut().enumerate() {
308+ *p = (((i + 1) * (1 << 15)) / nsyms) as u16;
309+ }
310+ cdf[nsyms] = 0;
311+ cdf
312+ }
313+
314+ #[test]
315+ fn adaptive_symbols_roundtrip() {
316+ for nsyms in 2..=16usize {
317+ let mut state = 0x2545_f491_4f6c_dd1d ^ nsyms as u64;
318+ let symbols: Vec<usize> = (0..4000)
319+ .map(|_| (rng(&mut state) % nsyms as u64) as usize)
320+ .collect();
321+
322+ let mut enc = SymbolEncoder::new();
323+ let mut cdf = flat_cdf(nsyms);
324+ for &s in &symbols {
325+ enc.symbol(s, &mut cdf);
326+ }
327+ let payload = enc.finish();
328+
329+ let mut dec = SymbolDecoder::new(&payload);
330+ let mut cdf = flat_cdf(nsyms);
331+ for (i, &want) in symbols.iter().enumerate() {
332+ let got = dec.symbol(&mut cdf);
333+ assert_eq!(got, want, "alphabet {nsyms}, symbol {i}");
334+ }
335+ }
336+ }
337+
338+ #[test]
339+ fn skewed_symbols_cost_less_than_a_bit() {
340+ // A 1-in-256 symbol against an adapting CDF must cost far under one bit
341+ // each: this is the property a range coder exists for, and it fails
342+ // loudly if the interval narrowing is wired backwards.
343+ let mut state = 0x9e37_79b9_7f4a_7c15;
344+ let symbols: Vec<usize> = (0..8000)
345+ .map(|_| usize::from(rng(&mut state).is_multiple_of(256)))
346+ .collect();
347+ let mut enc = SymbolEncoder::new();
348+ let mut cdf = flat_cdf(2);
349+ for &s in &symbols {
350+ enc.symbol(s, &mut cdf);
351+ }
352+ let payload = enc.finish();
353+ assert!(
354+ payload.len() < 8000 / 8 / 4,
355+ "8000 skewed symbols took {} bytes",
356+ payload.len()
357+ );
358+
359+ let mut dec = SymbolDecoder::new(&payload);
360+ let mut cdf = flat_cdf(2);
361+ for (i, &want) in symbols.iter().enumerate() {
362+ assert_eq!(dec.symbol(&mut cdf), want, "symbol {i}");
363+ }
364+ }
365+
366+ #[test]
367+ fn literals_roundtrip() {
368+ let mut state = 0x0123_4567_89ab_cdef;
369+ let values: Vec<(u32, u32)> = (0..2000)
370+ .map(|_| {
371+ let bits = 1 + (rng(&mut state) % 16) as u32;
372+ let value = (rng(&mut state) as u32) & ((1u32 << bits) - 1);
373+ (value, bits)
374+ })
375+ .collect();
376+
377+ let mut enc = SymbolEncoder::new();
378+ for &(v, bits) in &values {
379+ enc.literal(v, bits);
380+ }
381+ let payload = enc.finish();
382+ // Equiprobable bits cannot be compressed, so the payload is one bit per
383+ // written bit plus the flush.
384+ let total: u32 = values.iter().map(|&(_, b)| b).sum();
385+ assert!(payload.len() as u32 <= total / 8 + 4);
386+
387+ let mut dec = SymbolDecoder::new(&payload);
388+ for (i, &(want, bits)) in values.iter().enumerate() {
389+ assert_eq!(dec.literal(bits), want, "literal {i}");
390+ }
391+ }
392+
393+ #[test]
394+ fn mixed_symbols_and_literals_roundtrip() {
395+ let mut state = 0xdead_beef_cafe_f00d;
396+ let mut enc = SymbolEncoder::new();
397+ let mut cdf3 = flat_cdf(3);
398+ let mut cdf8 = flat_cdf(8);
399+ let mut written = Vec::new();
400+ for _ in 0..3000 {
401+ match rng(&mut state) % 3 {
402+ 0 => {
403+ let s = (rng(&mut state) % 3) as usize;
404+ enc.symbol(s, &mut cdf3);
405+ written.push((0u8, s as u32));
406+ }
407+ 1 => {
408+ let s = (rng(&mut state) % 8) as usize;
409+ enc.symbol(s, &mut cdf8);
410+ written.push((1, s as u32));
411+ }
412+ _ => {
413+ let v = (rng(&mut state) % 256) as u32;
414+ enc.literal(v, 8);
415+ written.push((2, v));
416+ }
417+ }
418+ }
419+ let payload = enc.finish();
420+
421+ let mut dec = SymbolDecoder::new(&payload);
422+ let mut cdf3 = flat_cdf(3);
423+ let mut cdf8 = flat_cdf(8);
424+ for (i, &(kind, want)) in written.iter().enumerate() {
425+ let got = match kind {
426+ 0 => dec.symbol(&mut cdf3) as u32,
427+ 1 => dec.symbol(&mut cdf8) as u32,
428+ _ => dec.literal(8),
429+ };
430+ assert_eq!(got, want, "item {i} of kind {kind}");
431+ }
432+ }
433+
434+ #[test]
435+ fn empty_payload_is_short() {
436+ assert!(SymbolEncoder::new().finish().len() <= 2);
437+ }
438+}