forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB552edc4Tahinli2 months ago2048 commits

msac.rs573 lines, 21.8 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 debug_assert!(n <= 32, "f(n) reads at most 32 bits");
283 if n == 0 {
284 return 0;
285 }
286 // The bit-at-a-time form of this loop was the renormalisation cost
287 // inside every `symbol_fixed`. Five bytes cover any 32-bit field at
288 // any bit offset, and a byte past the end reads as zero exactly as
289 // the per-bit `unwrap_or(0)` did.
290 let start = self.bit >> 3;
291 let off = (self.bit & 7) as u32;
292 let mut acc = 0u64;
293 for k in 0..5 {
294 acc = (acc << 8) | u64::from(self.data.get(start + k).copied().unwrap_or(0));
295 }
296 self.bit += n as usize;
297 ((acc >> (40 - off - n)) & ((1u64 << n) - 1)) as u32
298 }
299
300 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
301 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {
302 let s = self.symbol_fixed(cdf);
303 update_cdf(cdf, s);
304 s
305 }
306
307 /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec
308 /// uses for the literal and equiprobable reads, mirroring
309 /// [`SymbolEncoder::symbol_fixed`].
310 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
311 let nsyms = cdf.len() - 1;
312 let mut cur = self.range;
313 let mut prev;
314 let mut symbol = 0;
315 // Loop-invariant: the coder's range does not move until the symbol is
316 // chosen, so its top byte is computed once rather than per candidate.
317 let base = self.range >> 8;
318 loop {
319 prev = cur;
320 let f = u32::from(CDF_TOP - cdf[symbol]);
321 cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
322 + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
323 if self.value >= cur {
324 break;
325 }
326 symbol += 1;
327 }
328 self.range = prev - cur;
329 self.value -= cur;
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 /// Debug-only: the raw coder state (`range`, `value`) entering the next
351 /// read, for a byte-for-byte diff against a reference decoder's own
352 /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see
353 /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields.
354 pub(crate) fn debug_state(&self) -> (u32, u32) {
355 (self.range, self.value)
356 }
357
358 /// Reads `bits` raw bits, most significant first — the `L(n)` descriptor
359 /// of spec 4.10.4.
360 pub fn literal(&mut self, bits: u32) -> u32 {
361 let mut v = 0;
362 for _ in 0..bits {
363 v = (v << 1) | self.symbol_fixed(&EQUIPROBABLE) as u32;
364 }
365 v
366 }
367}
368
369#[cfg(test)]
370pub(crate) mod tests {
371 use super::*;
372
373 /// `f(n)` now assembles five bytes and shifts instead of walking bits.
374 /// This pins it against the per-bit form it replaced, at every start
375 /// offset, every width up to 32, and past the end of the buffer (where
376 /// both forms must read zeros).
377 #[test]
378 fn bulk_bit_reads_match_the_per_bit_form() {
379 let data: Vec<u8> = (0..40u32).map(|i| (i * 37 + 11) as u8).collect();
380 let per_bit = |start: usize, n: u32| -> u32 {
381 let mut bit = start;
382 let mut v = 0u32;
383 for _ in 0..n {
384 let byte = data.get(bit >> 3).copied().unwrap_or(0);
385 v = (v << 1) | u32::from((byte >> (7 - (bit & 7))) & 1);
386 bit += 1;
387 }
388 v
389 };
390 for start in 0..(data.len() * 8 + 16) {
391 for n in 0..=32u32 {
392 let mut d = SymbolDecoder::new(&data);
393 d.bit = start;
394 let got = d.f(n);
395 assert_eq!(got, per_bit(start, n), "start {start} width {n}");
396 assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");
397 }
398 }
399 }
400
401 // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now
402 // lives in the outer module (non-test code decodes with it too), so this
403 // re-export is what keeps those call sites resolving unmodified.
404 pub(crate) use super::SymbolDecoder;
405
406 /// A reproducible symbol stream: xorshift, so a failure names one seed.
407 fn rng(state: &mut u64) -> u64 {
408 *state ^= *state << 13;
409 *state ^= *state >> 7;
410 *state ^= *state << 17;
411 *state
412 }
413
414 fn flat_cdf(nsyms: usize) -> Vec<u16> {
415 let mut cdf = vec![0u16; nsyms + 1];
416 for (i, p) in cdf[..nsyms].iter_mut().enumerate() {
417 *p = (((i + 1) * (1 << 15)) / nsyms) as u16;
418 }
419 cdf[nsyms] = 0;
420 cdf
421 }
422
423 #[test]
424 fn adaptive_symbols_roundtrip() {
425 for nsyms in 2..=16usize {
426 let mut state = 0x2545_f491_4f6c_dd1d ^ nsyms as u64;
427 let symbols: Vec<usize> = (0..4000)
428 .map(|_| (rng(&mut state) % nsyms as u64) as usize)
429 .collect();
430
431 let mut enc = SymbolEncoder::new();
432 let mut cdf = flat_cdf(nsyms);
433 for &s in &symbols {
434 enc.symbol(s, &mut cdf);
435 }
436 let payload = enc.finish();
437
438 let mut dec = SymbolDecoder::new(&payload);
439 let mut cdf = flat_cdf(nsyms);
440 for (i, &want) in symbols.iter().enumerate() {
441 let got = dec.symbol(&mut cdf);
442 assert_eq!(got, want, "alphabet {nsyms}, symbol {i}");
443 }
444 }
445 }
446
447 #[test]
448 fn skewed_symbols_cost_less_than_a_bit() {
449 // A 1-in-256 symbol against an adapting CDF must cost far under one bit
450 // each: this is the property a range coder exists for, and it fails
451 // loudly if the interval narrowing is wired backwards.
452 let mut state = 0x9e37_79b9_7f4a_7c15;
453 let symbols: Vec<usize> = (0..8000)
454 .map(|_| usize::from(rng(&mut state).is_multiple_of(256)))
455 .collect();
456 let mut enc = SymbolEncoder::new();
457 let mut cdf = flat_cdf(2);
458 for &s in &symbols {
459 enc.symbol(s, &mut cdf);
460 }
461 let payload = enc.finish();
462 assert!(
463 payload.len() < 8000 / 8 / 4,
464 "8000 skewed symbols took {} bytes",
465 payload.len()
466 );
467
468 let mut dec = SymbolDecoder::new(&payload);
469 let mut cdf = flat_cdf(2);
470 for (i, &want) in symbols.iter().enumerate() {
471 assert_eq!(dec.symbol(&mut cdf), want, "symbol {i}");
472 }
473 }
474
475 #[test]
476 fn literals_roundtrip() {
477 let mut state = 0x0123_4567_89ab_cdef;
478 let values: Vec<(u32, u32)> = (0..2000)
479 .map(|_| {
480 let bits = 1 + (rng(&mut state) % 16) as u32;
481 let value = (rng(&mut state) as u32) & ((1u32 << bits) - 1);
482 (value, bits)
483 })
484 .collect();
485
486 let mut enc = SymbolEncoder::new();
487 for &(v, bits) in &values {
488 enc.literal(v, bits);
489 }
490 let payload = enc.finish();
491 // Equiprobable bits cannot be compressed, so the payload is one bit per
492 // written bit plus the flush.
493 let total: u32 = values.iter().map(|&(_, b)| b).sum();
494 assert!(payload.len() as u32 <= total / 8 + 4);
495
496 let mut dec = SymbolDecoder::new(&payload);
497 for (i, &(want, bits)) in values.iter().enumerate() {
498 assert_eq!(dec.literal(bits), want, "literal {i}");
499 }
500 }
501
502 #[test]
503 fn mixed_symbols_and_literals_roundtrip() {
504 let mut state = 0xdead_beef_cafe_f00d;
505 let mut enc = SymbolEncoder::new();
506 let mut cdf3 = flat_cdf(3);
507 let mut cdf8 = flat_cdf(8);
508 let mut written = Vec::new();
509 for _ in 0..3000 {
510 match rng(&mut state) % 3 {
511 0 => {
512 let s = (rng(&mut state) % 3) as usize;
513 enc.symbol(s, &mut cdf3);
514 written.push((0u8, s as u32));
515 }
516 1 => {
517 let s = (rng(&mut state) % 8) as usize;
518 enc.symbol(s, &mut cdf8);
519 written.push((1, s as u32));
520 }
521 _ => {
522 let v = (rng(&mut state) % 256) as u32;
523 enc.literal(v, 8);
524 written.push((2, v));
525 }
526 }
527 }
528 let payload = enc.finish();
529
530 let mut dec = SymbolDecoder::new(&payload);
531 let mut cdf3 = flat_cdf(3);
532 let mut cdf8 = flat_cdf(8);
533 for (i, &(kind, want)) in written.iter().enumerate() {
534 let got = match kind {
535 0 => dec.symbol(&mut cdf3) as u32,
536 1 => dec.symbol(&mut cdf8) as u32,
537 _ => dec.literal(8),
538 };
539 assert_eq!(got, want, "item {i} of kind {kind}");
540 }
541 }
542
543 /// The bit account is what a search prices decisions with, so it has to
544 /// agree with what the coder actually spends: over a long enough string the
545 /// two are within the coder's own rounding, a fraction of a percent.
546 #[test]
547 fn the_bit_account_matches_the_bytes_written() {
548 let mut enc = SymbolEncoder::new();
549 let mut state: u32 = 0x1234_5678;
550 let mut next = || {
551 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
552 state
553 };
554 // A skewed CDF, so that the account has something to be wrong about:
555 // an equiprobable string costs one bit a symbol however it is priced.
556 let skewed: [u16; 3] = [29000, 1 << 15, 0];
557 for _ in 0..20_000 {
558 let symbol = usize::from(next() % 100 < 12);
559 enc.symbol_fixed(symbol, &skewed);
560 }
561 let priced = enc.bits();
562 let spent = (enc.finish().len() * 8) as f64;
563 assert!(
564 (priced - spent).abs() / spent < 0.01,
565 "priced {priced:.0} bits, spent {spent:.0}"
566 );
567 }
568
569 #[test]
570 fn empty_payload_is_short() {
571 assert!(SymbolEncoder::new().finish().len() <= 2);
572 }
573}