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] 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 0b9edf6317..e11cca3eb0 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); + } }