From 4e72cc8664f93366535d5fb355e278e54eeb9f25 Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+MoonEyes@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:47:51 +0100 Subject: [PATCH 1/3] docs: a switch with a value needs it beside LEONIDA_AB merzleckeier measured on #2708 that LEONIDA_GUARD_HOT and LEONIDA_SKIP_TRY_A stay off on both sides when only LEONIDA_AB names them. Co-Authored-By: Claude Opus 5.5 --- docs/measuring_fps.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/measuring_fps.md b/docs/measuring_fps.md index fdfe194f1..1a8f902ef 100644 --- a/docs/measuring_fps.md +++ b/docs/measuring_fps.md @@ -23,7 +23,12 @@ both sides are measured in one scene, at one cache temperature, beside the same The same goes for every variable of section 5. - More than eight names, or a phase of one second or less, and there is no A/B at all, again without a word. Look for the `A/B phase` lines in the log. -- A switch named there no longer goes by its own variable. Only switches the code reads that way follow it; for any +- A plain on/off switch named there goes by the phase instead of its own variable. For a switch with a value or a list + the phase only says whether that value counts, so give the value too, in the same `-More`: without + `LEONIDA_GUARD_HOT=` or the hashes of `LEONIDA_SKIP_TRY_A` both sides are off and the A/B compares nothing with + nothing. The same goes for another switch it needs (`LEONIDA_PORT_GUARD` for `LEONIDA_GUARD_HOT`). "See the code" + under *Kind* in [switches.md](../d3d12/docs/switches.md) is a sign to look there first. +- Only switches the code reads that way follow it; for any other name the phases are logged and nothing changes, so check the name in [switches.md](../d3d12/docs/switches.md) or the code before you believe a "no difference". - Not every switch may be turned in play: `findings.md` has one that ends the title (`LEONIDA_ASYNC_SUBMIT`). @@ -31,10 +36,12 @@ both sides are measured in one scene, at one cache temperature, beside the same idle and busy time a frame and the submitting thread's work a frame. The first second of a phase is left out. Phases of 3.5 to 4 s worked in the runs of `findings.md` (one PC, one save: "about measuring there"). The idle camera -there goes round views of about 24 s with different draw counts, so phases of 15 s measured the views, not the switch. Standing, `findings.md` cuts the phases into stretches where the draw count -jumps, leaves out the first phase of a stretch and fits a level for each stretch; walking, the switch of bit *b* -has runs of 2^*b* phases off and 2^*b* on: each pair of neighbouring runs gives one difference, and their mean is the effect. Give the effect **with its standard error**. The scripts it names for this (`ab_pair.py`, `ab_eff.py`) are not in -the repository. +there goes round views of about 24 s with different draw counts, so phases of 15 s measured the views, not the switch. + +Standing, `findings.md` cuts the phases into stretches where the draw count jumps, leaves out the first phase of a +stretch and fits a level for each stretch; walking, the switch of bit *b* has runs of 2^*b* phases off and 2^*b* on: +each pair of neighbouring runs gives one difference, and their mean is the effect. Give the effect **with its standard +error**. The scripts it names for this (`ab_pair.py`, `ab_eff.py`) are not in the repository. The standard errors in `findings.md` are mostly 0.2 to 0.6 ms for a standing run of some minutes (up to 0.94) and 1 to 2 ms for a walking one (up to 2.24). Two separate From e5f9f3b47a20b684458e7e1df5297d51c6f1a4cf Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:43:54 -0600 Subject: [PATCH 2/3] leonida-formats: table-driven BC7 index residuals and packing (D3D12-FORMATS-BC7-POST-LUTS) The BC7 block loop of the BCPack decoder took 100-155 ns a block on top of the rANS lanes: every index residual was rebuilt bit by bit (two 4-iteration folds per byte), each index went through an add_index with per-element branches, endpoint residuals were done a column at a time and bc7_pack made about 45 Bits::put calls on a u128. - nibbles() reads a 256-entry table (also used by BC6H). - The sixteen indices of a set are added to the reference's in one pass with the shifts hoisted out of the loop (bc7_indices). - Endpoint residuals of a row go through one multiply-by-precision per column instead of a masked shift per column. - bc7_pack puts each channel's endpoints, the p-bits and each index set with one put, taking an anchor's top bit out of the fixed-width fields afterwards. Output is unchanged: a copy of the previous block loop is kept in the tests as the reference, and bc7_blocks_match_the_reference compares the two byte for byte on the shipped tables and on tables with arbitrary control words, dictionaries and reference widths (history wrapping), and on the error of an unused control code. AI-assisted: Claude Sonnet 5.5 Co-authored-by: Cursor --- d3d12/crates/leonida-formats/src/bcpack.rs | 484 +++++++++++++++++++-- 1 file changed, 445 insertions(+), 39 deletions(-) diff --git a/d3d12/crates/leonida-formats/src/bcpack.rs b/d3d12/crates/leonida-formats/src/bcpack.rs index 0b9edf631..e11cca3eb 100644 --- a/d3d12/crates/leonida-formats/src/bcpack.rs +++ b/d3d12/crates/leonida-formats/src/bcpack.rs @@ -670,12 +670,33 @@ fn bc5_pack(v: &Plain, out: &mut [u8]) { /// A byte's even and odd bits as two zigzag-coded 4-bit residuals. fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); + let [even, odd] = NIBBLES[usize::from(b)]; if odd_first { [odd, even] } else { [even, odd] } } +/// A zigzag-coded residual (0, -1, 1, -2, ...) as a signed value. +const fn unzigzag(u: u8) -> i16 { + (u >> 1) as i16 ^ -((u & 1) as i16) +} + +/// [`nibbles`] of every byte, as `[even, odd]`. +const NIBBLES: [[i16; 2]; 256] = { + let mut table = [[0i16; 2]; 256]; + let mut b = 0; + while b < 256 { + let (mut even, mut odd) = (0u8, 0u8); + let mut k = 0; + while k < 4 { + even |= ((b >> (2 * k) & 1) as u8) << k; + odd |= ((b >> (2 * k + 1) & 1) as u8) << k; + k += 1; + } + table[b] = [unzigzag(even), unzigzag(odd)]; + b += 1; + } + table +}; + /// Index residual plus reference, both left-aligned to 16 bits at their own /// widths, back to `bits` bits (signed). fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { @@ -822,19 +843,20 @@ fn bc7<'a>( }; // Rows the reference lacks build on its first row. let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); - let columns = if prec[3] > 0 { 8 } else { 6 }; - for c in 0..columns { - let p = prec[c / 2]; - if p == 0 { - continue; - } - let mask = 0xffffu16 << (16 - p); - for (row, st) in stored.iter().enumerate().take(subsets) { + // A column's residual sits in the top bits of its channel's precision: + // a multiplication moves it there and keeps the lanes of one row alike + // (a column of a channel with no bits, 0, stays 0). + let scale: [u16; 8] = std::array::from_fn(|c| match prec[c / 2] { + 0 => 0, + p => 1 << (16 - p), + }); + let keep = scale.map(|k| 0u16.wrapping_sub(k)); + for (row, st) in stored.iter().enumerate().take(subsets) { + let base = &r.rows[if row < common { row } else { 0 }]; + for c in 0..8 { let v = st[c]; - let residual = - (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); - let base = r.rows[if row < common { row } else { 0 }][c] & mask; - ep.rows[row][c] = base.wrapping_add(residual); + let residual = u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16; + ep.rows[row][c] = (base[c] & keep[c]).wrapping_add(residual.wrapping_mul(scale[c])); } } let bits = BC7_INDEX[mode]; @@ -844,17 +866,8 @@ fn bc7<'a>( ..Default::default() }; for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { - if bits[set] == 0 { - continue; - } - for (k, o) in offsets.into_iter().enumerate() { - for (b, &byte) in s[o..o + 2].iter().enumerate() { - let pair = nibbles(byte, k < 3); - for (h, &v) in pair.iter().enumerate() { - let p = 4 * k + 2 * b + h; - ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); - } - } + if bits[set] != 0 { + ix.ix[set] = bc7_indices(s, offsets, bits[set], &rx.ix[set], rx.bits[set]); } } history[i % HISTORY] = (ep, ix); @@ -863,6 +876,39 @@ fn bc7<'a>( Ok(()) } +/// One index set of a block: the residuals of the record's bytes at +/// `offsets` (each and the next) plus the reference's indices, at `bits` bits +/// (1 to 16) and the reference's `ref_bits`. +#[inline(always)] +fn bc7_indices( + s: &[u8], + offsets: [usize; 4], + bits: u8, + reference: &[i16; 16], + ref_bits: u8, +) -> [i16; 16] { + debug_assert!((1..=16).contains(&bits)); + let mut residual = [0i16; 16]; + for (k, o) in offsets.into_iter().enumerate() { + for b in 0..2 { + let [even, odd] = NIBBLES[usize::from(s[o + b])]; + let at = 4 * k + 2 * b; + [residual[at], residual[at + 1]] = if k < 3 { [odd, even] } else { [even, odd] }; + } + } + let down = 16 - u32::from(bits); + // A reference of no bits, or of more than 16, adds nothing. + let (up, keep) = if (1..=16).contains(&ref_bits) { + (16 - u32::from(ref_bits), u16::MAX) + } else { + (0, 0) + }; + std::array::from_fn(|p| { + let sum = ((residual[p] as u16) << down).wrapping_add(((reference[p] as u16) << up) & keep); + (sum as i16) >> down + }) +} + fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { let ctrl = ep.ctrl; let mode = ctrl & 7; @@ -893,26 +939,58 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { continue; } let drop = u32::from(ch == 0 && pbits(mode)); + // The channel's endpoints side by side (at most six of eight bits). + let n = u32::from(p) - drop; + let mut fields = 0u64; for e in 0..ends { - w.put(field(e / 2, 2 * ch + e % 2, p) >> drop, u32::from(p) - drop); + fields |= (field(e / 2, 2 * ch + e % 2, p) >> drop & ((1 << n) - 1)) << (e as u32 * n); } + w.put(fields, n * ends as u32); } - match mode { - 1 => (0..subsets).for_each(|row| w.put(field(row, 0, prec[0]) & 1, 1)), - m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), - _ => {} - } - let anchors: &[u8] = match subsets { - 2 => &[0, ANCHOR2[part]], - 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], - _ => &[0], + // The p-bits: one per subset in mode 1, one per endpoint in the others that have them. + let mut shared = 0u64; + let shared_bits = match mode { + 1 => { + for row in 0..subsets { + shared |= (field(row, 0, prec[0]) & 1) << row; + } + subsets + } + m if pbits(m) => { + for e in 0..ends { + shared |= (field(e / 2, e % 2, prec[0]) & 1) << e; + } + ends + } + _ => 0, }; + w.put(shared, shared_bits as u32); + // The anchors' indices have a bit less. + let anchors = 1u16 + | match subsets { + 2 => 1 << ANCHOR2[part], + 3 => 1 << ANCHOR3A[part] | 1 << ANCHOR3B[part], + _ => 0, + }; let mut indices = |set: usize| { - let bits = ix.bits[set]; + let bits = u32::from(ix.bits[set]); + debug_assert!((1..=4).contains(&bits)); + // All sixteen at the full width, then each anchor's top bit taken out, + // the highest first so that the others stay where they are. + let mask = (1u64 << bits) - 1; + let mut packed = 0u64; for (p, &v) in ix.ix[set].iter().enumerate() { - let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); - w.put(u64::from(v as u16), n); + packed |= (u64::from(v as u16) & mask) << (bits * p as u32); } + let (mut left, mut at) = (anchors, 16 * bits); + while left != 0 { + let p = 15 - left.leading_zeros(); + left ^= 1 << p; + let top = bits * p + bits - 1; + packed = packed & ((1u64 << top) - 1) | (packed >> top >> 1) << top; + at -= 1; + } + w.put(packed, at); }; match mode { 4 => { @@ -1647,4 +1725,332 @@ mod tests { } } } + + /// The BC7 block loop as it was before its index tables and packing were + /// made cheaper: one index and one bit at a time. + mod reference { + use super::*; + + pub fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); + let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + let (even, odd) = (z(half(b)), z(half(b >> 1))); + if odd_first { [odd, even] } else { [even, odd] } + } + + pub fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { + let up = |v: i16, b: u8| { + if b == 0 || b > 16 { + 0 + } else { + (v as u16) << (16 - b) + } + }; + let sum = up(cur, bits).wrapping_add(up(refv, ref_bits)) as i16; + if bits == 0 { 0 } else { sum >> (16 - bits) } + } + + pub fn pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { + let ctrl = ep.ctrl; + let mode = ctrl & 7; + let subsets = usize::from((ctrl & 0xff) >> 6); + let part = usize::from(ctrl >> 8 & 63); + let rot = bc7_rotation(ctrl); + let mut w = Bits::default(); + w.put(1 << mode, u32::from(mode) + 1); + match mode { + 0 => w.put(part as u64, 4), + 1 | 2 | 3 | 7 => w.put(part as u64, 6), + 4 => { + w.put(rot as u64, 2); + w.put(u64::from(ctrl >> 5 & 1), 1); + } + 5 => w.put(rot as u64, 2), + _ => {} + } + let ends = 2 * subsets; + let field = |row: usize, col: usize, p: u8| u64::from(ep.rows[row][col] >> (16 - p)); + let mut order = [0, 1, 2, 3]; + if rot != 0 { + order.swap(3, rot - 1); + } + for ch in order { + let p = prec[ch]; + if p == 0 { + continue; + } + let drop = u32::from(ch == 0 && pbits(mode)); + for e in 0..ends { + w.put(field(e / 2, 2 * ch + e % 2, p) >> drop, u32::from(p) - drop); + } + } + match mode { + 1 => (0..subsets).for_each(|row| w.put(field(row, 0, prec[0]) & 1, 1)), + m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), + _ => {} + } + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mut indices = |set: usize| { + let bits = ix.bits[set]; + for (p, &v) in ix.ix[set].iter().enumerate() { + let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + w.put(u64::from(v as u16), n); + } + }; + match mode { + 4 => { + indices(1); + indices(0); + } + 5 => { + indices(0); + indices(1); + } + _ => indices(0), + } + out.copy_from_slice(&w.v.to_le_bytes()); + } + + pub fn bc7<'a>( + records: impl Iterator, + out: impl Iterator, + t: &Tables, + ) -> Result<(), Error> { + let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY]; + let zero = (Bc7Ep::default(), Bc7Ix::default()); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; + if ctrl == 0 { + return Err(Error("unused BC7 control code")); + } + let mode = usize::from(ctrl & 7); + let subsets = usize::from((ctrl & 0xff) >> 6); + let prec = bc7_precision(ctrl); + let three = subsets == 3; + let or0 = |v: u8| if three { 0 } else { v }; + let if3 = |v: u8| if three { v } else { 0 }; + let stored = [ + [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], + [ + s[12], + s[13], + s[14], + s[15], + s[16], + s[17], + or0(s[18]), + or0(s[19]), + ], + [ + s[20], + s[21], + if3(s[10]), + if3(s[11]), + if3(s[18]), + if3(s[19]), + 0, + 0, + ], + ]; + let r = &pick(i, ep_ref, &history, &t.bc7, &zero).0; + let mut ep = Bc7Ep { + ctrl, + ..Default::default() + }; + let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); + let columns = if prec[3] > 0 { 8 } else { 6 }; + for c in 0..columns { + let p = prec[c / 2]; + if p == 0 { + continue; + } + let mask = 0xffffu16 << (16 - p); + for (row, st) in stored.iter().enumerate().take(subsets) { + let v = st[c]; + let residual = + (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); + let base = r.rows[if row < common { row } else { 0 }][c] & mask; + ep.rows[row][c] = base.wrapping_add(residual); + } + } + let bits = BC7_INDEX[mode]; + let rx = &pick(i, ix_ref, &history, &t.bc7, &zero).1; + let mut ix = Bc7Ix { + bits, + ..Default::default() + }; + for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { + if bits[set] == 0 { + continue; + } + for (k, o) in offsets.into_iter().enumerate() { + for (b, &byte) in s[o..o + 2].iter().enumerate() { + let pair = nibbles(byte, k < 3); + for (h, &v) in pair.iter().enumerate() { + let p = 4 * k + 2 * b + h; + ix.ix[set][p] = + add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); + } + } + } + } + history[i % HISTORY] = (ep, ix); + pack(&ep, &ix, prec, block); + } + Ok(()) + } + } + + /// A small, fixed-seed generator for the block tests. + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + } + + /// Tables whose BC7 control words and dictionary hold any value: every + /// mode, subset count, partition and rotation, and reference index widths + /// of 0 to 255. + fn wild_bc7_tables(rng: &mut Rng) -> Tables { + let mut t = Tables::builtin().unwrap(); + for c in &mut t.ctrl7 { + *c = (rng.next() as u16).max(1); + } + for (ep, ix) in &mut t.bc7 { + ep.ctrl = rng.next() as u16; + for v in ep.rows.as_flattened_mut() { + *v = rng.next() as u16; + } + ix.bits = [rng.next() as u8, rng.next() as u8]; + for v in ix.ix.as_flattened_mut() { + *v = rng.next() as i16; + } + } + t + } + + fn random_bc7_records(rng: &mut Rng, blocks: usize) -> Vec { + (0..blocks * 32).map(|_| rng.next() as u8).collect() + } + + /// The BC7 block loop and its packing give the reference's bytes for the + /// shipped tables and for tables of arbitrary control words, dictionaries + /// and references (history wraps: more blocks than the 256 it keeps). + #[test] + fn bc7_blocks_match_the_reference() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for round in 0..24 { + let t = if round == 0 { + Tables::builtin().unwrap() + } else { + wild_bc7_tables(&mut rng) + }; + let blocks = 700; + let records = random_bc7_records(&mut rng, blocks); + let mut got = vec![0u8; blocks * 16]; + let mut want = vec![0u8; blocks * 16]; + let a = bc7(records.chunks_exact(32), got.chunks_exact_mut(16), &t); + let b = reference::bc7(records.chunks_exact(32), want.chunks_exact_mut(16), &t); + assert_eq!(a, b, "round {round}"); + assert!(got == want, "round {round}"); + } + } + + /// A control code that no block may use stops the loop at that block, with + /// everything before it written as before. + #[test] + fn bc7_unused_control_code_stops_at_the_same_block() { + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + let mut t = Tables::builtin().unwrap(); + let blocks = 300; + let records = random_bc7_records(&mut rng, blocks); + let code = |s: &[u8]| usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31); + t.ctrl7[code(&records[200 * 32..])] = 0; + let mut got = vec![0xa5u8; blocks * 16]; + let mut want = vec![0xa5u8; blocks * 16]; + let a = bc7(records.chunks_exact(32), got.chunks_exact_mut(16), &t); + let b = reference::bc7(records.chunks_exact(32), want.chunks_exact_mut(16), &t); + assert!(a.is_err()); + assert_eq!(a, b); + assert!(got == want); + } + + /// The BC7 block loop against the reference on the shipped tables, per + /// mode (every block of the mode's first control code, random references) + /// and for every control code the table has: + /// `cargo test --release -p leonida-formats bc7_post_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn bc7_post_throughput() { + let t = Tables::builtin().unwrap(); + let mut rng = Rng(0x1234_5678_9abc_def1); + let blocks = 1 << 14; + let mut dst = vec![0u8; blocks * 16]; + let mut want = vec![0u8; blocks * 16]; + let mut run = |name: String, records: &[u8]| { + reference::bc7(records.chunks_exact(32), want.chunks_exact_mut(16), &t).unwrap(); + bc7(records.chunks_exact(32), dst.chunks_exact_mut(16), &t).unwrap(); + assert!(dst == want, "{name}"); + // Alternating batches, the fastest of each (the machine is not ours alone). + let (mut old, mut new) = (f64::MAX, f64::MAX); + for _ in 0..40 { + let started = std::time::Instant::now(); + for _ in 0..3 { + reference::bc7( + std::hint::black_box(records).chunks_exact(32), + dst.chunks_exact_mut(16), + &t, + ) + .unwrap(); + } + old = old.min(started.elapsed().as_secs_f64() / 3.0); + let started = std::time::Instant::now(); + for _ in 0..3 { + bc7( + std::hint::black_box(records).chunks_exact(32), + dst.chunks_exact_mut(16), + &t, + ) + .unwrap(); + } + new = new.min(started.elapsed().as_secs_f64() / 3.0); + } + let (old, new) = (old * 1e9 / blocks as f64, new * 1e9 / blocks as f64); + println!( + "BC7 {name}: reference {old:.1} ns/block, now {new:.1} ns/block ({:.2}x)", + old / new + ); + }; + let code_of = |s: &[u8]| usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31); + for mode in 0..8u16 { + let code = (0..512) + .find(|&c| t.ctrl7[c] != 0 && t.ctrl7[c] & 7 == mode) + .unwrap(); + let mut records = random_bc7_records(&mut rng, blocks); + for s in records.chunks_exact_mut(32) { + s[30] = (code & 31) as u8; + s[31] = (code >> 5) as u8; + assert_eq!(code_of(s), code); + } + run(format!("mode {mode}"), &records); + } + let mut records = random_bc7_records(&mut rng, blocks); + for s in records.chunks_exact_mut(32) { + while t.ctrl7[code_of(s)] == 0 { + s[30] = rng.next() as u8; + s[31] = rng.next() as u8; + } + } + run("all control codes".to_string(), &records); + } } From f536b3d508d8a47ed58f6838f0a34a2657fb21cd Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:01:21 -0600 Subject: [PATCH 3/3] leonida-formats: eight-byte-wide BC1/BC3/BC4/BC5 block post-processing (D3D12-FORMATS-BCN-POST-SWAR) After the rANS lanes the plain formats' block loop did its arithmetic a byte at a time: a per-element wrapping add and width mask for each of 8 endpoints and 32 indices, 16 scattered byte stores per quad/pair residual, a table lookup and shift per index to build the BC1/BC4 code words, and two 4-step folds per interleave(). - Widths holds the masks of the elements' bits (a word for the endpoints, four for the indices); endpoints and indices are summed with their references eight bytes at a time (top bits added apart for the 8-bit endpoints, masked sums for the at most 7-bit indices). - quads() takes a 256-entry const table and fills the four 4-pixel rows as words; pairs() builds eight pixels at a time. - BC1 and BC4 index codes are computed for eight indices at once (bc1_codes, bc4_codes) and packed by shifts (pack2, pack3). - interleave() reads a 16-entry const table. Output is unchanged: a copy of the previous loop is kept in the tests as the reference, and plain_blocks_match_the_reference compares the two byte for byte for BC1, 3, 4 and 5 on the shipped tables and on tables whose ranks and dictionaries hold any byte (history wrapping). index_codes_are_the_tables and index_codes_pack_by_position check the new code words and packers against the code tables for every byte. AI-assisted: Claude Sonnet 5.5 Co-authored-by: Cursor --- d3d12/crates/leonida-formats/src/bcpack.rs | 541 +++++++++++++++++++-- 1 file changed, 506 insertions(+), 35 deletions(-) diff --git a/d3d12/crates/leonida-formats/src/bcpack.rs b/d3d12/crates/leonida-formats/src/bcpack.rs index 0b9edf631..4c59101ad 100644 --- a/d3d12/crates/leonida-formats/src/bcpack.rs +++ b/d3d12/crates/leonida-formats/src/bcpack.rs @@ -492,10 +492,24 @@ fn references(s: &[u8], paired: bool) -> (usize, usize) { /// Two 4-bit symbols, the first on the even bits. fn interleave(a: u8, b: u8) -> u8 { - let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); - spread(a) | spread(b) << 1 + SPREAD[usize::from(a & 15)] | SPREAD[usize::from(b & 15)] << 1 } +/// A nibble's bits on the even bits of a byte. +const SPREAD: [u8; 16] = { + let mut t = [0; 16]; + let mut v = 0; + while v < 16 { + let mut k = 0; + while k < 4 { + t[v] |= ((v >> k & 1) << (2 * k)) as u8; + k += 1; + } + v += 1; + } + t +}; + /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first /// block into the dictionary. fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: &'a T) -> &'a T { @@ -512,21 +526,33 @@ fn zz(v: u8, bits: u32) -> u8 { ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask } -/// Element widths of the plain formats' endpoints and indices. +/// Element widths of the plain formats' endpoints and indices, as the masks +/// of their bits: the eight endpoints' in a word, the 32 indices' in four +/// (a byte each). struct Widths { - ep: [u8; 8], - ix: [u8; 32], + ep: u64, + ix: [u64; 4], paired: bool, } const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { - let mut ix = [0; 32]; + let mut mask = 0; let mut k = 0; - while k < ix3 + ix2 { - ix[k] = if k < ix3 { 3 } else { 2 }; + while k < 8 { + mask |= (((1u16 << ep[k]) - 1) as u8 as u64) << (8 * k); k += 1; } - Widths { ep, ix, paired } + let mut ix = [0; 4]; + let mut k = 0; + while k < ix3 + ix2 { + ix[k / 8] |= (if k < ix3 { 7u64 } else { 3 }) << (8 * (k % 8)); + k += 1; + } + Widths { + ep: mask, + ix, + paired, + } } const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); @@ -549,11 +575,19 @@ fn plain<'a>( let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; let mut v = residual(s); - for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { - *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; - } - for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { - *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + // Each element is summed with its reference modulo its width, eight + // bytes at a time (no carry leaves a byte: the top bits are added + // apart). + const HIGH: u64 = 0x8080_8080_8080_8080; + let (a, b) = (u64::from_le_bytes(v.ep), u64::from_le_bytes(*ep_ref)); + v.ep = ((((a & !HIGH) + (b & !HIGH)) ^ ((a ^ b) & HIGH)) & w.ep).to_le_bytes(); + // (Indices are at most seven bits wide: the masked sums stay in + // their bytes.) + let (rows, _) = v.ix.as_chunks_mut::<8>(); + let (refs, _) = ix_ref.as_chunks::<8>(); + for ((row, r), m) in rows.iter_mut().zip(refs).zip(w.ix) { + let sum = (u64::from_le_bytes(*row) & m) + (u64::from_le_bytes(*r) & m); + *row = (sum & m).to_le_bytes(); } history[i % HISTORY] = v; pack(&v, block); @@ -561,23 +595,53 @@ fn plain<'a>( Ok(()) } -/// 2-bit index residuals: one symbol per 2x2 quad. +/// 2-bit index residuals: one symbol per 2x2 quad, four of them for the 16 +/// pixels of a block (`ix` takes all 16, a byte each). fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { - for (q, &sym) in s.iter().enumerate() { - let v = rank[usize::from(sym)]; - let base = (q >> 1) * 8 + (q & 1) * 2; - for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { - ix[base + p] = v >> (2 * k) & 3; - } + // A row is four pixels, a word: a quad's top pair is the low half of its + // row's word if the quad is a left one, the high half if a right one; + // its bottom pair is the same in the row below. + let mut words = [0u32; 4]; + for (q, &sym) in s.iter().take(4).enumerate() { + let pixels = QUAD_PIXELS[usize::from(rank[usize::from(sym)])]; + let (row, shift) = ((q >> 1) * 2, 16 * (q & 1)); + words[row] |= (pixels & 0xffff) << shift; + words[row + 1] |= (pixels >> 16) << shift; + } + let (rows, _) = ix.as_chunks_mut::<4>(); + for (row, word) in rows.iter_mut().zip(words) { + *row = word.to_le_bytes(); } } -/// 3-bit index residuals: one symbol per two pixels in raster order. +/// A quad's symbol (2 bits for each of the quad's pixels 0, 1, 4 and 5) as +/// the four bytes they are. +const QUAD_PIXELS: [u32; 256] = { + let mut t = [0; 256]; + let mut v = 0; + while v < 256 { + let mut k = 0; + while k < 4 { + t[v] |= ((v >> (2 * k) & 3) as u32) << (8 * k); + k += 1; + } + v += 1; + } + t +}; + +/// 3-bit index residuals: one symbol per two pixels in raster order (`ix` +/// takes both, a byte each). fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { - for (k, &sym) in s.iter().enumerate() { - let v = rank[usize::from(sym & 63)]; - ix[2 * k] = v & 7; - ix[2 * k + 1] = v >> 4 & 7; + let (s, _) = s.as_chunks::<4>(); + let (ix, _) = ix.as_chunks_mut::<8>(); + for (s, ix) in s.iter().zip(ix) { + let mut word = 0u64; + for (k, &sym) in s.iter().enumerate() { + let v = u64::from(rank[usize::from(sym & 63)]); + word |= ((v & 7) | (v & 0x70) << 4) << (16 * k); + } + *ix = word.to_le_bytes(); } } @@ -626,16 +690,55 @@ fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { v } -/// Indices along the endpoint line -> BC1 and BC4 codes. -const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; +/// Indices along the endpoint line -> BC4 codes (`bc4_codes` is this, eight +/// at a time). +#[cfg(test)] const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; +/// Eight indices (a byte each, the low two bits count) as BC1 codes, which +/// are 0, 2, 3, 1 for 0, 1, 2, 3: the high bit of a code is the index's bits +/// xored, the low one the index's high bit. +fn bc1_codes(ix: u64) -> u64 { + const LOW: u64 = 0x0101_0101_0101_0101; + let (b0, b1) = (ix & LOW, ix >> 1 & LOW); + (b0 ^ b1) << 1 | b1 +} + +/// Eight indices (a byte each, the low three bits count) as BC4 codes, +/// which are 0, 2, 3, 4, 5, 6, 7, 1: the index plus one, but for the two +/// ends of the line (whose bits are all alike), which are 0 and 1. +fn bc4_codes(ix: u64) -> u64 { + const LOW: u64 = 0x0101_0101_0101_0101; + const THREE: u64 = 3 * LOW; + const SEVEN: u64 = 7 * LOW; + let x = ix & SEVEN; + let d = (x ^ x >> 1) & THREE; + let ends = !(d | d >> 1) & LOW; + ((x + LOW) & SEVEN) ^ ends +} + +/// Eight bytes of two bits each (the rest must be zero) as 16 bits, the +/// first byte lowest. +fn pack2(x: u64) -> u64 { + let x = (x | x >> 6) & 0x000f_000f_000f_000f; + let x = (x | x >> 12) & 0x0000_00ff_0000_00ff; + (x | x >> 24) & 0xffff +} + +/// Eight bytes of three bits each (the rest must be zero) as 24 bits, the +/// first byte lowest. +fn pack3(x: u64) -> u64 { + let x = (x | x >> 5) & 0x003f_003f_003f_003f; + let x = (x | x >> 10) & 0x0000_0fff_0000_0fff; + (x | x >> 20) & 0x00ff_ffff +} + fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); - let bits = (0..16).fold(0, |acc, p| { - acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) - }); + let (rows, _) = ix.as_chunks::<8>(); + let codes = |row: &[u8; 8]| pack2(bc1_codes(u64::from_le_bytes(*row) & 0x0303_0303_0303_0303)); + let bits = (codes(&rows[0]) | codes(&rows[1]) << 16) as u32; out[..2].copy_from_slice(&c0.to_le_bytes()); out[2..4].copy_from_slice(&c1.to_le_bytes()); out[4..8].copy_from_slice(&bits.to_le_bytes()); @@ -643,10 +746,10 @@ fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { /// BC4 half: endpoints are kept 128 below their stored value. fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { - let bits = (0..16).fold(0u64, |acc, p| { - acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) - }); - let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; + let (rows, _) = ix.as_chunks::<8>(); + let codes = |row: &[u8; 8]| pack3(bc4_codes(u64::from_le_bytes(*row))); + let bits = codes(&rows[0]) | codes(&rows[1]) << 24; + let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits << 16; out[..8].copy_from_slice(&v.to_le_bytes()); } @@ -1583,6 +1686,374 @@ mod tests { } } + /// The plain formats' (BC1, BC3, BC4, BC5) block loops as they were before + /// their masks, quads and packing were made cheaper. + mod reference_plain { + use super::*; + + const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; + const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; + + pub struct Widths { + ep: [u8; 8], + ix: [u8; 32], + paired: bool, + } + + const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { + let mut ix = [0; 32]; + let mut k = 0; + while k < ix3 + ix2 { + ix[k] = if k < ix3 { 3 } else { 2 }; + k += 1; + } + Widths { ep, ix, paired } + } + + const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); + const BC3: Widths = widths([5, 6, 5, 5, 6, 5, 8, 8], 16, 16, true); + const BC4: Widths = widths([8, 8, 0, 0, 0, 0, 0, 0], 16, 0, false); + const BC5: Widths = widths([8, 8, 8, 8, 0, 0, 0, 0], 32, 0, true); + + fn interleave(a: u8, b: u8) -> u8 { + let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); + spread(a) | spread(b) << 1 + } + + fn references(s: &[u8], paired: bool) -> (usize, usize) { + let (d, ix) = if paired { + (interleave(s[0], s[1]), interleave(s[2], s[3])) + } else { + (s[0], s[1]) + }; + let delta = (d >> 1) ^ (d & 1).wrapping_neg(); + (usize::from(ix.wrapping_add(delta)), usize::from(ix)) + } + + fn zz(v: u8, bits: u32) -> u8 { + let mask = ((1u32 << bits) - 1) as u8; + ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask + } + + pub fn plain<'a>( + records: impl Iterator, + out: impl Iterator, + dictionary: &[Plain], + w: &Widths, + residual: impl Fn(&[u8]) -> Plain, + pack: fn(&Plain, &mut [u8]), + ) -> Result<(), Error> { + let mut history = vec![Plain::default(); HISTORY]; + let zero = Plain::default(); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, w.paired); + let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; + let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; + let mut v = residual(s); + for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { + *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + } + for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { + *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + } + history[i % HISTORY] = v; + pack(&v, block); + } + Ok(()) + } + + fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { + for (q, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym)]; + let base = (q >> 1) * 8 + (q & 1) * 2; + for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { + ix[base + p] = v >> (2 * k) & 3; + } + } + } + + fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { + for (k, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym & 63)]; + ix[2 * k] = v & 7; + ix[2 * k + 1] = v >> 4 & 7; + } + } + + pub fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { + v.ep[k] = zz(s[2 + k], bits); + } + quads(&t.rank1, &s[8..12], &mut v.ix); + v + } + + pub fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain { + ep: [ + zz(s[14], 5), + zz(s[16], 6), + zz(s[18], 5), + zz(s[15], 5), + zz(s[17], 6), + zz(s[19], 5), + zz(s[4], 8), + zz(s[5], 8), + ], + ..Default::default() + }; + pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); + quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + v + } + + pub fn bc4_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + v.ep[..2].copy_from_slice(&[zz(s[2], 8), zz(s[3], 8)]); + pairs(&t.rank4, &s[4..12], &mut v.ix[..16]); + v + } + + pub fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for k in 0..4 { + v.ep[k] = zz(s[4 + k], 8); + } + pairs(&t.rank5, &s[8..24], &mut v.ix); + v + } + + fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { + let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); + let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); + let bits = (0..16).fold(0, |acc, p| { + acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) + }); + out[..2].copy_from_slice(&c0.to_le_bytes()); + out[2..4].copy_from_slice(&c1.to_le_bytes()); + out[4..8].copy_from_slice(&bits.to_le_bytes()); + } + + fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { + let bits = (0..16).fold(0u64, |acc, p| { + acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) + }); + let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; + out[..8].copy_from_slice(&v.to_le_bytes()); + } + + pub fn bc1_pack(v: &Plain, out: &mut [u8]) { + bc1_color(&v.ep, &v.ix, out); + } + + pub fn bc3_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); + bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); + } + + pub fn bc4_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); + } + + pub fn bc5_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); + bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); + } + + /// What `decode` does after the lanes, for `bc` (1, 3, 4 or 5). + pub fn post(bc: u8, t: &Tables, records: &[u8], out: &mut [u8]) -> Result<(), Error> { + let (stride, block) = post_sizes(bc); + let records = records.chunks_exact(stride); + let out = out.chunks_exact_mut(block); + match bc { + 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), + 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), + 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), + _ => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), + } + } + } + + /// Record and block sizes of the plain formats. + fn post_sizes(bc: u8) -> (usize, usize) { + match bc { + 1 => (12, 8), + 3 => (24, 16), + 4 => (12, 8), + _ => (24, 16), + } + } + + /// What `decode` does after the lanes, for `bc` (1, 3, 4 or 5), through the + /// code under test. + fn plain_post(bc: u8, t: &Tables, records: &[u8], out: &mut [u8]) -> Result<(), Error> { + let (stride, block) = post_sizes(bc); + let records = records.chunks_exact(stride); + let out = out.chunks_exact_mut(block); + match bc { + 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), + 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), + 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), + _ => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), + } + } + + /// A small, fixed-seed generator for the block tests. + struct PostRng(u64); + + impl PostRng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + } + + /// The shipped tables, or tables whose rank tables and dictionaries hold + /// any byte. + fn wild_plain_tables(rng: &mut PostRng) -> Tables { + let mut t = Tables::builtin().unwrap(); + for v in t + .rank1 + .iter_mut() + .chain(&mut t.rank3a) + .chain(&mut t.rank3c) + .chain(&mut t.rank4) + .chain(&mut t.rank5) + { + *v = rng.next() as u8; + } + for dictionary in [&mut t.bc1, &mut t.bc3, &mut t.bc4, &mut t.bc5] { + for p in dictionary.iter_mut() { + for v in p.ep.iter_mut().chain(&mut p.ix) { + *v = rng.next() as u8; + } + } + } + t + } + + /// The plain formats' block loops give the reference's bytes for the + /// shipped tables and for tables of arbitrary ranks and dictionaries + /// (history wraps: more blocks than the 256 it keeps). + #[test] + fn plain_blocks_match_the_reference() { + let mut rng = PostRng(0x9e37_79b9_7f4a_7c15); + for round in 0..16 { + let t = if round == 0 { + Tables::builtin().unwrap() + } else { + wild_plain_tables(&mut rng) + }; + for bc in [1, 3, 4, 5] { + let (stride, block) = post_sizes(bc); + let blocks = 700; + let records: Vec = (0..blocks * stride).map(|_| rng.next() as u8).collect(); + let mut got = vec![0u8; blocks * block]; + let mut want = vec![0u8; blocks * block]; + plain_post(bc, &t, &records, &mut got).unwrap(); + reference_plain::post(bc, &t, &records, &mut want).unwrap(); + assert!(got == want, "BC{bc}, round {round}"); + } + } + } + + /// The plain formats' block loops against the reference on the shipped + /// tables: + /// `cargo test --release -p leonida-formats plain_post_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn plain_post_throughput() { + let t = Tables::builtin().unwrap(); + let mut rng = PostRng(0x1234_5678_9abc_def1); + let blocks = 1 << 14; + for bc in [1, 3, 4, 5] { + let (stride, block) = post_sizes(bc); + let random: Vec = (0..blocks * stride).map(|_| rng.next() as u8).collect(); + // Random bytes pick random references: the branches that pick + // them are never right. Without references they always are. + let mut plain = random.clone(); + for record in plain.chunks_exact_mut(stride) { + record[..if bc == 3 || bc == 5 { 4 } else { 2 }].fill(0); + } + for (what, records) in [("random references", &random), ("no references", &plain)] { + let mut dst = vec![0u8; blocks * block]; + let mut want = vec![0u8; blocks * block]; + reference_plain::post(bc, &t, records, &mut want).unwrap(); + plain_post(bc, &t, records, &mut dst).unwrap(); + assert!(dst == want, "BC{bc}, {what}"); + // Alternating batches, the fastest of each (the machine is not ours alone). + let (mut old, mut new) = (f64::MAX, f64::MAX); + for _ in 0..40 { + let started = std::time::Instant::now(); + for _ in 0..3 { + reference_plain::post(bc, &t, std::hint::black_box(records), &mut dst) + .unwrap(); + } + old = old.min(started.elapsed().as_secs_f64() / 3.0); + let started = std::time::Instant::now(); + for _ in 0..3 { + plain_post(bc, &t, std::hint::black_box(records), &mut dst).unwrap(); + } + new = new.min(started.elapsed().as_secs_f64() / 3.0); + } + let (old, new) = (old * 1e9 / blocks as f64, new * 1e9 / blocks as f64); + println!( + "BC{bc} blocks, {what}: reference {old:.1} ns/block, now {new:.1} ns/block ({:.2}x)", + old / new + ); + } + } + } + + /// The eight-at-a-time index codes are the code tables' entries, for + /// every byte at every position (the bytes beside it any). + #[test] + fn index_codes_are_the_tables() { + const BC1_CODE: [u8; 4] = [0, 2, 3, 1]; + let mut rng = PostRng(0x0123_4567_89ab_cdef); + for x in 0..=255u8 { + for at in 0..8 { + let mut bytes = rng.next().to_le_bytes(); + bytes[at] = x; + let word = u64::from_le_bytes(bytes); + let one = bc1_codes(word & 0x0303_0303_0303_0303).to_le_bytes(); + let four = bc4_codes(word).to_le_bytes(); + for k in 0..8 { + assert_eq!( + one[k], + BC1_CODE[usize::from(bytes[k] & 3)], + "BC1 {bytes:?} at {k}" + ); + assert_eq!( + u64::from(four[k]), + BC4_CODE[usize::from(bytes[k] & 7)], + "BC4 {bytes:?} at {k}" + ); + } + } + } + } + + /// The packers put a byte's field where its position says. + #[test] + fn index_codes_pack_by_position() { + let mut rng = PostRng(0xfeed_face_cafe_beef); + for _ in 0..20_000 { + let word = rng.next(); + let (two, three) = (word & 0x0303_0303_0303_0303, word & 0x0707_0707_0707_0707); + let bytes = word.to_le_bytes(); + let want2: u64 = (0..8).map(|k| u64::from(bytes[k] & 3) << (2 * k)).sum(); + let want3: u64 = (0..8).map(|k| u64::from(bytes[k] & 7) << (3 * k)).sum(); + assert_eq!(pack2(two), want2); + assert_eq!(pack3(three), want3); + } + assert_eq!(pack2(0x0303_0303_0303_0303), 0xffff); + assert_eq!(pack3(0x0707_0707_0707_0707), 0xff_ffff); + } + /// Compares with reference outputs made outside the repository: /// `LEONIDA_BCPACK_TABLES` (the table file) and `LEONIDA_BCPACK_CASES`, a /// directory of `.bc` packed chunks with `.out` beside them.