edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! AV1 multi-symbol arithmetic coder (spec section 8.2) — the writer side of |
| 2 | //! the decoder the specification defines, plus the probability adaptation of |
| 3 | //! spec section 8.3. |
| 4 | //! |
| 5 | //! AV1 specifies only the decoder: every tile payload is a range-coded string |
| 6 | //! whose meaning is whatever the decoding process in section 8.2 recovers from |
| 7 | //! it. [`SymbolEncoder`] is the inverse of that process — it narrows the same |
| 8 | //! `[low, low + range)` interval the decoder tracks and flushes the shortest |
| 9 | //! prefix that pins the interval down, so the decoder's `decode_symbol` returns |
| 10 | //! the symbols in the order they were written whatever bytes follow. |
| 11 | //! |
| 12 | //! CDFs are held in the specification's own orientation: for an `n`-symbol |
| 13 | //! alphabet the slice has `n + 1` entries, `cdf[i]` is the cumulative |
| 14 | //! probability of symbols `0..=i` scaled to `1 << 15` (so `cdf[n - 1]` is |
| 15 | //! always `1 << 15`), and `cdf[n]` is the adaptation counter of section 8.3.2. |
| 16 | //! Decoders that store the complement (`(1 << 15) - cdf[i]`) compute the same |
| 17 | //! intervals; the arithmetic below takes the complement where the spec does. |
| 18 | |
| 19 | /// Probability precision dropped before the range multiply (spec `EC_PROB_SHIFT`). |
| 20 | const EC_PROB_SHIFT: u32 = 6; |
| 21 | |
| 22 | /// Minimum interval width reserved for every symbol (spec `EC_MIN_PROB`). |
| 23 | const EC_MIN_PROB: u32 = 4; |
| 24 | /// Total probability mass of a CDF (spec `1 << 15`). |
| 25 | const 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. |
| 29 | const 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)] |
| 38 | pub 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 | |
| 68 | impl Default for SymbolEncoder { |
| 69 | fn default() -> SymbolEncoder { |
| 70 | SymbolEncoder::new() |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | impl 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] |
| 270 | fn 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)] |
| 290 | pub 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 | /// Whether [`SymbolDecoder::symbol`] adapts the CDF it reads (spec 8.3.2). |
| 309 | /// `false` for a frame whose header sets `disable_cdf_update` -- libaom's |
| 310 | /// tile entry (`decodeframe.c:2909`, `allow_update_cdf = allow_update_cdf |
| 311 | /// && !cm->features.disable_cdf_update`) skips the adaptation there, so |
| 312 | /// reading on would drift this decoder's tables away from the encoder's |
| 313 | /// and desync mid-frame. Per-READER, not global: frames of one stream can |
| 314 | /// decode on different worker threads. |
| 315 | adapt: bool, |
| 316 | } |
| 317 | |
| 318 | impl Drop for SymbolDecoder<'_> { |
| 319 | fn drop(&mut self) { |
| 320 | symtrace::flush('r'); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | thread_local! { |
| 325 | /// The `(mi_row, mi_col)` the enclosing block reader is inside, for the |
| 326 | /// `EC_SYMR` trace. A symbol read carries no mi of its own, so without it |
| 327 | /// the per-read stream can only be located by correlating it against a |
| 328 | /// SEPARATE trace -- and that correlation is what mis-attributed reads in |
| 329 | /// rounds 22 and 23. Set by the mode readers at entry; `(-1,-1)` outside. |
| 330 | pub(crate) static SYMR_MI: std::cell::Cell<(i64, i64)> = |
| 331 | const { std::cell::Cell::new((-1, -1)) }; |
| 332 | /// A short tag for the READER PHASE ("intra", "inter", "mv", ...), printed |
| 333 | /// on every `EC_SYMR` line. The coefficient rungs stop well before some |
| 334 | /// divergences, so the per-read stream is the only instrument that covers |
| 335 | /// the inter path; without a phase its reads are unattributable. |
| 336 | pub(crate) static SYMR_PHASE: std::cell::Cell<&'static str> = |
| 337 | const { std::cell::Cell::new("") }; |
| 338 | /// The CDF TABLE NAME for the NEXT read, mirroring the oracle's |
| 339 | /// `ec_symr_cdf_tag`. `cdf0` alone cannot identify a table -- two rows |
| 340 | /// can share a first entry -- so this is what turns "two 2-symbol reads" |
| 341 | /// into a named pair. |
| 342 | /// |
| 343 | /// ONE-SHOT, consumed by the next `symbol()`. Round 30: it used to be |
| 344 | /// sticky, so every read after a tagged one carried that tag -- which is |
| 345 | /// how an 8-symbol read came to be labelled `interintra`, a 2-symbol |
| 346 | /// table. An EMPTY `cdf=` therefore means "no table set for this read", |
| 347 | /// never "the previous read's table". |
| 348 | pub(crate) static SYMR_CDF: std::cell::Cell<&'static str> = |
| 349 | const { std::cell::Cell::new("") }; |
| 350 | } |
| 351 | |
| 352 | impl<'a> SymbolDecoder<'a> { |
| 353 | /// `init_symbol` (spec 8.2.2). |
| 354 | #[must_use] |
| 355 | pub fn new(data: &'a [u8]) -> SymbolDecoder<'a> { |
| 356 | let mut d = SymbolDecoder { |
| 357 | data, |
| 358 | bit: 0, |
| 359 | win: 0, |
| 360 | win_bits: 0, |
| 361 | pos: 0, |
| 362 | value: 0, |
| 363 | range: 1 << 15, |
| 364 | max_bits: 8 * data.len() as i32 - 15, |
| 365 | adapt: true, |
| 366 | }; |
| 367 | let num_bits = usize::min(data.len() * 8, 15) as u32; |
| 368 | let buf = d.f(num_bits); |
| 369 | d.value = ((1 << 15) - 1) ^ (buf << (15 - num_bits)); |
| 370 | d |
| 371 | } |
| 372 | |
| 373 | /// Spec 5.9.2's `disable_cdf_update`, the reader side: `false` (the |
| 374 | /// default) adapts every CDF [`symbol`](Self::symbol) reads; `true` |
| 375 | /// leaves each table exactly as it was read, matching libaom's |
| 376 | /// `allow_update_cdf` (decodeframe.c:2909). Set once per tile reader by |
| 377 | /// the frame's own header bit. |
| 378 | pub(crate) fn set_cdf_update(&mut self, update: bool) { |
| 379 | self.adapt = update; |
| 380 | } |
| 381 | |
| 382 | /// `f(n)`: the next `n` bits, most significant first, zero past the end. |
| 383 | #[inline] |
| 384 | fn f(&mut self, n: u32) -> u32 { |
| 385 | debug_assert!(n <= 32, "f(n) reads at most 32 bits"); |
| 386 | if n == 0 { |
| 387 | return 0; |
| 388 | } |
| 389 | if self.win_bits < n { |
| 390 | self.refill(); |
| 391 | } |
| 392 | let v = (self.win >> (64 - n)) as u32; |
| 393 | self.win <<= n; |
| 394 | self.win_bits -= n; |
| 395 | self.bit += n as usize; |
| 396 | v |
| 397 | } |
| 398 | |
| 399 | /// Tops the window back up to at least 57 bits, reading bytes past the end |
| 400 | /// of `data` as zero exactly as the per-read `unwrap_or(0)` did. |
| 401 | fn refill(&mut self) { |
| 402 | while self.win_bits <= 56 { |
| 403 | let byte = self.data.get(self.pos).copied().unwrap_or(0); |
| 404 | self.pos += 1; |
| 405 | self.win |= u64::from(byte) << (56 - self.win_bits); |
| 406 | self.win_bits += 8; |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | /// Repositions the window at an arbitrary bit offset (the `f(n)` test's |
| 411 | /// only way in now that `bit` alone no longer names the read position). |
| 412 | #[cfg(test)] |
| 413 | fn seek_bits(&mut self, bit: usize) { |
| 414 | self.bit = bit; |
| 415 | self.pos = bit >> 3; |
| 416 | self.win = 0; |
| 417 | self.win_bits = 0; |
| 418 | let skip = (bit & 7) as u32; |
| 419 | if skip > 0 { |
| 420 | self.refill(); |
| 421 | self.win <<= skip; |
| 422 | self.win_bits -= skip; |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. |
| 427 | /// |
| 428 | pub(crate) fn set_symr_cdf(t: &'static str) { |
| 429 | SYMR_CDF.with(|c| c.set(t)); |
| 430 | } |
| 431 | |
| 432 | pub(crate) fn set_symr_phase(p: &'static str) { |
| 433 | SYMR_PHASE.with(|c| c.set(p)); |
| 434 | } |
| 435 | |
| 436 | pub(crate) fn set_symr_mi(mi_r: i64, mi_c: i64) { |
| 437 | SYMR_MI.with(|c| c.set((mi_r, mi_c))); |
| 438 | } |
| 439 | |
| 440 | /// The `(mi_row, mi_col)` the enclosing block reader last stamped, READ |
| 441 | /// back. `set_symr_mi` only writes; a per-unit interval rung needs to print |
| 442 | /// the mi, and a coefficient read carries none of its own -- without this a |
| 443 | /// ladder cannot be attributed to the block that read it. A copy, not a |
| 444 | /// borrow: the rungs call it from a `&SymbolDecoder`. |
| 445 | pub(crate) fn symr_mi() -> (i64, i64) { |
| 446 | SYMR_MI.with(std::cell::Cell::get) |
| 447 | } |
| 448 | |
| 449 | /// `EC_SYMR=1` dumps every symbol read's PRE state (before the read and |
| 450 | /// before the adaptation) together with the symbol and the post-read |
| 451 | /// range, so a divergence against a reference decoder can be bisected |
| 452 | /// read by read. `cdf0` is the PRE-adapt row[0] -- the reference's own |
| 453 | /// print of the same row is POST-adapt, so compare `32768 - ours_cdf0` |
| 454 | /// against its `cdf0`, never the raw numbers. |
| 455 | #[inline] |
| 456 | pub fn symbol(&mut self, cdf: &mut [u16]) -> usize { |
| 457 | // lane-av1422warp r33 (reviewer P2): this ran on EVERY symbol read of |
| 458 | // EVERY stream, production formats included, and `std::env::var_os` |
| 459 | // is a real environment scan each time (~30ns x every symbol). |
| 460 | // `env_flag!` keeps one `LazyLock<bool>` per call SITE, so the check |
| 461 | // compiles to an atomic load. The trace is byte-identical: same |
| 462 | // condition, same format, same fields. |
| 463 | let symr = crate::envflags::env_flag!("EC_SYMR"); |
| 464 | let (pre_value, pre_range, pre_bit) = (self.value, self.range, self.bit); |
| 465 | let pre_cdf0 = cdf.first().copied().unwrap_or(0); |
| 466 | // lane-census: the syntax census charges this symbol's bits to the |
| 467 | // TABLE it read, so every coding tool is accounted without a |
| 468 | // per-call-site label. Off (`EC_AV1_BITCENSUS` unset) this is one |
| 469 | // relaxed load. |
| 470 | let t0 = if crate::census::armed() { |
| 471 | self.tell_bits() |
| 472 | } else { |
| 473 | 0.0 |
| 474 | }; |
| 475 | let s = self.symbol_fixed(cdf); |
| 476 | // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets |
| 477 | // it codes every symbol against the tables it started with, so this |
| 478 | // reader must leave them untouched too (libaom: `allow_update_cdf = |
| 479 | // allow_update_cdf && !cm->features.disable_cdf_update`, |
| 480 | // decodeframe.c:2909). The flag is per-reader (see `Self::adapt`). |
| 481 | if self.adapt { |
| 482 | update_cdf(cdf, s); |
| 483 | } |
| 484 | if crate::census::armed() { |
| 485 | crate::census::charge(cdf.as_ptr() as usize, self.tell_bits() - t0); |
| 486 | } |
| 487 | if symr { |
| 488 | eprintln!( |
| 489 | "EC_SYMR ph={} cdf={} mi=({},{}) pre=({},{},{}) cdf0={} n={} s={} post_rng={}", |
| 490 | SYMR_PHASE.with(std::cell::Cell::get), |
| 491 | SYMR_CDF.with(|c| c.replace("")), |
| 492 | SYMR_MI.with(std::cell::Cell::get).0, |
| 493 | SYMR_MI.with(std::cell::Cell::get).1, |
| 494 | pre_value, |
| 495 | pre_range, |
| 496 | pre_bit, |
| 497 | pre_cdf0, |
| 498 | cdf.len() - 1, |
| 499 | s, |
| 500 | self.range |
| 501 | ); |
| 502 | } |
| 503 | s |
| 504 | } |
| 505 | |
| 506 | /// Bits consumed so far, fractionally -- the read position less the |
| 507 | /// information still held in the range (`log2(range)`, which starts at |
| 508 | /// 15). Differences between two of these are one read's cost; the |
| 509 | /// absolute value carries a constant offset (class `compare-range-not-tell`). |
| 510 | #[must_use] |
| 511 | pub fn tell_bits(&self) -> f64 { |
| 512 | self.bit as f64 - f64::from(self.range).log2() |
| 513 | } |
| 514 | |
| 515 | /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec |
| 516 | /// uses for the literal and equiprobable reads, mirroring |
| 517 | /// [`SymbolEncoder::symbol_fixed`]. |
| 518 | #[inline] |
| 519 | pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { |
| 520 | if symtrace::dir().is_some() { |
| 521 | let s = self.symbol_fixed_raw(cdf); |
| 522 | symtrace::push(s, cdf.len() - 1, cdf[0]); |
| 523 | return s; |
| 524 | } |
| 525 | self.symbol_fixed_raw(cdf) |
| 526 | } |
| 527 | |
| 528 | #[inline] |
| 529 | fn symbol_fixed_raw(&mut self, cdf: &[u16]) -> usize { |
| 530 | let nsyms = cdf.len() - 1; |
| 531 | if symtrace::ecdump_armed() { |
| 532 | symtrace::ecdump(0, self.value, self.range, self.bit as i64); |
| 533 | } |
| 534 | // Two-symbol alphabets are most of the stream (every flag, every bit of |
| 535 | // a literal), and their walk has exactly one boundary: computing it |
| 536 | // straight skips the loop and its bounds work. |
| 537 | if nsyms == 2 { |
| 538 | let f = u32::from(CDF_TOP - cdf[0]); |
| 539 | let cur = |
| 540 | (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + EC_MIN_PROB; |
| 541 | return self.bool_cur(cur); |
| 542 | } |
| 543 | // Loop-invariant: the coder's range does not move until the symbol is |
| 544 | // chosen, so its top byte is computed once rather than per candidate. |
| 545 | let base = self.range >> 8; |
| 546 | let mut prev = self.range; |
| 547 | // The floor every symbol above the candidate is owed, counted down |
| 548 | // instead of multiplied out per candidate. |
| 549 | let mut minp = EC_MIN_PROB * (nsyms - 1) as u32; |
| 550 | // The last boundary is always `CDF_TOP`, whose `cur` is 0, so the walk |
| 551 | // always stops inside the alphabet: the last candidate needs no test |
| 552 | // and its arithmetic is the fall-through below. |
| 553 | let mut symbol = nsyms - 1; |
| 554 | let mut cur = 0; |
| 555 | for (i, &c) in cdf[..nsyms - 1].iter().enumerate() { |
| 556 | let f = u32::from(CDF_TOP - c); |
| 557 | let c = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + minp; |
| 558 | if self.value >= c { |
| 559 | symbol = i; |
| 560 | cur = c; |
| 561 | break; |
| 562 | } |
| 563 | prev = c; |
| 564 | minp -= EC_MIN_PROB; |
| 565 | } |
| 566 | self.renorm(prev - cur, self.value - cur); |
| 567 | symbol |
| 568 | } |
| 569 | |
| 570 | /// Finishes a two-symbol read whose single boundary is `cur`: symbol 0 owns |
| 571 | /// `[cur, range)` and symbol 1 owns `[0, cur)`. |
| 572 | #[inline(always)] |
| 573 | fn bool_cur(&mut self, cur: u32) -> usize { |
| 574 | let value = self.value; |
| 575 | let (symbol, rng, val) = if value >= cur { |
| 576 | (0, self.range - cur, value - cur) |
| 577 | } else { |
| 578 | (1, cur, value) |
| 579 | }; |
| 580 | self.renorm(rng, val); |
| 581 | symbol |
| 582 | } |
| 583 | |
| 584 | /// Renormalises `rng` back into `[2^15, 2^16)` and shifts the same number of |
| 585 | /// bits into `val`, the tail every symbol read shares — the same shift the |
| 586 | /// encoder applied when it narrowed to this symbol. |
| 587 | #[inline(always)] |
| 588 | fn renorm(&mut self, rng: u32, val: u32) { |
| 589 | let bits = 16 - (32 - rng.leading_zeros()); |
| 590 | self.range = rng << bits; |
| 591 | let num_bits = u32::min(bits, self.max_bits.max(0) as u32); |
| 592 | let new_data = self.f(num_bits); |
| 593 | let padded = new_data << (bits - num_bits); |
| 594 | self.value = padded ^ (((val + 1) << bits) - 1); |
| 595 | self.max_bits -= bits as i32; |
| 596 | } |
| 597 | |
| 598 | /// Debug-only: the current bit offset into `data`, for cross-checking |
| 599 | /// against a reference decoder's own `aom_reader_tell()` while chasing a |
| 600 | /// desync (see `EC_AV1_TRACE`). Not spec state, just `self.bit`. |
| 601 | pub(crate) fn debug_bitpos(&self) -> usize { |
| 602 | self.bit |
| 603 | } |
| 604 | |
| 605 | /// Debug-only: the raw coder state (`range`, `value`) entering the next |
| 606 | /// read, for a byte-for-byte diff against a reference decoder's own |
| 607 | /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see |
| 608 | /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields. |
| 609 | pub(crate) fn debug_state(&self) -> (u32, u32) { |
| 610 | (self.range, self.value) |
| 611 | } |
| 612 | |
| 613 | /// Reads `bits` raw bits, most significant first — the `L(n)` descriptor |
| 614 | /// of spec 4.10.4. |
| 615 | /// |
| 616 | /// lane-coefread: `#[inline]`, because without it this was a real CALL per |
| 617 | /// raw bit across a codegen-unit boundary (the crate builds without LTO) -- |
| 618 | /// the coefficient sign pass and the Golomb tail read one bit at a time. |
| 619 | #[inline] |
| 620 | pub fn literal(&mut self, bits: u32) -> u32 { |
| 621 | if crate::census::armed() { |
| 622 | crate::census::charge_literal(bits); |
| 623 | } |
| 624 | let mut v = 0; |
| 625 | for _ in 0..bits { |
| 626 | // `EQUIPROBABLE`'s single boundary: `f >> EC_PROB_SHIFT` is 256, so |
| 627 | // the range multiply is a shift. |
| 628 | let cur = ((self.range >> 8) << 7) + EC_MIN_PROB; |
| 629 | let bit = self.bool_cur(cur); |
| 630 | if symtrace::dir().is_some() { |
| 631 | symtrace::push(bit, 2, EQUIPROBABLE[0]); |
| 632 | } |
| 633 | v = (v << 1) | bit as u32; |
| 634 | } |
| 635 | v |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | #[cfg(test)] |
| 640 | pub(crate) mod tests { |
| 641 | use super::*; |
| 642 | |
| 643 | /// `f(n)` now assembles five bytes and shifts instead of walking bits. |
| 644 | /// This pins it against the per-bit form it replaced, at every start |
| 645 | /// offset, every width up to 32, and past the end of the buffer (where |
| 646 | /// both forms must read zeros). |
| 647 | #[test] |
| 648 | fn bulk_bit_reads_match_the_per_bit_form() { |
| 649 | let data: Vec<u8> = (0..40u32).map(|i| (i * 37 + 11) as u8).collect(); |
| 650 | let per_bit = |start: usize, n: u32| -> u32 { |
| 651 | let mut v = 0u32; |
| 652 | for bit in (start..).take(n as usize) { |
| 653 | let byte = data.get(bit >> 3).copied().unwrap_or(0); |
| 654 | v = (v << 1) | u32::from((byte >> (7 - (bit & 7))) & 1); |
| 655 | } |
| 656 | v |
| 657 | }; |
| 658 | for start in 0..(data.len() * 8 + 16) { |
| 659 | for n in 0..=32u32 { |
| 660 | let mut d = SymbolDecoder::new(&data); |
| 661 | d.seek_bits(start); |
| 662 | let got = d.f(n); |
| 663 | assert_eq!(got, per_bit(start, n), "start {start} width {n}"); |
| 664 | assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance"); |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now |
| 670 | // lives in the outer module (non-test code decodes with it too), so this |
| 671 | // re-export is what keeps those call sites resolving unmodified. |
| 672 | pub(crate) use super::SymbolDecoder; |
| 673 | |
| 674 | /// A reproducible symbol stream: xorshift, so a failure names one seed. |
| 675 | fn rng(state: &mut u64) -> u64 { |
| 676 | *state ^= *state << 13; |
| 677 | *state ^= *state >> 7; |
| 678 | *state ^= *state << 17; |
| 679 | *state |
| 680 | } |
| 681 | |
| 682 | fn flat_cdf(nsyms: usize) -> Vec<u16> { |
| 683 | let mut cdf = vec![0u16; nsyms + 1]; |
| 684 | for (i, p) in cdf[..nsyms].iter_mut().enumerate() { |
| 685 | *p = (((i + 1) * (1 << 15)) / nsyms) as u16; |
| 686 | } |
| 687 | cdf[nsyms] = 0; |
| 688 | cdf |
| 689 | } |
| 690 | |
| 691 | #[test] |
| 692 | fn adaptive_symbols_roundtrip() { |
| 693 | for nsyms in 2..=16usize { |
| 694 | let mut state = 0x2545_f491_4f6c_dd1d ^ nsyms as u64; |
| 695 | let symbols: Vec<usize> = (0..4000) |
| 696 | .map(|_| (rng(&mut state) % nsyms as u64) as usize) |
| 697 | .collect(); |
| 698 | |
| 699 | let mut enc = SymbolEncoder::new(); |
| 700 | let mut cdf = flat_cdf(nsyms); |
| 701 | for &s in &symbols { |
| 702 | enc.symbol(s, &mut cdf); |
| 703 | } |
| 704 | let payload = enc.finish(); |
| 705 | |
| 706 | let mut dec = SymbolDecoder::new(&payload); |
| 707 | let mut cdf = flat_cdf(nsyms); |
| 708 | for (i, &want) in symbols.iter().enumerate() { |
| 709 | let got = dec.symbol(&mut cdf); |
| 710 | assert_eq!(got, want, "alphabet {nsyms}, symbol {i}"); |
| 711 | } |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | #[test] |
| 716 | fn skewed_symbols_cost_less_than_a_bit() { |
| 717 | // A 1-in-256 symbol against an adapting CDF must cost far under one bit |
| 718 | // each: this is the property a range coder exists for, and it fails |
| 719 | // loudly if the interval narrowing is wired backwards. |
| 720 | let mut state = 0x9e37_79b9_7f4a_7c15; |
| 721 | let symbols: Vec<usize> = (0..8000) |
| 722 | .map(|_| usize::from(rng(&mut state).is_multiple_of(256))) |
| 723 | .collect(); |
| 724 | let mut enc = SymbolEncoder::new(); |
| 725 | let mut cdf = flat_cdf(2); |
| 726 | for &s in &symbols { |
| 727 | enc.symbol(s, &mut cdf); |
| 728 | } |
| 729 | let payload = enc.finish(); |
| 730 | assert!( |
| 731 | payload.len() < 8000 / 8 / 4, |
| 732 | "8000 skewed symbols took {} bytes", |
| 733 | payload.len() |
| 734 | ); |
| 735 | |
| 736 | let mut dec = SymbolDecoder::new(&payload); |
| 737 | let mut cdf = flat_cdf(2); |
| 738 | for (i, &want) in symbols.iter().enumerate() { |
| 739 | assert_eq!(dec.symbol(&mut cdf), want, "symbol {i}"); |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | #[test] |
| 744 | fn literals_roundtrip() { |
| 745 | let mut state = 0x0123_4567_89ab_cdef; |
| 746 | let values: Vec<(u32, u32)> = (0..2000) |
| 747 | .map(|_| { |
| 748 | let bits = 1 + (rng(&mut state) % 16) as u32; |
| 749 | let value = (rng(&mut state) as u32) & ((1u32 << bits) - 1); |
| 750 | (value, bits) |
| 751 | }) |
| 752 | .collect(); |
| 753 | |
| 754 | let mut enc = SymbolEncoder::new(); |
| 755 | for &(v, bits) in &values { |
| 756 | enc.literal(v, bits); |
| 757 | } |
| 758 | let payload = enc.finish(); |
| 759 | // Equiprobable bits cannot be compressed, so the payload is one bit per |
| 760 | // written bit plus the flush. |
| 761 | let total: u32 = values.iter().map(|&(_, b)| b).sum(); |
| 762 | assert!(payload.len() as u32 <= total / 8 + 4); |
| 763 | |
| 764 | let mut dec = SymbolDecoder::new(&payload); |
| 765 | for (i, &(want, bits)) in values.iter().enumerate() { |
| 766 | assert_eq!(dec.literal(bits), want, "literal {i}"); |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | #[test] |
| 771 | fn mixed_symbols_and_literals_roundtrip() { |
| 772 | let mut state = 0xdead_beef_cafe_f00d; |
| 773 | let mut enc = SymbolEncoder::new(); |
| 774 | let mut cdf3 = flat_cdf(3); |
| 775 | let mut cdf8 = flat_cdf(8); |
| 776 | let mut written = Vec::new(); |
| 777 | for _ in 0..3000 { |
| 778 | match rng(&mut state) % 3 { |
| 779 | 0 => { |
| 780 | let s = (rng(&mut state) % 3) as usize; |
| 781 | enc.symbol(s, &mut cdf3); |
| 782 | written.push((0u8, s as u32)); |
| 783 | } |
| 784 | 1 => { |
| 785 | let s = (rng(&mut state) % 8) as usize; |
| 786 | enc.symbol(s, &mut cdf8); |
| 787 | written.push((1, s as u32)); |
| 788 | } |
| 789 | _ => { |
| 790 | let v = (rng(&mut state) % 256) as u32; |
| 791 | enc.literal(v, 8); |
| 792 | written.push((2, v)); |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | let payload = enc.finish(); |
| 797 | |
| 798 | let mut dec = SymbolDecoder::new(&payload); |
| 799 | let mut cdf3 = flat_cdf(3); |
| 800 | let mut cdf8 = flat_cdf(8); |
| 801 | for (i, &(kind, want)) in written.iter().enumerate() { |
| 802 | let got = match kind { |
| 803 | 0 => dec.symbol(&mut cdf3) as u32, |
| 804 | 1 => dec.symbol(&mut cdf8) as u32, |
| 805 | _ => dec.literal(8), |
| 806 | }; |
| 807 | assert_eq!(got, want, "item {i} of kind {kind}"); |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | /// The bit account is what a search prices decisions with, so it has to |
| 812 | /// agree with what the coder actually spends: over a long enough string the |
| 813 | /// two are within the coder's own rounding, a fraction of a percent. |
| 814 | #[test] |
| 815 | fn the_bit_account_matches_the_bytes_written() { |
| 816 | let mut enc = SymbolEncoder::new(); |
| 817 | let mut state: u32 = 0x1234_5678; |
| 818 | let mut next = || { |
| 819 | state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); |
| 820 | state |
| 821 | }; |
| 822 | // A skewed CDF, so that the account has something to be wrong about: |
| 823 | // an equiprobable string costs one bit a symbol however it is priced. |
| 824 | let skewed: [u16; 3] = [29000, 1 << 15, 0]; |
| 825 | for _ in 0..20_000 { |
| 826 | let symbol = usize::from(next() % 100 < 12); |
| 827 | enc.symbol_fixed(symbol, &skewed); |
| 828 | } |
| 829 | let priced = enc.bits(); |
| 830 | let spent = (enc.finish().len() * 8) as f64; |
| 831 | assert!( |
| 832 | (priced - spent).abs() / spent < 0.01, |
| 833 | "priced {priced:.0} bits, spent {spent:.0}" |
| 834 | ); |
| 835 | } |
| 836 | |
| 837 | #[test] |
| 838 | fn empty_payload_is_short() { |
| 839 | assert!(SymbolEncoder::new().finish().len() <= 2); |
| 840 | } |
| 841 | /// The spec-literal 8.2.6 walk, as `symbol_fixed` read it before the |
| 842 | /// two-symbol shortcut and the last-candidate fall-through: every |
| 843 | /// candidate tested, `EC_MIN_PROB` multiplied out, one shared tail. |
| 844 | fn ref_symbol_fixed(d: &mut SymbolDecoder<'_>, cdf: &[u16]) -> usize { |
| 845 | let nsyms = cdf.len() - 1; |
| 846 | let mut cur = d.range; |
| 847 | let mut prev = cur; |
| 848 | let mut symbol = nsyms - 1; |
| 849 | let base = d.range >> 8; |
| 850 | for (i, &c) in cdf[..nsyms].iter().enumerate() { |
| 851 | prev = cur; |
| 852 | let f = u32::from(CDF_TOP - c); |
| 853 | cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) |
| 854 | + EC_MIN_PROB * (nsyms - 1 - i) as u32; |
| 855 | if d.value >= cur { |
| 856 | symbol = i; |
| 857 | break; |
| 858 | } |
| 859 | } |
| 860 | d.range = prev - cur; |
| 861 | d.value -= cur; |
| 862 | let bits = 16 - (32 - d.range.leading_zeros()); |
| 863 | d.range <<= bits; |
| 864 | let num_bits = u32::min(bits, d.max_bits.max(0) as u32); |
| 865 | let new_data = d.f(num_bits); |
| 866 | let padded = new_data << (bits - num_bits); |
| 867 | d.value = padded ^ (((d.value + 1) << bits) - 1); |
| 868 | d.max_bits -= bits as i32; |
| 869 | symbol |
| 870 | } |
| 871 | |
| 872 | /// The reader's fast paths must be the spec walk, symbol for symbol and |
| 873 | /// register for register: a long mixed stream is decoded twice in lockstep |
| 874 | /// and both the symbol and the coder state `(range, value)` are compared |
| 875 | /// after every read, so a divergence that has not yet changed a symbol |
| 876 | /// still fails here. |
| 877 | #[test] |
| 878 | fn fast_paths_match_the_spec_literal_walk() { |
| 879 | let mut state = 0x0123_4567_89ab_cdef; |
| 880 | let mut enc = SymbolEncoder::new(); |
| 881 | let mut cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect(); |
| 882 | let mut written: Vec<(usize, u32)> = Vec::new(); |
| 883 | for _ in 0..20_000 { |
| 884 | let pick = (rng(&mut state) % 16) as usize; |
| 885 | if pick == 15 { |
| 886 | let width = 1 + (rng(&mut state) % 16) as u32; |
| 887 | let v = (rng(&mut state) as u32) & ((1u32 << width) - 1); |
| 888 | enc.literal(v, width); |
| 889 | written.push((usize::MAX, width)); |
| 890 | } else { |
| 891 | let nsyms = pick + 2; |
| 892 | let sym = (rng(&mut state) % nsyms as u64) as usize; |
| 893 | enc.symbol(sym, &mut cdfs[pick]); |
| 894 | written.push((pick, sym as u32)); |
| 895 | } |
| 896 | } |
| 897 | let payload = enc.finish(); |
| 898 | |
| 899 | let mut fast = SymbolDecoder::new(&payload); |
| 900 | let mut slow = SymbolDecoder::new(&payload); |
| 901 | let mut fast_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect(); |
| 902 | let mut slow_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect(); |
| 903 | for (i, &(pick, arg)) in written.iter().enumerate() { |
| 904 | let (a, b) = if pick == usize::MAX { |
| 905 | let a = fast.literal(arg); |
| 906 | let mut b = 0u32; |
| 907 | for _ in 0..arg { |
| 908 | b = (b << 1) | ref_symbol_fixed(&mut slow, &EQUIPROBABLE) as u32; |
| 909 | } |
| 910 | (a, b) |
| 911 | } else { |
| 912 | let a = fast.symbol(&mut fast_cdfs[pick]) as u32; |
| 913 | let b = ref_symbol_fixed(&mut slow, &slow_cdfs[pick]); |
| 914 | update_cdf(&mut slow_cdfs[pick], b); |
| 915 | (a, b as u32) |
| 916 | }; |
| 917 | assert_eq!(a, b, "item {i} (pick {pick})"); |
| 918 | assert_eq!( |
| 919 | a, |
| 920 | if pick == usize::MAX { a } else { arg }, |
| 921 | "item {i} vs written" |
| 922 | ); |
| 923 | assert_eq!( |
| 924 | fast.debug_state(), |
| 925 | slow.debug_state(), |
| 926 | "coder state after item {i} (pick {pick})" |
| 927 | ); |
| 928 | assert_eq!( |
| 929 | fast_cdfs[pick.min(14)], |
| 930 | slow_cdfs[pick.min(14)], |
| 931 | "cdf after item {i}" |
| 932 | ); |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | /// lane-av1txr: spec 5.9.2's `disable_cdf_update`, the reader half -- |
| 937 | /// [`SymbolDecoder::set_cdf_update`]. A reader told not to adapt must |
| 938 | /// reproduce a writer that never adapted |
| 939 | /// ([`SymbolEncoder::symbol_fixed`]), and the DEFAULT reader must not: the |
| 940 | /// flag is what keeps a real `aomenc --cdf-update-mode=0` stream in sync |
| 941 | /// (its tiles desynced at the first multi-symbol block without it). |
| 942 | #[test] |
| 943 | fn a_reader_told_not_to_adapt_matches_a_non_adapting_writer() { |
| 944 | let mut state = 0x2545_f491_4f6c_dd1du64; |
| 945 | let mut enc = SymbolEncoder::new(); |
| 946 | let cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect(); |
| 947 | let mut written = Vec::new(); |
| 948 | for i in 0..600 { |
| 949 | let pick = i % cdfs.len(); |
| 950 | let nsyms = pick + 2; |
| 951 | let sym = (rng(&mut state) % nsyms as u64) as usize; |
| 952 | enc.symbol_fixed(sym, &cdfs[pick]); |
| 953 | written.push((pick, sym)); |
| 954 | } |
| 955 | let payload = enc.finish(); |
| 956 | |
| 957 | let mut fixed = SymbolDecoder::new(&payload); |
| 958 | fixed.set_cdf_update(false); |
| 959 | let mut adapting = SymbolDecoder::new(&payload); |
| 960 | let mut fixed_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect(); |
| 961 | let mut adapting_cdfs: Vec<Vec<u16>> = (2..=16).map(flat_cdf).collect(); |
| 962 | let mut adapting_mismatches = 0usize; |
| 963 | for (i, &(pick, sym)) in written.iter().enumerate() { |
| 964 | assert_eq!( |
| 965 | fixed.symbol(&mut fixed_cdfs[pick]), |
| 966 | sym, |
| 967 | "non-adapting reader, item {i} (pick {pick})" |
| 968 | ); |
| 969 | if adapting.symbol(&mut adapting_cdfs[pick]) != sym { |
| 970 | adapting_mismatches += 1; |
| 971 | } |
| 972 | } |
| 973 | assert_eq!( |
| 974 | fixed_cdfs, |
| 975 | (2..=16).map(flat_cdf).collect::<Vec<_>>(), |
| 976 | "the non-adapting reader still moved a table" |
| 977 | ); |
| 978 | assert!( |
| 979 | adapting_mismatches > 0, |
| 980 | "the adaptation flag is inert: the default reader reproduced a non-adapting writer" |
| 981 | ); |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | /// Symbol-by-symbol writer/reader trace (`EC_AV1_SYMTRACE=<dir>`), the |
| 986 | /// instrument a desync between OUR writer and OUR reader is bisected with: |
| 987 | /// every non-pricing [`SymbolEncoder`] and every [`SymbolDecoder`] dumps one |
| 988 | /// line per symbol (`index value nsyms cdf0`) into `<dir>/w-<n>.txt` / |
| 989 | /// `<dir>/r-<n>.txt`, and the first line where the two differ names the |
| 990 | /// divergent symbol. `EC_AV1_SYMTRACE_AT=<index>` additionally prints a |
| 991 | /// backtrace at that index on both sides, which names the syntax element. |
| 992 | /// Off (the variable unset) this is one relaxed load per symbol. |
| 993 | pub(crate) mod symtrace { |
| 994 | use std::cell::RefCell; |
| 995 | use std::collections::VecDeque; |
| 996 | use std::sync::OnceLock; |
| 997 | |
| 998 | static DIR: OnceLock<Option<String>> = OnceLock::new(); |
| 999 | static AT: OnceLock<Option<(usize, usize)>> = OnceLock::new(); |
| 1000 | static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 1001 | |
| 1002 | thread_local! { |
| 1003 | static BUF: RefCell<(String, usize)> = const { RefCell::new((String::new(), 0)) }; |
| 1004 | static ECD: RefCell<VecDeque<(u32, u32, u32, u32)>> = const { RefCell::new(VecDeque::new()) }; |
| 1005 | // lane-av1dumploud: the file's PATH travels with it, so a short write |
| 1006 | // can name the file it truncated instead of reconstructing a name. |
| 1007 | static ECD_READER: RefCell<Option<(std::fs::File, String)>> = const { RefCell::new(None) }; |
| 1008 | static ECD_IDX: RefCell<usize> = const { RefCell::new(0) }; |
| 1009 | } |
| 1010 | |
| 1011 | /// lane-av1mix: `(low, value, rng, bitpos)` state register dump, one line |
| 1012 | /// per symbol read, byte-for-byte diffable against libaom's `EC_ECDUMP` |
| 1013 | /// (`decodetxb.c`, `r->ec.dif` masked to 16 bits / `r->ec.rng` / |
| 1014 | /// `od_ec_dec_tell`). Reader-only, `EC_AV1_ECDUMP=<dir>`: each reader |
| 1015 | /// writes `<dir>/ecdump-<n>.txt`. |
| 1016 | pub(crate) fn ecdump(low: u32, value: u32, rng: u32, bitpos: i64) { |
| 1017 | if !ecdump_armed() { |
| 1018 | return; |
| 1019 | } |
| 1020 | let dir = std::env::var("EC_AV1_ECDUMP").unwrap_or_else(|_| "/tmp".to_string()); |
| 1021 | let idx = ECD_IDX.with(|c| { |
| 1022 | let mut g = c.borrow_mut(); |
| 1023 | let n = *g; |
| 1024 | *g += 1; |
| 1025 | n |
| 1026 | }); |
| 1027 | let _ = idx; |
| 1028 | let line = format!("{idx} ({low},{value},{rng},{bitpos})\n"); |
| 1029 | ECD_READER.with(|f| { |
| 1030 | use std::io::Write; |
| 1031 | let mut slot = f.borrow_mut(); |
| 1032 | if slot.is_none() { |
| 1033 | let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1034 | let path = format!("{dir}/ecdump-{seq:05}.txt"); |
| 1035 | eprintln!("ECDUMP -> {path}"); |
| 1036 | *slot = Some((std::fs::File::create(&path).expect("ecdump file"), path)); |
| 1037 | } |
| 1038 | // lane-av1dumploud: loud on a short write. This file is one line |
| 1039 | // per symbol for a whole run, so its total length is unknowable at |
| 1040 | // open time -- the failure line says "an unknown number of" rather |
| 1041 | // than declaring a length it would have to invent. |
| 1042 | let (file, path) = slot.as_mut().expect("just opened"); |
| 1043 | if let Err(e) = file.write_all(line.as_bytes()) { |
| 1044 | panic!( |
| 1045 | "ec-av1 dump FAILED [EC_AV1_ECDUMP] {path}: \ |
| 1046 | write failed after a partial line of {} bytes: {e}", |
| 1047 | line.len() |
| 1048 | ); |
| 1049 | } |
| 1050 | }); |
| 1051 | ECD.with(|q| { |
| 1052 | let mut q = q.borrow_mut(); |
| 1053 | q.push_back((low, value, rng, bitpos as u32)); |
| 1054 | if q.len() > 512 { |
| 1055 | q.pop_front(); |
| 1056 | } |
| 1057 | }); |
| 1058 | } |
| 1059 | |
| 1060 | /// lane-av1mix: the last `n` dumped register states (most recent last). |
| 1061 | #[allow(dead_code)] // diagnostic helper for lane sessions |
| 1062 | pub(crate) fn ecdump_recent(n: usize) -> Vec<(u32, u32, u32, u32)> { |
| 1063 | if std::env::var_os("EC_AV1_ECDUMP").is_none() { |
| 1064 | return Vec::new(); |
| 1065 | } |
| 1066 | ECD.with(|q| { |
| 1067 | let q = q.borrow(); |
| 1068 | let skip = q.len().saturating_sub(n); |
| 1069 | q.iter().skip(skip).copied().collect() |
| 1070 | }) |
| 1071 | } |
| 1072 | |
| 1073 | pub(crate) fn dir() -> Option<&'static str> { |
| 1074 | DIR.get_or_init(|| { |
| 1075 | crate::envflags::var("EC_AV1_SYMTRACE") |
| 1076 | .ok() |
| 1077 | .filter(|v| !v.is_empty()) |
| 1078 | }) |
| 1079 | .as_deref() |
| 1080 | } |
| 1081 | |
| 1082 | /// lane-av1mix: `EC_AV1_ECDUMP=<dir>` arms the decoder state-register dump. |
| 1083 | pub(crate) fn ecdump_armed() -> bool { |
| 1084 | static ARMED: std::sync::LazyLock<bool> = |
| 1085 | std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_ECDUMP").is_some()); |
| 1086 | *ARMED |
| 1087 | } |
| 1088 | |
| 1089 | /// `EC_AV1_SYMTRACE_AT=<i>` or `=<from>:<to>` (inclusive). |
| 1090 | fn at() -> Option<(usize, usize)> { |
| 1091 | *AT.get_or_init(|| { |
| 1092 | let v = crate::envflags::var("EC_AV1_SYMTRACE_AT").ok()?; |
| 1093 | let (a, b) = v.split_once(':').unwrap_or((v.as_str(), v.as_str())); |
| 1094 | Some((a.parse().ok()?, b.parse().ok()?)) |
| 1095 | }) |
| 1096 | } |
| 1097 | |
| 1098 | /// A caller's own annotation, interleaved with this coder's symbol lines |
| 1099 | /// (`# ...`) so the writer/reader diff shows the state around a desync. |
| 1100 | pub(crate) fn note(line: &str) { |
| 1101 | if dir().is_none() { |
| 1102 | return; |
| 1103 | } |
| 1104 | BUF.with(|b| { |
| 1105 | let (buf, _) = &mut *b.borrow_mut(); |
| 1106 | buf.push_str("# "); |
| 1107 | buf.push_str(line); |
| 1108 | buf.push('\n'); |
| 1109 | }); |
| 1110 | } |
| 1111 | |
| 1112 | pub(crate) fn push(value: usize, nsyms: usize, cdf0: u16) { |
| 1113 | BUF.with(|b| { |
| 1114 | let (buf, n) = &mut *b.borrow_mut(); |
| 1115 | if at().is_some_and(|(a, b)| (a..=b).contains(n)) { |
| 1116 | eprintln!( |
| 1117 | "SYMTRACE at {n}: {}", |
| 1118 | std::backtrace::Backtrace::force_capture() |
| 1119 | ); |
| 1120 | } |
| 1121 | buf.push_str(&format!("{n} {value} {nsyms} {cdf0}\n")); |
| 1122 | *n += 1; |
| 1123 | }); |
| 1124 | } |
| 1125 | |
| 1126 | /// Flushes this coder's lines as `<dir>/<side>-<n>.txt` and starts the |
| 1127 | /// next coder's trace. |
| 1128 | pub(crate) fn flush(side: char) { |
| 1129 | let Some(dir) = dir() else { return }; |
| 1130 | BUF.with(|b| { |
| 1131 | let (buf, n) = &mut *b.borrow_mut(); |
| 1132 | if !buf.is_empty() { |
| 1133 | // lane-av1dumploud: loud on a short write. `std::fs::write` |
| 1134 | // returned a `Result` this used to discard, and the check was |
| 1135 | // hand-rolled against the buffer length only; lane-av1pinloud |
| 1136 | // folded it into the shared writer so this site also gets the |
| 1137 | // on-disk length check the dump path already had. |
| 1138 | let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1139 | crate::dumpio::pin( |
| 1140 | "EC_AV1_SYMTRACE", |
| 1141 | format!("{dir}/{side}-{seq:05}.txt"), |
| 1142 | buf.as_bytes(), |
| 1143 | ); |
| 1144 | } |
| 1145 | buf.clear(); |
| 1146 | *n = 0; |
| 1147 | }); |
| 1148 | } |
| 1149 | } |