forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiB5c8eff8Tahinli2 months ago2949 commits

msac.rs891 lines, 34.4 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 /// `log2` of the interval width the bit account started from — the coder's
51 /// width at [`Self::new`] or at the last [`Self::reset_bits`].
52 bits_base: f64,
53 /// How many bits the renormalisation has shifted `rng` up by since the
54 /// account started. A symbol costs `log2(r) - log2(rng)` for the widths it
55 /// narrows between, and the next symbol's `r` is this symbol's `rng`
56 /// shifted left by the renormalisation, so the whole string's cost
57 /// telescopes to `bits_base + shifts - log2(rng)` — one `log2` per price
58 /// asked for, instead of one per symbol (libaom's `od_ec_enc_tell_frac`
59 /// reads its account the same way).
60 shifts: u32,
61 /// Whether this coder only prices: the bit account depends on nothing but
62 /// how far each symbol narrows `rng`, so a pricer keeps the interval width
63 /// and drops the value bookkeeping (`low`, `cnt`, `precarry`) whose only
64 /// consumer is [`Self::finish`].
65 pricing: bool,
66}
67
68impl Default for SymbolEncoder {
69 fn default() -> SymbolEncoder {
70 SymbolEncoder::new()
71 }
72}
73
74impl SymbolEncoder {
75 /// A new encoder holding the full interval, as the decoder's
76 /// `init_symbol` process assumes.
77 pub fn new() -> SymbolEncoder {
78 SymbolEncoder {
79 low: 0,
80 rng: 0x8000,
81 cnt: -9,
82 precarry: Vec::new(),
83 bits_base: 15.0,
84 shifts: 0,
85 pricing: false,
86 }
87 }
88
89 /// A coder that only prices, for a search that wants [`Self::bits`] and
90 /// will never ask for the bytes. Every symbol narrows `rng` exactly as it
91 /// would in a writing coder, so the account is the same to the bit.
92 pub fn pricer() -> SymbolEncoder {
93 SymbolEncoder {
94 pricing: true,
95 ..SymbolEncoder::new()
96 }
97 }
98
99 /// What the symbols written so far cost, in bits.
100 pub fn bits(&self) -> f64 {
101 self.bits_base + f64::from(self.shifts) - f64::from(self.rng).log2()
102 }
103
104 /// The coder's current interval width — libaom's `od_ec_enc_rng` /
105 /// decoder's `rng` field. Exposed only for the rng-register bisect trace
106 /// (`EC_RNG=1`); not part of the bitstream contract.
107 pub(crate) fn rng(&self) -> u32 {
108 self.rng
109 }
110
111 /// The exact bit position the stream has committed to so far (libaom's
112 /// `od_ec_enc_tell`, `entenc.c`): `cnt + 10` undoes the `-9` `cnt` starts
113 /// at and reserves the one bit `finish` always spends, and `precarry`
114 /// holds one `u16` per byte already flushed. Pairs with the decoder's
115 /// `aom_reader_tell`, which counts the same bits consumed.
116 pub fn tell(&self) -> i32 {
117 debug_assert!(!self.pricing, "a pricer keeps no byte position");
118 self.cnt + 10 + self.precarry.len() as i32 * 8
119 }
120
121 /// Forgets the cost accumulated so far, so that the next stretch of
122 /// symbols can be priced on its own.
123 pub fn reset_bits(&mut self) {
124 self.bits_base = f64::from(self.rng).log2();
125 self.shifts = 0;
126 }
127
128 /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder
129 /// will after reading it (spec 8.3.2).
130 ///
131 /// # Panics
132 /// Panics if `symbol` is not a symbol of `cdf`'s alphabet, or if `cdf` is
133 /// shorter than a two-symbol alphabet's three entries.
134 pub fn symbol(&mut self, symbol: usize, cdf: &mut [u16]) {
135 self.symbol_fixed(symbol, cdf);
136 update_cdf(cdf, symbol);
137 }
138
139 /// Writes `symbol` against a CDF that does not adapt — the form the spec
140 /// uses for the literal and equiprobable reads.
141 ///
142 /// # Panics
143 /// Panics if `symbol` is not a symbol of `cdf`'s alphabet, or if `cdf` is
144 /// shorter than a two-symbol alphabet's three entries.
145 pub fn symbol_fixed(&mut self, symbol: usize, cdf: &[u16]) {
146 assert!(cdf.len() >= 3, "a CDF covers at least two symbols");
147 if !self.pricing && symtrace::dir().is_some() {
148 symtrace::push(symbol, cdf.len() - 1, cdf[0]);
149 }
150 let nsyms = cdf.len() - 1;
151 assert!(symbol < nsyms, "symbol {symbol} is outside the alphabet");
152
153 // The decoder walks the alphabet computing the same two boundaries and
154 // stops at the first symbol whose lower boundary the coded value has
155 // fallen below, so the encoder only has to narrow to that symbol's
156 // slice of the interval.
157 let r = self.rng;
158 let fh = u32::from(CDF_TOP - cdf[symbol]);
159 let v = (((r >> 8) * (fh >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
160 + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
161 let mut low = self.low;
162 let rng = if symbol > 0 {
163 let fl = u32::from(CDF_TOP - cdf[symbol - 1]);
164 let u = (((r >> 8) * (fl >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
165 + EC_MIN_PROB * (nsyms - symbol) as u32;
166 low += u64::from(r - u);
167 u - v
168 } else {
169 // Symbol 0 owns the top of the interval, so only its width moves.
170 r - v
171 };
172 // What this symbol really cost is how far it narrowed the interval,
173 // which is not quite its nominal probability: the coder works the
174 // range through an eight-bit multiply and hands every symbol above
175 // this one a floor of `EC_MIN_PROB`. Pricing the narrowing rather than
176 // the table entry is what makes the account match the bytes; the
177 // narrowing itself is read off `rng` and `shifts` by [`Self::bits`].
178 if self.pricing {
179 let d = 16 - (32 - rng.leading_zeros());
180 self.rng = rng << d;
181 self.shifts += d;
182 } else {
183 self.normalize(low, rng);
184 }
185 }
186
187 /// Writes `bits` raw bits of `value`, most significant first — the `L(n)`
188 /// descriptor of spec 4.10.4, which is `bits` equiprobable symbols.
189 ///
190 /// # Panics
191 /// Panics if `bits` exceeds 32.
192 pub fn literal(&mut self, value: u32, bits: u32) {
193 assert!(bits <= 32, "a literal is at most 32 bits");
194 for i in (0..bits).rev() {
195 let bit = (value >> i) & 1;
196 self.symbol_fixed(bit as usize, &EQUIPROBABLE);
197 }
198 }
199
200 /// Flushes the coder and returns the payload bytes.
201 ///
202 /// The flush writes the shortest value inside the final interval that stays
203 /// inside it however the decoder pads the string, which is what lets a tile
204 /// payload end on a byte boundary with no terminator.
205 pub fn finish(mut self) -> Vec<u8> {
206 assert!(!self.pricing, "a pricer holds no bytes to flush");
207 symtrace::flush('w');
208 // Round the interval's low end up to a value with 14 low zero bits,
209 // then set bit 14: the result is inside the interval (the interval is
210 // at least 2^15 wide before normalisation) and its tail bits are all
211 // zero, so they need not be written at all.
212 let m: u64 = 0x3fff;
213 let mut e = ((self.low + m) & !m) | (m + 1);
214 let mut c = self.cnt;
215 let mut s = 10 + c;
216 while s > 0 {
217 self.precarry.push((e >> (c + 16)) as u16);
218 e &= (1u64 << (c + 16)) - 1;
219 s -= 8;
220 c -= 8;
221 }
222
223 // Each flushed entry may have overflowed a byte; the overflow is a
224 // carry into the byte written before it.
225 let mut out = vec![0u8; self.precarry.len()];
226 let mut carry = 0u32;
227 for (byte, &pre) in out.iter_mut().zip(self.precarry.iter()).rev() {
228 let v = u32::from(pre) + carry;
229 *byte = v as u8;
230 carry = v >> 8;
231 }
232 out
233 }
234
235 /// Renormalises the interval back into `[2^15, 2^16)`, flushing whole bytes
236 /// of `low` once they can no longer change.
237 fn normalize(&mut self, low: u64, rng: u32) {
238 debug_assert!(rng > 0 && rng <= 0xffff);
239 let d = 16 - (32 - rng.leading_zeros()) as i32;
240 let mut c = self.cnt;
241 let mut s = c + d;
242 let mut low = low;
243 if s >= 0 {
244 // At least one byte at the top of `low` is settled: a later carry
245 // can still reach it, which is why it is kept in the precarry
246 // buffer as a `u16` rather than truncated to a byte here.
247 c += 16;
248 let mut m = (1u64 << c) - 1;
249 if s >= 8 {
250 self.precarry.push((low >> c) as u16);
251 low &= m;
252 c -= 8;
253 m >>= 8;
254 }
255 self.precarry.push((low >> c) as u16);
256 s = c + d - 24;
257 low &= m;
258 }
259 self.low = low << d;
260 self.rng = rng << d;
261 self.cnt = s;
262 self.shifts += d as u32;
263 }
264}
265
266/// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent
267/// fraction of the way towards the extreme the observed symbol implies, and the
268/// counter in the last entry slows the rate down for the first 32 symbols.
269#[inline]
270fn update_cdf(cdf: &mut [u16], symbol: usize) {
271 let nsyms = cdf.len() - 1;
272 let count = cdf[nsyms];
273 let rate = 3 + (nsyms >> 1).min(2) + (count >> 4) as usize;
274 for (i, p) in cdf[..nsyms - 1].iter_mut().enumerate() {
275 if i < symbol {
276 *p -= *p >> rate;
277 } else {
278 *p += (CDF_TOP - *p) >> rate;
279 }
280 }
281 cdf[nsyms] = count + 1 - (count >> 5);
282}
283
284/// The decoding process of spec 8.2, the exact inverse of [`SymbolEncoder`]:
285/// reads the symbols a [`SymbolEncoder`] wrote, in the order it wrote them,
286/// adapting every CDF identically (spec 8.3.2) so the two stay in step. This
287/// is the reader half of the arithmetic coder a real AV1 decoder's tile
288/// reader is built on top of.
289#[derive(Debug)]
290pub struct SymbolDecoder<'a> {
291 data: &'a [u8],
292 /// Next bit to read, as a bit offset into `data`.
293 bit: usize,
294 /// The bits from `bit` onward, left-aligned at the MSB, zero past the end
295 /// of `data`; only the top `win_bits` are valid. The renormalisation of
296 /// every symbol read one to fifteen bits, and assembling them out of
297 /// `data` per read was five byte loads and two variable shifts each; the
298 /// window pays that once per eight bytes instead.
299 win: u64,
300 win_bits: u32,
301 /// Next byte of `data` to shift into `win`.
302 pos: usize,
303 value: u32,
304 range: u32,
305 /// Bits left before the decoder starts padding with zeros (spec
306 /// `SymbolMaxBits`), which goes negative at the end of the string.
307 max_bits: i32,
308}
309
310impl Drop for SymbolDecoder<'_> {
311 fn drop(&mut self) {
312 symtrace::flush('r');
313 }
314}
315
316impl<'a> SymbolDecoder<'a> {
317 /// `init_symbol` (spec 8.2.2).
318 #[must_use]
319 pub fn new(data: &'a [u8]) -> SymbolDecoder<'a> {
320 let mut d = SymbolDecoder {
321 data,
322 bit: 0,
323 win: 0,
324 win_bits: 0,
325 pos: 0,
326 value: 0,
327 range: 1 << 15,
328 max_bits: 8 * data.len() as i32 - 15,
329 };
330 let num_bits = usize::min(data.len() * 8, 15) as u32;
331 let buf = d.f(num_bits);
332 d.value = ((1 << 15) - 1) ^ (buf << (15 - num_bits));
333 d
334 }
335
336 /// `f(n)`: the next `n` bits, most significant first, zero past the end.
337 #[inline]
338 fn f(&mut self, n: u32) -> u32 {
339 debug_assert!(n <= 32, "f(n) reads at most 32 bits");
340 if n == 0 {
341 return 0;
342 }
343 if self.win_bits < n {
344 self.refill();
345 }
346 let v = (self.win >> (64 - n)) as u32;
347 self.win <<= n;
348 self.win_bits -= n;
349 self.bit += n as usize;
350 v
351 }
352
353 /// Tops the window back up to at least 57 bits, reading bytes past the end
354 /// of `data` as zero exactly as the per-read `unwrap_or(0)` did.
355 fn refill(&mut self) {
356 while self.win_bits <= 56 {
357 let byte = self.data.get(self.pos).copied().unwrap_or(0);
358 self.pos += 1;
359 self.win |= u64::from(byte) << (56 - self.win_bits);
360 self.win_bits += 8;
361 }
362 }
363
364 /// Repositions the window at an arbitrary bit offset (the `f(n)` test's
365 /// only way in now that `bit` alone no longer names the read position).
366 #[cfg(test)]
367 fn seek_bits(&mut self, bit: usize) {
368 self.bit = bit;
369 self.pos = bit >> 3;
370 self.win = 0;
371 self.win_bits = 0;
372 let skip = (bit & 7) as u32;
373 if skip > 0 {
374 self.refill();
375 self.win <<= skip;
376 self.win_bits -= skip;
377 }
378 }
379
380 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
381 #[inline]
382 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {
383 // lane-census: the syntax census charges this symbol's bits to the
384 // TABLE it read, so every coding tool is accounted without a
385 // per-call-site label. Off (`EC_AV1_BITCENSUS` unset) this is one
386 // relaxed load.
387 let t0 = if crate::census::armed() { self.tell_bits() } else { 0.0 };
388 let s = self.symbol_fixed(cdf);
389 update_cdf(cdf, s);
390 if crate::census::armed() {
391 crate::census::charge(cdf.as_ptr() as usize, self.tell_bits() - t0);
392 }
393 s
394 }
395
396 /// Bits consumed so far, fractionally -- the read position less the
397 /// information still held in the range (`log2(range)`, which starts at
398 /// 15). Differences between two of these are one read's cost; the
399 /// absolute value carries a constant offset (class `compare-range-not-tell`).
400 #[must_use]
401 pub fn tell_bits(&self) -> f64 {
402 self.bit as f64 - f64::from(self.range).log2()
403 }
404
405 /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec
406 /// uses for the literal and equiprobable reads, mirroring
407 /// [`SymbolEncoder::symbol_fixed`].
408 #[inline]
409 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
410 if symtrace::dir().is_some() {
411 let s = self.symbol_fixed_raw(cdf);
412 symtrace::push(s, cdf.len() - 1, cdf[0]);
413 return s;
414 }
415 self.symbol_fixed_raw(cdf)
416 }
417
418 #[inline]
419 fn symbol_fixed_raw(&mut self, cdf: &[u16]) -> usize {
420 let nsyms = cdf.len() - 1;
421 // Two-symbol alphabets are most of the stream (every flag, every bit of
422 // a literal), and their walk has exactly one boundary: computing it
423 // straight skips the loop and its bounds work.
424 if nsyms == 2 {
425 let f = u32::from(CDF_TOP - cdf[0]);
426 let cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
427 + EC_MIN_PROB;
428 return self.bool_cur(cur);
429 }
430 // Loop-invariant: the coder's range does not move until the symbol is
431 // chosen, so its top byte is computed once rather than per candidate.
432 let base = self.range >> 8;
433 let mut prev = self.range;
434 // The floor every symbol above the candidate is owed, counted down
435 // instead of multiplied out per candidate.
436 let mut minp = EC_MIN_PROB * (nsyms - 1) as u32;
437 // The last boundary is always `CDF_TOP`, whose `cur` is 0, so the walk
438 // always stops inside the alphabet: the last candidate needs no test
439 // and its arithmetic is the fall-through below.
440 let mut symbol = nsyms - 1;
441 let mut cur = 0;
442 for (i, &c) in cdf[..nsyms - 1].iter().enumerate() {
443 let f = u32::from(CDF_TOP - c);
444 let c = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + minp;
445 if self.value >= c {
446 symbol = i;
447 cur = c;
448 break;
449 }
450 prev = c;
451 minp -= EC_MIN_PROB;
452 }
453 self.renorm(prev - cur, self.value - cur);
454 symbol
455 }
456
457 /// Finishes a two-symbol read whose single boundary is `cur`: symbol 0 owns
458 /// `[cur, range)` and symbol 1 owns `[0, cur)`.
459 #[inline(always)]
460 fn bool_cur(&mut self, cur: u32) -> usize {
461 let value = self.value;
462 let (symbol, rng, val) = if value >= cur {
463 (0, self.range - cur, value - cur)
464 } else {
465 (1, cur, value)
466 };
467 self.renorm(rng, val);
468 symbol
469 }
470
471 /// Renormalises `rng` back into `[2^15, 2^16)` and shifts the same number of
472 /// bits into `val`, the tail every symbol read shares — the same shift the
473 /// encoder applied when it narrowed to this symbol.
474 #[inline(always)]
475 fn renorm(&mut self, rng: u32, val: u32) {
476 let bits = 16 - (32 - rng.leading_zeros());
477 self.range = rng << bits;
478 let num_bits = u32::min(bits, self.max_bits.max(0) as u32);
479 let new_data = self.f(num_bits);
480 let padded = new_data << (bits - num_bits);
481 self.value = padded ^ (((val + 1) << bits) - 1);
482 self.max_bits -= bits as i32;
483 }
484
485 /// Debug-only: the current bit offset into `data`, for cross-checking
486 /// against a reference decoder's own `aom_reader_tell()` while chasing a
487 /// desync (see `EC_AV1_TRACE`). Not spec state, just `self.bit`.
488 pub(crate) fn debug_bitpos(&self) -> usize {
489 self.bit
490 }
491
492 /// Debug-only: the raw coder state (`range`, `value`) entering the next
493 /// read, for a byte-for-byte diff against a reference decoder's own
494 /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see
495 /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields.
496 pub(crate) fn debug_state(&self) -> (u32, u32) {
497 (self.range, self.value)
498 }
499
500 /// Reads `bits` raw bits, most significant first — the `L(n)` descriptor
501 /// of spec 4.10.4.
502 ///
503 /// lane-coefread: `#[inline]`, because without it this was a real CALL per
504 /// raw bit across a codegen-unit boundary (the crate builds without LTO) --
505 /// the coefficient sign pass and the Golomb tail read one bit at a time.
506 #[inline]
507 pub fn literal(&mut self, bits: u32) -> u32 {
508 if crate::census::armed() {
509 crate::census::charge_literal(bits);
510 }
511 let mut v = 0;
512 for _ in 0..bits {
513 // `EQUIPROBABLE`'s single boundary: `f >> EC_PROB_SHIFT` is 256, so
514 // the range multiply is a shift.
515 let cur = ((self.range >> 8) << 7) + EC_MIN_PROB;
516 let bit = self.bool_cur(cur);
517 if symtrace::dir().is_some() {
518 symtrace::push(bit, 2, EQUIPROBABLE[0]);
519 }
520 v = (v << 1) | bit as u32;
521 }
522 v
523 }
524}
525
526#[cfg(test)]
527pub(crate) mod tests {
528 use super::*;
529
530 /// `f(n)` now assembles five bytes and shifts instead of walking bits.
531 /// This pins it against the per-bit form it replaced, at every start
532 /// offset, every width up to 32, and past the end of the buffer (where
533 /// both forms must read zeros).
534 #[test]
535 fn bulk_bit_reads_match_the_per_bit_form() {
536 let data: Vec<u8> = (0..40u32).map(|i| (i * 37 + 11) as u8).collect();
537 let per_bit = |start: usize, n: u32| -> u32 {
538 let mut bit = start;
539 let mut v = 0u32;
540 for _ in 0..n {
541 let byte = data.get(bit >> 3).copied().unwrap_or(0);
542 v = (v << 1) | u32::from((byte >> (7 - (bit & 7))) & 1);
543 bit += 1;
544 }
545 v
546 };
547 for start in 0..(data.len() * 8 + 16) {
548 for n in 0..=32u32 {
549 let mut d = SymbolDecoder::new(&data);
550 d.seek_bits(start);
551 let got = d.f(n);
552 assert_eq!(got, per_bit(start, n), "start {start} width {n}");
553 assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");
554 }
555 }
556 }
557
558 // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now
559 // lives in the outer module (non-test code decodes with it too), so this
560 // re-export is what keeps those call sites resolving unmodified.
561 pub(crate) use super::SymbolDecoder;
562
563 /// A reproducible symbol stream: xorshift, so a failure names one seed.
564 fn rng(state: &mut u64) -> u64 {
565 *state ^= *state << 13;
566 *state ^= *state >> 7;
567 *state ^= *state << 17;
568 *state
569 }
570
571 fn flat_cdf(nsyms: usize) -> Vec<u16> {
572 let mut cdf = vec![0u16; nsyms + 1];
573 for (i, p) in cdf[..nsyms].iter_mut().enumerate() {
574 *p = (((i + 1) * (1 << 15)) / nsyms) as u16;
575 }
576 cdf[nsyms] = 0;
577 cdf
578 }
579
580 #[test]
581 fn adaptive_symbols_roundtrip() {
582 for nsyms in 2..=16usize {
583 let mut state = 0x2545_f491_4f6c_dd1d ^ nsyms as u64;
584 let symbols: Vec<usize> = (0..4000)
585 .map(|_| (rng(&mut state) % nsyms as u64) as usize)
586 .collect();
587
588 let mut enc = SymbolEncoder::new();
589 let mut cdf = flat_cdf(nsyms);
590 for &s in &symbols {
591 enc.symbol(s, &mut cdf);
592 }
593 let payload = enc.finish();
594
595 let mut dec = SymbolDecoder::new(&payload);
596 let mut cdf = flat_cdf(nsyms);
597 for (i, &want) in symbols.iter().enumerate() {
598 let got = dec.symbol(&mut cdf);
599 assert_eq!(got, want, "alphabet {nsyms}, symbol {i}");
600 }
601 }
602 }
603
604 #[test]
605 fn skewed_symbols_cost_less_than_a_bit() {
606 // A 1-in-256 symbol against an adapting CDF must cost far under one bit
607 // each: this is the property a range coder exists for, and it fails
608 // loudly if the interval narrowing is wired backwards.
609 let mut state = 0x9e37_79b9_7f4a_7c15;
610 let symbols: Vec<usize> = (0..8000)
611 .map(|_| usize::from(rng(&mut state).is_multiple_of(256)))
612 .collect();
613 let mut enc = SymbolEncoder::new();
614 let mut cdf = flat_cdf(2);
615 for &s in &symbols {
616 enc.symbol(s, &mut cdf);
617 }
618 let payload = enc.finish();
619 assert!(
620 payload.len() < 8000 / 8 / 4,
621 "8000 skewed symbols took {} bytes",
622 payload.len()
623 );
624
625 let mut dec = SymbolDecoder::new(&payload);
626 let mut cdf = flat_cdf(2);
627 for (i, &want) in symbols.iter().enumerate() {
628 assert_eq!(dec.symbol(&mut cdf), want, "symbol {i}");
629 }
630 }
631
632 #[test]
633 fn literals_roundtrip() {
634 let mut state = 0x0123_4567_89ab_cdef;
635 let values: Vec<(u32, u32)> = (0..2000)
636 .map(|_| {
637 let bits = 1 + (rng(&mut state) % 16) as u32;
638 let value = (rng(&mut state) as u32) & ((1u32 << bits) - 1);
639 (value, bits)
640 })
641 .collect();
642
643 let mut enc = SymbolEncoder::new();
644 for &(v, bits) in &values {
645 enc.literal(v, bits);
646 }
647 let payload = enc.finish();
648 // Equiprobable bits cannot be compressed, so the payload is one bit per
649 // written bit plus the flush.
650 let total: u32 = values.iter().map(|&(_, b)| b).sum();
651 assert!(payload.len() as u32 <= total / 8 + 4);
652
653 let mut dec = SymbolDecoder::new(&payload);
654 for (i, &(want, bits)) in values.iter().enumerate() {
655 assert_eq!(dec.literal(bits), want, "literal {i}");
656 }
657 }
658
659 #[test]
660 fn mixed_symbols_and_literals_roundtrip() {
661 let mut state = 0xdead_beef_cafe_f00d;
662 let mut enc = SymbolEncoder::new();
663 let mut cdf3 = flat_cdf(3);
664 let mut cdf8 = flat_cdf(8);
665 let mut written = Vec::new();
666 for _ in 0..3000 {
667 match rng(&mut state) % 3 {
668 0 => {
669 let s = (rng(&mut state) % 3) as usize;
670 enc.symbol(s, &mut cdf3);
671 written.push((0u8, s as u32));
672 }
673 1 => {
674 let s = (rng(&mut state) % 8) as usize;
675 enc.symbol(s, &mut cdf8);
676 written.push((1, s as u32));
677 }
678 _ => {
679 let v = (rng(&mut state) % 256) as u32;
680 enc.literal(v, 8);
681 written.push((2, v));
682 }
683 }
684 }
685 let payload = enc.finish();
686
687 let mut dec = SymbolDecoder::new(&payload);
688 let mut cdf3 = flat_cdf(3);
689 let mut cdf8 = flat_cdf(8);
690 for (i, &(kind, want)) in written.iter().enumerate() {
691 let got = match kind {
692 0 => dec.symbol(&mut cdf3) as u32,
693 1 => dec.symbol(&mut cdf8) as u32,
694 _ => dec.literal(8),
695 };
696 assert_eq!(got, want, "item {i} of kind {kind}");
697 }
698 }
699
700 /// The bit account is what a search prices decisions with, so it has to
701 /// agree with what the coder actually spends: over a long enough string the
702 /// two are within the coder's own rounding, a fraction of a percent.
703 #[test]
704 fn the_bit_account_matches_the_bytes_written() {
705 let mut enc = SymbolEncoder::new();
706 let mut state: u32 = 0x1234_5678;
707 let mut next = || {
708 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
709 state
710 };
711 // A skewed CDF, so that the account has something to be wrong about:
712 // an equiprobable string costs one bit a symbol however it is priced.
713 let skewed: [u16; 3] = [29000, 1 << 15, 0];
714 for _ in 0..20_000 {
715 let symbol = usize::from(next() % 100 < 12);
716 enc.symbol_fixed(symbol, &skewed);
717 }
718 let priced = enc.bits();
719 let spent = (enc.finish().len() * 8) as f64;
720 assert!(
721 (priced - spent).abs() / spent < 0.01,
722 "priced {priced:.0} bits, spent {spent:.0}"
723 );
724 }
725
726 #[test]
727 fn empty_payload_is_short() {
728 assert!(SymbolEncoder::new().finish().len() <= 2);
729 }
730 /// The spec-literal 8.2.6 walk, as `symbol_fixed` read it before the
731 /// two-symbol shortcut and the last-candidate fall-through: every
732 /// candidate tested, `EC_MIN_PROB` multiplied out, one shared tail.
733 fn ref_symbol_fixed(d: &mut SymbolDecoder<'_>, cdf: &[u16]) -> usize {
734 let nsyms = cdf.len() - 1;
735 let mut cur = d.range;
736 let mut prev = cur;
737 let mut symbol = nsyms - 1;
738 let base = d.range >> 8;
739 for (i, &c) in cdf[..nsyms].iter().enumerate() {
740 prev = cur;
741 let f = u32::from(CDF_TOP - c);
742 cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
743 + EC_MIN_PROB * (nsyms - 1 - i) as u32;
744 if d.value >= cur {
745 symbol = i;
746 break;
747 }
748 }
749 d.range = prev - cur;
750 d.value -= cur;
751 let bits = 16 - (32 - d.range.leading_zeros());
752 d.range <<= bits;
753 let num_bits = u32::min(bits, d.max_bits.max(0) as u32);
754 let new_data = d.f(num_bits);
755 let padded = new_data << (bits - num_bits);
756 d.value = padded ^ (((d.value + 1) << bits) - 1);
757 d.max_bits -= bits as i32;
758 symbol
759 }
760
761 /// The reader's fast paths must be the spec walk, symbol for symbol and
762 /// register for register: a long mixed stream is decoded twice in lockstep
763 /// and both the symbol and the coder state `(range, value)` are compared
764 /// after every read, so a divergence that has not yet changed a symbol
765 /// still fails here.
766 #[test]
767 fn fast_paths_match_the_spec_literal_walk() {
768 let mut state = 0x0123_4567_89ab_cdef;
769 let mut enc = SymbolEncoder::new();
770 let mut cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect();
771 let mut written: Vec<(usize, u32)> = Vec::new();
772 for _ in 0..20_000 {
773 let pick = (rng(&mut state) % 16) as usize;
774 if pick == 15 {
775 let width = 1 + (rng(&mut state) % 16) as u32;
776 let v = (rng(&mut state) as u32) & ((1u32 << width) - 1);
777 enc.literal(v, width);
778 written.push((usize::MAX, width));
779 } else {
780 let nsyms = pick + 2;
781 let sym = (rng(&mut state) % nsyms as u64) as usize;
782 enc.symbol(sym, &mut cdfs[pick]);
783 written.push((pick, sym as u32));
784 }
785 }
786 let payload = enc.finish();
787
788 let mut fast = SymbolDecoder::new(&payload);
789 let mut slow = SymbolDecoder::new(&payload);
790 let mut fast_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect();
791 let mut slow_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect();
792 for (i, &(pick, arg)) in written.iter().enumerate() {
793 let (a, b) = if pick == usize::MAX {
794 let a = fast.literal(arg);
795 let mut b = 0u32;
796 for _ in 0..arg {
797 b = (b << 1) | ref_symbol_fixed(&mut slow, &EQUIPROBABLE) as u32;
798 }
799 (a, b)
800 } else {
801 let a = fast.symbol(&mut fast_cdfs[pick]) as u32;
802 let b = ref_symbol_fixed(&mut slow, &slow_cdfs[pick]);
803 update_cdf(&mut slow_cdfs[pick], b);
804 (a, b as u32)
805 };
806 assert_eq!(a, b, "item {i} (pick {pick})");
807 assert_eq!(a, if pick == usize::MAX { a } else { arg }, "item {i} vs written");
808 assert_eq!(
809 fast.debug_state(),
810 slow.debug_state(),
811 "coder state after item {i} (pick {pick})"
812 );
813 assert_eq!(fast_cdfs[pick.min(14)], slow_cdfs[pick.min(14)], "cdf after item {i}");
814 }
815 }
816}
817
818/// Symbol-by-symbol writer/reader trace (`EC_AV1_SYMTRACE=<dir>`), the
819/// instrument a desync between OUR writer and OUR reader is bisected with:
820/// every non-pricing [`SymbolEncoder`] and every [`SymbolDecoder`] dumps one
821/// line per symbol (`index value nsyms cdf0`) into `<dir>/w-<n>.txt` /
822/// `<dir>/r-<n>.txt`, and the first line where the two differ names the
823/// divergent symbol. `EC_AV1_SYMTRACE_AT=<index>` additionally prints a
824/// backtrace at that index on both sides, which names the syntax element.
825/// Off (the variable unset) this is one relaxed load per symbol.
826pub(crate) mod symtrace {
827 use std::cell::RefCell;
828 use std::sync::OnceLock;
829
830 static DIR: OnceLock<Option<String>> = OnceLock::new();
831 static AT: OnceLock<Option<(usize, usize)>> = OnceLock::new();
832 static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
833
834 thread_local! {
835 static BUF: RefCell<(String, usize)> = const { RefCell::new((String::new(), 0)) };
836 }
837
838 pub(crate) fn dir() -> Option<&'static str> {
839 DIR.get_or_init(|| crate::envflags::var("EC_AV1_SYMTRACE").ok().filter(|v| !v.is_empty()))
840 .as_deref()
841 }
842
843 /// `EC_AV1_SYMTRACE_AT=<i>` or `=<from>:<to>` (inclusive).
844 fn at() -> Option<(usize, usize)> {
845 *AT.get_or_init(|| {
846 let v = crate::envflags::var("EC_AV1_SYMTRACE_AT").ok()?;
847 let (a, b) = v.split_once(':').unwrap_or((v.as_str(), v.as_str()));
848 Some((a.parse().ok()?, b.parse().ok()?))
849 })
850 }
851
852 /// A caller's own annotation, interleaved with this coder's symbol lines
853 /// (`# ...`) so the writer/reader diff shows the state around a desync.
854 pub(crate) fn note(line: &str) {
855 if dir().is_none() {
856 return;
857 }
858 BUF.with(|b| {
859 let (buf, _) = &mut *b.borrow_mut();
860 buf.push_str("# ");
861 buf.push_str(line);
862 buf.push('\n');
863 });
864 }
865
866 pub(crate) fn push(value: usize, nsyms: usize, cdf0: u16) {
867 BUF.with(|b| {
868 let (buf, n) = &mut *b.borrow_mut();
869 if at().is_some_and(|(a, b)| (a..=b).contains(n)) {
870 eprintln!("SYMTRACE at {n}: {}", std::backtrace::Backtrace::force_capture());
871 }
872 buf.push_str(&format!("{n} {value} {nsyms} {cdf0}\n"));
873 *n += 1;
874 });
875 }
876
877 /// Flushes this coder's lines as `<dir>/<side>-<n>.txt` and starts the
878 /// next coder's trace.
879 pub(crate) fn flush(side: char) {
880 let Some(dir) = dir() else { return };
881 BUF.with(|b| {
882 let (buf, n) = &mut *b.borrow_mut();
883 if !buf.is_empty() {
884 let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
885 let _ = std::fs::write(format!("{dir}/{side}-{seq:05}.txt"), buf.as_bytes());
886 }
887 buf.clear();
888 *n = 0;
889 });
890 }
891}