forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

msac.rs537 lines, 20.2 KiBHistoryRawDownload
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`).
20const EC_PROB_SHIFT: u32 = 6;
21
22/// Minimum interval width reserved for every symbol (spec `EC_MIN_PROB`).
23const EC_MIN_PROB: u32 = 4;
24/// Total probability mass of a CDF (spec `1 << 15`).
25const CDF_TOP: u16 = 1 << 15;
26
27/// A CDF for a two-symbol alphabet with fixed, equal probabilities — the
28/// `L(n)` literal coder of spec 4.10.4 reads its bits through one of these.
29const EQUIPROBABLE: [u16; 3] = [1 << 14, CDF_TOP, 0];
30
31/// Writer for one AV1 symbol-coded string (one tile payload).
32///
33/// Symbols are written with [`SymbolEncoder::symbol`] (adapting the CDF as the
34/// decoder will) or [`SymbolEncoder::symbol_fixed`]; raw bits go through
35/// [`SymbolEncoder::literal`]. [`SymbolEncoder::finish`] flushes and returns
36/// the payload bytes.
37#[derive(Debug, Clone)]
38pub struct SymbolEncoder {
39 /// Low end of the current interval, kept shifted up so that the top of the
40 /// active window sits at bit `cnt + 16`.
41 low: u64,
42 /// Width of the current interval, always renormalised into `[2^15, 2^16)`.
43 rng: u32,
44 /// Bits of headroom left in `low` before a byte has to be flushed; starts
45 /// at `-9` so that the first flush happens once 9 bits have accumulated.
46 cnt: i32,
47 /// Flushed bytes before carry propagation: each entry can exceed `0xff` by
48 /// the carry it owes the byte before it, which [`Self::finish`] adds in.
49 precarry: Vec<u16>,
50 /// What every symbol written so far cost against the CDF it was written
51 /// with, in bits. The arithmetic coder spends `-log2(p)` on a symbol of
52 /// probability `p` to within the rounding of its interval, so this is what
53 /// a search may price a decision with without coding it twice.
54 bits: f64,
55}
56
57impl Default for SymbolEncoder {
58 fn default() -> SymbolEncoder {
59 SymbolEncoder::new()
60 }
61}
62
63impl SymbolEncoder {
64 /// A new encoder holding the full interval, as the decoder's
65 /// `init_symbol` process assumes.
66 pub fn new() -> SymbolEncoder {
67 SymbolEncoder {
68 low: 0,
69 rng: 0x8000,
70 cnt: -9,
71 precarry: Vec::new(),
72 bits: 0.0,
73 }
74 }
75
76 /// What the symbols written so far cost, in bits.
77 pub fn bits(&self) -> f64 {
78 self.bits
79 }
80
81 /// The coder's current interval width — libaom's `od_ec_enc_rng` /
82 /// decoder's `rng` field. Exposed only for the rng-register bisect trace
83 /// (`EC_RNG=1`); not part of the bitstream contract.
84 pub(crate) fn rng(&self) -> u32 {
85 self.rng
86 }
87
88 /// The exact bit position the stream has committed to so far (libaom's
89 /// `od_ec_enc_tell`, `entenc.c`): `cnt + 10` undoes the `-9` `cnt` starts
90 /// at and reserves the one bit `finish` always spends, and `precarry`
91 /// holds one `u16` per byte already flushed. Pairs with the decoder's
92 /// `aom_reader_tell`, which counts the same bits consumed.
93 pub fn tell(&self) -> i32 {
94 self.cnt + 10 + self.precarry.len() as i32 * 8
95 }
96
97 /// Forgets the cost accumulated so far, so that the next stretch of
98 /// symbols can be priced on its own.
99 pub fn reset_bits(&mut self) {
100 self.bits = 0.0;
101 }
102
103 /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder
104 /// will after reading it (spec 8.3.2).
105 ///
106 /// # Panics
107 /// Panics if `symbol` is not a symbol of `cdf`'s alphabet, or if `cdf` is
108 /// shorter than a two-symbol alphabet's three entries.
109 pub fn symbol(&mut self, symbol: usize, cdf: &mut [u16]) {
110 self.symbol_fixed(symbol, cdf);
111 update_cdf(cdf, symbol);
112 }
113
114 /// Writes `symbol` against a CDF that does not adapt — the form the spec
115 /// uses for the literal and equiprobable reads.
116 ///
117 /// # Panics
118 /// Panics if `symbol` is not a symbol of `cdf`'s alphabet, or if `cdf` is
119 /// shorter than a two-symbol alphabet's three entries.
120 pub fn symbol_fixed(&mut self, symbol: usize, cdf: &[u16]) {
121 assert!(cdf.len() >= 3, "a CDF covers at least two symbols");
122 let nsyms = cdf.len() - 1;
123 assert!(symbol < nsyms, "symbol {symbol} is outside the alphabet");
124
125 // The decoder walks the alphabet computing the same two boundaries and
126 // stops at the first symbol whose lower boundary the coded value has
127 // fallen below, so the encoder only has to narrow to that symbol's
128 // slice of the interval.
129 let r = self.rng;
130 let fh = u32::from(CDF_TOP - cdf[symbol]);
131 let v = (((r >> 8) * (fh >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
132 + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
133 let mut low = self.low;
134 let rng = if symbol > 0 {
135 let fl = u32::from(CDF_TOP - cdf[symbol - 1]);
136 let u = (((r >> 8) * (fl >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
137 + EC_MIN_PROB * (nsyms - symbol) as u32;
138 low += u64::from(r - u);
139 u - v
140 } else {
141 // Symbol 0 owns the top of the interval, so only its width moves.
142 r - v
143 };
144 // What this symbol really cost is how far it narrowed the interval,
145 // which is not quite its nominal probability: the coder works the
146 // range through an eight-bit multiply and hands every symbol above
147 // this one a floor of `EC_MIN_PROB`. Pricing the narrowing rather than
148 // the table entry is what makes the account match the bytes.
149 self.bits -= (f64::from(rng) / f64::from(r)).log2();
150 self.normalize(low, rng);
151 }
152
153 /// Writes `bits` raw bits of `value`, most significant first — the `L(n)`
154 /// descriptor of spec 4.10.4, which is `bits` equiprobable symbols.
155 ///
156 /// # Panics
157 /// Panics if `bits` exceeds 32.
158 pub fn literal(&mut self, value: u32, bits: u32) {
159 assert!(bits <= 32, "a literal is at most 32 bits");
160 for i in (0..bits).rev() {
161 let bit = (value >> i) & 1;
162 self.symbol_fixed(bit as usize, &EQUIPROBABLE);
163 }
164 }
165
166 /// Flushes the coder and returns the payload bytes.
167 ///
168 /// The flush writes the shortest value inside the final interval that stays
169 /// inside it however the decoder pads the string, which is what lets a tile
170 /// payload end on a byte boundary with no terminator.
171 pub fn finish(mut self) -> Vec<u8> {
172 // Round the interval's low end up to a value with 14 low zero bits,
173 // then set bit 14: the result is inside the interval (the interval is
174 // at least 2^15 wide before normalisation) and its tail bits are all
175 // zero, so they need not be written at all.
176 let m: u64 = 0x3fff;
177 let mut e = ((self.low + m) & !m) | (m + 1);
178 let mut c = self.cnt;
179 let mut s = 10 + c;
180 while s > 0 {
181 self.precarry.push((e >> (c + 16)) as u16);
182 e &= (1u64 << (c + 16)) - 1;
183 s -= 8;
184 c -= 8;
185 }
186
187 // Each flushed entry may have overflowed a byte; the overflow is a
188 // carry into the byte written before it.
189 let mut out = vec![0u8; self.precarry.len()];
190 let mut carry = 0u32;
191 for (byte, &pre) in out.iter_mut().zip(self.precarry.iter()).rev() {
192 let v = u32::from(pre) + carry;
193 *byte = v as u8;
194 carry = v >> 8;
195 }
196 out
197 }
198
199 /// Renormalises the interval back into `[2^15, 2^16)`, flushing whole bytes
200 /// of `low` once they can no longer change.
201 fn normalize(&mut self, low: u64, rng: u32) {
202 debug_assert!(rng > 0 && rng <= 0xffff);
203 let d = 16 - (32 - rng.leading_zeros()) as i32;
204 let mut c = self.cnt;
205 let mut s = c + d;
206 let mut low = low;
207 if s >= 0 {
208 // At least one byte at the top of `low` is settled: a later carry
209 // can still reach it, which is why it is kept in the precarry
210 // buffer as a `u16` rather than truncated to a byte here.
211 c += 16;
212 let mut m = (1u64 << c) - 1;
213 if s >= 8 {
214 self.precarry.push((low >> c) as u16);
215 low &= m;
216 c -= 8;
217 m >>= 8;
218 }
219 self.precarry.push((low >> c) as u16);
220 s = c + d - 24;
221 low &= m;
222 }
223 self.low = low << d;
224 self.rng = rng << d;
225 self.cnt = s;
226 }
227}
228
229/// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent
230/// fraction of the way towards the extreme the observed symbol implies, and the
231/// counter in the last entry slows the rate down for the first 32 symbols.
232fn update_cdf(cdf: &mut [u16], symbol: usize) {
233 let nsyms = cdf.len() - 1;
234 let count = cdf[nsyms];
235 let rate = 3 + (nsyms >> 1).min(2) + (count >> 4) as usize;
236 for (i, p) in cdf[..nsyms - 1].iter_mut().enumerate() {
237 if i < symbol {
238 *p -= *p >> rate;
239 } else {
240 *p += (CDF_TOP - *p) >> rate;
241 }
242 }
243 cdf[nsyms] = count + 1 - (count >> 5);
244}
245
246/// The decoding process of spec 8.2, the exact inverse of [`SymbolEncoder`]:
247/// reads the symbols a [`SymbolEncoder`] wrote, in the order it wrote them,
248/// adapting every CDF identically (spec 8.3.2) so the two stay in step. This
249/// is the reader half of the arithmetic coder a real AV1 decoder's tile
250/// reader is built on top of.
251#[derive(Debug)]
252pub struct SymbolDecoder<'a> {
253 data: &'a [u8],
254 /// Next bit to read, as a bit offset into `data`.
255 bit: usize,
256 value: u32,
257 range: u32,
258 /// Bits left before the decoder starts padding with zeros (spec
259 /// `SymbolMaxBits`), which goes negative at the end of the string.
260 max_bits: i32,
261}
262
263impl<'a> SymbolDecoder<'a> {
264 /// `init_symbol` (spec 8.2.2).
265 #[must_use]
266 pub fn new(data: &'a [u8]) -> SymbolDecoder<'a> {
267 let mut d = SymbolDecoder {
268 data,
269 bit: 0,
270 value: 0,
271 range: 1 << 15,
272 max_bits: 8 * data.len() as i32 - 15,
273 };
274 let num_bits = usize::min(data.len() * 8, 15) as u32;
275 let buf = d.f(num_bits);
276 d.value = ((1 << 15) - 1) ^ (buf << (15 - num_bits));
277 d
278 }
279
280 /// `f(n)`: the next `n` bits, most significant first, zero past the end.
281 fn f(&mut self, n: u32) -> u32 {
282 let mut v = 0;
283 for _ in 0..n {
284 let byte = self.data.get(self.bit >> 3).copied().unwrap_or(0);
285 v = (v << 1) | u32::from((byte >> (7 - (self.bit & 7))) & 1);
286 self.bit += 1;
287 }
288 v
289 }
290
291 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
292 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {
293 let s = self.symbol_fixed(cdf);
294 update_cdf(cdf, s);
295 s
296 }
297
298 /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec
299 /// uses for the literal and equiprobable reads, mirroring
300 /// [`SymbolEncoder::symbol_fixed`].
301 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
302 let nsyms = cdf.len() - 1;
303 let mut cur = self.range;
304 let mut prev;
305 let mut symbol = 0;
306 // bisect scratch (lane-cdffwd2): rng_before, matching libaom
307 // entdec.c's own EC_RNG trace field of the same name.
308 let rng_before = self.range;
309 loop {
310 prev = cur;
311 let f = u32::from(CDF_TOP - cdf[symbol]);
312 cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
313 + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
314 if self.value >= cur {
315 break;
316 }
317 symbol += 1;
318 }
319 self.range = prev - cur;
320 self.value -= cur;
321 if std::env::var_os("EC_RNG").is_some() {
322 use std::sync::atomic::{AtomicU64, Ordering};
323 static N: AtomicU64 = AtomicU64::new(0);
324 let n = N.fetch_add(1, Ordering::SeqCst);
325 eprintln!(
326 "EC_RNG n={n} rng_before={rng_before} rng_after={} nsyms={nsyms} symbol={symbol}",
327 self.range
328 );
329 }
330
331 // Renormalise back into `[2^15, 2^16)`, the same shift the encoder
332 // applied when it narrowed to this symbol.
333 let bits = 16 - (32 - self.range.leading_zeros());
334 self.range <<= bits;
335 let num_bits = u32::min(bits, self.max_bits.max(0) as u32);
336 let new_data = self.f(num_bits);
337 let padded = new_data << (bits - num_bits);
338 self.value = padded ^ (((self.value + 1) << bits) - 1);
339 self.max_bits -= bits as i32;
340 symbol
341 }
342
343 /// Debug-only: the current bit offset into `data`, for cross-checking
344 /// against a reference decoder's own `aom_reader_tell()` while chasing a
345 /// desync (see `EC_AV1_TRACE`). Not spec state, just `self.bit`.
346 pub(crate) fn debug_bitpos(&self) -> usize {
347 self.bit
348 }
349
350 /// Reads `bits` raw bits, most significant first — the `L(n)` descriptor
351 /// of spec 4.10.4.
352 pub fn literal(&mut self, bits: u32) -> u32 {
353 let mut v = 0;
354 for _ in 0..bits {
355 v = (v << 1) | self.symbol_fixed(&EQUIPROBABLE) as u32;
356 }
357 v
358 }
359}
360
361#[cfg(test)]
362pub(crate) mod tests {
363 use super::*;
364
365 // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now
366 // lives in the outer module (non-test code decodes with it too), so this
367 // re-export is what keeps those call sites resolving unmodified.
368 pub(crate) use super::SymbolDecoder;
369
370 /// A reproducible symbol stream: xorshift, so a failure names one seed.
371 fn rng(state: &mut u64) -> u64 {
372 *state ^= *state << 13;
373 *state ^= *state >> 7;
374 *state ^= *state << 17;
375 *state
376 }
377
378 fn flat_cdf(nsyms: usize) -> Vec<u16> {
379 let mut cdf = vec![0u16; nsyms + 1];
380 for (i, p) in cdf[..nsyms].iter_mut().enumerate() {
381 *p = (((i + 1) * (1 << 15)) / nsyms) as u16;
382 }
383 cdf[nsyms] = 0;
384 cdf
385 }
386
387 #[test]
388 fn adaptive_symbols_roundtrip() {
389 for nsyms in 2..=16usize {
390 let mut state = 0x2545_f491_4f6c_dd1d ^ nsyms as u64;
391 let symbols: Vec<usize> = (0..4000)
392 .map(|_| (rng(&mut state) % nsyms as u64) as usize)
393 .collect();
394
395 let mut enc = SymbolEncoder::new();
396 let mut cdf = flat_cdf(nsyms);
397 for &s in &symbols {
398 enc.symbol(s, &mut cdf);
399 }
400 let payload = enc.finish();
401
402 let mut dec = SymbolDecoder::new(&payload);
403 let mut cdf = flat_cdf(nsyms);
404 for (i, &want) in symbols.iter().enumerate() {
405 let got = dec.symbol(&mut cdf);
406 assert_eq!(got, want, "alphabet {nsyms}, symbol {i}");
407 }
408 }
409 }
410
411 #[test]
412 fn skewed_symbols_cost_less_than_a_bit() {
413 // A 1-in-256 symbol against an adapting CDF must cost far under one bit
414 // each: this is the property a range coder exists for, and it fails
415 // loudly if the interval narrowing is wired backwards.
416 let mut state = 0x9e37_79b9_7f4a_7c15;
417 let symbols: Vec<usize> = (0..8000)
418 .map(|_| usize::from(rng(&mut state).is_multiple_of(256)))
419 .collect();
420 let mut enc = SymbolEncoder::new();
421 let mut cdf = flat_cdf(2);
422 for &s in &symbols {
423 enc.symbol(s, &mut cdf);
424 }
425 let payload = enc.finish();
426 assert!(
427 payload.len() < 8000 / 8 / 4,
428 "8000 skewed symbols took {} bytes",
429 payload.len()
430 );
431
432 let mut dec = SymbolDecoder::new(&payload);
433 let mut cdf = flat_cdf(2);
434 for (i, &want) in symbols.iter().enumerate() {
435 assert_eq!(dec.symbol(&mut cdf), want, "symbol {i}");
436 }
437 }
438
439 #[test]
440 fn literals_roundtrip() {
441 let mut state = 0x0123_4567_89ab_cdef;
442 let values: Vec<(u32, u32)> = (0..2000)
443 .map(|_| {
444 let bits = 1 + (rng(&mut state) % 16) as u32;
445 let value = (rng(&mut state) as u32) & ((1u32 << bits) - 1);
446 (value, bits)
447 })
448 .collect();
449
450 let mut enc = SymbolEncoder::new();
451 for &(v, bits) in &values {
452 enc.literal(v, bits);
453 }
454 let payload = enc.finish();
455 // Equiprobable bits cannot be compressed, so the payload is one bit per
456 // written bit plus the flush.
457 let total: u32 = values.iter().map(|&(_, b)| b).sum();
458 assert!(payload.len() as u32 <= total / 8 + 4);
459
460 let mut dec = SymbolDecoder::new(&payload);
461 for (i, &(want, bits)) in values.iter().enumerate() {
462 assert_eq!(dec.literal(bits), want, "literal {i}");
463 }
464 }
465
466 #[test]
467 fn mixed_symbols_and_literals_roundtrip() {
468 let mut state = 0xdead_beef_cafe_f00d;
469 let mut enc = SymbolEncoder::new();
470 let mut cdf3 = flat_cdf(3);
471 let mut cdf8 = flat_cdf(8);
472 let mut written = Vec::new();
473 for _ in 0..3000 {
474 match rng(&mut state) % 3 {
475 0 => {
476 let s = (rng(&mut state) % 3) as usize;
477 enc.symbol(s, &mut cdf3);
478 written.push((0u8, s as u32));
479 }
480 1 => {
481 let s = (rng(&mut state) % 8) as usize;
482 enc.symbol(s, &mut cdf8);
483 written.push((1, s as u32));
484 }
485 _ => {
486 let v = (rng(&mut state) % 256) as u32;
487 enc.literal(v, 8);
488 written.push((2, v));
489 }
490 }
491 }
492 let payload = enc.finish();
493
494 let mut dec = SymbolDecoder::new(&payload);
495 let mut cdf3 = flat_cdf(3);
496 let mut cdf8 = flat_cdf(8);
497 for (i, &(kind, want)) in written.iter().enumerate() {
498 let got = match kind {
499 0 => dec.symbol(&mut cdf3) as u32,
500 1 => dec.symbol(&mut cdf8) as u32,
501 _ => dec.literal(8),
502 };
503 assert_eq!(got, want, "item {i} of kind {kind}");
504 }
505 }
506
507 /// The bit account is what a search prices decisions with, so it has to
508 /// agree with what the coder actually spends: over a long enough string the
509 /// two are within the coder's own rounding, a fraction of a percent.
510 #[test]
511 fn the_bit_account_matches_the_bytes_written() {
512 let mut enc = SymbolEncoder::new();
513 let mut state: u32 = 0x1234_5678;
514 let mut next = || {
515 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
516 state
517 };
518 // A skewed CDF, so that the account has something to be wrong about:
519 // an equiprobable string costs one bit a symbol however it is priced.
520 let skewed: [u16; 3] = [29000, 1 << 15, 0];
521 for _ in 0..20_000 {
522 let symbol = usize::from(next() % 100 < 12);
523 enc.symbol_fixed(symbol, &skewed);
524 }
525 let priced = enc.bits();
526 let spent = (enc.finish().len() * 8) as f64;
527 assert!(
528 (priced - spent).abs() / spent < 0.01,
529 "priced {priced:.0} bits, spent {spent:.0}"
530 );
531 }
532
533 #[test]
534 fn empty_payload_is_short() {
535 assert!(SymbolEncoder::new().finish().len() <= 2);
536 }
537}