forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

msac.rs772 lines, 30.0 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 let nsyms = cdf.len() - 1;
148 assert!(symbol < nsyms, "symbol {symbol} is outside the alphabet");
149
150 // The decoder walks the alphabet computing the same two boundaries and
151 // stops at the first symbol whose lower boundary the coded value has
152 // fallen below, so the encoder only has to narrow to that symbol's
153 // slice of the interval.
154 let r = self.rng;
155 let fh = u32::from(CDF_TOP - cdf[symbol]);
156 let v = (((r >> 8) * (fh >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
157 + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
158 let mut low = self.low;
159 let rng = if symbol > 0 {
160 let fl = u32::from(CDF_TOP - cdf[symbol - 1]);
161 let u = (((r >> 8) * (fl >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
162 + EC_MIN_PROB * (nsyms - symbol) as u32;
163 low += u64::from(r - u);
164 u - v
165 } else {
166 // Symbol 0 owns the top of the interval, so only its width moves.
167 r - v
168 };
169 // What this symbol really cost is how far it narrowed the interval,
170 // which is not quite its nominal probability: the coder works the
171 // range through an eight-bit multiply and hands every symbol above
172 // this one a floor of `EC_MIN_PROB`. Pricing the narrowing rather than
173 // the table entry is what makes the account match the bytes; the
174 // narrowing itself is read off `rng` and `shifts` by [`Self::bits`].
175 if self.pricing {
176 let d = 16 - (32 - rng.leading_zeros());
177 self.rng = rng << d;
178 self.shifts += d;
179 } else {
180 self.normalize(low, rng);
181 }
182 }
183
184 /// Writes `bits` raw bits of `value`, most significant first — the `L(n)`
185 /// descriptor of spec 4.10.4, which is `bits` equiprobable symbols.
186 ///
187 /// # Panics
188 /// Panics if `bits` exceeds 32.
189 pub fn literal(&mut self, value: u32, bits: u32) {
190 assert!(bits <= 32, "a literal is at most 32 bits");
191 for i in (0..bits).rev() {
192 let bit = (value >> i) & 1;
193 self.symbol_fixed(bit as usize, &EQUIPROBABLE);
194 }
195 }
196
197 /// Flushes the coder and returns the payload bytes.
198 ///
199 /// The flush writes the shortest value inside the final interval that stays
200 /// inside it however the decoder pads the string, which is what lets a tile
201 /// payload end on a byte boundary with no terminator.
202 pub fn finish(mut self) -> Vec<u8> {
203 assert!(!self.pricing, "a pricer holds no bytes to flush");
204 // Round the interval's low end up to a value with 14 low zero bits,
205 // then set bit 14: the result is inside the interval (the interval is
206 // at least 2^15 wide before normalisation) and its tail bits are all
207 // zero, so they need not be written at all.
208 let m: u64 = 0x3fff;
209 let mut e = ((self.low + m) & !m) | (m + 1);
210 let mut c = self.cnt;
211 let mut s = 10 + c;
212 while s > 0 {
213 self.precarry.push((e >> (c + 16)) as u16);
214 e &= (1u64 << (c + 16)) - 1;
215 s -= 8;
216 c -= 8;
217 }
218
219 // Each flushed entry may have overflowed a byte; the overflow is a
220 // carry into the byte written before it.
221 let mut out = vec![0u8; self.precarry.len()];
222 let mut carry = 0u32;
223 for (byte, &pre) in out.iter_mut().zip(self.precarry.iter()).rev() {
224 let v = u32::from(pre) + carry;
225 *byte = v as u8;
226 carry = v >> 8;
227 }
228 out
229 }
230
231 /// Renormalises the interval back into `[2^15, 2^16)`, flushing whole bytes
232 /// of `low` once they can no longer change.
233 fn normalize(&mut self, low: u64, rng: u32) {
234 debug_assert!(rng > 0 && rng <= 0xffff);
235 let d = 16 - (32 - rng.leading_zeros()) as i32;
236 let mut c = self.cnt;
237 let mut s = c + d;
238 let mut low = low;
239 if s >= 0 {
240 // At least one byte at the top of `low` is settled: a later carry
241 // can still reach it, which is why it is kept in the precarry
242 // buffer as a `u16` rather than truncated to a byte here.
243 c += 16;
244 let mut m = (1u64 << c) - 1;
245 if s >= 8 {
246 self.precarry.push((low >> c) as u16);
247 low &= m;
248 c -= 8;
249 m >>= 8;
250 }
251 self.precarry.push((low >> c) as u16);
252 s = c + d - 24;
253 low &= m;
254 }
255 self.low = low << d;
256 self.rng = rng << d;
257 self.cnt = s;
258 self.shifts += d as u32;
259 }
260}
261
262/// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent
263/// fraction of the way towards the extreme the observed symbol implies, and the
264/// counter in the last entry slows the rate down for the first 32 symbols.
265#[inline]
266fn update_cdf(cdf: &mut [u16], symbol: usize) {
267 let nsyms = cdf.len() - 1;
268 let count = cdf[nsyms];
269 let rate = 3 + (nsyms >> 1).min(2) + (count >> 4) as usize;
270 for (i, p) in cdf[..nsyms - 1].iter_mut().enumerate() {
271 if i < symbol {
272 *p -= *p >> rate;
273 } else {
274 *p += (CDF_TOP - *p) >> rate;
275 }
276 }
277 cdf[nsyms] = count + 1 - (count >> 5);
278}
279
280/// The decoding process of spec 8.2, the exact inverse of [`SymbolEncoder`]:
281/// reads the symbols a [`SymbolEncoder`] wrote, in the order it wrote them,
282/// adapting every CDF identically (spec 8.3.2) so the two stay in step. This
283/// is the reader half of the arithmetic coder a real AV1 decoder's tile
284/// reader is built on top of.
285#[derive(Debug)]
286pub struct SymbolDecoder<'a> {
287 data: &'a [u8],
288 /// Next bit to read, as a bit offset into `data`.
289 bit: usize,
290 /// The bits from `bit` onward, left-aligned at the MSB, zero past the end
291 /// of `data`; only the top `win_bits` are valid. The renormalisation of
292 /// every symbol read one to fifteen bits, and assembling them out of
293 /// `data` per read was five byte loads and two variable shifts each; the
294 /// window pays that once per eight bytes instead.
295 win: u64,
296 win_bits: u32,
297 /// Next byte of `data` to shift into `win`.
298 pos: usize,
299 value: u32,
300 range: u32,
301 /// Bits left before the decoder starts padding with zeros (spec
302 /// `SymbolMaxBits`), which goes negative at the end of the string.
303 max_bits: i32,
304}
305
306impl<'a> SymbolDecoder<'a> {
307 /// `init_symbol` (spec 8.2.2).
308 #[must_use]
309 pub fn new(data: &'a [u8]) -> SymbolDecoder<'a> {
310 let mut d = SymbolDecoder {
311 data,
312 bit: 0,
313 win: 0,
314 win_bits: 0,
315 pos: 0,
316 value: 0,
317 range: 1 << 15,
318 max_bits: 8 * data.len() as i32 - 15,
319 };
320 let num_bits = usize::min(data.len() * 8, 15) as u32;
321 let buf = d.f(num_bits);
322 d.value = ((1 << 15) - 1) ^ (buf << (15 - num_bits));
323 d
324 }
325
326 /// `f(n)`: the next `n` bits, most significant first, zero past the end.
327 #[inline]
328 fn f(&mut self, n: u32) -> u32 {
329 debug_assert!(n <= 32, "f(n) reads at most 32 bits");
330 if n == 0 {
331 return 0;
332 }
333 if self.win_bits < n {
334 self.refill();
335 }
336 let v = (self.win >> (64 - n)) as u32;
337 self.win <<= n;
338 self.win_bits -= n;
339 self.bit += n as usize;
340 v
341 }
342
343 /// Tops the window back up to at least 57 bits, reading bytes past the end
344 /// of `data` as zero exactly as the per-read `unwrap_or(0)` did.
345 fn refill(&mut self) {
346 while self.win_bits <= 56 {
347 let byte = self.data.get(self.pos).copied().unwrap_or(0);
348 self.pos += 1;
349 self.win |= u64::from(byte) << (56 - self.win_bits);
350 self.win_bits += 8;
351 }
352 }
353
354 /// Repositions the window at an arbitrary bit offset (the `f(n)` test's
355 /// only way in now that `bit` alone no longer names the read position).
356 #[cfg(test)]
357 fn seek_bits(&mut self, bit: usize) {
358 self.bit = bit;
359 self.pos = bit >> 3;
360 self.win = 0;
361 self.win_bits = 0;
362 let skip = (bit & 7) as u32;
363 if skip > 0 {
364 self.refill();
365 self.win <<= skip;
366 self.win_bits -= skip;
367 }
368 }
369
370 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
371 #[inline]
372 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {
373 let s = self.symbol_fixed(cdf);
374 update_cdf(cdf, s);
375 s
376 }
377
378 /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec
379 /// uses for the literal and equiprobable reads, mirroring
380 /// [`SymbolEncoder::symbol_fixed`].
381 #[inline]
382 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
383 let nsyms = cdf.len() - 1;
384 // Two-symbol alphabets are most of the stream (every flag, every bit of
385 // a literal), and their walk has exactly one boundary: computing it
386 // straight skips the loop and its bounds work.
387 if nsyms == 2 {
388 let f = u32::from(CDF_TOP - cdf[0]);
389 let cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
390 + EC_MIN_PROB;
391 return self.bool_cur(cur);
392 }
393 // Loop-invariant: the coder's range does not move until the symbol is
394 // chosen, so its top byte is computed once rather than per candidate.
395 let base = self.range >> 8;
396 let mut prev = self.range;
397 // The floor every symbol above the candidate is owed, counted down
398 // instead of multiplied out per candidate.
399 let mut minp = EC_MIN_PROB * (nsyms - 1) as u32;
400 // The last boundary is always `CDF_TOP`, whose `cur` is 0, so the walk
401 // always stops inside the alphabet: the last candidate needs no test
402 // and its arithmetic is the fall-through below.
403 let mut symbol = nsyms - 1;
404 let mut cur = 0;
405 for (i, &c) in cdf[..nsyms - 1].iter().enumerate() {
406 let f = u32::from(CDF_TOP - c);
407 let c = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + minp;
408 if self.value >= c {
409 symbol = i;
410 cur = c;
411 break;
412 }
413 prev = c;
414 minp -= EC_MIN_PROB;
415 }
416 self.renorm(prev - cur, self.value - cur);
417 symbol
418 }
419
420 /// Finishes a two-symbol read whose single boundary is `cur`: symbol 0 owns
421 /// `[cur, range)` and symbol 1 owns `[0, cur)`.
422 #[inline(always)]
423 fn bool_cur(&mut self, cur: u32) -> usize {
424 let value = self.value;
425 let (symbol, rng, val) = if value >= cur {
426 (0, self.range - cur, value - cur)
427 } else {
428 (1, cur, value)
429 };
430 self.renorm(rng, val);
431 symbol
432 }
433
434 /// Renormalises `rng` back into `[2^15, 2^16)` and shifts the same number of
435 /// bits into `val`, the tail every symbol read shares — the same shift the
436 /// encoder applied when it narrowed to this symbol.
437 #[inline(always)]
438 fn renorm(&mut self, rng: u32, val: u32) {
439 let bits = 16 - (32 - rng.leading_zeros());
440 self.range = rng << bits;
441 let num_bits = u32::min(bits, self.max_bits.max(0) as u32);
442 let new_data = self.f(num_bits);
443 let padded = new_data << (bits - num_bits);
444 self.value = padded ^ (((val + 1) << bits) - 1);
445 self.max_bits -= bits as i32;
446 }
447
448 /// Debug-only: the current bit offset into `data`, for cross-checking
449 /// against a reference decoder's own `aom_reader_tell()` while chasing a
450 /// desync (see `EC_AV1_TRACE`). Not spec state, just `self.bit`.
451 pub(crate) fn debug_bitpos(&self) -> usize {
452 self.bit
453 }
454
455 /// Debug-only: the raw coder state (`range`, `value`) entering the next
456 /// read, for a byte-for-byte diff against a reference decoder's own
457 /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see
458 /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields.
459 pub(crate) fn debug_state(&self) -> (u32, u32) {
460 (self.range, self.value)
461 }
462
463 /// Reads `bits` raw bits, most significant first — the `L(n)` descriptor
464 /// of spec 4.10.4.
465 ///
466 /// lane-coefread: `#[inline]`, because without it this was a real CALL per
467 /// raw bit across a codegen-unit boundary (the crate builds without LTO) --
468 /// the coefficient sign pass and the Golomb tail read one bit at a time.
469 #[inline]
470 pub fn literal(&mut self, bits: u32) -> u32 {
471 let mut v = 0;
472 for _ in 0..bits {
473 // `EQUIPROBABLE`'s single boundary: `f >> EC_PROB_SHIFT` is 256, so
474 // the range multiply is a shift.
475 let cur = ((self.range >> 8) << 7) + EC_MIN_PROB;
476 v = (v << 1) | self.bool_cur(cur) as u32;
477 }
478 v
479 }
480}
481
482#[cfg(test)]
483pub(crate) mod tests {
484 use super::*;
485
486 /// `f(n)` now assembles five bytes and shifts instead of walking bits.
487 /// This pins it against the per-bit form it replaced, at every start
488 /// offset, every width up to 32, and past the end of the buffer (where
489 /// both forms must read zeros).
490 #[test]
491 fn bulk_bit_reads_match_the_per_bit_form() {
492 let data: Vec<u8> = (0..40u32).map(|i| (i * 37 + 11) as u8).collect();
493 let per_bit = |start: usize, n: u32| -> u32 {
494 let mut bit = start;
495 let mut v = 0u32;
496 for _ in 0..n {
497 let byte = data.get(bit >> 3).copied().unwrap_or(0);
498 v = (v << 1) | u32::from((byte >> (7 - (bit & 7))) & 1);
499 bit += 1;
500 }
501 v
502 };
503 for start in 0..(data.len() * 8 + 16) {
504 for n in 0..=32u32 {
505 let mut d = SymbolDecoder::new(&data);
506 d.seek_bits(start);
507 let got = d.f(n);
508 assert_eq!(got, per_bit(start, n), "start {start} width {n}");
509 assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");
510 }
511 }
512 }
513
514 // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now
515 // lives in the outer module (non-test code decodes with it too), so this
516 // re-export is what keeps those call sites resolving unmodified.
517 pub(crate) use super::SymbolDecoder;
518
519 /// A reproducible symbol stream: xorshift, so a failure names one seed.
520 fn rng(state: &mut u64) -> u64 {
521 *state ^= *state << 13;
522 *state ^= *state >> 7;
523 *state ^= *state << 17;
524 *state
525 }
526
527 fn flat_cdf(nsyms: usize) -> Vec<u16> {
528 let mut cdf = vec![0u16; nsyms + 1];
529 for (i, p) in cdf[..nsyms].iter_mut().enumerate() {
530 *p = (((i + 1) * (1 << 15)) / nsyms) as u16;
531 }
532 cdf[nsyms] = 0;
533 cdf
534 }
535
536 #[test]
537 fn adaptive_symbols_roundtrip() {
538 for nsyms in 2..=16usize {
539 let mut state = 0x2545_f491_4f6c_dd1d ^ nsyms as u64;
540 let symbols: Vec<usize> = (0..4000)
541 .map(|_| (rng(&mut state) % nsyms as u64) as usize)
542 .collect();
543
544 let mut enc = SymbolEncoder::new();
545 let mut cdf = flat_cdf(nsyms);
546 for &s in &symbols {
547 enc.symbol(s, &mut cdf);
548 }
549 let payload = enc.finish();
550
551 let mut dec = SymbolDecoder::new(&payload);
552 let mut cdf = flat_cdf(nsyms);
553 for (i, &want) in symbols.iter().enumerate() {
554 let got = dec.symbol(&mut cdf);
555 assert_eq!(got, want, "alphabet {nsyms}, symbol {i}");
556 }
557 }
558 }
559
560 #[test]
561 fn skewed_symbols_cost_less_than_a_bit() {
562 // A 1-in-256 symbol against an adapting CDF must cost far under one bit
563 // each: this is the property a range coder exists for, and it fails
564 // loudly if the interval narrowing is wired backwards.
565 let mut state = 0x9e37_79b9_7f4a_7c15;
566 let symbols: Vec<usize> = (0..8000)
567 .map(|_| usize::from(rng(&mut state).is_multiple_of(256)))
568 .collect();
569 let mut enc = SymbolEncoder::new();
570 let mut cdf = flat_cdf(2);
571 for &s in &symbols {
572 enc.symbol(s, &mut cdf);
573 }
574 let payload = enc.finish();
575 assert!(
576 payload.len() < 8000 / 8 / 4,
577 "8000 skewed symbols took {} bytes",
578 payload.len()
579 );
580
581 let mut dec = SymbolDecoder::new(&payload);
582 let mut cdf = flat_cdf(2);
583 for (i, &want) in symbols.iter().enumerate() {
584 assert_eq!(dec.symbol(&mut cdf), want, "symbol {i}");
585 }
586 }
587
588 #[test]
589 fn literals_roundtrip() {
590 let mut state = 0x0123_4567_89ab_cdef;
591 let values: Vec<(u32, u32)> = (0..2000)
592 .map(|_| {
593 let bits = 1 + (rng(&mut state) % 16) as u32;
594 let value = (rng(&mut state) as u32) & ((1u32 << bits) - 1);
595 (value, bits)
596 })
597 .collect();
598
599 let mut enc = SymbolEncoder::new();
600 for &(v, bits) in &values {
601 enc.literal(v, bits);
602 }
603 let payload = enc.finish();
604 // Equiprobable bits cannot be compressed, so the payload is one bit per
605 // written bit plus the flush.
606 let total: u32 = values.iter().map(|&(_, b)| b).sum();
607 assert!(payload.len() as u32 <= total / 8 + 4);
608
609 let mut dec = SymbolDecoder::new(&payload);
610 for (i, &(want, bits)) in values.iter().enumerate() {
611 assert_eq!(dec.literal(bits), want, "literal {i}");
612 }
613 }
614
615 #[test]
616 fn mixed_symbols_and_literals_roundtrip() {
617 let mut state = 0xdead_beef_cafe_f00d;
618 let mut enc = SymbolEncoder::new();
619 let mut cdf3 = flat_cdf(3);
620 let mut cdf8 = flat_cdf(8);
621 let mut written = Vec::new();
622 for _ in 0..3000 {
623 match rng(&mut state) % 3 {
624 0 => {
625 let s = (rng(&mut state) % 3) as usize;
626 enc.symbol(s, &mut cdf3);
627 written.push((0u8, s as u32));
628 }
629 1 => {
630 let s = (rng(&mut state) % 8) as usize;
631 enc.symbol(s, &mut cdf8);
632 written.push((1, s as u32));
633 }
634 _ => {
635 let v = (rng(&mut state) % 256) as u32;
636 enc.literal(v, 8);
637 written.push((2, v));
638 }
639 }
640 }
641 let payload = enc.finish();
642
643 let mut dec = SymbolDecoder::new(&payload);
644 let mut cdf3 = flat_cdf(3);
645 let mut cdf8 = flat_cdf(8);
646 for (i, &(kind, want)) in written.iter().enumerate() {
647 let got = match kind {
648 0 => dec.symbol(&mut cdf3) as u32,
649 1 => dec.symbol(&mut cdf8) as u32,
650 _ => dec.literal(8),
651 };
652 assert_eq!(got, want, "item {i} of kind {kind}");
653 }
654 }
655
656 /// The bit account is what a search prices decisions with, so it has to
657 /// agree with what the coder actually spends: over a long enough string the
658 /// two are within the coder's own rounding, a fraction of a percent.
659 #[test]
660 fn the_bit_account_matches_the_bytes_written() {
661 let mut enc = SymbolEncoder::new();
662 let mut state: u32 = 0x1234_5678;
663 let mut next = || {
664 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
665 state
666 };
667 // A skewed CDF, so that the account has something to be wrong about:
668 // an equiprobable string costs one bit a symbol however it is priced.
669 let skewed: [u16; 3] = [29000, 1 << 15, 0];
670 for _ in 0..20_000 {
671 let symbol = usize::from(next() % 100 < 12);
672 enc.symbol_fixed(symbol, &skewed);
673 }
674 let priced = enc.bits();
675 let spent = (enc.finish().len() * 8) as f64;
676 assert!(
677 (priced - spent).abs() / spent < 0.01,
678 "priced {priced:.0} bits, spent {spent:.0}"
679 );
680 }
681
682 #[test]
683 fn empty_payload_is_short() {
684 assert!(SymbolEncoder::new().finish().len() <= 2);
685 }
686 /// The spec-literal 8.2.6 walk, as `symbol_fixed` read it before the
687 /// two-symbol shortcut and the last-candidate fall-through: every
688 /// candidate tested, `EC_MIN_PROB` multiplied out, one shared tail.
689 fn ref_symbol_fixed(d: &mut SymbolDecoder<'_>, cdf: &[u16]) -> usize {
690 let nsyms = cdf.len() - 1;
691 let mut cur = d.range;
692 let mut prev = cur;
693 let mut symbol = nsyms - 1;
694 let base = d.range >> 8;
695 for (i, &c) in cdf[..nsyms].iter().enumerate() {
696 prev = cur;
697 let f = u32::from(CDF_TOP - c);
698 cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
699 + EC_MIN_PROB * (nsyms - 1 - i) as u32;
700 if d.value >= cur {
701 symbol = i;
702 break;
703 }
704 }
705 d.range = prev - cur;
706 d.value -= cur;
707 let bits = 16 - (32 - d.range.leading_zeros());
708 d.range <<= bits;
709 let num_bits = u32::min(bits, d.max_bits.max(0) as u32);
710 let new_data = d.f(num_bits);
711 let padded = new_data << (bits - num_bits);
712 d.value = padded ^ (((d.value + 1) << bits) - 1);
713 d.max_bits -= bits as i32;
714 symbol
715 }
716
717 /// The reader's fast paths must be the spec walk, symbol for symbol and
718 /// register for register: a long mixed stream is decoded twice in lockstep
719 /// and both the symbol and the coder state `(range, value)` are compared
720 /// after every read, so a divergence that has not yet changed a symbol
721 /// still fails here.
722 #[test]
723 fn fast_paths_match_the_spec_literal_walk() {
724 let mut state = 0x0123_4567_89ab_cdef;
725 let mut enc = SymbolEncoder::new();
726 let mut cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect();
727 let mut written: Vec<(usize, u32)> = Vec::new();
728 for _ in 0..20_000 {
729 let pick = (rng(&mut state) % 16) as usize;
730 if pick == 15 {
731 let width = 1 + (rng(&mut state) % 16) as u32;
732 let v = (rng(&mut state) as u32) & ((1u32 << width) - 1);
733 enc.literal(v, width);
734 written.push((usize::MAX, width));
735 } else {
736 let nsyms = pick + 2;
737 let sym = (rng(&mut state) % nsyms as u64) as usize;
738 enc.symbol(sym, &mut cdfs[pick]);
739 written.push((pick, sym as u32));
740 }
741 }
742 let payload = enc.finish();
743
744 let mut fast = SymbolDecoder::new(&payload);
745 let mut slow = SymbolDecoder::new(&payload);
746 let mut fast_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect();
747 let mut slow_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect();
748 for (i, &(pick, arg)) in written.iter().enumerate() {
749 let (a, b) = if pick == usize::MAX {
750 let a = fast.literal(arg);
751 let mut b = 0u32;
752 for _ in 0..arg {
753 b = (b << 1) | ref_symbol_fixed(&mut slow, &EQUIPROBABLE) as u32;
754 }
755 (a, b)
756 } else {
757 let a = fast.symbol(&mut fast_cdfs[pick]) as u32;
758 let b = ref_symbol_fixed(&mut slow, &slow_cdfs[pick]);
759 update_cdf(&mut slow_cdfs[pick], b);
760 (a, b as u32)
761 };
762 assert_eq!(a, b, "item {i} (pick {pick})");
763 assert_eq!(a, if pick == usize::MAX { a } else { arg }, "item {i} vs written");
764 assert_eq!(
765 fast.debug_state(),
766 slow.debug_state(),
767 "coder state after item {i} (pick {pick})"
768 );
769 assert_eq!(fast_cdfs[pick.min(14)], slow_cdfs[pick.min(14)], "cdf after item {i}");
770 }
771 }
772}