From 34c0ee5dc8bb299c8af52cfca2c3883db314fc98 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:07:43 -0500 Subject: [PATCH 1/5] DirectStorage: BCPack entropy stage for all modes, not yet called The rANS lanes a BCPack stream is split into, for BC1, BC3, BC4, BC5, BC6H and BC7: a port of the decoder module of Microsoft's silicon-rans sample (MIT), with the byte feeder and symbol release after the format notes of bcpack-decoder and bcpack-rs (MIT, no code taken). The 128 static models are generated by scripts/gen_bcpack_tables.py from the sample. Nothing calls it yet; DirectStorage still refuses BCPack requests. Tested against fixtures from an encoder written independently from the notes (tests/data/bcpack/generate.py) and a round-trip encoder. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 (1M context) --- THIRD_PARTY.md | 2 + crates/xcl/src/hle/bcpack/lanes.rs | 352 +++++++++++++++++++++++ crates/xcl/src/hle/bcpack/mod.rs | 105 +++++++ crates/xcl/src/hle/bcpack/rans_tables.rs | 161 +++++++++++ crates/xcl/src/hle/bcpack/tests.rs | 266 +++++++++++++++++ crates/xcl/src/hle/mod.rs | 1 + scripts/gen_bcpack_tables.py | 63 ++++ tests/data/bcpack/.gitattributes | 3 + tests/data/bcpack/bc1-1-8.bin | Bin 0 -> 61 bytes tests/data/bcpack/bc1-1-8.lanes | Bin 0 -> 12 bytes tests/data/bcpack/bc1-16-1.bin | Bin 0 -> 194 bytes tests/data/bcpack/bc1-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc1-16-9.bin | Bin 0 -> 256 bytes tests/data/bcpack/bc1-16-9.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc1-2-0.bin | Bin 0 -> 90 bytes tests/data/bcpack/bc1-2-0.lanes | Bin 0 -> 24 bytes tests/data/bcpack/bc1-700-2.bin | Bin 0 -> 7082 bytes tests/data/bcpack/bc1-700-2.lanes | Bin 0 -> 8400 bytes tests/data/bcpack/bc1-8192-3.bin | 3 + tests/data/bcpack/bc3-16-1.bin | Bin 0 -> 178 bytes tests/data/bcpack/bc3-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc4-16-1.bin | Bin 0 -> 194 bytes tests/data/bcpack/bc4-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc5-16-1.bin | Bin 0 -> 178 bytes tests/data/bcpack/bc5-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc6-16-1.bin | Bin 0 -> 244 bytes tests/data/bcpack/bc6-16-1.lanes | Bin 0 -> 256 bytes tests/data/bcpack/bc7-16-1.bin | Bin 0 -> 260 bytes tests/data/bcpack/bc7-16-1.lanes | Bin 0 -> 256 bytes tests/data/bcpack/bc7-2-0.bin | Bin 0 -> 121 bytes tests/data/bcpack/bc7-2-0.lanes | Bin 0 -> 32 bytes tests/data/bcpack/bc7-700-2.bin | Bin 0 -> 9735 bytes tests/data/bcpack/bc7-700-2.lanes | Bin 0 -> 11200 bytes tests/data/bcpack/bc7-8192-3.bin | 1 + tests/data/bcpack/generate.py | 186 ++++++++++++ 35 files changed, 1143 insertions(+) create mode 100644 crates/xcl/src/hle/bcpack/lanes.rs create mode 100644 crates/xcl/src/hle/bcpack/mod.rs create mode 100644 crates/xcl/src/hle/bcpack/rans_tables.rs create mode 100644 crates/xcl/src/hle/bcpack/tests.rs create mode 100644 scripts/gen_bcpack_tables.py create mode 100644 tests/data/bcpack/.gitattributes create mode 100644 tests/data/bcpack/bc1-1-8.bin create mode 100644 tests/data/bcpack/bc1-1-8.lanes create mode 100644 tests/data/bcpack/bc1-16-1.bin create mode 100644 tests/data/bcpack/bc1-16-1.lanes create mode 100644 tests/data/bcpack/bc1-16-9.bin create mode 100644 tests/data/bcpack/bc1-16-9.lanes create mode 100644 tests/data/bcpack/bc1-2-0.bin create mode 100644 tests/data/bcpack/bc1-2-0.lanes create mode 100644 tests/data/bcpack/bc1-700-2.bin create mode 100644 tests/data/bcpack/bc1-700-2.lanes create mode 100644 tests/data/bcpack/bc1-8192-3.bin create mode 100644 tests/data/bcpack/bc3-16-1.bin create mode 100644 tests/data/bcpack/bc3-16-1.lanes create mode 100644 tests/data/bcpack/bc4-16-1.bin create mode 100644 tests/data/bcpack/bc4-16-1.lanes create mode 100644 tests/data/bcpack/bc5-16-1.bin create mode 100644 tests/data/bcpack/bc5-16-1.lanes create mode 100644 tests/data/bcpack/bc6-16-1.bin create mode 100644 tests/data/bcpack/bc6-16-1.lanes create mode 100644 tests/data/bcpack/bc7-16-1.bin create mode 100644 tests/data/bcpack/bc7-16-1.lanes create mode 100644 tests/data/bcpack/bc7-2-0.bin create mode 100644 tests/data/bcpack/bc7-2-0.lanes create mode 100644 tests/data/bcpack/bc7-700-2.bin create mode 100644 tests/data/bcpack/bc7-700-2.lanes create mode 100644 tests/data/bcpack/bc7-8192-3.bin create mode 100644 tests/data/bcpack/generate.py diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 4afc9f29d..f1c75771f 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -10,6 +10,8 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | [FFmpeg](https://ffmpeg.org/) | LGPL-2.1+ | XMA1/XMA2 decoder and tables (`crates/xcl/src/hle/xma2/`) – after `libavcodec/wmaprodec.c`, `wmaprodata.h`, `wma.c`, `sinewin_tablegen.h`, `libavutil/float_dsp.c`, `tx_template.c` | port to safe Rust with annotation | | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | +| [silicon-rans](https://github.com/microsoft/silicon-rans) (Microsoft) | MIT | BCPack entropy stage: the rANS lane in `crates/xcl/src/hle/bcpack/lanes.rs` (after the `decoder` module of `mdu_minirans.v`) and its model tables in `hle/bcpack/rans_tables.rs` (generated by `scripts/gen_bcpack_tables.py` from the same file) | port to Rust with annotation; tables | +| [bcpack-decoder](https://github.com/Tim0219800/bcpack-decoder) (Tim0219800), [bcpack-rs](https://github.com/Ahmet-Dedeler/bcpack-rs) (Ahmet Dedeler) | MIT | no code; the BCPack stream layout, lane widths and byte feeder rule in `hle/bcpack/` follow their format notes (`docs/SPEC.md`, `docs/BCPACK_SPEC.md`) | specification | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/hle/bcpack/lanes.rs b/crates/xcl/src/hle/bcpack/lanes.rs new file mode 100644 index 000000000..54e45a8db --- /dev/null +++ b/crates/xcl/src/hle/bcpack/lanes.rs @@ -0,0 +1,352 @@ +//! The entropy stage of BCPack: a set of rANS decoders ("lanes") that share one byte stream. +//! +//! Every lane yields one symbol per 8 bytes of output. A lane's own bytes are a chain of +//! fragments, each a 2- or 3-byte header and its payload: +//! * byte 0: bits 0–3 the model `q`, bit 4 "reset the state when this fragment ends", bit 5 +//! "a third header byte follows", bits 6–7 `z`, by how many bits this fragment's symbols are +//! narrower than the lane's, +//! * the payload length: byte 1 plus 1, or with a third byte `(byte 2 << 8 | byte 1) + 257`; +//! it counts every byte the lane reads in the fragment, the first state bytes included. +//! +//! The state is 32 bits with the lower limit `L` = 2^24 and 16-bit probabilities; a byte is +//! shifted in while it is below `L`, a symbol leaves while it is above. A fragment's encoder +//! started at `L`, so a decoded fragment ends there, or at `L >> 8` / `L >> 16` when the +//! encoder dropped trailing zero bytes. +//! +//! Which lane gets which byte of the stream is decided clock by clock, as in the hardware: +//! * each lane holds one byte of input and one symbol of output; in a clock it first applies +//! its last symbol to the state and takes a byte, then reads a header byte or shifts the byte +//! in and decodes, +//! * the lanes that ask for a byte are served in lane order, eight bytes a clock at most; a +//! lane that asked and got none does nothing in that clock, +//! * a lane hands its symbol over only when its place in the symbol vector is free, and the +//! places are freed together when every lane has filled its own. A lane with a symbol it +//! cannot hand over does nothing either. +//! +//! The lane is a port of the `decoder` module of Microsoft's silicon-rans sample +//! (https://github.com/microsoft/silicon-rans, `mdu_minirans.v` at commit 2f6827d, Copyright (c) +//! Microsoft Corporation, MIT), made for XCL on 2026-11-23: same registers, same two phases, +//! same control states. The sample leaves the feeder and the symbol vector out; the two rules +//! above are from the public format notes of bcpack-decoder +//! (https://github.com/Tim0219800/bcpack-decoder, `docs/SPEC.md`) and bcpack-rs +//! (https://github.com/Ahmet-Dedeler/bcpack-rs, `docs/BCPACK_SPEC.md`), both MIT, which report +//! them as checked against retail streams; no code was taken from either. + +use super::rans_tables::FREQ; +use super::Error; + +/// The lower limit of the rANS state. +pub const L: u32 = 1 << 24; +/// Bytes the feeder hands out per clock. +const FEED_WINDOW: usize = 8; + +/// One of the 16 static models at one symbol width: the cumulative base and the per-symbol +/// frequency of each segment. Segment 0 is symbol 0, segment k >= 1 the symbols +/// `2^(k-1) .. 2^k`. Slot 0 belongs to no symbol: symbol 0 starts at slot 1. +#[derive(Clone, Copy)] +struct Model { + /// `base[k]` for the segments in use, 65536 for the rest + base: [u32; 10], + freq: [u32; 9], +} + +impl Model { + fn new(bits: usize, q: usize) -> Self { + let mut m = Model { base: [65536; 10], freq: [1; 9] }; + let mut at = 0u32; + for k in 0..=bits { + m.base[k] = at; + m.freq[k] = FREQ[bits - 1][q][k] as u32; + at += m.freq[k] * if k < 2 { 1 } else { 1 << (k - 1) }; + } + m + } + + /// The symbol of slot `cf` (1..=65535). + fn symbol(&self, cf: u32) -> u32 { + let mut seg = 0; + for k in 1..9 { + seg += (cf >= self.base[k]) as usize; + } + ((1u32 << seg) >> 1) + (cf - self.base[seg]) / self.freq[seg] + } + + /// The state after `sym` left state `x`. + fn advance(&self, x: u32, sym: u32) -> u32 { + let seg = (32 - sym.leading_zeros()) as usize; + let cfa = self.base[seg] + self.freq[seg] * (sym - ((1u32 << seg) >> 1)); + let (f, cf) = if cfa == 0 { (self.freq[seg] - 1, 1) } else { (self.freq[seg], cfa) }; + f.wrapping_mul(x >> 16).wrapping_add(x & 0xFFFF).wrapping_sub(cf) + } +} + +/// Where a fragment's decoding may end: the state its encoder started from, less the zero +/// bytes (two at most) the encoder's first symbol pushed out and the encoder did not store. +fn is_end_state(x: u32) -> bool { + x == L || x == L >> 8 || x == L >> 16 +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Ctrl { + Hdr0, + Hdr1, + Hdr2, + Processing, + /// the fragment's bytes are all in the state; symbols still leave + Draining, + Done, +} + +struct Lane { + /// the lane's symbol width + bits: u8, + ctrl: Ctrl, + input_buf: u8, + input_buf_full: bool, + sym: u32, + sym_buf_full: bool, + /// its place in the symbol vector is taken + slot_full: bool, + input_remaining: u32, + output_remaining: u32, + /// the state after the last symbol was applied + p0: u32, + /// the state the symbol in `sym` was read from + p1: u32, + hdr3: bool, + flush: bool, + q: u8, + model: Model, + stalled: bool, +} + +/// Decode the lanes of one stream: `widths[i]` is lane i's symbol width in bits (1..=8), +/// `units` the number of symbols every lane holds. The symbols come back unit by unit +/// (`symbols[unit * lanes + lane]`), with the number of bytes of `src` the lanes read. +pub(super) fn decode(src: &[u8], widths: &[u8], units: usize) -> Result<(Vec, usize), Error> { + let mut pos = 0; + let symbols = run(widths, units, |_| { + let b = src.get(pos).copied(); + pos += b.is_some() as usize; + b + })?; + Ok((symbols, pos)) +} + +/// [`decode`] with the stream as a function: the next byte, for the lane that gets it. +pub(super) fn run(widths: &[u8], units: usize, mut next: impl FnMut(usize) -> Option) -> Result, Error> { + let n = widths.len(); + assert!(n > 0 && widths.iter().all(|w| (1..=8).contains(w))); + if units == 0 { + return Ok(Vec::new()); + } + if units > u32::MAX as usize { + return Err(Error::OutputSize); + } + // grows with the units the stream really yields: the size a request names costs nothing + let mut symbols: Vec = Vec::new(); + let mut lanes: Vec = widths + .iter() + .map(|&bits| Lane { + bits, + ctrl: Ctrl::Hdr0, + input_buf: 0, + input_buf_full: false, + sym: 0, + sym_buf_full: false, + slot_full: false, + input_remaining: 0, + output_remaining: units as u32, + p0: 0, + p1: 0, + hdr3: false, + flush: false, + q: 0, + model: Model::new(bits as usize, 0), + stalled: false, + }) + .collect(); + let mut released = 0usize; + + // a lane is done when it has its symbols and has read its last fragment to the end + while lanes.iter().any(|l| l.ctrl != Ctrl::Done || l.sym_buf_full) { + let mut progress = false; + + // phase 0: the feeder fills input buffers, a lane applies its symbol and hands it over + let mut served = 0; + for (i, l) in lanes.iter_mut().enumerate() { + let blocked_on_output = l.sym_buf_full && l.slot_full; + let need = !l.input_buf_full + && match l.ctrl { + Ctrl::Hdr0 | Ctrl::Hdr1 | Ctrl::Hdr2 => true, + Ctrl::Processing => l.input_remaining > 0, + Ctrl::Draining | Ctrl::Done => false, + }; + let mut fed = None; + if need && !blocked_on_output && served < FEED_WINDOW { + // the stream never grows: a lane that waits for a byte past its end waits forever + let Some(b) = next(i) else { return Err(Error::Truncated { lane: i }) }; + fed = Some(b); + served += 1; + } + l.stalled = blocked_on_output || (need && fed.is_none()); + if l.stalled { + continue; + } + if matches!(l.ctrl, Ctrl::Processing | Ctrl::Draining) { + let p0 = if l.sym_buf_full { l.model.advance(l.p1, l.sym) } else { l.p1 }; + progress |= p0 != l.p0; + l.p0 = p0; + } + if let Some(b) = fed { + l.input_buf = b; + l.input_buf_full = true; + progress = true; + } + if l.sym_buf_full { + // the lane's last symbol leaves a state its encoder started from + let done = units - l.output_remaining as usize; + if l.output_remaining == 0 { + if !is_end_state(l.model.advance(l.p1, l.sym)) { + return Err(Error::EndState { lane: i }); + } + } + if symbols.len() < done * n { + symbols.try_reserve(n).map_err(|_| Error::OutputSize)?; + symbols.resize(done * n, 0); + } + symbols[(done - 1) * n + i] = l.sym as u8; + l.sym_buf_full = false; + l.slot_full = true; + progress = true; + } + } + + // phase 1: header bytes, or a byte into the state and a symbol out of it + for (i, l) in lanes.iter_mut().enumerate() { + if l.stalled { + continue; + } + match l.ctrl { + Ctrl::Hdr0 => { + if l.input_buf_full { + let b = l.input_buf; + l.input_buf_full = false; + l.input_remaining = 0; + l.q = b & 15; + l.flush = b & 0x10 != 0; + l.hdr3 = b & 0x20 != 0; + let z = b >> 6; + if z >= l.bits { + return Err(Error::Width { lane: i }); + } + l.model = Model::new((l.bits - z) as usize, l.q as usize); + l.ctrl = Ctrl::Hdr1; + progress = true; + } + } + Ctrl::Hdr1 => { + if l.input_buf_full { + l.input_buf_full = false; + if l.hdr3 { + l.input_remaining = l.input_buf as u32; + l.ctrl = Ctrl::Hdr2; + } else { + l.input_remaining = l.input_buf as u32 + 1; + l.ctrl = Ctrl::Processing; + } + progress = true; + } + } + Ctrl::Hdr2 => { + if l.input_buf_full { + l.input_buf_full = false; + l.input_remaining = ((l.input_buf as u32) << 8 | l.input_remaining) + 257; + l.ctrl = Ctrl::Processing; + progress = true; + } + } + Ctrl::Processing => { + let feed = l.p0 < L && l.input_remaining > 0 && l.input_buf_full; + let x = if feed { l.p0 << 8 | l.input_buf as u32 } else { l.p0 }; + let out = x > L && l.output_remaining > 0; + if out { + l.sym = l.model.symbol(x & 0xFFFF); + if x & 0xFFFF == 0 { + return Err(Error::Symbol { lane: i }); + } + l.output_remaining -= 1; + } + progress |= feed || out || x != l.p1; + l.p1 = x; + l.sym_buf_full = out; + if feed { + l.input_buf_full = false; + l.input_remaining -= 1; + } + if l.input_remaining == 0 { + progress = true; + if l.output_remaining == 0 { + l.ctrl = Ctrl::Done; + } else if x == L { + l.ctrl = Ctrl::Hdr0; + if l.flush { + l.p1 = 0; + } + } else { + l.ctrl = Ctrl::Draining; + } + } + } + Ctrl::Draining => { + let x = l.p0; + let out = x > L && l.output_remaining > 0; + if out { + l.sym = l.model.symbol(x & 0xFFFF); + if x & 0xFFFF == 0 { + return Err(Error::Symbol { lane: i }); + } + l.output_remaining -= 1; + } + progress |= out || x != l.p1; + l.p1 = x; + l.sym_buf_full = out; + if x <= L { + progress = true; + if l.output_remaining == 0 { + l.ctrl = Ctrl::Done; + } else { + l.ctrl = Ctrl::Hdr0; + if l.flush { + // The hardware drops whatever state is left here. A state that + // is thrown away took symbols with it unless it is where the + // fragment's encoder started, so anything else is damage. + if !is_end_state(x) { + return Err(Error::EndState { lane: i }); + } + l.p0 = 0; + l.p1 = 0; + } + } + } + } + Ctrl::Done => {} + } + } + + // the symbol vector leaves when every lane has put its symbol in + if lanes.iter().all(|l| l.slot_full) { + for l in lanes.iter_mut() { + l.slot_full = false; + } + released += 1; + progress = true; + } + if !progress { + // nothing moved in a whole clock, so nothing ever will + return Err(Error::Stuck); + } + } + debug_assert_eq!((released, symbols.len()), (units, units * n)); + Ok(symbols) +} diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs new file mode 100644 index 000000000..e35c2c062 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -0,0 +1,105 @@ +//! BCPack, the console's lossless packing of BCn texture blocks (`DSTORAGE_BCPACK_MODE`, the +//! DirectStorage stage between zlib and swizzle): a stream unpacks to plain BCn blocks. +//! +//! A stream has no header. The fields of the blocks are split over 12 or 16 rANS lanes, one +//! symbol per lane for every 8 bytes of output, and the lanes share the byte stream +//! (`lanes.rs`). The blocks are then rebuilt from the symbols; that part differs per format. +//! +//! What is here: the entropy stage for BC1, BC3, BC4, BC5, BC6H and BC7 ([`lane_widths`]); no +//! lane layout is published for BC2. Nothing calls it yet: DirectStorage still refuses every +//! request with a BCPack stage. +//! +//! What is not: the rebuild of blocks from the symbols, for any format. +//! +//! Nothing here was compared with what a console writes for the same input: the entropy stage +//! follows Microsoft's published decoder sample and the public format notes of bcpack-decoder +//! (Tim0219800) and bcpack-rs (Ahmet Dedeler), both MIT, whose authors report them as matching +//! retail streams. The tests check against streams built independently from those notes +//! (`tests/data/bcpack`), not against hardware output. + +mod lanes; +mod rans_tables; + +/// Why a stream was not unpacked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// no lane layout for this mode + Unsupported, + /// the output is not a whole number of blocks, or too large + OutputSize, + /// the stream ends before the lane has its bytes + Truncated { lane: usize }, + /// a fragment narrows the lane's symbols to nothing + Width { lane: usize }, + /// the state points at the slot no symbol has + Symbol { lane: usize }, + /// the lane's last symbol leaves a state no encoder starts from + EndState { lane: usize }, + /// the lanes wait for each other or for a byte their fragments do not have + Stuck, + /// bytes other than zero padding follow the stream + Trailing { consumed: usize }, +} + +impl Error { + /// The kind of failure, without its numbers. + pub fn kind(&self) -> &'static str { + match self { + Error::Unsupported => "unsupported", + Error::OutputSize => "output size", + Error::Truncated { .. } => "truncated", + Error::Width { .. } => "width", + Error::Symbol { .. } => "reserved slot", + Error::EndState { .. } => "end state", + Error::Stuck => "stuck", + Error::Trailing { .. } => "trailing data", + } + } +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + Error::Unsupported => write!(f, "no decoder for this mode"), + Error::OutputSize => write!(f, "the output size is not a whole number of blocks"), + Error::Truncated { lane } => write!(f, "the stream ends while lane {lane} waits for a byte"), + Error::Width { lane } => write!(f, "a fragment of lane {lane} narrows its symbols to nothing"), + Error::Symbol { lane } => write!(f, "lane {lane} reads the reserved slot"), + Error::EndState { lane } => write!(f, "lane {lane} ends in a state no encoder starts from"), + Error::Stuck => write!(f, "the lanes cannot go on"), + Error::Trailing { consumed } => write!(f, "data follows the stream's {consumed} bytes"), + } + } +} + +/// The symbol width of each lane of a `DSTORAGE_BCPACK_MODE` (1 BC1 … 7 BC7), in stream order. +/// Every lane holds one symbol per 8 bytes of output: one per BC1/BC4 block, two per 16-byte +/// block. +pub fn lane_widths(mode: u8) -> Option<&'static [u8]> { + Some(match mode { + 1 => &[8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8], + 3 => &[4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8], + 4 => &[8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6], + 5 => &[4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6], + 6 => &[4, 4, 8, 8, 8, 5, 5, 5, 6, 6, 6, 8, 8, 8, 8, 5], + 7 => &[4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5], + _ => return None, + }) +} + +/// The symbols of a stream that unpacks to `out_len` bytes, unit by unit +/// (`symbols[unit * lanes + lane]`). Zero padding may follow the stream. +pub fn decode_lanes(mode: u8, src: &[u8], out_len: usize) -> Result, Error> { + let widths = lane_widths(mode).ok_or(Error::Unsupported)?; + if out_len % 8 != 0 { + return Err(Error::OutputSize); + } + let (symbols, consumed) = lanes::decode(src, widths, out_len / 8)?; + if src[consumed..].iter().any(|&b| b != 0) { + return Err(Error::Trailing { consumed }); + } + Ok(symbols) +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/xcl/src/hle/bcpack/rans_tables.rs b/crates/xcl/src/hle/bcpack/rans_tables.rs new file mode 100644 index 000000000..7466a9c58 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/rans_tables.rs @@ -0,0 +1,161 @@ +// Generated by scripts/gen_bcpack_tables.py from Microsoft's silicon-rans sample (mdu_minirans.v, +// https://github.com/microsoft/silicon-rans commit 2f6827d): Copyright (c) Microsoft Corporation, MIT. +// `FREQ[bits - 1][q][segment]`: the frequency of each symbol of a segment, out of 65536. Segment 0 +// is symbol 0, segment k >= 1 is the symbols 2^(k-1) .. 2^k - 1. + +#![allow(clippy::unreadable_literal)] + +pub static FREQ: [[[u16; 9]; 16]; 8] = [ + // 1-bit alphabet + [ + [32768, 32768, 0, 0, 0, 0, 0, 0, 0], + [38761, 26775, 0, 0, 0, 0, 0, 0, 0], + [44484, 21052, 0, 0, 0, 0, 0, 0, 0], + [49818, 15718, 0, 0, 0, 0, 0, 0, 0], + [54623, 10913, 0, 0, 0, 0, 0, 0, 0], + [58721, 6815, 0, 0, 0, 0, 0, 0, 0], + [61911, 3625, 0, 0, 0, 0, 0, 0, 0], + [64036, 1500, 0, 0, 0, 0, 0, 0, 0], + [65121, 415, 0, 0, 0, 0, 0, 0, 0], + [65477, 59, 0, 0, 0, 0, 0, 0, 0], + [65534, 2, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + ], + // 2-bit alphabet + [ + [16384, 16384, 16384, 0, 0, 0, 0, 0, 0], + [21168, 17592, 13388, 0, 0, 0, 0, 0, 0], + [26354, 18130, 10526, 0, 0, 0, 0, 0, 0], + [31900, 17918, 7859, 0, 0, 0, 0, 0, 0], + [37750, 16874, 5456, 0, 0, 0, 0, 0, 0], + [43800, 14920, 3408, 0, 0, 0, 0, 0, 0], + [49850, 12062, 1812, 0, 0, 0, 0, 0, 0], + [55537, 8499, 750, 0, 0, 0, 0, 0, 0], + [60308, 4812, 208, 0, 0, 0, 0, 0, 0], + [63575, 1901, 30, 0, 0, 0, 0, 0, 0], + [65132, 402, 1, 0, 0, 0, 0, 0, 0], + [65511, 23, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + ], + // 3-bit alphabet + [ + [8192, 8192, 8192, 8192, 0, 0, 0, 0, 0], + [11073, 10095, 8796, 6694, 0, 0, 0, 0, 0], + [14406, 11948, 9065, 5263, 0, 0, 0, 0, 0], + [18234, 13666, 8958, 3930, 0, 0, 0, 0, 0], + [22624, 15126, 8437, 2728, 0, 0, 0, 0, 0], + [27657, 16143, 7460, 1704, 0, 0, 0, 0, 0], + [33414, 16436, 6031, 906, 0, 0, 0, 0, 0], + [39920, 15616, 4250, 375, 0, 0, 0, 0, 0], + [47024, 13284, 2406, 104, 0, 0, 0, 0, 0], + [54201, 9375, 950, 15, 0, 0, 0, 0, 0], + [60388, 4744, 200, 1, 0, 0, 0, 0, 0], + [64250, 1262, 10, 1, 0, 0, 0, 0, 0], + [65456, 74, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + ], + // 4-bit alphabet + [ + [4096, 4096, 4096, 4096, 4096, 0, 0, 0, 0], + [5665, 5407, 5048, 4398, 3347, 0, 0, 0, 0], + [7539, 6867, 5973, 4532, 2632, 0, 0, 0, 0], + [9773, 8461, 6833, 4479, 1965, 0, 0, 0, 0], + [12447, 10177, 7564, 4218, 1364, 0, 0, 0, 0], + [15679, 11977, 8072, 3730, 852, 0, 0, 0, 0], + [19640, 13774, 8217, 3016, 453, 0, 0, 0, 0], + [24559, 15361, 7808, 2124, 188, 0, 0, 0, 0], + [30704, 16320, 6642, 1203, 52, 0, 0, 0, 0], + [38280, 15920, 4688, 476, 7, 0, 0, 0, 0], + [47169, 13219, 2372, 99, 1, 0, 0, 0, 0], + [56354, 7896, 631, 4, 1, 0, 0, 0, 0], + [63248, 2208, 34, 1, 1, 0, 0, 0, 0], + [65465, 57, 1, 1, 1, 0, 0, 0, 0], + [65521, 1, 1, 1, 1, 0, 0, 0, 0], + [65521, 1, 1, 1, 1, 0, 0, 0, 0], + ], + // 5-bit alphabet + [ + [2048, 2048, 2048, 2048, 2048, 2048, 0, 0, 0], + [2865, 2799, 2704, 2524, 2200, 1673, 0, 0, 0], + [3858, 3682, 3434, 2986, 2266, 1316, 0, 0, 0], + [5063, 4709, 4230, 3418, 2240, 982, 0, 0, 0], + [6536, 5912, 5088, 3782, 2109, 682, 0, 0, 0], + [8366, 7314, 5988, 4036, 1865, 426, 0, 0, 0], + [10688, 8952, 6888, 4108, 1507, 227, 0, 0, 0], + [13713, 10847, 7680, 3904, 1062, 94, 0, 0, 0], + [17758, 12946, 8160, 3320, 602, 26, 0, 0, 0], + [23272, 15008, 7960, 2344, 237, 4, 0, 0, 0], + [30841, 16327, 6610, 1187, 48, 1, 0, 0, 0], + [41006, 15348, 3947, 316, 1, 1, 0, 0, 0], + [53291, 9957, 1104, 14, 1, 1, 0, 0, 0], + [63380, 2084, 22, 1, 1, 1, 0, 0, 0], + [65505, 1, 1, 1, 1, 1, 0, 0, 0], + [65505, 1, 1, 1, 1, 1, 0, 0, 0], + ], + // 6-bit alphabet + [ + [1024, 1024, 1024, 1024, 1024, 1024, 1024, 0, 0], + [1441, 1423, 1400, 1352, 1262, 1099, 837, 0, 0], + [1951, 1907, 1841, 1717, 1493, 1133, 658, 0, 0], + [2577, 2487, 2354, 2115, 1709, 1120, 491, 0, 0], + [3350, 3186, 2956, 2544, 1890, 1055, 341, 0, 0], + [4324, 4042, 3657, 2994, 2019, 932, 213, 0, 0], + [5581, 5107, 4476, 3444, 2055, 754, 113, 0, 0], + [7258, 6454, 5424, 3840, 1952, 531, 47, 0, 0], + [9579, 8179, 6473, 4080, 1660, 301, 13, 0, 0], + [12907, 10365, 7504, 3980, 1171, 119, 2, 0, 0], + [17852, 12988, 8164, 3304, 594, 23, 1, 0, 0], + [25441, 15565, 7673, 1974, 155, 1, 1, 0, 0], + [37208, 16084, 4978, 552, 4, 1, 1, 0, 0], + [53649, 9731, 1042, 4, 1, 1, 1, 0, 0], + [65147, 327, 1, 1, 1, 1, 1, 0, 0], + [65473, 1, 1, 1, 1, 1, 1, 0, 0], + ], + // 7-bit alphabet + [ + [512, 512, 512, 512, 512, 512, 512, 512, 0], + [722, 718, 712, 700, 676, 632, 550, 418, 0], + [981, 971, 952, 920, 858, 748, 566, 329, 0], + [1300, 1276, 1244, 1178, 1058, 854, 559, 246, 0], + [1696, 1654, 1593, 1478, 1272, 946, 526, 171, 0], + [2198, 2126, 2022, 1828, 1498, 1009, 467, 106, 0], + [2852, 2728, 2554, 2238, 1721, 1028, 376, 57, 0], + [3736, 3522, 3227, 2712, 1920, 977, 266, 23, 0], + [4979, 4601, 4090, 3236, 2040, 831, 151, 6, 0], + [6807, 6101, 5182, 3752, 1991, 586, 59, 1, 0], + [9634, 8218, 6494, 4082, 1652, 296, 11, 1, 0], + [14275, 11165, 7784, 3836, 988, 74, 1, 1, 0], + [22449, 14759, 8042, 2489, 272, 1, 1, 1, 0], + [37625, 16023, 4866, 509, 1, 1, 1, 1, 0], + [60485, 4663, 132, 1, 1, 1, 1, 1, 0], + [65409, 1, 1, 1, 1, 1, 1, 1, 0], + ], + // 8-bit alphabet + [ + [256, 256, 256, 256, 256, 256, 256, 256, 256], + [362, 360, 359, 356, 350, 338, 316, 275, 209], + [492, 488, 486, 476, 460, 429, 374, 284, 164], + [653, 647, 638, 622, 589, 529, 426, 280, 123], + [853, 843, 828, 796, 739, 636, 473, 264, 85], + [1108, 1090, 1063, 1011, 914, 748, 504, 234, 53], + [1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28], + [1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12], + [2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3], + [3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1], + [5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1], + [7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1], + [12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1], + [22767, 14857, 8012, 2432, 240, 1, 1, 1, 1], + [47343, 13141, 2332, 35, 1, 1, 1, 1, 1], + [65281, 1, 1, 1, 1, 1, 1, 1, 1], + ], +]; diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs new file mode 100644 index 000000000..ff82c01fa --- /dev/null +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -0,0 +1,266 @@ +//! Tests of the BCPack decoder on synthetic streams: the fixtures of `tests/data/bcpack` +//! (built by its `generate.py`, an encoder written from the format notes and not from this +//! decoder) and streams of the encoder below. None of them shows what a console would write. + +use super::lanes::{self, L}; +use super::rans_tables::FREQ; +use super::{decode_lanes, lane_widths, Error}; + +pub(crate) fn data(name: &str) -> Option> { + std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack").join(name)).ok() +} + +/// `bc--` → (mode, units) +fn fixture(stem: &str) -> (u8, usize) { + let mut p = stem.strip_prefix("bc").unwrap().split('-'); + (p.next().unwrap().parse().unwrap(), p.next().unwrap().parse().unwrap()) +} + +/// A `.lanes` file (all of lane 0, then lane 1 …) in the decoder's order. +fn by_unit(lane_major: &[u8], lanes: usize) -> Vec { + let units = lane_major.len() / lanes; + (0..units * lanes).map(|i| lane_major[(i % lanes) * units + i / lanes]).collect() +} + +const FIXTURES: [&str; 14] = [ + "bc1-1-8", "bc1-2-0", "bc1-16-1", "bc1-16-9", "bc1-700-2", "bc1-8192-3", "bc3-16-1", "bc4-16-1", "bc5-16-1", "bc6-16-1", "bc7-2-0", "bc7-16-1", + "bc7-700-2", "bc7-8192-3", +]; + +/// The symbols of the two 64 KiB fixtures, which ship without a `.lanes` file (`generate.py`). +pub(crate) fn large_fixture_symbols(mode: u8) -> Vec { + let n = lane_widths(mode).unwrap().len(); + let mut s = vec![0u8; 8192 * n]; + if mode == 1 { + for i in (0..8192).step_by(511) { + s[i * n + 2] = 30; + s[i * n + 8] = 5; + } + for i in (31..8192).step_by(31) { + s[i * n] = 2; + } + } + s +} + +#[test] +fn fixtures_decode_to_their_lanes() { + for stem in FIXTURES { + let (mode, units) = fixture(stem); + let n = lane_widths(mode).unwrap().len(); + let bin = data(&format!("{stem}.bin")).unwrap(); + let want = match data(&format!("{stem}.lanes")) { + Some(l) => by_unit(&l, n), + None => large_fixture_symbols(mode), + }; + assert_eq!(want.len(), units * n, "{stem}"); + // bc1-1-8 has states cut to fewer bytes than an encoder that starts at `L` can drop, + // which the hardware's decoder does not take either + if stem == "bc1-1-8" { + assert!(decode_lanes(mode, &bin, units * 8).is_err(), "{stem}"); + continue; + } + assert_eq!(decode_lanes(mode, &bin, units * 8).as_deref(), Ok(&want[..]), "{stem}"); + // zero padding after the stream is not part of it; anything else is + let mut padded = bin.clone(); + padded.extend([0; 37]); + assert_eq!(decode_lanes(mode, &padded, units * 8).as_deref(), Ok(&want[..]), "{stem} padded"); + padded.push(1); + assert_eq!(decode_lanes(mode, &padded, units * 8), Err(Error::Trailing { consumed: bin.len() }), "{stem}"); + } +} + +/// The 8-bit model 11 as US 11,234,023 prints it (its `base_table[8][12]`, counted from 1). +#[test] +fn model_matches_the_patent_excerpt() { + let base = [0u32, 7575, 14276, 25440, 41008, 56352, 64256, 65344, 65408]; + let freq = [7575u16, 6701, 5582, 3892, 1918, 494, 34, 1, 1]; + assert_eq!(FREQ[7][11], freq); + let mut at = 0; + for k in 0..9 { + assert_eq!(at, base[k]); + at += freq[k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }; + } + assert_eq!(at, 65536); + for (bits, per_q) in FREQ.iter().enumerate() { + for f in per_q { + let total: u32 = (0..9).map(|k| f[k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }).sum(); + assert_eq!(total, 65536); + assert!(f[..bits + 2].iter().all(|&v| v >= 1) && f[bits + 2..].iter().all(|&v| v == 0)); + } + } +} + +// --------------------------------------------------------------------------------------- +// a test encoder: any model, any fragment sizes +// --------------------------------------------------------------------------------------- + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) as u32 + } + fn below(&mut self, n: u32) -> u32 { + self.next() % n + } +} + +/// (frequency, first slot) of `sym` in model (`bits`, `q`). +fn slot(bits: usize, q: usize, sym: u32) -> (u32, u32) { + let seg = (32 - sym.leading_zeros()) as usize; + let base: u32 = (0..seg).map(|k| FREQ[bits - 1][q][k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }).sum(); + let f = FREQ[bits - 1][q][seg] as u32; + let cf = base + f * (sym - ((1u32 << seg) >> 1)); + if cf == 0 { + (f - 1, 1) + } else { + (f, cf) + } +} + +/// One flushed fragment: header, state, payload. `trim`: drop the zero bytes an encoder +/// that starts at `L` may drop (those its first symbol pushed out). +fn fragment(symbols: &[u8], lane_bits: usize, z: usize, q: usize, trim: bool) -> Vec { + let mut x = L; + let mut emitted = Vec::new(); + let mut droppable = 0; + for (k, &s) in symbols.iter().rev().enumerate() { + let (f, cf) = slot(lane_bits - z, q, s as u32); + while x >= f << 16 { + emitted.push(x as u8); + x >>= 8; + } + if k == 0 { + droppable = emitted.len(); + } + x = (x / f) << 16 | (x % f + cf); + } + let mut body = x.to_be_bytes().to_vec(); + body.extend(emitted.iter().rev()); + if trim { + body.truncate(body.len() - droppable); + } + let mode = (z << 6 | 0x10 | q) as u8; + let mut out = if body.len() <= 256 { + vec![mode, (body.len() - 1) as u8] + } else { + let n = body.len() - 257; + vec![mode | 0x20, n as u8, (n >> 8) as u8] + }; + out.extend(body); + out +} + +/// A stream of random symbols and fragments, with its symbols (the decoder's order). The +/// lanes' bytes are put in the order the decoder asks for them, so this checks the decoder +/// against the encoder's arithmetic and itself, not the byte order against anything. +fn random_stream(widths: &[u8], units: usize, rng: &mut Rng) -> (Vec, Vec) { + let n = widths.len(); + let mut symbols = vec![0u8; units * n]; + let mut queues: Vec> = Vec::new(); + for (l, &w) in widths.iter().enumerate() { + let mut bytes = Vec::new(); + let mut at = 0; + while at < units { + let longest = if rng.below(4) == 0 { 700 } else { 40 }; + let len = (1 + rng.below(longest) as usize).min(units - at); + let z = rng.below(4).min(w as u32 - 1) as usize; + let q = rng.below(16) as usize; + let bits = w as usize - z; + // the steeper models leave one slot to most symbols: keep those symbols rare + let frag: Vec = (0..len) + .map(|_| { + let top = if q >= 8 && rng.below(8) != 0 { 1u32 << bits.min(2) } else { 1 << bits }; + rng.below(top) as u8 + }) + .collect(); + for (k, &s) in frag.iter().enumerate() { + symbols[(at + k) * n + l] = s; + } + bytes.extend(fragment(&frag, w as usize, z, q, rng.below(2) == 0)); + at += len; + } + queues.push(bytes.into()); + } + let mut stream = Vec::new(); + let got = lanes::run(widths, units, |lane| { + let b = queues[lane].pop_front(); + stream.extend(b); + b + }) + .expect("the encoder's own fragments decode"); + assert_eq!(got, symbols); + assert!(queues.iter().all(|q| q.is_empty()), "every fragment was read to its end"); + (stream, symbols) +} + +#[test] +fn random_streams_round_trip_in_every_model() { + let mut rng = Rng(0x5EED); + let dump = std::env::var_os("XCL_BCPACK_DUMP").map(std::path::PathBuf::from); + for round in 0..60 { + for mode in [1u8, 3, 4, 5, 6, 7] { + let widths = lane_widths(mode).unwrap(); + let units = [1, 2, 7, 64, 300, 2048][round % 6] * if mode == 1 || mode == 4 { 1 } else { 2 }; + let (stream, symbols) = random_stream(widths, units, &mut rng); + assert_eq!(decode_lanes(mode, &stream, units * 8).as_deref(), Ok(&symbols[..]), "mode {mode} round {round}"); + // every byte of the stream is needed + assert!(decode_lanes(mode, &stream[..stream.len() - 1], units * 8).is_err()); + if let Some(dir) = &dump { + // for a comparison with other decoders: the stream and its lanes, lane by lane + let stem = dir.join(format!("r{round}-bc{mode}-{units}")); + let n = widths.len(); + let lane_major: Vec = (0..units * n).map(|i| symbols[(i % units) * n + i / units]).collect(); + std::fs::write(stem.with_extension("bin"), &stream).unwrap(); + std::fs::write(stem.with_extension("lanes"), lane_major).unwrap(); + } + } + } +} + +/// Damaged input ends in an answer, never a panic or a hang. (The answer can be other +/// symbols: a stream has no checksum, and under a uniform model any bytes are symbols.) +#[test] +fn damaged_streams_end_cleanly() { + let mut rng = Rng(7); + for stem in ["bc1-2-0", "bc1-16-1", "bc1-16-9", "bc7-16-1", "bc1-700-2", "bc7-700-2"] { + let (mode, units) = fixture(stem); + let bin = data(&format!("{stem}.bin")).unwrap(); + let check = |bytes: &[u8], units: usize| decode_lanes(mode, bytes, units * 8); + // every byte of a stream is some lane's: a shorter one is never whole + for cut in (0..bin.len()).step_by((bin.len() / 300).max(1)) { + assert!(check(&bin[..cut], units).is_err(), "{stem} cut at {cut}"); + } + for _ in 0..400 { + let mut b = bin.clone(); + let at = rng.below(b.len() as u32) as usize; + match rng.below(3) { + 0 => b[at] ^= 1 << rng.below(8), + 1 => b[at] = rng.next() as u8, + _ => { + b.remove(at); + } + } + let _ = check(&b, units); + } + // the wrong number of blocks, and a size that is no number of blocks + assert!(check(&bin, units + 1).is_err()); + assert!(check(&bin, units - 1).is_err()); + assert_eq!(decode_lanes(mode, &bin, units * 8 + 4), Err(Error::OutputSize)); + } + // noise, and headers that claim more than there is + for len in [0usize, 1, 2, 3, 47, 48, 64, 500, 5000] { + for _ in 0..40 { + let noise: Vec = (0..len).map(|_| rng.next() as u8).collect(); + for mode in [1u8, 7] { + let _ = decode_lanes(mode, &noise, 64 * 8); + } + } + } + assert!(decode_lanes(1, &[0xFF; 4096], 1 << 20).is_err()); + assert!(decode_lanes(7, &[0x00; 4096], 1 << 20).is_err()); + assert_eq!(decode_lanes(2, &[], 16), Err(Error::Unsupported)); + assert_eq!(decode_lanes(1, &[], 0), Ok(Vec::new())); +} diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index b07db46f0..10b8ed782 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -11,6 +11,7 @@ use crate::config::Config; use crate::util::glob_match; pub mod acphal; +pub mod bcpack; pub mod d3d12_layout; pub mod d3d12x; pub mod dstorage; diff --git a/scripts/gen_bcpack_tables.py b/scripts/gen_bcpack_tables.py new file mode 100644 index 000000000..01874f749 --- /dev/null +++ b/scripts/gen_bcpack_tables.py @@ -0,0 +1,63 @@ +"""Generate crates/xcl/src/hle/bcpack/rans_tables.rs from Microsoft's silicon-rans sample +(MIT): the per-segment symbol frequencies of the 16 static models, for alphabets of 1 to 8 +bits. The cumulative bases are not stored: base[k + 1] = base[k] + freq[k] * symbols(k), which +this script checks against the sample's own `base_table`, and so are not the reciprocal tables +(`rf`, `rs`, `rn`): the decoder divides, and this script checks that the sample's reciprocal +path gives the same symbol for every slot of every model. + +usage: python scripts/gen_bcpack_tables.py +(https://github.com/microsoft/silicon-rans/blob/main/mdu_minirans.v, commit 2f6827d)""" +import io, os, re, sys + +src = io.open(sys.argv[1], encoding='utf-8').read() +OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'crates', 'xcl', 'src', 'hle', 'bcpack', 'rans_tables.rs') +WIDTHS, MODELS, SEGS = 8, 16, 9 # the sample has a 9-bit alphabet and a 10th segment as well; no BCPack lane is that wide + + +def table(name): + m = re.search(r'assign\s+' + name + r'\s*=\s*\'\{(.*?)\};\s*//\s*end\s+' + name, src, re.S) + rows = [[int(v) for v in r.split(',')] for r in re.findall(r"'\{\s*([0-9,\s]+?)\s*\}", m.group(1))] + assert len(rows) == 9 * 16 and all(len(r) == 10 for r in rows), name + return [rows[w * 16:(w + 1) * 16] for w in range(9)] + + +base, freq, rf, rs, rn = (table(n + '_table') for n in ('base', 'freq', 'rf', 'rs', 'rn')) + + +def symbols(seg): + return 1 if seg < 2 else 1 << (seg - 1) + + +for w in range(WIDTHS): + for q in range(MODELS): + b, f = base[w][q], freq[w][q] + nseg = w + 2 # segment 0 is symbol 0, segment k >= 1 is symbols [2^(k-1), 2^k) + acc = 0 + for k in range(nseg): + assert b[k] == acc and f[k] >= 1, (w, q, k) + acc += f[k] * symbols(k) + assert acc == 65536 and not any(f[nseg:]), (w, q) + # the sample's inverse (comparator chain, then a reciprocal multiply) is a division + for cf in range(65536): + seg = max((k for k in range(1, nseg) if cf >= b[k]), default=0) + steps = ((((cf - b[seg] + rn[w][q][seg]) & 0xFFFF) * rf[w][q][seg]) >> 15) >> rs[w][q][seg] + assert steps == (cf - b[seg]) // f[seg], (w, q, cf) + +out = io.open(OUT, 'w', encoding='utf-8', newline='\n') +out.write('''// Generated by scripts/gen_bcpack_tables.py from Microsoft's silicon-rans sample (mdu_minirans.v, +// https://github.com/microsoft/silicon-rans commit 2f6827d): Copyright (c) Microsoft Corporation, MIT. +// `FREQ[bits - 1][q][segment]`: the frequency of each symbol of a segment, out of 65536. Segment 0 +// is symbol 0, segment k >= 1 is the symbols 2^(k-1) .. 2^k - 1. + +#![allow(clippy::unreadable_literal)] + +''') +out.write(f'pub static FREQ: [[[u16; {SEGS}]; {MODELS}]; {WIDTHS}] = [\n') +for w in range(WIDTHS): + out.write(f' // {w + 1}-bit alphabet\n [\n') + for q in range(MODELS): + out.write(' [' + ', '.join(str(v) for v in freq[w][q][:SEGS]) + '],\n') + out.write(' ],\n') +out.write('];\n') +out.close() +print('wrote', os.path.normpath(OUT)) diff --git a/tests/data/bcpack/.gitattributes b/tests/data/bcpack/.gitattributes new file mode 100644 index 000000000..eb1e5257b --- /dev/null +++ b/tests/data/bcpack/.gitattributes @@ -0,0 +1,3 @@ +*.bin binary +*.lanes binary +*.bc1 binary diff --git a/tests/data/bcpack/bc1-1-8.bin b/tests/data/bcpack/bc1-1-8.bin new file mode 100644 index 0000000000000000000000000000000000000000..95050750104bba3b8a87fbfd3152de5cdbca3c2f GIT binary patch literal 61 vcmWd-fB+_DCNN-RRB%uLA_hhVFeqU-;E*7o;lKn^22#NY1R$BZ?6dp;k8B0> literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-1-8.lanes b/tests/data/bcpack/bc1-1-8.lanes new file mode 100644 index 0000000000000000000000000000000000000000..ccac41a29d0822dd0d55fb83f5815b29ab4fe629 GIT binary patch literal 12 TcmXS6kPzTu;^L^wKFbdP46p)% literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-16-1.bin b/tests/data/bcpack/bc1-16-1.bin new file mode 100644 index 0000000000000000000000000000000000000000..8201430b29f3438adf986120394b582a5cde33d5 GIT binary patch literal 194 zcmWF#m>_Tg2n2;W`Ptby*%_gLL4W}ajx*dbf4AuC`8$H;!82~~Y+w**Jf(BHnkzuy zf`FhfuP{hCNFlde21oIXSIamY!p=VD=iB!q!s*}XoMRI@`FOo0QaMX`-+wj{niF8k z6RcvKwuoEQN22kG`u*ixT<)h`3g)@;aE3mck+ha0@HPv(LI?v(14GeOqufJmEPRaz hI`UWX5k_u#JWn)S-&tYdk18mGJEbMFy?96OzOsuSo?7SjI`gY7Vtm;OhqOy#V zvdm0O%uEc-jEu|-%uI~T%pe{UGXo0#VPatcDqv;+s$gPf z1S(`?X0>EVRprzy%C#uAWKRvsm7C#^BQZxsecp_~tBp=9!o0FvOcFd|Y`oGu@@x`9 W@*K;~PT&kkTkg8{c5a8^p$!1gBp6@- literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-16-9.bin b/tests/data/bcpack/bc1-16-9.bin new file mode 100644 index 0000000000000000000000000000000000000000..2462981a12c54f93f7cce54e7cf4dd4dd16789a1 GIT binary patch literal 256 zcmZQzfB7iD=wxw-K(vwJ0&2ZFTl1HthlpG>BOy)=&Jd*ld9R+c>KNDrE0*10v9wsAqgXg|UjQ?M2Lr24?m;@*HNeJjUYU z970?IjLh5uT}>pPSBf8^!C-J&uI+{M}?E(d!tY9bCwk9`)(v iF|CMiZAyIi=PAxqC~`9~{{2Gkmo(r0npb7}{sI90K`xa5 literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-2-0.bin b/tests/data/bcpack/bc1-2-0.bin new file mode 100644 index 0000000000000000000000000000000000000000..9583e4063373e40259f736e8622928308c97e60c GIT binary patch literal 90 zcmWd-fB;rj7BFCBWD#HiA_gV~FgVKaW5xytmxk-iC%$A%Fz|qhgLJV10V5EA6wXuq OxYcN-@jZwx5D5S%Kn;}u literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-2-0.lanes b/tests/data/bcpack/bc1-2-0.lanes new file mode 100644 index 0000000000000000000000000000000000000000..7067007a8691df02d8cff548c7a872e808990d60 GIT binary patch literal 24 gcmX?loq<7KQq5M3mqSR9M}Tvlk?P8i##`?J07tzC00000 literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-700-2.bin b/tests/data/bcpack/bc1-700-2.bin new file mode 100644 index 0000000000000000000000000000000000000000..b3470659eaf67b97f40fe98d47f2f0be8133b666 GIT binary patch literal 7082 zcmV;b8&%{mFfcGMFfcH`zqk;%xDdDj0RRC2009622@nAg5CISaIV1y69t1xe0R1{w z$p!5$Ioesvua&<946x)dUpPo}xi?kj>CR&3v5A+7^b^{gg zVt9M&o--NchMfB9R(5mO98}(QMht6If3&=mRn|OOW1pYg^v^i&I$C(9Td@BY6n(Q; zQ%Z=?+ijJ_`t~$MOHi1szPLkOZj8{ppR5%x^j$j%S9(6?`+mHkXyh}ObOi@TVbm)f zJFOr|QsYy)Bgo)_nv3mlUlk5U66&E$zA zkY=(2YRvn5zWpARtar#cE4D_AY2piW(GSTw-m&5PGnnL$xhmWh(o z2Ts#DSzbYI2lb05x1$YxmkmtBS)PO_q!X104V!&Z?}k(cPOF&Eb}%W%mK4x!9KeO2 zZ*z3KL=YuvXok}M3l#7efjy1-VJp0lR=ZlMj=b2CA*9ulq$X4S)4nl5nQ^6&ldeo0 zxrnjZ(ga26Rbm(**_7#FKB!Xw1=sGT#~3X(H+TTN)&U+KFaevezu)RN!2l2$DZH>R z=ZhkL--|U0vQ1r4fQW>ANKvqS&# z+JUlZX0mZ~%Mz!9Ej4uK%XVb(PSVvh-)v1oTH1Z)C(|KSE}HX`qv;X-8ls z4h zMNIToHIwX*Xag3kKiO)rS<#jHIW$nBV4h$}7HxtLGmpI6KAkPiEXNG;VAeF_y5%SF zZYWK`KP>*8ffpghW@k@cGlv_~j;u1qm6v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~%lkq-|AeWeicq$(N|4V_azy%wMn*APXy749eZL``-_Vpbc$7L#a zS9u)x_VF?HUUgbc8%BBK0%+!Y5B}9>7)D0gf2$YT z3;O%&sGLp6MaUMq;sO01F>zz%`p^|5=ABoW^LP|wh1;r~MH4n{6U(?&&|jDpGUU)7 z5{d?AQLM;?5z(DZp7*pLaXQ3*5N4SMK1L7Jn4VJCggHvuLdXu+M)R;#_ZO@cC*KVa z{3@82%smXr1A6-cTCa-f3q)F~*h!_gUxri23fy{qykcb#)fbAS|0{{#F0N4OQ UbaY?<0ssI2000000000009dupE&u=k literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-700-2.lanes b/tests/data/bcpack/bc1-700-2.lanes new file mode 100644 index 0000000000000000000000000000000000000000..6eac67a555fcbc19d88a01cfbd6fa580241059a5 GIT binary patch literal 8400 zcmeI0^_x}o_x5*pckhWabEdmfY6wA6N=Xrh6p&E5L68tB5hNuCkVaZ^Kw3c zln{CL=g)Yq>wA7Y`@Hwr>t1W!ueG+5lDMt;{1H8*#+Q!lzVU^`ZGW(2-}z>(KO4Zb zUe>bKwl;tKx_$GHe>6FEZ}_VzZ#Un%xAFGNKFi+!;`w*qo?6iD)sEP;NQWHHoYXI; z)`X$mz4L)wv9eN1!^E2INc;KX>e91)n-8UC(Qj@ z-|g$s{mKQ(I`?7P^BrW-jv2e>lfPtU&-<9T>799TzgrCS6|;L@xcBRhg?lRR*Z$#X z$*7W&_|=s?vYAKPe>1k;sk7&cf1aItJ^Sc@Mz6+HC8meAw0`$&RFYh6_Td35es4KF zzv21x6~jk2Z*=do6I<&&xW*s&@QD4-mnTR5@_5_I_)puP*pDu}|DbgmaiZ73UYUnG zf7$U>8FJ&M7~&kcfwsRZhgy>qiWer-|oLZt06k=A+ST-f4zME+nWE( z4Ubv)?WzSwQoC2yPoA#~yfa{mpP#>Pd(S0X!mIE6`2K&_XWpxMz1O7WjWa%f)L~EC zEwyV6{Nkr$>!vO}HZx}D{GXbWnnX|EXOXl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a`lz?RPkz~nQLpYa++uP#qdqUYB;#jad6V%3_uvs-RB^7dJsm8(`6 z*~hy7raa(gZ0z*LSW|Cow|WP<)|fm`xN&g%z(*IKj0sh>UwS%pYUSFqdV`L+vv&xy zo4X$@KVH>s(y!B6j62cb{%V%`VE^n!srRxTo#{7cbjAHM@c9$zJ^$)Cu}RtV@5$1b zI$bKc4GsVPab@jSMd)dE2W;IP-ZyP2byIl$u!w%0+IQb-_8D5aBW@->C+)wPgT9<~ zaY?Hgy${u$^)!3NdD!U6?|UDt$Gz;ivU{ToGhY{mf9u)z zmyS*FH}Jyr9V`AVe^q#J*`JfrKaI9)+_Z*t8?pS$wxfGJ?EiD*DiQxEeafFdOm~*t z88`ax5kGfps^py+x@hfBhfjR_`S?yHpUwTdMe7}zXNT8%^)%;H<$;pw;bRk_Tg2spX<`8hc`*%_gL0SZpk-!?zG_3QZquakq99OT*XynOblKcdxK0Rk5U zczJn+LCQf&`DHUW3g^CB#_JGvR;zO2zLU;Q|GZ?5O*qXfJUf+>{hjdVgK;JS50#D6 zSigxjmd(1qoag-MmlIrEovwvG3P@Ue`}Kr~kONu`3_J}+xqDbnxE$zUT%eP}z{p^D RL-5BTh6g1;OE!RP0suRTK#~9e literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc3-16-1.lanes b/tests/data/bcpack/bc3-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..21f601d7437039d16955def9df1091723115036f GIT binary patch literal 192 zcmWlQI}QO+7={1$of+;BgA8LbjnEMzMB!2CtwLuXN~@rfScBdQY{qqxlka@RF#{)z z3L(Zp(w1vDm&V{(V@}rjWPGS)S1nil*}Spw-Fm*~txoG+uf#!Vs!qV@e^oZ8rl1a( z2n7(qfv_NHC<%!$F#}Kl5)d+`IEX1373nCfZoygPITOjUWY~^?e3?+*?3*u|mF1l( Sx_@r*>HIi8znAOc{rUm$u@Gti literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc4-16-1.bin b/tests/data/bcpack/bc4-16-1.bin new file mode 100644 index 0000000000000000000000000000000000000000..1801a52bbe43c260f759735187f97f6d9b4f381b GIT binary patch literal 194 zcmWF#m>_Tg2n2=sg*kzM5egWf;CSI}^P^k8e!ue|Ie5uIo`np5XP^8dTKyqF;DP`z zKPNv(IY=qLOcqDs%tuRjog~jaFQ2&gq_b16SKhgaof}U75}q4SS|-eYFwW$l`o&b! zf)5WDz5XUvrnZc0%K5o3C%ClDc)o^*``XDz0k^J(vlvH&9nfk>;JMO}b0~gK$q5I8 cyy-e@3_x307!KU9O}oLj>OmQUzy_EL0Rp~BkpKVy literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc4-16-1.lanes b/tests/data/bcpack/bc4-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..d10778ce73b3e5b24019d43065a3ef7259392687 GIT binary patch literal 192 zcmYe!V<>X5k_u#JWn)S-&tWfo@V9(JS;6Zm+*gg`r`xVFlTcH!H)64sH#Qa1)91D@ z4?el~7yk#bxhKQJO4!oM*jQQFSs2)unAsTES(({@#;`K5vNJF_Tg2spXW7D{ z-^9w)mhqgQ`*MOy+l=RHoUWaG6mTp2^@ND916mCUJXacW_LQ7(FkoDu!^QwKn}y*( P+6{&WWefrvz-|HnAXGws literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc5-16-1.lanes b/tests/data/bcpack/bc5-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..b99826baf8ef04b5dff6739eca1cd47166971221 GIT binary patch literal 192 zcmWkoZ3+Ql7<|5;UdvjwiFS*$twe}?{EHPviyz>v5H_Tg2spXY7iF5Sd#X;IzofCRklRElBXybS2hrV%Z91eRtGymgg$= z&N@H$e&Gz){-fqQovxh>II&hd{B!Z`28Zc$Bf`?18v;*X&0TN9#=x?_#OX^1`$}E5 zOAFZzS0B<#J9Jqg;X&Cp4h9wpfnyt{7g})#oWC;T#g7UN5rzpTHiR%#By3^GP;}T) R#jxi!D}#Ut1H*Ngp8)1xR7(H= literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc6-16-1.lanes b/tests/data/bcpack/bc6-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..02e458dacd8308cee9aa2605ff3d5f88d1af8d96 GIT binary patch literal 256 zcmWlTEl&eM5QgVtclP$mUVE_j!Ck|Fp{@-j4dfDn!lS^V>TrY*egOtug+`H7@C$G# z1OmZ7pr(?b*n5*n-b|j%Jc?06h_C<~!#!gX3y!tr*on2LQ+3iD&hqi3ckKLh^4DMI zPw$r(H!{EdSiY`OC?i+%PO(und6fe(ARx3R4l}dKU;rw{}o<#e$1UtaQg?1svlMW literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-16-1.bin b/tests/data/bcpack/bc7-16-1.bin new file mode 100644 index 0000000000000000000000000000000000000000..43e4a405cff81216b6b3b912ce21f39271615f7e GIT binary patch literal 260 zcmWF#m>_Tg2spXw|!z!;UJ3J+E1TKFeVcVPLop^CJNF0$&^e literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-16-1.lanes b/tests/data/bcpack/bc7-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..850bc0d027be6e36941ec475ca428c3a06a28547 GIT binary patch literal 256 zcmWN}FHgfj7=ZEj?!CMB?%G>>{hzK~gCW6ep@hMf5ELE-7Bz<>gzyP4=qWUcWP(qC zLm?0dz5y5{LD5J2+wmAvA=1>=u?Fs1%N0t73W+H}AeAtutH+b4&&#{rm(B0ZRwlKz&gXHN q=afX9RvE8FWpqxJ7)f8QmtXe>8I<{@AW1AFk$bcv=RO~2yg={*Yj@!mv7rMtDUo*!WB9KbXvlDJ|~C2LT1%h;~ozUF!~l*JxR zWFC(Iq@pMW{vJuda|&TZGRkB z#B+uLQ?$7nGQ65!?s@dbQ8+p3tD6X$WwDM6Q7P_;zQX2Pg!pA*Jfa+|VIm)YniWoL zQy!AQsx! z5vQNq3nN4aSH9dVKWCzc zlnAFaDgev0yG+(vgzTG)UV+qA%2z_yN>qvjO`NGVb53sTq(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K~Ym`j5qb@Ly19tYSp2H(IjbX24}p5n@EKfW}#PyzIWqI!;UTRIXbVYUT=fng&j S$F1QAg1H)!IMjjtpZph>n%K_( literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-700-2.lanes b/tests/data/bcpack/bc7-700-2.lanes new file mode 100644 index 0000000000000000000000000000000000000000..e16eece098525b8d9b1a95ce598a7db8ff605417 GIT binary patch literal 11200 zcmW++bwCu|7oDB%+3ujbyF&z&5CKI(8bOd0B&2NpP*hN{<5TSJ?k-F$?C!usMSt`C z{@Gn-cHVpUoOAE;&btB-q!0o}1qee^EG_^jmZTX3!7uIf`W| zmcvK{=Lmu!P>upg0EGks9D`sSLj{aLKv4(=fDj1qW8pA@0JH#u`OgqRasa^!a2n%K|h)3pkv{8IB@B45ev+WLX3PXp|q6Msbvb0fxg7 zer^ijK#pW_7T`yvaae$GG)usI&;TW%S(M;ljsS6zAPE{oX&58~7>nTo2%;&JK6(AU+5RptBh5$SYBrD*V;p2e?0+b&X zrZ@nGFo;D3C{5A`KRiOC1j)b*Op^ozaX7)@7z0B9ilVdt25^q&niQZAKQBw52#JFX zBVY*#2T+E@X_SExUP3g-!^WZo5Op!c@|1p5E{2u^MngAea z4&YEeqj*hle7q=y{g*%(%IgnD`Q+g!1VwlrP!s@J6v1iWzf=-X91Vdi0`tiNb09$g zD9B?=@Ko_E!WczBD2xFlFMkT;17J`B07#hEImb|Z?t(mL|6M0wK5i037?k0m;pc(` zFby+2q#%NVB+O?c&GHE$pdcE6a0(+C9$bVc2ZjiS1t1211SkXW`hXFf2ZS#R9M2Ao zFa*nxAb>M0$Y%#iK^RXyN+TezZ$3RRzEsczhR_&_@z4ENB?KHw5(1V)SOH4mERG9E zfTxM(V20O;fB|7Xbd+QG(gC6Xz~>dttA@fMelh?<5k`PRyeLp!%m{>H1PSsGKop1Y z+9UuF<7)*WAb5RK1j9fG27@dJ^T^VC8RG$hNRnXqWaCJ_azQA+5`JkQ|B>gF0scQE zh~p4KpdbP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#aW3?%0Hkd`2I(+)Bx~YCCkA&xt^w$7qA_ EfAjZsk^lez literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-8192-3.bin b/tests/data/bcpack/bc7-8192-3.bin new file mode 100644 index 000000000..c362eec97 --- /dev/null +++ b/tests/data/bcpack/bc7-8192-3.bin @@ -0,0 +1 @@ +KKKKKˆaa”””””òDD‡‡‡‡‡eÀÀŽŽŽŽŽD²²²²²‰ˆ6ò� KKKK6eÎ¥””””�D ×‡‡‡‡Î‰�ŽŽŽŽ í²²²²ttttttttt•• ‰‰‰‰‰‰‰‰‰ \ No newline at end of file diff --git a/tests/data/bcpack/generate.py b/tests/data/bcpack/generate.py new file mode 100644 index 000000000..18b738c6b --- /dev/null +++ b/tests/data/bcpack/generate.py @@ -0,0 +1,186 @@ +"""Generate synthetic q=0 and q=15 BCPack vectors using the encoder's byte counts. + +The multiplexer never decodes rANS. Each inverse step records the number +of bytes the forward step will need later. +""" + +import random +import struct +from collections import deque +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +BC1 = (8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8) +BC7 = (4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5) + + +WIDTHS = { + 1: BC1, + 3: (4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8), + 4: (8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), + 5: (4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), + 6: (4, 4, 8, 8, 8, 5, 5, 5, 6, 6, 6, 8, 8, 8, 8, 5), + 7: BC7, +} + + +def record_header(mode, body_size): + if body_size <= 256: + return bytes((mode, body_size - 1)) + return bytes((mode | 32,)) + struct.pack('= count << 16: + emitted.append(state & 255) + state >>= 8 + counts.append(len(emitted) - start) + whole, remainder = divmod(state, count) + state = (whole << 16) + lo + remainder + mode = 16 | model | (reduction << 6) + size = 4 + len(emitted) + state_bytes = state.to_bytes(4, 'big') + self.continuation = None + if carry and emitted: + # First record ends immediately after the initial state. Its first + # unfulfilled normalisation request starts the continuation header. + self.header = deque(bytes((mode & ~16, 3)) + state_bytes) + self.payload = deque() + self.continuation = (deque(record_header(mode, len(emitted))), + deque(reversed(emitted))) + elif trim: + assert len(symbols) == 1 and not any(emitted) + state_bytes = state_bytes.rstrip(b'\x00') + self.header = deque(record_header(mode, len(state_bytes)) + state_bytes) + self.payload = deque() + counts = [0] + else: + self.header = deque(record_header(mode, size) + state_bytes) + self.payload = deque(reversed(emitted)) + self.counts = deque(reversed(counts)) + self.buffered = False + self.owed = 0 + self.ahead = False + + def wants(self): + return self.header or (self.payload and not self.buffered + and (self.owed or not self.ahead)) + + def tick(self, served, stalled, out): + if self.header: + if served: + out.append(self.header.popleft()) + return + if served: + out.append(self.payload.popleft()) + self.buffered = True + if self.owed: + if self.buffered: + self.owed -= 1 + self.buffered = False + return + if self.counts and not (self.ahead or stalled): + self.owed = self.counts.popleft() + self.ahead = True + if self.buffered and self.owed: + self.buffered = False + self.owed -= 1 + + +def encode(symbols, widths, reductions, model=0, carry=False, trim=False): + lanes = [EncoderLane(*spec, model, carry, trim) for spec in zip(symbols, widths, reductions)] + out = bytearray() + while any(lane.header or lane.counts or lane.owed for lane in lanes): + wanted = [i for i, lane in enumerate(lanes) if lane.wants()] + for i, lane in enumerate(lanes): + lane.tick(i in wanted[:8], i in wanted[8:], out) + if lane.owed and lane.continuation: + lane.header, lane.payload = lane.continuation + lane.continuation = None + if all(lane.ahead for lane in lanes): + for lane in lanes: + lane.ahead = False + assert all(not lane.payload and not lane.buffered for lane in lanes) + return bytes(out) + + +def generate(mode, units, seed, reduced, **options): + widths = WIDTHS[mode] + rng = random.Random(seed) + reductions = [rng.randrange(4) if reduced else 0 for width in widths] + symbols = [[rng.randrange(1 << (width - reduction)) for _ in range(units)] + for width, reduction in zip(widths, reductions)] + if mode == 1: + symbols[1] = [0] * units + path = ROOT / f'bc{mode}-{units}-{seed}' + path.with_suffix('.bin').write_bytes(encode(symbols, widths, reductions, **options)) + path.with_suffix('.lanes').write_bytes(b''.join(map(bytes, symbols))) + return symbols, path + + +def seed_channels(slot): + return [(7 * slot + 13 * k) % (1 << w) for k, w in enumerate(BC1[2:8])] + + +def assemble(symbols): + blocks = [] + raw = bytearray() + for i, (ref, _, *fields) in enumerate(zip(*symbols)): + d = 255 - ref // 2 if ref & 1 else ref // 2 + predictor = ([0] * 6 if d == 0 else + blocks[i-d] if i >= d else seed_channels((i-d) % 256)) + channels = [] + for v, base, w in zip(fields, predictor, BC1[2:8]): + delta = ~(v >> 1) if v & 1 else v >> 1 + channels.append((base + delta) % (1 << w)) + blocks.append(channels) + for r, g, b in (channels[:3], channels[3:]): + raw.extend(struct.pack('> (2 * (2*(y%2) + x%2))) & 3 + indices |= px << (2 * (4*y + x)) + raw.extend(struct.pack(' Date: Mon, 23 Nov 2026 17:08:05 -0500 Subject: [PATCH 2/5] DirectStorage: BCPack BC1 requests are unpacked, tables from bcpack-rs BC1 blocks are rebuilt from the 12 lanes of the entropy stage (bc1.rs, after the BC1 sections of the bcpack-decoder and bcpack-rs format notes, MIT, no code taken). The rebuild needs two tables of constants that no stream carries: the 255 endpoint sets a stream starts with and the order of the 256 selector quadrants. bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs, MIT) estimated both from retail data; bc1_fitted.rs is generated from its data files by scripts/gen_bcpack_bc1_tables.py and carries its MIT notice. The constants belong to the codec, not to a game. dstorage.rs runs the BCPack stage for BC1, alone or after zlib; every other mode is refused and counted as before. A stream the decoder does not take fails the request with E_DECOMPRESSION and writes nothing. report.json gets dstorage.bcpack_unpacked per mode (requests, bytes rebuilt, failed). The output is an approximation where an estimate is off: one history entry is not known (a block that refers to it fails the request), 17 differ by a step or so between fits on two halves of the data, and 8 rare quadrants may be swapped with their mirror. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 (1M context) --- THIRD_PARTY.md | 3 +- crates/xcl/src/hle/bcpack/bc1.rs | 95 ++++++++++ crates/xcl/src/hle/bcpack/bc1_fitted.rs | 125 +++++++++++++ crates/xcl/src/hle/bcpack/mod.rs | 58 +++++- crates/xcl/src/hle/bcpack/tests.rs | 111 +++++++++++- crates/xcl/src/hle/dstorage.rs | 223 +++++++++++++++++++++--- crates/xcl/src/report.rs | 2 +- scripts/gen_bcpack_bc1_tables.py | 84 +++++++++ tests/data/bcpack/bc1-1-8.bc1 | 1 + tests/data/bcpack/bc1-16-1.bc1 | Bin 0 -> 128 bytes tests/data/bcpack/bc1-16-9.bc1 | 1 + tests/data/bcpack/bc1-2-0.bc1 | 1 + tests/data/bcpack/bc1-700-2.bc1 | Bin 0 -> 5600 bytes 13 files changed, 663 insertions(+), 41 deletions(-) create mode 100644 crates/xcl/src/hle/bcpack/bc1.rs create mode 100644 crates/xcl/src/hle/bcpack/bc1_fitted.rs create mode 100644 scripts/gen_bcpack_bc1_tables.py create mode 100644 tests/data/bcpack/bc1-1-8.bc1 create mode 100644 tests/data/bcpack/bc1-16-1.bc1 create mode 100644 tests/data/bcpack/bc1-16-9.bc1 create mode 100644 tests/data/bcpack/bc1-2-0.bc1 create mode 100644 tests/data/bcpack/bc1-700-2.bc1 diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index f1c75771f..fd42e6a9e 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,7 +11,8 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [silicon-rans](https://github.com/microsoft/silicon-rans) (Microsoft) | MIT | BCPack entropy stage: the rANS lane in `crates/xcl/src/hle/bcpack/lanes.rs` (after the `decoder` module of `mdu_minirans.v`) and its model tables in `hle/bcpack/rans_tables.rs` (generated by `scripts/gen_bcpack_tables.py` from the same file) | port to Rust with annotation; tables | -| [bcpack-decoder](https://github.com/Tim0219800/bcpack-decoder) (Tim0219800), [bcpack-rs](https://github.com/Ahmet-Dedeler/bcpack-rs) (Ahmet Dedeler) | MIT | no code; the BCPack stream layout, lane widths and byte feeder rule in `hle/bcpack/` follow their format notes (`docs/SPEC.md`, `docs/BCPACK_SPEC.md`) | specification | +| [bcpack-decoder](https://github.com/Tim0219800/bcpack-decoder) (Tim0219800), [bcpack-rs](https://github.com/Ahmet-Dedeler/bcpack-rs) (Ahmet Dedeler) | MIT | no code; the BCPack stream layout, lane widths, byte feeder rule and BC1 block rule in `hle/bcpack/` follow their format notes (`docs/SPEC.md`, `docs/BCPACK_SPEC.md`) | specification | +| bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs) | MIT (notice in the file) | `crates/xcl/src/hle/bcpack/bc1_fitted.rs` (generated by `scripts/gen_bcpack_bc1_tables.py` from `data/bc1_window.json` and `data/bc1_quad_table.json`): the two tables of BC1 constants BCPack streams do not carry, as bcpack-rs estimated them from retail data | data tables (estimates; codec constants, not game content) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/hle/bcpack/bc1.rs b/crates/xcl/src/hle/bcpack/bc1.rs new file mode 100644 index 000000000..eba66aac5 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc1.rs @@ -0,0 +1,95 @@ +//! BC1 blocks from the 12 lanes of a BCPack BC1 stream (one symbol per lane and block). +//! +//! For block `i`, in stream order: +//! * lane 0 is a distance `d` back to the block whose endpoints predict this one's: symbol 0 is +//! "none" (predict zeros), an even symbol `v` is `v / 2`, an odd one `255 - v / 2`. Block +//! `i - d` is meant, and before block 0 a built-in history of 255 endpoint sets, the same for +//! every stream ([`Tables::history`]), +//! * lane 1 was 0 in every stream the format notes describe, +//! * lanes 2–7 are the differences of R0, G0, B0, R1, G1, B1 from the prediction, 0, -1, 1, +//! -2, 2 … for the symbols 0, 1, 2, 3, 4 …, modulo the channel's range (5, 6, 5 bits), +//! * lanes 8–11 are the selectors of the top-left, top-right, bottom-left and bottom-right 2×2 +//! texels, each symbol the index of one of the 256 possible quadrants in a fixed order +//! ([`Tables::quadrants`]). +//! +//! The blocks are in the order of the surface's memory, tiled as the console stores it. +//! +//! After the BC1 sections of the public format notes of bcpack-decoder (Tim0219800, +//! https://github.com/Tim0219800/bcpack-decoder, `docs/SPEC.md`) and bcpack-rs (Ahmet Dedeler, +//! https://github.com/Ahmet-Dedeler/bcpack-rs, `docs/BCPACK_SPEC.md`), both MIT; no code was +//! taken from either. Written for XCL on 2026-11-23. + +use super::{lanes, lane_widths, Error}; + +/// The constants of the BC1 rebuild that are not in a stream. +pub struct Tables { + /// The endpoints `[R0, G0, B0, R1, G1, B1]` of the blocks before a stream's first: + /// `history[256 - k]` is the block `k` before block 0 (k = 1..=255; entry 0 is never read). + /// `None`: not known. + pub history: [Option<[u8; 6]>; 256], + /// The selectors of each quadrant symbol, 2 bits a texel: bits 0–1 the top-left texel, + /// 2–3 top-right, 4–5 bottom-left, 6–7 bottom-right. + pub quadrants: [u8; 256], +} + +/// The range of each endpoint channel. +const RANGE: [u8; 6] = [32, 64, 32, 32, 64, 32]; + +/// Unpack a BC1 stream to its `out_len` bytes of blocks. +pub fn decode(src: &[u8], out_len: usize, tables: &Tables) -> Result, Error> { + let widths = lane_widths(1).unwrap(); + if out_len % 8 != 0 { + return Err(Error::OutputSize); + } + let (symbols, consumed) = lanes::decode(src, widths, out_len / 8)?; + if src[consumed..].iter().any(|&b| b != 0) { + return Err(Error::Trailing { consumed }); + } + assemble(&symbols, tables) +} + +/// The endpoints `[R0, G0, B0, R1, G1, B1]` of a block. +fn endpoints(block: &[u8]) -> [u8; 6] { + let c0 = u16::from_le_bytes([block[0], block[1]]); + let c1 = u16::from_le_bytes([block[2], block[3]]); + [(c0 >> 11) as u8, (c0 >> 5 & 63) as u8, (c0 & 31) as u8, (c1 >> 11) as u8, (c1 >> 5 & 63) as u8, (c1 & 31) as u8] +} + +/// The blocks of `symbols` (12 per block, in [`super::decode_lanes`]'s order). +pub fn assemble(symbols: &[u8], tables: &Tables) -> Result, Error> { + let blocks = symbols.len() / 12; + let mut out = Vec::new(); + out.try_reserve_exact(blocks * 8).map_err(|_| Error::OutputSize)?; + out.resize(blocks * 8, 0u8); + for (i, s) in symbols.chunks_exact(12).enumerate() { + if s[1] != 0 { + return Err(Error::Lane1 { block: i }); + } + let v = s[0] as usize; + let d = if v % 2 == 0 { v / 2 } else { 255 - v / 2 }; + let predicted = if d == 0 { + [0; 6] + } else if d <= i { + endpoints(&out[(i - d) * 8..]) + } else { + let slot = 256 + i - d; + tables.history[slot].ok_or(Error::History { block: i, slot })? + }; + let mut e = [0u16; 6]; + for c in 0..6 { + let v = s[2 + c] as i32; + let delta = if v % 2 == 0 { v / 2 } else { -(v / 2) - 1 }; + e[c] = (predicted[c] as i32 + delta).rem_euclid(RANGE[c] as i32) as u16; + } + let [tl, tr, bl, br] = [8, 9, 10, 11].map(|l| tables.quadrants[s[l] as usize]); + let b = &mut out[i * 8..i * 8 + 8]; + b[..2].copy_from_slice(&(e[0] << 11 | e[1] << 5 | e[2]).to_le_bytes()); + b[2..4].copy_from_slice(&(e[3] << 11 | e[4] << 5 | e[5]).to_le_bytes()); + // a row of the block is four texels, 2 bits each, the left one lowest + b[4] = (tl & 15) | (tr & 15) << 4; + b[5] = (tl >> 4) | (tr >> 4) << 4; + b[6] = (bl & 15) | (br & 15) << 4; + b[7] = (bl >> 4) | (br >> 4) << 4; + } + Ok(out) +} diff --git a/crates/xcl/src/hle/bcpack/bc1_fitted.rs b/crates/xcl/src/hle/bcpack/bc1_fitted.rs new file mode 100644 index 000000000..e7bafc2a1 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc1_fitted.rs @@ -0,0 +1,125 @@ +// Generated by scripts/gen_bcpack_bc1_tables.py from the tables of +// bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs, commit c51ec52, +// data/bc1_window.json and data/bc1_quad_table.json), used under its MIT license: +// +// MIT License +// +// Copyright (c) 2026 Ahmet Dedeler +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// The constants of BCPack's BC1 block rebuild that no stream carries. They were estimated by +// bcpack-rs from retail data (decoded blocks against the next smaller mip level, which is +// stored unpacked); they are constants of the codec, not game content. Being estimates, they +// make the BC1 output of XCL an approximation wherever one of them is wrong: +// * history: 254 of the 255 entries that can be read; the `None` ones were never referred to +// in the data of the fit. Fits on two halves of that data differ, by a step or so, in +// 17 entries (12, 14, 30, 47, 59, 67, 70, 83, 108, 125, 127, 130, 152, 159, 176, 231, 236). +// * quadrants: all 256. Fits on two halves of the data swap 8 entries +// (229, 230, 231, 235, 247, 248, 254, 255; rare mirror pairs). +// A block rebuilt from a history entry carries its error, and so do the blocks that refer to it. + +use super::bc1::Tables; + +pub static TABLES: Tables = Tables { + history: [ + None, Some([7, 29, 6, 8, 30, 7]), Some([15, 29, 15, 16, 36, 17]), Some([20, 37, 14, 3, 6, 2]), + None, Some([10, 21, 11, 6, 15, 7]), Some([12, 23, 11, 7, 15, 6]), Some([12, 26, 12, 7, 15, 7]), + Some([22, 36, 15, 20, 32, 14]), Some([14, 23, 8, 1, 2, 1]), Some([23, 5, 30, 9, 5, 30]), Some([11, 22, 11, 7, 15, 7]), + Some([17, 22, 7, 10, 11, 3]), Some([12, 25, 12, 7, 16, 7]), Some([13, 28, 8, 5, 12, 3]), Some([11, 20, 8, 16, 31, 14]), + Some([23, 32, 30, 17, 12, 29]), Some([8, 44, 30, 6, 26, 30]), Some([10, 24, 30, 6, 45, 30]), Some([10, 12, 4, 8, 8, 2]), + Some([16, 23, 30, 14, 6, 26]), Some([12, 25, 13, 10, 22, 12]), Some([19, 27, 10, 13, 16, 5]), Some([11, 24, 12, 4, 11, 6]), + Some([29, 60, 29, 6, 13, 6]), Some([17, 31, 11, 1, 2, 1]), Some([26, 54, 24, 12, 24, 10]), Some([23, 48, 30, 20, 37, 30]), + Some([16, 23, 10, 10, 15, 6]), Some([11, 24, 10, 6, 13, 5]), Some([18, 52, 30, 14, 22, 30]), Some([14, 51, 30, 9, 34, 30]), + Some([2, 3, 1, 19, 37, 16]), Some([14, 15, 30, 10, 32, 30]), Some([29, 57, 27, 27, 52, 25]), Some([13, 29, 15, 8, 20, 11]), + Some([13, 17, 5, 9, 10, 3]), Some([18, 50, 29, 15, 10, 29]), Some([11, 25, 13, 8, 19, 10]), Some([17, 31, 12, 6, 12, 4]), + Some([22, 18, 30, 19, 41, 30]), Some([10, 22, 11, 8, 18, 9]), Some([18, 30, 31, 10, 44, 30]), Some([25, 50, 24, 2, 4, 1]), + Some([11, 30, 31, 7, 15, 29]), Some([12, 19, 8, 11, 16, 7]), Some([19, 29, 30, 14, 55, 28]), Some([9, 20, 10, 4, 10, 5]), + Some([12, 23, 10, 7, 14, 5]), Some([26, 53, 25, 6, 13, 6]), Some([19, 27, 31, 11, 19, 30]), Some([21, 31, 30, 22, 31, 30]), + Some([10, 19, 5, 11, 21, 6]), Some([30, 50, 3, 29, 46, 2]), Some([15, 9, 30, 7, 9, 30]), Some([14, 18, 6, 11, 14, 4]), + Some([28, 56, 26, 4, 7, 3]), Some([8, 20, 10, 6, 13, 7]), Some([28, 58, 26, 15, 32, 14]), Some([10, 19, 8, 7, 10, 4]), + Some([16, 22, 9, 13, 17, 7]), Some([1, 2, 1, 14, 28, 12]), Some([22, 45, 30, 9, 15, 30]), Some([19, 22, 30, 16, 23, 31]), + Some([25, 50, 24, 21, 43, 20]), Some([6, 11, 4, 16, 31, 13]), Some([13, 25, 8, 3, 6, 1]), Some([5, 9, 3, 12, 24, 10]), + Some([16, 29, 13, 8, 14, 6]), Some([20, 37, 16, 13, 26, 10]), Some([18, 35, 15, 5, 9, 3]), Some([13, 25, 11, 7, 12, 5]), + Some([11, 21, 7, 7, 14, 4]), Some([20, 39, 16, 11, 21, 8]), Some([16, 31, 12, 4, 8, 2]), Some([22, 41, 30, 18, 23, 30]), + Some([24, 50, 24, 9, 20, 8]), Some([3, 12, 7, 4, 16, 8]), Some([18, 27, 12, 16, 22, 10]), Some([24, 49, 23, 13, 28, 12]), + Some([24, 49, 24, 18, 38, 18]), Some([17, 32, 12, 14, 28, 9]), Some([20, 10, 31, 13, 10, 31]), Some([7, 8, 2, 5, 5, 1]), + Some([1, 2, 1, 10, 21, 9]), Some([10, 18, 6, 1, 1, 0]), Some([22, 46, 21, 1, 3, 1]), Some([11, 20, 8, 8, 14, 5]), + Some([17, 35, 31, 14, 14, 29]), Some([16, 22, 31, 12, 40, 31]), Some([12, 22, 9, 8, 15, 6]), Some([18, 15, 30, 15, 33, 31]), + Some([19, 32, 30, 15, 43, 31]), Some([18, 35, 15, 8, 15, 5]), Some([21, 43, 20, 18, 37, 17]), Some([10, 17, 6, 9, 15, 6]), + Some([14, 27, 12, 7, 14, 5]), Some([8, 15, 7, 12, 26, 11]), Some([18, 37, 17, 1, 1, 0]), Some([17, 45, 30, 15, 33, 31]), + Some([13, 24, 11, 8, 17, 7]), Some([23, 47, 22, 16, 32, 15]), Some([18, 33, 13, 11, 22, 8]), Some([4, 10, 4, 8, 17, 7]), + Some([1, 2, 1, 3, 7, 3]), Some([11, 22, 9, 6, 12, 4]), Some([16, 28, 11, 13, 24, 9]), Some([12, 24, 12, 7, 13, 6]), + Some([23, 47, 22, 7, 15, 6]), Some([11, 32, 30, 11, 31, 30]), Some([14, 26, 11, 10, 19, 7]), Some([20, 41, 19, 1, 3, 1]), + Some([14, 27, 12, 8, 17, 6]), Some([11, 21, 9, 8, 15, 6]), Some([1, 2, 1, 7, 13, 6]), Some([19, 34, 14, 16, 30, 12]), + Some([13, 27, 13, 7, 16, 7]), Some([15, 32, 16, 8, 19, 9]), Some([15, 42, 31, 11, 22, 30]), Some([23, 48, 23, 5, 10, 4]), + Some([22, 45, 21, 11, 23, 10]), Some([31, 62, 30, 31, 61, 29]), Some([13, 26, 11, 5, 8, 3]), Some([19, 39, 19, 9, 21, 10]), + Some([7, 14, 2, 6, 12, 2]), Some([21, 42, 20, 4, 7, 3]), Some([10, 17, 7, 8, 13, 5]), Some([10, 22, 8, 11, 19, 7]), + Some([19, 33, 31, 12, 31, 31]), Some([21, 43, 20, 5, 11, 5]), Some([9, 21, 8, 8, 13, 7]), Some([10, 21, 10, 6, 13, 6]), + Some([15, 29, 12, 11, 21, 8]), Some([21, 43, 20, 9, 19, 8]), Some([3, 8, 3, 5, 11, 5]), Some([16, 31, 13, 9, 18, 7]), + Some([11, 21, 11, 6, 13, 6]), Some([10, 21, 10, 7, 15, 7]), Some([27, 3, 1, 26, 1, 0]), Some([18, 37, 18, 16, 32, 16]), + Some([12, 23, 10, 9, 18, 7]), Some([12, 25, 12, 8, 18, 8]), Some([11, 20, 9, 2, 5, 1]), Some([7, 15, 7, 8, 18, 9]), + Some([17, 33, 15, 13, 24, 11]), Some([9, 19, 9, 7, 15, 7]), Some([21, 43, 20, 13, 28, 12]), Some([17, 36, 17, 2, 4, 2]), + Some([10, 19, 9, 6, 13, 5]), Some([20, 41, 19, 7, 14, 7]), Some([3, 9, 6, 2, 8, 5]), Some([13, 24, 10, 11, 20, 8]), + Some([18, 39, 18, 6, 10, 5]), Some([19, 38, 18, 8, 17, 8]), Some([16, 35, 17, 4, 11, 4]), Some([11, 23, 11, 10, 21, 10]), + Some([17, 36, 17, 7, 15, 7]), Some([13, 27, 13, 7, 13, 7]), Some([9, 15, 4, 8, 13, 4]), Some([9, 19, 7, 6, 9, 3]), + Some([19, 39, 19, 11, 25, 11]), Some([11, 23, 11, 8, 17, 8]), Some([14, 29, 14, 7, 16, 7]), Some([12, 22, 8, 5, 9, 4]), + Some([10, 20, 9, 8, 17, 8]), Some([21, 41, 19, 15, 32, 14]), Some([14, 28, 13, 1, 2, 0]), Some([8, 16, 8, 7, 14, 7]), + Some([9, 18, 8, 8, 16, 7]), Some([10, 17, 7, 3, 4, 1]), Some([14, 28, 13, 2, 4, 1]), Some([14, 30, 14, 3, 6, 3]), + Some([19, 38, 18, 5, 11, 5]), Some([12, 26, 12, 1, 2, 1]), Some([9, 16, 6, 8, 13, 5]), Some([8, 13, 4, 7, 11, 4]), + Some([16, 35, 16, 4, 8, 4]), Some([13, 28, 13, 4, 9, 4]), Some([15, 31, 15, 6, 13, 6]), Some([12, 24, 11, 9, 19, 9]), + Some([9, 19, 8, 7, 14, 6]), Some([14, 28, 13, 5, 10, 4]), Some([10, 21, 7, 4, 6, 2]), Some([16, 34, 17, 11, 25, 12]), + Some([15, 30, 15, 8, 16, 8]), Some([13, 27, 13, 10, 20, 10]), Some([9, 20, 9, 0, 1, 0]), Some([16, 32, 15, 2, 4, 2]), + Some([13, 27, 12, 3, 6, 3]), Some([13, 26, 12, 12, 23, 11]), Some([12, 25, 12, 5, 11, 5]), Some([11, 23, 11, 5, 11, 5]), + Some([16, 34, 16, 7, 13, 6]), Some([16, 35, 31, 15, 25, 31]), Some([16, 33, 16, 7, 16, 7]), Some([13, 26, 13, 8, 19, 8]), + Some([18, 35, 17, 11, 23, 10]), Some([18, 36, 18, 13, 28, 13]), Some([12, 25, 12, 4, 9, 4]), Some([9, 18, 7, 6, 11, 4]), + Some([15, 30, 14, 9, 20, 9]), Some([17, 35, 16, 9, 19, 9]), Some([11, 24, 11, 2, 4, 2]), Some([16, 33, 16, 0, 1, 0]), + Some([15, 31, 15, 4, 9, 4]), Some([16, 31, 15, 14, 27, 13]), Some([14, 29, 14, 13, 25, 12]), Some([11, 23, 11, 3, 6, 3]), + Some([16, 32, 16, 10, 22, 10]), Some([11, 22, 11, 4, 9, 4]), Some([11, 22, 10, 1, 2, 0]), Some([8, 14, 5, 2, 4, 1]), + Some([9, 16, 6, 6, 10, 4]), Some([10, 21, 10, 9, 19, 9]), Some([14, 29, 14, 11, 23, 11]), Some([9, 18, 8, 6, 13, 6]), + Some([6, 13, 6, 5, 11, 5]), Some([7, 14, 6, 0, 1, 0]), Some([4, 7, 2, 3, 4, 1]), Some([10, 20, 9, 4, 8, 4]), + Some([9, 17, 7, 5, 9, 3]), Some([7, 14, 7, 1, 2, 1]), Some([10, 20, 10, 6, 11, 5]), Some([8, 15, 5, 4, 6, 2]), + Some([8, 17, 8, 1, 2, 1]), Some([10, 20, 10, 3, 6, 3]), Some([7, 10, 3, 6, 8, 3]), Some([8, 15, 7, 6, 12, 6]), + Some([9, 19, 9, 2, 4, 2]), Some([6, 11, 4, 3, 4, 1]), Some([6, 11, 4, 0, 1, 0]), Some([8, 16, 7, 2, 5, 2]), + Some([16, 34, 16, 15, 29, 15]), Some([7, 16, 7, 5, 10, 5]), Some([8, 14, 5, 5, 9, 3]), Some([9, 18, 8, 4, 8, 4]), + Some([5, 9, 3, 4, 7, 2]), Some([9, 18, 8, 5, 10, 5]), Some([6, 12, 6, 2, 4, 2]), Some([7, 12, 5, 4, 7, 3]), + Some([5, 11, 5, 1, 2, 1]), Some([8, 17, 8, 3, 6, 3]), Some([16, 31, 31, 16, 32, 31]), Some([7, 14, 7, 3, 6, 3]), + Some([5, 11, 6, 4, 9, 4]), Some([7, 15, 7, 4, 8, 4]), Some([2, 4, 2, 0, 0, 1]), Some([5, 11, 5, 3, 6, 3]), + Some([4, 8, 4, 1, 1, 1]), Some([3, 6, 3, 1, 2, 1]), Some([2, 4, 1, 1, 2, 1]), Some([4, 8, 4, 3, 6, 3]), + Some([3, 6, 3, 2, 4, 2]), Some([4, 9, 4, 2, 4, 2]), Some([17, 27, 31, 15, 34, 31]), Some([0, 0, 1, 0, 0, 0]), + ], + quadrants: [ + 170, 255, 0, 85, 250, 175, 251, 191, 254, 239, 187, 238, 223, 186, 90, 174, + 127, 234, 171, 247, 253, 165, 95, 245, 221, 119, 102, 153, 42, 138, 162, 80, + 5, 168, 17, 154, 68, 63, 166, 169, 207, 190, 252, 243, 106, 235, 126, 231, + 219, 189, 122, 167, 218, 15, 173, 87, 213, 10, 93, 117, 47, 110, 240, 143, + 248, 230, 61, 242, 185, 37, 124, 155, 59, 133, 206, 236, 88, 179, 211, 160, + 82, 222, 123, 43, 183, 94, 199, 237, 91, 178, 142, 204, 111, 25, 246, 159, + 100, 232, 229, 41, 249, 51, 70, 34, 181, 215, 45, 120, 86, 134, 136, 104, + 145, 149, 146, 210, 135, 125, 118, 103, 157, 89, 101, 217, 21, 55, 147, 92, + 198, 53, 108, 205, 57, 69, 220, 84, 115, 81, 83, 197, 46, 139, 141, 39, + 226, 31, 244, 29, 216, 241, 114, 163, 79, 116, 184, 202, 58, 172, 209, 137, + 71, 38, 98, 152, 112, 13, 161, 26, 74, 107, 27, 208, 164, 233, 7, 177, + 158, 182, 228, 78, 188, 227, 62, 203, 130, 49, 2, 40, 76, 19, 196, 32, + 14, 11, 8, 150, 128, 224, 9, 176, 105, 96, 6, 144, 35, 151, 140, 214, + 33, 109, 121, 50, 200, 72, 132, 23, 18, 212, 77, 113, 1, 54, 99, 156, + 201, 64, 4, 16, 225, 97, 148, 73, 75, 30, 180, 22, 3, 12, 192, 66, + 129, 24, 48, 36, 195, 60, 194, 20, 65, 131, 44, 56, 67, 52, 28, 193, + ], +}; diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs index e35c2c062..845acaa39 100644 --- a/crates/xcl/src/hle/bcpack/mod.rs +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -5,25 +5,31 @@ //! symbol per lane for every 8 bytes of output, and the lanes share the byte stream //! (`lanes.rs`). The blocks are then rebuilt from the symbols; that part differs per format. //! -//! What is here: the entropy stage for BC1, BC3, BC4, BC5, BC6H and BC7 ([`lane_widths`]); no -//! lane layout is published for BC2. Nothing calls it yet: DirectStorage still refuses every -//! request with a BCPack stage. +//! What is here: +//! * the entropy stage for BC1, BC3, BC4, BC5, BC6H and BC7 ([`lane_widths`]); no lane layout +//! is published for BC2, +//! * the rebuild of BC1 blocks ([`bc1`]), which needs two tables of constants that are not in +//! the stream ([`bc1::Tables`]). XCL has the estimates bcpack-rs made of them +//! (`bc1_fitted.rs`), so its BC1 blocks are an approximation wherever an estimate is off. //! -//! What is not: the rebuild of blocks from the symbols, for any format. +//! What is not: the rebuild of the other formats. Their lanes decode, but how the symbols map +//! to block bits is not published in a form XCL can use, so those requests are still refused. //! //! Nothing here was compared with what a console writes for the same input: the entropy stage -//! follows Microsoft's published decoder sample and the public format notes of bcpack-decoder -//! (Tim0219800) and bcpack-rs (Ahmet Dedeler), both MIT, whose authors report them as matching -//! retail streams. The tests check against streams built independently from those notes -//! (`tests/data/bcpack`), not against hardware output. +//! follows Microsoft's published decoder sample and the BC1 rules the public format notes of +//! bcpack-decoder (Tim0219800) and bcpack-rs (Ahmet Dedeler), both MIT, whose authors report +//! them as matching retail streams. The tests check against streams built independently from +//! those notes (`tests/data/bcpack`), not against hardware output. +pub mod bc1; +mod bc1_fitted; mod lanes; mod rans_tables; /// Why a stream was not unpacked. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Error { - /// no lane layout for this mode + /// no block rebuild for this mode (or no lane layout, or no tables) Unsupported, /// the output is not a whole number of blocks, or too large OutputSize, @@ -39,6 +45,10 @@ pub enum Error { Stuck, /// bytes other than zero padding follow the stream Trailing { consumed: usize }, + /// BC1 lane 1 is not zero; what it then means is not known + Lane1 { block: usize }, + /// a block refers to an entry of the built-in history that is not known + History { block: usize, slot: usize }, } impl Error { @@ -53,6 +63,8 @@ impl Error { Error::EndState { .. } => "end state", Error::Stuck => "stuck", Error::Trailing { .. } => "trailing data", + Error::Lane1 { .. } => "lane 1", + Error::History { .. } => "unknown history", } } } @@ -68,6 +80,8 @@ impl std::fmt::Display for Error { Error::EndState { lane } => write!(f, "lane {lane} ends in a state no encoder starts from"), Error::Stuck => write!(f, "the lanes cannot go on"), Error::Trailing { consumed } => write!(f, "data follows the stream's {consumed} bytes"), + Error::Lane1 { block } => write!(f, "BC1 block {block} has a non-zero lane 1 symbol"), + Error::History { block, slot } => write!(f, "BC1 block {block} refers to the unknown history entry {slot}"), } } } @@ -101,5 +115,31 @@ pub fn decode_lanes(mode: u8, src: &[u8], out_len: usize) -> Result, Err Ok(symbols) } +/// The BC1 constants, when XCL has them: the estimates of bcpack-rs, and in the tests the +/// made-up set their fixtures were built with. +fn bc1_tables() -> Option<&'static bc1::Tables> { + #[cfg(test)] + { + Some(tests::tables()) + } + #[cfg(not(test))] + { + Some(&bc1_fitted::TABLES) + } +} + +/// Whether [`decode`] has a block rebuild for `mode`. +pub fn can_decode(mode: u8) -> bool { + mode == 1 && bc1_tables().is_some() +} + +/// Unpack a stream of `mode` to its `out_len` bytes of BCn blocks. +pub fn decode(mode: u8, src: &[u8], out_len: usize) -> Result, Error> { + match (mode, bc1_tables()) { + (1, Some(t)) => bc1::decode(src, out_len, t), + _ => Err(Error::Unsupported), + } +} + #[cfg(test)] pub(crate) mod tests; diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index ff82c01fa..a5ab53aef 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -4,7 +4,20 @@ use super::lanes::{self, L}; use super::rans_tables::FREQ; -use super::{decode_lanes, lane_widths, Error}; +use super::{bc1, decode_lanes, lane_widths, Error}; + +/// The tables the fixtures' `.bc1` files were made with: history entry `slot` has the +/// channels `(7 * slot + 13 * k) mod range`, and a quadrant symbol is its own selectors. +pub(crate) fn tables() -> &'static bc1::Tables { + static T: std::sync::OnceLock = std::sync::OnceLock::new(); + T.get_or_init(|| { + let range = [32usize, 64, 32, 32, 64, 32]; + bc1::Tables { + history: std::array::from_fn(|slot| Some(std::array::from_fn(|k| ((7 * slot + 13 * k) % range[k]) as u8))), + quadrants: std::array::from_fn(|s| s as u8), + } + }) +} pub(crate) fn data(name: &str) -> Option> { std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack").join(name)).ok() @@ -70,6 +83,57 @@ fn fixtures_decode_to_their_lanes() { } } +#[test] +fn bc1_fixtures_decode_to_their_blocks() { + for stem in FIXTURES.iter().filter(|s| s.starts_with("bc1-") && **s != "bc1-1-8") { + let (_, units) = fixture(stem); + let bin = data(&format!("{stem}.bin")).unwrap(); + let blocks = bc1::decode(&bin, units * 8, tables()).unwrap(); + match data(&format!("{stem}.bc1")) { + Some(want) => assert_eq!(blocks, want, "{stem}"), + None => assert_eq!(blocks, bc1::assemble(&large_fixture_symbols(1), tables()).unwrap(), "{stem}"), + } + assert_eq!(super::decode(1, &bin, units * 8).as_deref(), Ok(&blocks[..]), "{stem}"); + } + // the modes without a block rebuild + for mode in [0u8, 2, 3, 4, 5, 6, 7, 8, 15] { + assert!(!super::can_decode(mode)); + assert_eq!(super::decode(mode, &[], 16), Err(Error::Unsupported)); + } +} + +/// One BC1 block by hand: every field of the rebuild, without the entropy stage. +#[test] +fn bc1_block_rebuild() { + let t = tables(); + // block 0: no reference; R0 +3, G0 -1, B0 0, R1 -2, G1 +5, B1 +1; the four quadrants + let b0 = [0u8, 0, 6, 1, 0, 3, 10, 2, 0b11_10_01_00, 0b00_00_00_01, 0b10_10_10_10, 0b11_00_11_00]; + // block 1: one block back; R0 -4 (wraps to 31), the rest unchanged + let b1 = [2u8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + // block 2: 255 back, which is before the stream: history entry 256 + 2 - 255 = 3 + let b2 = [1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let out = bc1::assemble(&[b0, b1, b2].concat(), t).unwrap(); + let c = |r: u16, g: u16, b: u16| (r << 11 | g << 5 | b).to_le_bytes(); + assert_eq!(out[0..2], c(3, 63, 0)); + assert_eq!(out[2..4], c(30, 5, 1)); + // rows: left quadrant's two texels in the low nibble, right quadrant's in the high one + assert_eq!(out[4..8], [0b00_01_01_00, 0b00_00_11_10, 0b11_00_10_10, 0b11_00_10_10]); + assert_eq!(out[8..10], c(31, 63, 0)); + assert_eq!(out[10..12], c(30, 5, 1)); + assert_eq!(out[12..16], [0; 4]); + let h = t.history[3].unwrap().map(|v| v as u16); + assert_eq!(out[16..20], [c(h[0], h[1], h[2]), c(h[3], h[4], h[5])].concat()[..]); + + // lane 1 is not understood beyond "0" + let mut odd = b0; + odd[1] = 1; + assert_eq!(bc1::assemble(&odd, t), Err(Error::Lane1 { block: 0 })); + // an unknown history entry stops the stream instead of guessing + let mut holes = bc1::Tables { history: t.history, quadrants: t.quadrants }; + holes.history[3] = None; + assert_eq!(bc1::assemble(&[b0, b1, b2].concat(), &holes), Err(Error::History { block: 2, slot: 3 })); +} + /// The 8-bit model 11 as US 11,234,023 prints it (its `base_table[8][12]`, counted from 1). #[test] fn model_matches_the_patent_excerpt() { @@ -228,7 +292,13 @@ fn damaged_streams_end_cleanly() { for stem in ["bc1-2-0", "bc1-16-1", "bc1-16-9", "bc7-16-1", "bc1-700-2", "bc7-700-2"] { let (mode, units) = fixture(stem); let bin = data(&format!("{stem}.bin")).unwrap(); - let check = |bytes: &[u8], units: usize| decode_lanes(mode, bytes, units * 8); + let check = |bytes: &[u8], units: usize| { + let lanes = decode_lanes(mode, bytes, units * 8); + if mode == 1 { + assert_eq!(super::decode(1, bytes, units * 8).is_ok(), lanes.is_ok()); + } + lanes + }; // every byte of a stream is some lane's: a shorter one is never whole for cut in (0..bin.len()).step_by((bin.len() / 300).max(1)) { assert!(check(&bin[..cut], units).is_err(), "{stem} cut at {cut}"); @@ -256,6 +326,7 @@ fn damaged_streams_end_cleanly() { let noise: Vec = (0..len).map(|_| rng.next() as u8).collect(); for mode in [1u8, 7] { let _ = decode_lanes(mode, &noise, 64 * 8); + let _ = super::decode(mode, &noise, 64 * 8); } } } @@ -264,3 +335,39 @@ fn damaged_streams_end_cleanly() { assert_eq!(decode_lanes(2, &[], 16), Err(Error::Unsupported)); assert_eq!(decode_lanes(1, &[], 0), Ok(Vec::new())); } + +/// The tables XCL ships (`bc1_fitted.rs`) are whole and in the layout [`bc1::assemble`] reads. +#[test] +fn fitted_bc1_tables_are_well_formed() { + let t = &super::bc1_fitted::TABLES; + // every quadrant once, the four uniform ones first + let mut seen = [false; 256]; + for &q in &t.quadrants { + assert!(!std::mem::replace(&mut seen[q as usize], true), "quadrant {q:#04x} twice"); + } + let uniform = |s: usize| t.quadrants[s] & 3; + for s in 0..4 { + assert_eq!(t.quadrants[s], uniform(s) * 0x55); + } + for h in t.history.iter().flatten() { + assert!(h.iter().zip([32, 64, 32, 32, 64, 32]).all(|(&c, range)| c < range)); + } + + // a first block that takes the endpoints of the block before the stream as they are + let mut s = [0u8; 12]; + s[0] = 2; + s[8..].copy_from_slice(&[0, 1, 2, 3]); + let b = bc1::assemble(&s, t).unwrap(); + let e = t.history[255].unwrap().map(u16::from); + assert_eq!(b[..2], (e[0] << 11 | e[1] << 5 | e[2]).to_le_bytes()); + assert_eq!(b[2..4], (e[3] << 11 | e[4] << 5 | e[5]).to_le_bytes()); + let row = |left: usize, right: usize| uniform(left) * 5 | uniform(right) * 5 << 4; + assert_eq!(b[4..], [row(0, 1), row(0, 1), row(2, 3), row(2, 3)]); + + // an entry the estimate does not have ends the rebuild + if let Some(slot) = (1..256).find(|&k| t.history[k].is_none()) { + let d = 256 - slot; + s[0] = if d < 128 { 2 * d } else { 2 * (255 - d) + 1 } as u8; + assert_eq!(bc1::assemble(&s, t), Err(Error::History { block: 0, slot })); + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 557266edc..32b215b9f 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -24,9 +24,10 @@ //! then 5 more. //! //! Each queue has a worker thread: submitted requests run in order (file reads through the -//! VFS like the title's own, memory copies, zlib), a status entry gets the first failure of -//! the requests since the previous one, a signal sets the fence from the CPU. Methods not -//! listed are logged and answer E_NOTIMPL; BCPack and other console formats are refused. +//! VFS like the title's own, memory copies, zlib, BCPack where `hle::bcpack` rebuilds the +//! blocks of the mode), a status entry gets the first failure of the requests since the +//! previous one, a signal sets the fence from the CPU. Methods not listed are logged and +//! answer E_NOTIMPL; the other BCPack modes and the hardware swizzle are refused. #![allow(non_snake_case)] @@ -131,7 +132,7 @@ fn bcpack_name(mode: u8) -> String { BCPACK_NAMES.get(mode as usize).map_or_else(|| format!("mode {mode}"), |n| n.to_string()) } -/// BCPack requests refused at enqueue (XCL has no BCPack decoder), by mode. +/// BCPack requests refused at enqueue (XCL has no decoder for their mode), by mode. struct BcpackRefusals { requests: [AtomicU64; 16], with_zlib: [AtomicU64; 16], @@ -197,10 +198,81 @@ pub struct BcpackStats { pub struct DStorageStats { /// BCPack requests refused (no decoder), by `DSTORAGE_BCPACK_MODE` pub bcpack_refused: BTreeMap, + /// BCPack requests the decoder ran on, by `DSTORAGE_BCPACK_MODE` + #[serde(default)] + pub bcpack_unpacked: BTreeMap, } pub fn stats() -> DStorageStats { - DStorageStats { bcpack_refused: BCPACK.stats() } + DStorageStats { bcpack_refused: BCPACK.stats(), bcpack_unpacked: UNPACKED.stats() } +} + +/// BCPack requests that reached the decoder, by mode. +struct BcpackUnpacked { + requests: [AtomicU64; 16], + bytes: [AtomicU64; 16], + failed: [AtomicU64; 16], +} + +impl BcpackUnpacked { + const fn new() -> Self { + const Z: AtomicU64 = AtomicU64::new(0); + Self { requests: [Z; 16], bytes: [Z; 16], failed: [Z; 16] } + } + + fn stats(&self) -> BTreeMap { + (1..16u8) + .filter(|&m| self.requests[m as usize].load(Ordering::Relaxed) + self.failed[m as usize].load(Ordering::Relaxed) > 0) + .map(|m| { + let i = m as usize; + let s = BcpackUnpackStats { + requests: self.requests[i].load(Ordering::Relaxed), + destination_bytes: self.bytes[i].load(Ordering::Relaxed), + failed: self.failed[i].load(Ordering::Relaxed), + }; + (bcpack_name(m), s) + }) + .collect() + } +} + +static UNPACKED: BcpackUnpacked = BcpackUnpacked::new(); + +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +pub struct BcpackUnpackStats { + /// requests whose blocks were rebuilt + pub requests: u64, + /// bytes of blocks rebuilt for them (counted before the write to the destination) + pub destination_bytes: u64, + /// requests whose stream the decoder did not take (they fail with E_DECOMPRESSION) + pub failed: u64, +} + +/// The BCPack stage of a request: `packed` to the `n` bytes of blocks of its mode. +fn bcpack_unpack(r: &Request, packed: &[u8], n: usize) -> Result, HRESULT> { + let bc = r.bcpack(); + let i = bc as usize & 0xF; + match super::bcpack::decode(bc, packed, n) { + Ok(blocks) => { + if UNPACKED.requests[i].fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("DirectStorage: BCPack {}: first request unpacked ({} to {n} bytes)", bcpack_name(bc), packed.len()); + } + UNPACKED.bytes[i].fetch_add(n as u64, Ordering::Relaxed); + Ok(blocks) + } + Err(e) => { + let k = UNPACKED.failed[i].fetch_add(1, Ordering::Relaxed) + 1; + // one warning per mode and kind of failure, then a running count + warn_once( + &format!("BCPack {} stream ({})", bcpack_name(bc), e.kind()), + format_args!("{e} (packed={}, dst={n}); the request fails with E_DECOMPRESSION", packed.len()), + ); + if k <= 16 || k.is_power_of_two() { + crate::xlog_info!("DirectStorage: BCPack {} streams not unpacked so far: {k}", bcpack_name(bc)); + } + Err(E_DECOMPRESSION) + } + } } /// Log a refused BCPack request: one warning per mode and zlib stage, then a running count on @@ -674,20 +746,24 @@ impl Request { return Err(E_DESTINATION_SIZE); } } - // Two-stage zlib -> BCPack: validate intermediate bounds when supplied, then refuse BCPack - // (counted and logged at enqueue, `BcpackRefusals`). - (true, _) => { + // Two-stage zlib -> BCPack: validate intermediate bounds when supplied, then refuse the + // BCPack modes without a decoder (counted and logged at enqueue, `BcpackRefusals`). + (true, bc) => { if self.intermediate_size != 0 && (self.intermediate_size <= self.source_size || self.destination_size <= self.intermediate_size) { return Err(E_DESTINATION_SIZE); } - return Err(E_DECOMPRESSION); + if !super::bcpack::can_decode(bc) { + return Err(E_DECOMPRESSION); + } } - // Single-stage BCPack: `intermediate_size` must be 0, then refuse BCPack. - (false, _) => { + // Single-stage BCPack: `intermediate_size` must be 0, then refuse the modes without a decoder. + (false, bc) => { if self.intermediate_size != 0 { return Err(E_DESTINATION_SIZE); } - return Err(E_DECOMPRESSION); + if !super::bcpack::can_decode(bc) { + return Err(E_DECOMPRESSION); + } } } Ok(()) @@ -805,23 +881,31 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us b }; - if r.swizzle() != 0 || r.bcpack() != 0 { + let bc = r.bcpack(); + if r.swizzle() != 0 || (bc != 0 && !super::bcpack::can_decode(bc)) { return Err(E_DECOMPRESSION); } - let payload: Vec = if r.zlib() { + // the stages in the console's order: zlib, then BCPack + let stage1: Vec = if r.zlib() { let stage1_len = if r.intermediate_size != 0 { r.intermediate_size as usize } else { n }; let mut d = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&src, stage1_len).map_err(|_| E_ZLIB_DATA)?; - if d.len() != stage1_len { + // zlib yields `intermediate_size` bytes; when the title names none, the destination's + // size, or before BCPack a stream of any size up to it. That last case is XCL's + // leniency, as is a BCPack stream no smaller than its blocks: the GDK documents + // `IntermediateSize` as the size of the stream BCPack reads, and what the console does + // with a request that leaves it 0 was not tested. + if d.len() != stage1_len && (bc == 0 || r.intermediate_size != 0) { return Err(E_ZLIB_DATA); } - if d.len() < n { + if bc == 0 && d.len() < n { d.resize(n, 0); } d } else { src }; + let payload = if bc != 0 { bcpack_unpack(r, &stage1, n)? } else { stage1 }; if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; @@ -1411,7 +1495,7 @@ mod tests { let mem = Request::parse(&request(SOURCE_MEMORY_BIT | 1, 0x1000, 64, 0x2000, 0x99, 20)); assert_eq!((mem.offset, mem.check(true)), (0, Ok(())), "a memory source has no offset"); assert_eq!(Request::parse(&request(1, 0x1000, 20, 0x2000, 0, 20)).check(false), Err(E_DESTINATION_SIZE)); - assert_eq!(Request::parse(&request(3, 0x1000, 64, 0x2000, 0, 20)).check(false), Err(E_DECOMPRESSION), "BCPack"); + assert_eq!(Request::parse(&request(15, 0x1000, 64, 0x2000, 0, 20)).check(false), Err(E_DECOMPRESSION), "BCPack BC7"); assert_eq!(Request::parse(&request(0, 0, 64, 0x2000, 0, 64)).check(false), Err(E_ACCESS_VIOLATION)); } @@ -1636,12 +1720,15 @@ mod tests { // Zlib only with invalid intermediate_size (<= src or > dst) assert_eq!(Request::parse(&request_ex(ZLIB_BIT, 0x1000, 0, 128, 0x2000, 0, 20, 20, 0)).check(false), Err(E_DESTINATION_SIZE)); assert_eq!(Request::parse(&request_ex(ZLIB_BIT, 0x1000, 0, 64, 0x2000, 0, 20, 96, 0)).check(false), Err(E_DESTINATION_SIZE)); - // Two-stage zlib + BCPack: valid sizes -> E_DECOMPRESSION, invalid intermediate -> E_DESTINATION_SIZE - assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DECOMPRESSION)); + // Two-stage zlib + BCPack: valid sizes -> E_DECOMPRESSION without a decoder for the mode, invalid intermediate -> E_DESTINATION_SIZE + assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc7, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DECOMPRESSION)); + assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Ok(())); + assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc1, 0x1000, 0, 256, 0x2000, 0, 20, 20, 0)).check(false), Err(E_DESTINATION_SIZE)); assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc7, 0x1000, 0, 256, 0x2000, 0, 20, 20, 0)).check(false), Err(E_DESTINATION_SIZE)); assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc7, 0x1000, 0, 64, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DESTINATION_SIZE)); - // Single-stage BCPack: intermediate must be 0, then E_DECOMPRESSION - assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Err(E_DECOMPRESSION)); + // Single-stage BCPack: intermediate must be 0, then E_DECOMPRESSION without a decoder for the mode + assert_eq!(Request::parse(&request_ex(bc7, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Err(E_DECOMPRESSION)); + assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Ok(())); assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DESTINATION_SIZE)); // Hardware swizzle mode unsupported assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_DECOMPRESSION)); @@ -2122,19 +2209,99 @@ mod tests { let counts = BcpackRefusals::new(); let bc7 = Request::parse(&request(SOURCE_MEMORY_BIT | 7 << BCPACK_SHIFT, 0x1000, 0x10000, 0x2000, 0, 0x4000)); let bc7_zlib = Request::parse(&request(SOURCE_MEMORY_BIT | ZLIB_BIT | 7 << BCPACK_SHIFT, 0x1000, 0x10000, 0x2000, 0, 0x4000)); - let bc1 = Request::parse(&request(SOURCE_MEMORY_BIT | 1 << BCPACK_SHIFT, 0x1000, 0x8000, 0x2000, 0, 0x1000)); - for (i, r) in [&bc7, &bc7_zlib, &bc1, &bc7].into_iter().enumerate() { + let bc3 = Request::parse(&request(SOURCE_MEMORY_BIT | 3 << BCPACK_SHIFT, 0x1000, 0x8000, 0x2000, 0, 0x1000)); + for (i, r) in [&bc7, &bc7_zlib, &bc3, &bc7].into_iter().enumerate() { assert_eq!(r.check(true), Err(E_DECOMPRESSION), "the request fails as before"); assert_eq!(counts.note(r), i as u64 + 1); } let s = counts.stats(); - assert_eq!(s.keys().collect::>(), ["BC1", "BC7"]); + assert_eq!(s.keys().collect::>(), ["BC3", "BC7"]); assert_eq!((s["BC7"].requests, s["BC7"].with_zlib, s["BC7"].destination_bytes), (3, 1, 0x30000)); - assert_eq!((s["BC1"].requests, s["BC1"].with_zlib, s["BC1"].destination_bytes), (1, 0, 0x8000)); - assert_eq!(counts.summary(), "BC1 1 (32768 bytes), BC7 3 (196608 bytes)"); - for m in 1..=7u64 { + assert_eq!((s["BC3"].requests, s["BC3"].with_zlib, s["BC3"].destination_bytes), (1, 0, 0x8000)); + assert_eq!(counts.summary(), "BC3 1 (32768 bytes), BC7 3 (196608 bytes)"); + // every mode without a block rebuild; BC1 has one (in the tests, with their tables) + for m in 1..=15u64 { let r = Request::parse(&request(SOURCE_MEMORY_BIT | m << BCPACK_SHIFT, 0x1000, 64, 0x2000, 0, 20)); - assert_eq!(r.check(true), Err(E_DECOMPRESSION)); + assert_eq!(r.check(true), if m == 1 { Ok(()) } else { Err(E_DECOMPRESSION) }, "mode {m}"); + } + } + + /// BC1 requests through a queue: BCPack alone and after zlib, against blocks built + /// independently of the decoder (`tests/data/bcpack`). + #[test] + fn bcpack_bc1_requests_are_unpacked_alone_and_after_zlib() { + use crate::hle::bcpack::tests as fx; + let bc1 = SOURCE_MEMORY_BIT | 1 << BCPACK_SHIFT; + let small = fx::data("bc1-16-1.bin").unwrap(); + let small_blocks = fx::data("bc1-16-1.bc1").unwrap(); + // 64 KiB of blocks; zero padding after the stream (as in a title's files) lets zlib shrink it + let mut large = fx::data("bc1-8192-3.bin").unwrap(); + large.resize(large.len() + 2048, 0); + let large_blocks = crate::hle::bcpack::bc1::assemble(&fx::large_fixture_symbols(1), fx::tables()).unwrap(); + let zipped = miniz_oxide::deflate::compress_to_vec_zlib(&large, 6); + assert!(zipped.len() < large.len() && large_blocks.len() == 0x10000); + unsafe { + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&32u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 8, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + let before = stats().bcpack_unpacked.get("BC1").cloned().unwrap_or_default(); + + // (options, source, destination size, intermediate size) → status, destination + let damaged = &small[..small.len() - 1]; + let cases: [(u64, &[u8], usize, usize, HRESULT, Option<&[u8]>); 7] = [ + (bc1, &small, small_blocks.len(), 0, S_OK, Some(&small_blocks)), + (bc1 | ZLIB_BIT, &zipped, 0x10000, large.len(), S_OK, Some(&large_blocks)), + (bc1 | ZLIB_BIT, &zipped, 0x10000, 0, S_OK, Some(&large_blocks)), + // the intermediate size is zlib's output to the byte + (bc1 | ZLIB_BIT, &zipped, 0x10000, large.len() + 1, E_ZLIB_DATA, None), + // a stream that is not whole, and one for another number of blocks + (bc1, damaged, small_blocks.len(), 0, E_DECOMPRESSION, None), + (bc1, &small, small_blocks.len() + 8, 0, E_DECOMPRESSION, None), + // control: the same bytes without the BCPack stage are not the blocks + (SOURCE_MEMORY_BIT, &small[..small_blocks.len()], small_blocks.len(), 0, S_OK, Some(&small[..small_blocks.len()])), + ]; + let mut dsts: Vec> = cases.iter().map(|c| vec![0xCDu8; c.2 + 64]).collect(); + for (i, (c, dst)) in cases.iter().zip(dsts.iter_mut()).enumerate() { + enqueue(q, request_ex(c.0, dst.as_mut_ptr() as u64, 0, c.2 as u32, c.1.as_ptr() as u64, 0, c.1.len() as u32, c.3 as u32, 0).as_ptr()); + status(q, s, i as u32); + } + submit(q); + let t = std::time::Instant::now(); + while !complete(s, cases.len() as u32 - 1) && t.elapsed().as_secs() < 10 { + std::thread::yield_now(); + } + for (i, (c, dst)) in cases.iter().zip(&dsts).enumerate() { + assert_eq!(hresult(s, i as u32), c.4, "request {i}"); + match c.5 { + Some(want) => assert!(&dst[..c.2] == want, "request {i}: the destination has the blocks"), + None => assert!(dst[..c.2].iter().all(|&b| b == 0xCD), "request {i}: a failed request writes nothing"), + } + assert!(dst[c.2..].iter().all(|&b| b == 0xCD), "request {i}: nothing past the destination size"); + } + assert_ne!(small[..small_blocks.len()], small_blocks[..], "the control differs from the blocks"); + let after = stats().bcpack_unpacked["BC1"].clone(); + assert!(after.requests >= before.requests + 3 && after.destination_bytes >= before.destination_bytes + 0x20000 + small_blocks.len() as u64); + assert!(after.failed >= before.failed + 2); + queue_close(q); + queue_release(q); + status_release(s); } } diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 378f4b378..d54f98b78 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -75,7 +75,7 @@ pub struct Report { /// XCL slots it called that XCL does not implement #[serde(default)] pub xgameruntime: crate::hle::xgameruntime::api::ApiStats, - /// DirectStorage: BCPack requests refused (no decoder) by mode, and bytes filled under + /// DirectStorage: BCPack requests unpacked and refused (no decoder) by mode, and bytes filled under /// `XCL_DSTORAGE_BCPACK_FILL` #[serde(default)] pub dstorage: crate::hle::dstorage::DStorageStats, diff --git a/scripts/gen_bcpack_bc1_tables.py b/scripts/gen_bcpack_bc1_tables.py new file mode 100644 index 000000000..f23536bf0 --- /dev/null +++ b/scripts/gen_bcpack_bc1_tables.py @@ -0,0 +1,84 @@ +"""Generate crates/xcl/src/hle/bcpack/bc1_fitted.rs from the two BC1 tables bcpack-rs publishes +(Ahmet Dedeler, MIT): the endpoint history a BCPack BC1 stream starts with and the order of +its 256 selector quadrants. Neither is in a stream or in a public specification; bcpack-rs +estimated them from retail streams (see its README for how, and how sure each entry is). + +usage: python scripts/gen_bcpack_bc1_tables.py /data/bc1_window.json /data/bc1_quad_table.json +(https://github.com/Ahmet-Dedeler/bcpack-rs, commit c51ec52)""" +import io, json, os, sys + +window = json.load(io.open(sys.argv[1], encoding='utf-8'))['slots'] +quads = json.load(io.open(sys.argv[2], encoding='utf-8'))['entries'] +OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'crates', 'xcl', 'src', 'hle', 'bcpack', 'bc1_fitted.rs') + +assert len(window) == 256 and len(quads) == 256 +RANGE = [32, 64, 32, 32, 64, 32] +history = [] +for s in window: + if s is None: + history.append(None) + continue + v = s['value'] + assert len(v) == 6 and all(0 <= c < r for c, r in zip(v, RANGE)) + history.append(v) +# a symbol's four selectors: top-left, top-right, bottom-left, bottom-right texel of the quadrant +codes = [None] * 256 +for e in quads: + c = e['codes'] + assert len(c) == 4 and all(0 <= x < 4 for x in c) and codes[e['sym']] is None + codes[e['sym']] = c[0] | c[1] << 2 | c[2] << 4 | c[3] << 6 +assert sorted(codes) == list(range(256)) +unsure_h = [i for i, s in enumerate(window) if s is not None and not s.get('halves_agree', True)] +unsure_q = sorted(e['sym'] for e in quads if not e.get('stable_halves', True)) + +out = io.open(OUT, 'w', encoding='utf-8', newline='\n') +out.write(f'''// Generated by scripts/gen_bcpack_bc1_tables.py from the tables of +// bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs, commit c51ec52, +// data/bc1_window.json and data/bc1_quad_table.json), used under its MIT license: +// +// MIT License +// +// Copyright (c) 2026 Ahmet Dedeler +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// The constants of BCPack's BC1 block rebuild that no stream carries. They were estimated by +// bcpack-rs from retail data (decoded blocks against the next smaller mip level, which is +// stored unpacked); they are constants of the codec, not game content. Being estimates, they +// make the BC1 output of XCL an approximation wherever one of them is wrong: +// * history: {sum(h is not None for h in history)} of the 255 entries that can be read; the `None` ones were never referred to +// in the data of the fit. Fits on two halves of that data differ, by a step or so, in +// {len(unsure_h)} entries ({', '.join(map(str, unsure_h))}). +// * quadrants: all 256. Fits on two halves of the data swap {len(unsure_q)} entries +// ({', '.join(map(str, unsure_q))}; rare mirror pairs). +// A block rebuilt from a history entry carries its error, and so do the blocks that refer to it. + +use super::bc1::Tables; + +pub static TABLES: Tables = Tables {{ + history: [ +''') +for i in range(0, 256, 4): + out.write(' ' + ' '.join('None,' if h is None else 'Some([' + ', '.join(str(c) for c in h) + ']),' for h in history[i:i + 4]) + '\n') +out.write(' ],\n quadrants: [\n') +for i in range(0, 256, 16): + out.write(' ' + ', '.join(str(c) for c in codes[i:i + 16]) + ',\n') +out.write(' ],\n};\n') +out.close() +print('wrote', os.path.normpath(OUT)) diff --git a/tests/data/bcpack/bc1-1-8.bc1 b/tests/data/bcpack/bc1-1-8.bc1 new file mode 100644 index 000000000..902d3ff18 --- /dev/null +++ b/tests/data/bcpack/bc1-1-8.bc1 @@ -0,0 +1 @@ +ê·o”¾gý \ No newline at end of file diff --git a/tests/data/bcpack/bc1-16-1.bc1 b/tests/data/bcpack/bc1-16-1.bc1 new file mode 100644 index 0000000000000000000000000000000000000000..224f45bab89ccf7a42e2948bb2e6c62c1a878ed2 GIT binary patch literal 128 zcmV-`0Du3M4Bav15RCw#BS>F~lWn0P6J7`eK-$25M+I-iW&)5&Q;)QT5|{yU+|mR&$hzw^+DliQ)`c}}nsSG>@NfN!{2)8Anx iMJ$vTfQEp0<$*FKMi?;wJ;-}P1tP(H2xMnH77wuyQ#X(R literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-16-9.bc1 b/tests/data/bcpack/bc1-16-9.bc1 new file mode 100644 index 000000000..1f4321f3d --- /dev/null +++ b/tests/data/bcpack/bc1-16-9.bc1 @@ -0,0 +1 @@ +5Àöåvî'vâäüàŠFjEŠš—GÌB?‘5ªÑfY9>Ág’ËÇ€¶ü¢öz¼ÕûŠâ&Këò!¹èˆð1p(4¦ÿßæ“†¶+ëb”ÞˆâÚ¼ûÃDþ°áöÃ3ŒRÏ}µÉî·)®éˆåwisRiVPAp*>EXi4G~He(dA- zMBaU*zxebR&lDhk0rd~jJ z&IIt*L{V*I0yu4D66#;m^Dw4Zq8VmhH6GtYWm!mF&8miZ&Kp z8c*`t8Po61w}EPVK^kOr02gFL=(*h~R5M;+LQOGLK=a((g)m-G1UD;p3MW&w>A>D^ zvs@fJk^h0Xv`~#EwxeKHf;eZ|UgcL$>(o$uBknt93g<*i3*U0NxjoMs7{G6OXoSlO za)Mt^%TTp;HOfcK!T0t-vb+*Y-D@-p$qi)i;!vGMdELXY= zyM5x7*+1LYG!Si@2>H7OawOzME_BYOCU?@4YDfHU1^rh3ZxAabf3Mzs_OII!MTjv% zU~w`QBxD?y2FrkrTUmg%sjaG~4DZ0AOW%<95F-qO`jI@Fr0$b}L`}pMiV0Onitxa&PP=ao=KJ)^#xK-}2u@*Rmn)#z^bMm{yjy*nIMoX2VB8Rh2 z-RcXocCdi{%$o%HC*ST>jakT~B+o?m?2?K`#Df|6KC!GT2kVSX!L(8qj3{ z1#gtg4#5pxxU(EfAV8?we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0S=L`uhij=eRpL=&`1UmQ}(5pd2<0_-CmxjCPXf z*<9^4*Yd+5L9~c%HdGFipdK@{sDY^cS2c5A?_7d7RyHJgQ-$@;&$t$j`i=53j6Y2r zn0;p^J%8Xb^Hjy&Ua1h8cQrQ&x5<6dOBl2=v94l}BZVk0GzEi`3YX6Nv4pDXb`_As6O0&k) zDW_?SIvOgpx|Ec&ey^$w2|qWqixwWWh$#bWHGB+IqGrw}i!^KwFh>n6ITt)2by4e^ zOW})xFJJ-g{8{cHijR$4V+Od5aHQn6Fe{i-@U7C?CdLwczFaTbF*T-rkIJ!eVWQ~V z4@$SAHEn_1KVvPttUQZN1t7+}#$xw1vRWPKtp<*9J!mgX>ur22WOLn=+f zULTytp>-iWUwR0NlE=woTP`A^P_K%%wgd$CTQ*o9lV672x9t@f7cKSCxGm9@Fq$-B u4Sc1HV&cF2sVE{Z--^pYvMp+pS*6W}j&E-T<}Zo}hRq)7e6OZKbOdLqQqsKu literal 0 HcmV?d00001 From 6fd5a606d759bab19881a1be294ebc5bd891bf83 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Mon, 23 Nov 2026 23:34:29 +0100 Subject: [PATCH 3/5] DirectStorage: BCPack BC4 block rebuild, without its tables, not yet called Stacked on #273 (BC1), which is stacked on #208 (entropy stage). Adds hle/bcpack/bc4.rs: BC4 blocks from the 12 lane symbols of a BC4 stream, in the form of #273's bc1.rs. Lane 0 is a back-reference to the block whose endpoints predict this one's (or to a built-in history before block 0, or 128/128 for none), lane 1 must be 0, lanes 2-3 are zigzag differences of A0/A1 modulo 256, and lanes 4-11 are the 3-bit selectors two texels at a time through a 64-entry pair table, row by row, left half first. The rebuild needs two constants that no stream carries: the order of the 64 pairs and the 255-entry history. XCL has no source for them it can take, so they are a parameter (bc4::Tables), nothing is shipped and nothing calls the rebuild: DirectStorage refuses BC4 requests exactly as before. Every BC4 chunk of the retail title checked here predicts from the history in its first blocks, so the pair table alone would unlock none of them. Checked: - tests/data/bcpack/generate.py builds bc4-300-4 (300 blocks, predictions from the history and from the stream) with made-up tables and its own per-texel Python assembly; the decoder gives the same blocks, and refuses a block whose history entry is unknown. - A hand-built three-block case covers every field, wrapping differences and a non-zero lane 1. AI-assisted. --- crates/xcl/src/hle/bcpack/bc4.rs | 76 +++++++++++++++++++++++++++++ crates/xcl/src/hle/bcpack/mod.rs | 5 ++ crates/xcl/src/hle/bcpack/tests.rs | 65 ++++++++++++++++++++++-- tests/data/bcpack/bc4-300-4.bc4 | Bin 0 -> 2400 bytes tests/data/bcpack/bc4-300-4.bin | Bin 0 -> 3076 bytes tests/data/bcpack/bc4-300-4.lanes | Bin 0 -> 3600 bytes tests/data/bcpack/generate.py | 41 +++++++++++++++- 7 files changed, 182 insertions(+), 5 deletions(-) create mode 100644 crates/xcl/src/hle/bcpack/bc4.rs create mode 100644 tests/data/bcpack/bc4-300-4.bc4 create mode 100644 tests/data/bcpack/bc4-300-4.bin create mode 100644 tests/data/bcpack/bc4-300-4.lanes diff --git a/crates/xcl/src/hle/bcpack/bc4.rs b/crates/xcl/src/hle/bcpack/bc4.rs new file mode 100644 index 000000000..57efcc4fc --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc4.rs @@ -0,0 +1,76 @@ +//! BC4 blocks from the 12 lanes of a BCPack BC4 stream (one symbol per lane and block). +//! +//! For block `i`, in stream order: +//! * lane 0 is a distance `d` back to the block whose endpoints predict this one's, read as in +//! BC1: symbol 0 is "none" (predict 128 for both), an even symbol `v` is `v / 2`, an odd one +//! `255 - v / 2`. Before block 0 the prediction comes from a built-in history of 255 endpoint +//! pairs ([`Tables::history`]), +//! * lane 1 was 0 in every stream seen, +//! * lanes 2 and 3 are the differences of A0 and A1 from the prediction, 0, -1, 1, -2, 2 … for +//! the symbols 0, 1, 2, 3, 4 …, modulo 256, +//! * lanes 4–11 are the 3-bit selectors two texels at a time: lanes 4 and 5 the left and right +//! halves of the top row, 6 and 7 the second row, and so on. Each symbol is the index of one +//! of the 64 possible pairs in a fixed order ([`Tables::pair_codes`]). +//! +//! The rebuild needs both tables. No stream carries them, and XCL has no source for them it can +//! take, so they are a parameter and nothing calls this yet. + +use super::{decode_lanes, Error}; + +/// The constants of the BC4 rebuild that are not in a stream. +pub struct Tables { + /// The endpoints `[A0, A1]` of the blocks before a stream's first: `history[256 - k]` is + /// the block `k` before block 0 (k = 1..=255; entry 0 is never read). `None`: not known. + pub history: [Option<[u8; 2]>; 256], + /// The selectors of each pair symbol: bits 0–2 the left texel, 3–5 the right one. + pub pair_codes: [u8; 64], +} + +/// Unpack a BC4 stream to its `out_len` bytes of blocks. +pub fn decode(src: &[u8], out_len: usize, tables: &Tables) -> Result, Error> { + assemble(&decode_lanes(4, src, out_len)?, tables) +} + +/// The blocks of `symbols` (12 per block, in [`super::decode_lanes`]'s order). +pub fn assemble(symbols: &[u8], tables: &Tables) -> Result, Error> { + let blocks = symbols.len() / 12; + let mut out = Vec::new(); + out.try_reserve_exact(blocks * 8).map_err(|_| Error::OutputSize)?; + out.resize(blocks * 8, 0u8); + for (i, s) in symbols.chunks_exact(12).enumerate() { + if s[1] != 0 { + return Err(Error::Lane1 { block: i }); + } + let predicted = match back_reference(s[0]) { + 0 => [128, 128], + d if d <= i => [out[(i - d) * 8], out[(i - d) * 8 + 1]], + d => { + let slot = 256 + i - d; + tables.history[slot].ok_or(Error::History { block: i, slot })? + } + }; + let b = &mut out[i * 8..i * 8 + 8]; + b[0] = predicted[0].wrapping_add(delta(s[2])); + b[1] = predicted[1].wrapping_add(delta(s[3])); + b[2..8].copy_from_slice(&selector_rows(s[4..12].iter().copied(), &tables.pair_codes).to_le_bytes()[..6]); + } + Ok(out) +} + +/// Lane 0 of BC4, as BC1's: the symbols 0, 1, 2, 3, 4 … are 0, 255, 1, +/// 254, 2 … blocks back. +pub(super) fn back_reference(v: u8) -> usize { + let v = v as usize; + if v % 2 == 0 { v / 2 } else { 255 - v / 2 } +} + +/// A difference symbol: 0, -1, 1, -2, 2 … as a wrapping 8-bit step. +pub(super) fn delta(v: u8) -> u8 { + if v % 2 == 0 { v / 2 } else { !(v / 2) } +} + +/// The 48 selector bits of a BC4 block (3 bits a texel, the top-left texel lowest) from its +/// eight pair symbols, two per row, left half first. +pub(super) fn selector_rows(halves: impl Iterator, codes: &[u8; 64]) -> u64 { + halves.enumerate().map(|(h, s)| (codes[s as usize] as u64) << (6 * h)).fold(0, |a, b| a | b) +} diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs index 845acaa39..c415e5098 100644 --- a/crates/xcl/src/hle/bcpack/mod.rs +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -12,6 +12,10 @@ //! the stream ([`bc1::Tables`]). XCL has the estimates bcpack-rs made of them //! (`bc1_fitted.rs`), so its BC1 blocks are an approximation wherever an estimate is off. //! +//! * the rebuild of BC4 blocks ([`bc4`]), which also needs two tables of constants that are +//! not in the stream ([`bc4::Tables`]). XCL has no source for them it can take, so nothing +//! calls it and BC4 requests are still refused. +//! //! What is not: the rebuild of the other formats. Their lanes decode, but how the symbols map //! to block bits is not published in a form XCL can use, so those requests are still refused. //! @@ -23,6 +27,7 @@ pub mod bc1; mod bc1_fitted; +pub mod bc4; mod lanes; mod rans_tables; diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index a5ab53aef..18925687a 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -4,7 +4,7 @@ use super::lanes::{self, L}; use super::rans_tables::FREQ; -use super::{bc1, decode_lanes, lane_widths, Error}; +use super::{bc1, bc4, decode_lanes, lane_widths, Error}; /// The tables the fixtures' `.bc1` files were made with: history entry `slot` has the /// channels `(7 * slot + 13 * k) mod range`, and a quadrant symbol is its own selectors. @@ -35,9 +35,9 @@ fn by_unit(lane_major: &[u8], lanes: usize) -> Vec { (0..units * lanes).map(|i| lane_major[(i % lanes) * units + i / lanes]).collect() } -const FIXTURES: [&str; 14] = [ +const FIXTURES: [&str; 15] = [ "bc1-1-8", "bc1-2-0", "bc1-16-1", "bc1-16-9", "bc1-700-2", "bc1-8192-3", "bc3-16-1", "bc4-16-1", "bc5-16-1", "bc6-16-1", "bc7-2-0", "bc7-16-1", - "bc7-700-2", "bc7-8192-3", + "bc7-700-2", "bc7-8192-3", "bc4-300-4", ]; /// The symbols of the two 64 KiB fixtures, which ship without a `.lanes` file (`generate.py`). @@ -371,3 +371,62 @@ fn fitted_bc1_tables_are_well_formed() { assert_eq!(bc1::assemble(&s, t), Err(Error::History { block: 0, slot })); } } + +/// The made-up constants the BC3/BC4/BC5 fixtures were built with (`generate.py`): pair symbol +/// `s` is the selectors `(5s + 3) mod 64`, history entry `slot` holds `(7 slot + 13 k) mod 256`. +fn made_up_pairs() -> [u8; 64] { + std::array::from_fn(|s| ((5 * s + 3) % 64) as u8) +} + +fn made_up_history(slot: usize) -> Option<[u8; N]> { + Some(std::array::from_fn(|k| ((7 * slot + 13 * k) % 256) as u8)) +} + +fn bc4_tables() -> bc4::Tables { + bc4::Tables { history: std::array::from_fn(made_up_history), pair_codes: made_up_pairs() } +} + +#[test] +fn bc4_fixture_decodes_to_its_blocks() { + let tables = bc4_tables(); + let bin = data("bc4-300-4.bin").unwrap(); + let want = data("bc4-300-4.bc4").unwrap(); + assert_eq!(bc4::decode(&bin, 300 * 8, &tables).as_deref(), Ok(&want[..])); + // a block that predicts from an entry nobody knows is refused, not guessed + let lanes = data("bc4-300-4.lanes").unwrap(); + let i = (0..300).find(|&i| bc4::back_reference(lanes[i]) > i).unwrap(); + let slot = 256 + i - bc4::back_reference(lanes[i]); + let mut gap = bc4_tables(); + gap.history[slot] = None; + assert_eq!(bc4::decode(&bin, 300 * 8, &gap), Err(Error::History { block: i, slot })); + // a cut stream and the lanes' own errors come through + assert!(bc4::decode(&bin[..bin.len() - 1], 300 * 8, &tables).is_err()); + assert_eq!(bc4::decode(&bin, 300 * 8 + 4, &tables), Err(Error::OutputSize)); +} + +/// Three blocks by hand: every field, both kinds of prediction, wrapping differences. +#[test] +fn bc4_block_rebuild() { + let mut tables = bc4_tables(); + tables.pair_codes = std::array::from_fn(|s| s as u8); + tables.history[255] = Some([250, 3]); + let halves = [0o01u8, 0o23, 0o45, 0o67, 0o70, 0o52, 0o34, 0o16]; + #[rustfmt::skip] + let symbols = [ + // 1 block back: the history's last entry; +10 and -4 + 2, 0, 20, 7, halves[0], halves[1], halves[2], halves[3], halves[4], halves[5], halves[6], halves[7], + // 1 block back: block 0; -1 and +0 + 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // no prediction: 128 for both; +1 and -128 + 0, 0, 2, 255, 63, 63, 63, 63, 63, 63, 63, 63, + ]; + let out = bc4::assemble(&symbols, &tables).unwrap(); + // texel (x, y) has bits 3 (4y + x): the left texel of a pair is its low three bits + let rows = 0o16_34_52_70_67_45_23_01u64.to_le_bytes(); + assert_eq!(out[..8], [4, 255, rows[0], rows[1], rows[2], rows[3], rows[4], rows[5]]); + assert_eq!(out[8..16], [3, 255, 0, 0, 0, 0, 0, 0]); + assert_eq!(out[16..24], [129, 0, 255, 255, 255, 255, 255, 255]); + let mut lane1 = symbols; + lane1[12 + 1] = 1; + assert_eq!(bc4::assemble(&lane1, &tables), Err(Error::Lane1 { block: 1 })); +} diff --git a/tests/data/bcpack/bc4-300-4.bc4 b/tests/data/bcpack/bc4-300-4.bc4 new file mode 100644 index 0000000000000000000000000000000000000000..0613ecbb6a9f1ee31ad85186be8d2cf68d1d39fc GIT binary patch literal 2400 zcmV-m37_`MvMU8F!pX9E7xX1Re$uhGjZEBsNB0IMkE-_kc>#LSukZBGC_FR=&{0G@Czsha@x4z8jFKoy?SYh|#Uw!UZkoo);KX=)o8}2Y< z=p>3g1*;-n&$;dXF8Sm%>X(nwzRTDmT5a0`K>y0+zMZ=!k+BGQ_Dpj=rX(8L$Vx#0 zLulxd^-Q+tTPc5To^HG;vMf*}Y=qVdK9nfqMhc8$vJkt6?hGXeEpb_;(WnGR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N^@Eo+Sj%>U(W=zY>yO|KigulfDOW%pMRP{x>w= z5)F0vibvIU`!2b_tPf+jJvgFdi+L{wnWL#mt8u-evf8kILimXWOY$rHVy{idvniC$ zKZv>K{8Rjd{r_O?stN+6Jy2`e zcKDnDuM?q=5Y#|Rb$RT7v0kv6FdO9#q2$WODA+xyUh%Mfi#BKBTQ(2E0t!H!F?jS1 zO+O6F&id%D41H)Z6da*Bs!u5Y1{hD9j^7aOF67(g@*>z> z#vNGyQ=j@-kMa20b~2;{F%2=en>;1zqw16q%YJwbs$`51JIvMwEH`yC9zEi_65}Q# zmyGh~gY(L_G$(3Wb&f_r=j^LzTh|0lH9xR~1XHFI?FGrTo)+`s#9%tcCOfUB)?&ua ziUX?NfS(1yvt1tb?I|QFB14eQuc5ZJMOCFqgr$7Wl=uGv3J5#Cec-2MUMW%gQ*~*V zT@i)5zk~u&{=l5xI{twp3p04adMHag(!pO*iX!!~!Uho7Lgcq2D5GD*RIVi4H59mtn4XF>@K$ z8@}PHkf&7nbY{Bcj|>3D27IHbCFeG-8Z_870&2_Q$^pzcHH!68U)B-d%Ho#hGB>%H_S3(hCTEXUM+x zSxN~{32XsrAX8u~Jo=yb%jT+=$MWK02nRw~g4GPS~$jRkdc+VQXiF3FlFjw+lr^$8~i`>u+aU5^d Sf8HmoB)2RVT#ys~?=8xT{;jD1 literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc4-300-4.bin b/tests/data/bcpack/bc4-300-4.bin new file mode 100644 index 0000000000000000000000000000000000000000..7e70afb67925461546980caad93890f1833b473f GIT binary patch literal 3076 zcmV+f4EysiFfcF>5D*YAFE20T zXy$+QRj^X}QDJkfDrz`SQ?SRUz@Kmwt1xgbQG`MwPpe)Qs(Ia&v8P-LO%PyL7!-3x zXPUp+#y;0^Mg0%>U%oTFwQ~5lL-8pR|AhAb zztmriK|SkOKP51ViHl`t%JYpjJ!Avd2~u(#3{0PfJ5i2rYIJ7<8=oz0IZ1~NH%DaF zc%U!->yNU9H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11aa9`b{0K5GWUPx!-Bt3!-4<`OOU8?oa1aoYYH;vi)T(~oXTTcC#sunzy zaB4C~T8B`kjNe>c7;{h+S@$47HE*=0rwgaKSVe;e$5k^=63 zYI9bYRrI1<72n6>c)$a(RI_ZY zm~qqOq^2rOGB|A z-Yi0>)Z}W+N*B7~rEVBSX0+8XNdYVa7du}WNyb$tNO!k7N3J(4TJ3I|;9tbMMo;eX zflK!2`^bLYMWNyT9n65xU9D);M5p-UL*`%Fmog_g?nQedLUuq`uFH{&)f>BHL5!o+ zGf>y~lh99^KpfHaKOjR-=SmZukeS`sJ`$OYrfiv6^`z81J>l(@bWSdT?L6vLJUCUp zJA7FE8xR8Q4V;2gI&*W$2mUq=)Vw)bIr8AuY%}@*KJt!CI3QuCH&f72g&p5K_=ns5 zHd#V2XQ3E2*Xp{hHDnKKwiSqfuUVIbGytH8rwnXO*EF=BFb7XPFZXmAui}bmtE#&=E~lXeRDX zKkmxqg*Brp7UZE0uDUZVswu-s72Atgaq$>@k|`8g6u|G26F2gB%$~$=5`6H!5?4%a z=_WuqCEjOc5lJ{en_X;{hcQvJ5D}p-4_1`*Vn#4XLt2w34(WlKY^6r(4e_3X zk{g8P%Q9|T4B;K93%df8v~*0Nw6P7o3fSXkf+1&D=wvdkj16ri9j1j`<`1FGVrJQy(WkW7pK S0ssI200000000000001MT+7Y? literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc4-300-4.lanes b/tests/data/bcpack/bc4-300-4.lanes new file mode 100644 index 0000000000000000000000000000000000000000..52e997c4e1477e734dba7909cd729026b92ffb2f GIT binary patch literal 3600 zcmeHH{rl5|flr$@O`4=l(k5w|_rBz%X`41}nx=WvIfmXCA_yq%aWGJBa_;oD$@%z# zBFHIIHeTkTKInH-Q4|rjQvnZmkBXjehweP}1Oz$foZA>~9uvpy_!I6AxX+KD-#)K@ zf6wsc&(81G@~>@_u73KCi$=FziLYL}_`)q4_q89}zv7Y`KV8?^3~st_@h{%laPXtq z%kN#qnCx%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zSTynxjx;o9UX)wb#s7^0E*HKMa?6_Kr8x@;w2?X zgLAzKky2@#i$(wpMG!ec!30huj8RjDQ6c+?Bo$*REEGDn@0KNwL&W9)4Pk;9k&_Hp z9TIp)mjSS0lzN2%+&~9*KdhRJ9O{{pSXU-`Adk$9XyAYjiY$moY1bkva0nwZ+Kvli zdH_P@fDesIRPl>JA&27Qu^^3gs?CB~VBp|F0GTLQm3$cSp$YUA1@@tK$pyQik)W(f>w^N52?(W{S3^BAuuLxt8V-ndvsro!*ldnds<{x#8(u~lTP-{+r4l`& z`gt}zst1K?A#!4-)nM4dFotaz4m7R}^!zd-J8+?e12qkn!b(l4YW0Eb`L#)gw5qI8 z5U4(zGg~PK_Z2uNjNM^|YfvI>oY8)!_?ANsCY@T}RMG<0$RwHxDpndBL?qZ846ABu zNMmugg4C0C|Q4rXkgSn}gtq*jxE%LT!4>KewE4s() zey7Nm;{w;v+Rb!U6;*#+g9NO?G>UX8=JZUrL+8oWQ1{LldjW%gQ`SHHi1&b zrTea2mEdm4OWcV<73w3c+k}H*r;Bwh&IetqR(4!I#p^9DU3UQ081}MZ$dwy7!Gkdx J+tk>o|1Z6D=%xSw literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/generate.py b/tests/data/bcpack/generate.py index 18b738c6b..f17fb056f 100644 --- a/tests/data/bcpack/generate.py +++ b/tests/data/bcpack/generate.py @@ -117,13 +117,13 @@ def encode(symbols, widths, reductions, model=0, carry=False, trim=False): return bytes(out) -def generate(mode, units, seed, reduced, **options): +def generate(mode, units, seed, reduced, quiet_lane1=False, **options): widths = WIDTHS[mode] rng = random.Random(seed) reductions = [rng.randrange(4) if reduced else 0 for width in widths] symbols = [[rng.randrange(1 << (width - reduction)) for _ in range(units)] for width, reduction in zip(widths, reductions)] - if mode == 1: + if mode == 1 or quiet_lane1: symbols[1] = [0] * units path = ROOT / f'bc{mode}-{units}-{seed}' path.with_suffix('.bin').write_bytes(encode(symbols, widths, reductions, **options)) @@ -159,6 +159,39 @@ def assemble(symbols): return bytes(raw) +# Made-up constants for the BC3/BC4/BC5 fixtures (the real ones are not public under a licence +# XCL can take): pair symbol s means the selectors (5s + 3) mod 64, left texel in bits 0-2. +def made_up_pair(s): + return (5 * s + 3) % 64 + + +def made_up_history(slot, count): + return [(7 * slot + 13 * k) % 256 for k in range(count)] + + +def pair_selectors(halves): + """48 selector bits of a 4x4 block from its pair symbols, two a row, left half first.""" + bits = 0 + for y in range(4): + for x in range(4): + sel = made_up_pair(halves[2*y + x//2]) >> (3 * (x % 2)) & 7 + bits |= sel << (3 * (4*y + x)) + return bits.to_bytes(6, 'little') + + +def assemble_bc4(symbols): + blocks = [] + raw = bytearray() + for i, (ref, _, d0, d1, *halves) in enumerate(zip(*symbols)): + d = 255 - ref // 2 if ref & 1 else ref // 2 + predictor = ([128, 128] if d == 0 else + blocks[i-d] if i >= d else made_up_history((i-d) % 256, 2)) + ends = [(p + (~(v >> 1) if v & 1 else v >> 1)) % 256 for p, v in zip(predictor, (d0, d1))] + blocks.append(ends) + raw.extend(bytes(ends) + pair_selectors(halves)) + return bytes(raw) + + if __name__ == '__main__': for mode in WIDTHS: cases = [(2, 0, False), (16, 1, True), (700, 2, False)] @@ -173,6 +206,10 @@ def assemble(symbols): syms, path = generate(1, units, seed, False, **extra) path.with_suffix('.bc1').write_bytes(assemble(syms)) + # 300 blocks: the first ones predict from the history, the later ones from the stream + syms, path = generate(4, 300, 4, False, quiet_lane1=True) + path.with_suffix('.bc4').write_bytes(assemble_bc4(syms)) + for mode, widths in [(1, BC1), (7, BC7)]: units = 8192 syms = [[0] * units for _ in widths] From f58df2fe99e44525155585e90cc9bee3e58eff20 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Mon, 23 Nov 2026 23:35:38 +0100 Subject: [PATCH 4/5] DirectStorage: BCPack BC5 block rebuild, without its tables, not yet called Stacked on the BC4 rebuild. Adds hle/bcpack/bc5.rs: BC5 blocks from the 12 lanes, two symbols per lane and block (units 2i and 2i+1). Lane 0 is a back-reference split over the two units (even bits in the first, odd bits in the second) and then read as BC4's; lane 1 must be 0 in both; lanes 2 and 3 are the differences of R0/R1 and G0/G1, one per unit; lanes 4-7 and 8-11 are the red and green selectors, a row per lane, the row's left half in the first unit and its right half in the second, through a pair table as BC4's. It reuses BC4's back-reference, difference and selector helpers. As for BC4, the pair order and the 255-entry history of endpoints (R0, R1, G0, G1) are not in a stream and XCL has no source for them it can take: they are a parameter, nothing is shipped or wired, and BC5 requests are refused as before. Every BC5 chunk of the retail title checked here predicts from the history in its first blocks. Checked: - generate.py builds bc5-600-5 (300 blocks) with the made-up tables and its own Python assembly; the decoder gives the same blocks, refuses an unknown history entry and a size of half a block. - A hand-built two-block case: the split back-reference (one block back, then 255 back), both channels' differences and selector rows, lane 1. AI-assisted. --- crates/xcl/src/hle/bcpack/bc5.rs | 75 +++++++++++++++++++++++++++++ crates/xcl/src/hle/bcpack/mod.rs | 7 +-- crates/xcl/src/hle/bcpack/tests.rs | 54 +++++++++++++++++++-- tests/data/bcpack/bc5-600-5.bc5 | Bin 0 -> 4800 bytes tests/data/bcpack/bc5-600-5.bin | Bin 0 -> 5484 bytes tests/data/bcpack/bc5-600-5.lanes | Bin 0 -> 7200 bytes tests/data/bcpack/generate.py | 21 ++++++++ 7 files changed, 151 insertions(+), 6 deletions(-) create mode 100644 crates/xcl/src/hle/bcpack/bc5.rs create mode 100644 tests/data/bcpack/bc5-600-5.bc5 create mode 100644 tests/data/bcpack/bc5-600-5.bin create mode 100644 tests/data/bcpack/bc5-600-5.lanes diff --git a/crates/xcl/src/hle/bcpack/bc5.rs b/crates/xcl/src/hle/bcpack/bc5.rs new file mode 100644 index 000000000..4c6bbb0f1 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc5.rs @@ -0,0 +1,75 @@ +//! BC5 blocks from the 12 lanes of a BCPack BC5 stream (two symbols per lane and block: units +//! `2i` and `2i + 1`, called `u0` and `u1` here). +//! +//! For block `i`, in stream order: +//! * lane 0 holds a back-reference in two 4-bit halves: bit `k` of `u0` is bit `2k` of the +//! symbol, bit `k` of `u1` bit `2k + 1`; the symbol then reads as BC4's lane 0 +//! ([`super::bc4`]). Symbol 0 predicts 128 for all four endpoints, and before block 0 the +//! prediction comes from a built-in history ([`Tables::history`]), +//! * lane 1 was 0 in every stream seen, in both units, +//! * lane 2 is the difference of R0 (`u0`) and R1 (`u1`) from the prediction, lane 3 the same for +//! G0 and G1, as BC4's lanes 2 and 3, +//! * lanes 4–7 are the red selectors, one row each from the top, the left half of the row in +//! `u0` and the right half in `u1`, through a pair table as BC4's +//! ([`Tables::pair_codes`]); lanes 8–11 the green ones. +//! +//! As for BC4, XCL has no source it can take for the two tables, so nothing calls this yet. + +use super::bc4::{back_reference, delta, selector_rows}; +use super::{decode_lanes, Error}; + +/// The constants of the BC5 rebuild that are not in a stream. +pub struct Tables { + /// The endpoints `[R0, R1, G0, G1]` of the blocks before a stream's first: + /// `history[256 - k]` is the block `k` before block 0 (k = 1..=255; entry 0 is never read). + /// `None`: not known. + pub history: [Option<[u8; 4]>; 256], + /// The selectors of each pair symbol: bits 0–2 the left texel, 3–5 the right one. + pub pair_codes: [u8; 64], +} + +/// Unpack a BC5 stream to its `out_len` bytes of blocks. +pub fn decode(src: &[u8], out_len: usize, tables: &Tables) -> Result, Error> { + if out_len % 16 != 0 { + return Err(Error::OutputSize); + } + assemble(&decode_lanes(5, src, out_len)?, tables) +} + +/// The 8-bit symbol whose even bits are `even` and odd bits `odd` (BC3 and BC5 lane 0). +pub(super) fn interleave(even: u8, odd: u8) -> u8 { + (0..4).map(|k| (even >> k & 1) << (2 * k) | (odd >> k & 1) << (2 * k + 1)).fold(0, |x, y| x | y) +} + +/// The blocks of `symbols` (24 per block, in [`super::decode_lanes`]'s order). +pub fn assemble(symbols: &[u8], tables: &Tables) -> Result, Error> { + let blocks = symbols.len() / 24; + let mut out = Vec::new(); + out.try_reserve_exact(blocks * 16).map_err(|_| Error::OutputSize)?; + out.resize(blocks * 16, 0u8); + for (i, s) in symbols.chunks_exact(24).enumerate() { + let (u0, u1) = s.split_at(12); + if u0[1] != 0 || u1[1] != 0 { + return Err(Error::Lane1 { block: i }); + } + let predicted = match back_reference(interleave(u0[0], u1[0])) { + 0 => [128; 4], + d if d <= i => { + let p = &out[(i - d) * 16..]; + [p[0], p[1], p[8], p[9]] + } + d => { + let slot = 256 + i - d; + tables.history[slot].ok_or(Error::History { block: i, slot })? + } + }; + let o = &mut out[i * 16..i * 16 + 16]; + for (c, lanes) in [4..8, 8..12].into_iter().enumerate() { + o[8 * c] = predicted[2 * c].wrapping_add(delta(u0[2 + c])); + o[8 * c + 1] = predicted[2 * c + 1].wrapping_add(delta(u1[2 + c])); + let halves = lanes.flat_map(|l| [u0[l], u1[l]]); + o[8 * c + 2..8 * c + 8].copy_from_slice(&selector_rows(halves, &tables.pair_codes).to_le_bytes()[..6]); + } + } + Ok(out) +} diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs index c415e5098..a0f2d428f 100644 --- a/crates/xcl/src/hle/bcpack/mod.rs +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -12,9 +12,9 @@ //! the stream ([`bc1::Tables`]). XCL has the estimates bcpack-rs made of them //! (`bc1_fitted.rs`), so its BC1 blocks are an approximation wherever an estimate is off. //! -//! * the rebuild of BC4 blocks ([`bc4`]), which also needs two tables of constants that are -//! not in the stream ([`bc4::Tables`]). XCL has no source for them it can take, so nothing -//! calls it and BC4 requests are still refused. +//! * the rebuild of BC4 and BC5 blocks ([`bc4`], [`bc5`]), which also needs two tables of +//! constants each that are not in the stream ([`bc4::Tables`], [`bc5::Tables`]). XCL has no +//! source for them it can take, so nothing calls it and those requests are still refused. //! //! What is not: the rebuild of the other formats. Their lanes decode, but how the symbols map //! to block bits is not published in a form XCL can use, so those requests are still refused. @@ -28,6 +28,7 @@ pub mod bc1; mod bc1_fitted; pub mod bc4; +pub mod bc5; mod lanes; mod rans_tables; diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index 18925687a..8f86a359c 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -4,7 +4,7 @@ use super::lanes::{self, L}; use super::rans_tables::FREQ; -use super::{bc1, bc4, decode_lanes, lane_widths, Error}; +use super::{bc1, bc4, bc5, decode_lanes, lane_widths, Error}; /// The tables the fixtures' `.bc1` files were made with: history entry `slot` has the /// channels `(7 * slot + 13 * k) mod range`, and a quadrant symbol is its own selectors. @@ -35,9 +35,9 @@ fn by_unit(lane_major: &[u8], lanes: usize) -> Vec { (0..units * lanes).map(|i| lane_major[(i % lanes) * units + i / lanes]).collect() } -const FIXTURES: [&str; 15] = [ +const FIXTURES: [&str; 16] = [ "bc1-1-8", "bc1-2-0", "bc1-16-1", "bc1-16-9", "bc1-700-2", "bc1-8192-3", "bc3-16-1", "bc4-16-1", "bc5-16-1", "bc6-16-1", "bc7-2-0", "bc7-16-1", - "bc7-700-2", "bc7-8192-3", "bc4-300-4", + "bc7-700-2", "bc7-8192-3", "bc4-300-4", "bc5-600-5", ]; /// The symbols of the two 64 KiB fixtures, which ship without a `.lanes` file (`generate.py`). @@ -430,3 +430,51 @@ fn bc4_block_rebuild() { lane1[12 + 1] = 1; assert_eq!(bc4::assemble(&lane1, &tables), Err(Error::Lane1 { block: 1 })); } + +fn bc5_tables() -> bc5::Tables { + bc5::Tables { history: std::array::from_fn(made_up_history), pair_codes: made_up_pairs() } +} + +#[test] +fn bc5_fixture_decodes_to_its_blocks() { + let tables = bc5_tables(); + let bin = data("bc5-600-5.bin").unwrap(); + let want = data("bc5-600-5.bc5").unwrap(); + assert_eq!(bc5::decode(&bin, 300 * 16, &tables).as_deref(), Ok(&want[..])); + let lanes = data("bc5-600-5.lanes").unwrap(); + let d = |i: usize| bc4::back_reference(bc5::interleave(lanes[2 * i], lanes[2 * i + 1])); + let i = (0..300).find(|&i| d(i) > i).unwrap(); + let mut gap = bc5_tables(); + gap.history[256 + i - d(i)] = None; + assert_eq!(bc5::decode(&bin, 300 * 16, &gap), Err(Error::History { block: i, slot: 256 + i - d(i) })); + // half a block + assert_eq!(bc5::decode(&bin, 300 * 16 - 8, &tables), Err(Error::OutputSize)); +} + +/// Two blocks by hand: the back-reference split over both units, both channels' fields. +#[test] +fn bc5_block_rebuild() { + let mut tables = bc5_tables(); + tables.pair_codes = std::array::from_fn(|s| s as u8); + tables.history[255] = Some([10, 20, 30, 40]); + #[rustfmt::skip] + let symbols = [ + // block 0, unit a: lane 0 gives bits 0, 2, 4, 6 of the back-reference (here 2: one + // block back, the history's last entry); R0 +2, G0 +0; red rows' left halves, green's + 0, 0, 4, 0, 0o01, 0o02, 0o03, 0o04, 0o11, 0o12, 0o13, 0o14, + // unit b: bits 1, 3, 5, 7 of the back-reference; R1 -2, G1 -128; the right halves + 1, 0, 3, 255, 0o05, 0o06, 0o07, 0o10, 0o15, 0o16, 0o17, 0o20, + // block 1: back-reference 1, 255 blocks back: history entry 2; nothing else + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let out = bc5::assemble(&symbols, &tables).unwrap(); + let red = 0o10_04_07_03_06_02_05_01u64.to_le_bytes(); + let green = 0o20_14_17_13_16_12_15_11u64.to_le_bytes(); + assert_eq!(out[..8], [12, 18, red[0], red[1], red[2], red[3], red[4], red[5]]); + assert_eq!(out[8..16], [30, 168, green[0], green[1], green[2], green[3], green[4], green[5]]); + assert_eq!(out[16..32], [14, 27, 0, 0, 0, 0, 0, 0, 40, 53, 0, 0, 0, 0, 0, 0]); + let mut lane1 = symbols; + lane1[36 + 1] = 1; + assert_eq!(bc5::assemble(&lane1, &tables), Err(Error::Lane1 { block: 1 })); +} diff --git a/tests/data/bcpack/bc5-600-5.bc5 b/tests/data/bcpack/bc5-600-5.bc5 new file mode 100644 index 0000000000000000000000000000000000000000..426b40ae4693f71aee072c075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y=Ays>)~NLEh;7= zJL+Wmnj6rrIb?nl+?^j-znq&K7B?y0c?shjMLeXth2qf$!58rn?B)zY3GSWX;780> z-Z)m@;MV-f1r~pDrmAn>5aJ)h=;KLI8qG^+;VOW<*Q-BT?k3`mXNVcGz>69eNzVGr z;l@bMeET^rC3ekcu3V7oA{=h<=XMSsN&HJv@VNL)D&uiVXRTkyQf{5sgis8l{|0_V z`olpC9PGC|ljlc(FaA-rQIoGdn&wz8@(GtqvHG5c3Iv2bopvimL}dLGtxtrAu;-g) zG-SHHPpKO5a;c*c>N0trAm5rX;`O|~XhD?u59FvJoJ@4km6Z?Tf+I+r$z{YL>xOm_5|#VVFI@6v{k0foGS~+ zl-B3NkliKJ+~0YHb8b&)w0Aa#0@=Y^6x{3`zXdT~h&_a6d5&3VwIWmTN>3G3d7hHC zxK3CK(Q~CfMcxyr=#~eR7_i9MjuA{7oAaz<_8r#^+kinPf+$tME)QP%ll_z8lyF@M z4ad{GOWf0cdGo!q?ACKUE)gG8FEOwW@ezMzj%0H3Wq9_mure#V$d){|RJ}$2_oe>7 F{{f@y19t!b literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc5-600-5.lanes b/tests/data/bcpack/bc5-600-5.lanes new file mode 100644 index 0000000000000000000000000000000000000000..c522ba3562b8293d2b6b91da6b0e91854745158a GIT binary patch literal 7200 zcmeHs`5XImooDX*Y?`x4)3nXqG`-TMX_Bfi!*IAGpmMCb178%BT?PCiqA1EC2o8f6 zA_D?)$^eSEDEj5=F)Sj^tS-pIshlG!rywGNF!7Jr-=@!#q)(c@kJsmu_wjlYG{E5? z3e!B!z&L=h1j?Wg!XXF%U>J&$RCC4{5};WWAs~tbD2Sv;^|5Ch`PuPg$BJcS_$3!^NJfGmk{D92MgLGla&GiW0j z;t3j}L6Rn#yA%rW1VwOUBb#Pvl%pvG#b};{Sd=9R07E$xM?t)=<3=hIE4kKiv7iCch z17QXtniB%B5XJK}4I(5$Hjm>3iQqKHphyER2sIWk4JI(afC!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e*!jk>r zT2Ebh1Gd&Y0aN_Q=Ot(nE;g|R4$JmLtaY00QMuh-2V)J7#_hBhn4_uT^8?5=HmVeR zXbCC(hAqaOMcKB+SZes^c)O+LUOr!UPyrp<3En&;qpblECCM_MQ+mt$6 zcAT-4Yig-%*BP53g-g3*cS)kmf`_K8*Yo`GkQwKTL{!spNvR=Zd1hw9&dU|+Y&RQhdE#(hI7wATkXku8hLO@^x&!q8hxfuXSJQT@)4yvE2k*ecC%^Q zTiweLCS${HSI}67MVl&dvJi-<8jjQ`HEK|FW6jCiy|!&3O`ax->9hoEtsUbLrWk46 zn$k@UXt$jjWfdK7HeY9jg__U|7TTRyPba`E^-M7#hugKL>k?sW%(_CF;w6FCvbzKa zTniWk#RMfs9i_^)Cu`b^e|YMw#-OP za;;v#-9@k%pc`ksPP<{)%wcM!`J#B8+6_R{SSh7L=Cq)at0ifQ{-QNz@^N=T!mV<> znJq_2GXx;ulv{BD=~_6zjs3i~mnjHmq@Z#lzUtTWS&R>xDTp~AYCVf&t0~jW8a96I z%++BV?DDbB4<&m#2q{#U8so@V$}Mm%Z{tYzT*=5tR9Y-&O_uD2+buOv2^{q3zG;=| zV4EXQ(HgaFebtSS*kv~6et8o`S;>fGVqv_`{CO>XDj z3h_tf+NvZuX_eHVJHm&R-3RdA3YP$Hky+a%V+}w#STG2LgaFE#m^e}67ROf$kEsi! zY+78}vKBS%_e%>_ny`d9+DhO8c{l=!jomaa60Wnr0Hp^^Q7TKoWT0^z_aS?{75V=J Da}~eb literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/generate.py b/tests/data/bcpack/generate.py index f17fb056f..ac385e5c6 100644 --- a/tests/data/bcpack/generate.py +++ b/tests/data/bcpack/generate.py @@ -192,6 +192,25 @@ def assemble_bc4(symbols): return bytes(raw) +def assemble_bc5(symbols): + blocks = [] + raw = bytearray() + units = list(zip(*symbols)) + for i in range(len(units) // 2): + a, b = units[2*i], units[2*i + 1] + ref = sum((a[0] >> k & 1) << (2*k) | (b[0] >> k & 1) << (2*k + 1) for k in range(4)) + d = 255 - ref // 2 if ref & 1 else ref // 2 + predictor = ([128] * 4 if d == 0 else + blocks[i-d] if i >= d else made_up_history((i-d) % 256, 4)) + diffs = (a[2], b[2], a[3], b[3]) + ends = [(p + (~(v >> 1) if v & 1 else v >> 1)) % 256 for p, v in zip(predictor, diffs)] + blocks.append(ends) + for c in range(2): + halves = [u[4 + 4*c + y] for y in range(4) for u in (a, b)] + raw.extend(bytes(ends[2*c:2*c + 2]) + pair_selectors(halves)) + return bytes(raw) + + if __name__ == '__main__': for mode in WIDTHS: cases = [(2, 0, False), (16, 1, True), (700, 2, False)] @@ -209,6 +228,8 @@ def assemble_bc4(symbols): # 300 blocks: the first ones predict from the history, the later ones from the stream syms, path = generate(4, 300, 4, False, quiet_lane1=True) path.with_suffix('.bc4').write_bytes(assemble_bc4(syms)) + syms, path = generate(5, 600, 5, False, quiet_lane1=True) + path.with_suffix('.bc5').write_bytes(assemble_bc5(syms)) for mode, widths in [(1, BC1), (7, BC7)]: units = 8192 From e02a0033071233a140dd3dfcb0286a3466e0159d Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Mon, 23 Nov 2026 23:38:26 +0100 Subject: [PATCH 5/5] DirectStorage: BCPack BC3 block rebuild, without its tables, not yet called Stacked on the BC5 rebuild. Adds hle/bcpack/bc3.rs: BC3 blocks from the 12 lanes, two symbols per lane and block. Lane 0 is BC5's split back-reference (prediction 128/128 for alpha and 0 for colour when there is none), lane 1 must be 0, lane 2 holds the A0/A1 differences, lanes 3-6 the alpha selector rows through a pair table as BC4's, lanes 7-9 the red/green/blue differences of colour 0 (first unit) and colour 1 (second unit) modulo 32, 64 and 32, and lanes 10-11 the colour selectors as BC1's 2x2 quadrants (top-left/top-right, bottom-left/bottom-right). Three constants are not in a stream: the alpha pair order, the quadrant order and the 255-entry history of endpoints (A0, A1, R0, G0, B0, R1, G1, B1). XCL has no source for them it can take, so they are a parameter and nothing is shipped or wired; BC3 requests are refused as before. Of the 35 BC3 chunks of the retail title checked here, 8 never predict from the history, so the two orders alone would unlock those 8. Checked: - generate.py builds bc3-600-6 (300 blocks) with made-up tables and its own per-texel Python assembly; the decoder gives the same blocks, refuses an unknown history entry and half a block. - A hand-built two-block case: every field, colour differences wrapping in 5 and 6 bits, a prediction from a rebuilt block's colours, lane 1. AI-assisted. --- crates/xcl/src/hle/bcpack/bc3.rs | 93 +++++++++++++++++++++++++++++ crates/xcl/src/hle/bcpack/mod.rs | 8 ++- crates/xcl/src/hle/bcpack/tests.rs | 69 ++++++++++++++++++++- tests/data/bcpack/bc3-600-6.bc3 | Bin 0 -> 4800 bytes tests/data/bcpack/bc3-600-6.bin | Bin 0 -> 5484 bytes tests/data/bcpack/bc3-600-6.lanes | Bin 0 -> 7200 bytes tests/data/bcpack/generate.py | 33 ++++++++++ 7 files changed, 197 insertions(+), 6 deletions(-) create mode 100644 crates/xcl/src/hle/bcpack/bc3.rs create mode 100644 tests/data/bcpack/bc3-600-6.bc3 create mode 100644 tests/data/bcpack/bc3-600-6.bin create mode 100644 tests/data/bcpack/bc3-600-6.lanes diff --git a/crates/xcl/src/hle/bcpack/bc3.rs b/crates/xcl/src/hle/bcpack/bc3.rs new file mode 100644 index 000000000..5e70ef715 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc3.rs @@ -0,0 +1,93 @@ +//! BC3 blocks from the 12 lanes of a BCPack BC3 stream (two symbols per lane and block: units +//! `2i` and `2i + 1`, called `u0` and `u1` here). +//! +//! For block `i`, in stream order: +//! * lane 0 is the back-reference split over both units as in BC5 ([`super::bc5`]). Symbol 0 +//! predicts 128 for both alpha endpoints and 0 for the colour ones, and before block 0 the +//! prediction comes from a built-in history ([`Tables::history`]), +//! * lane 1 was 0 in every stream seen, in both units, +//! * lane 2 is the difference of A0 (`u0`) and A1 (`u1`) from the prediction, modulo 256, +//! * lanes 3–6 are the alpha selectors, one row each from the top, the left half of the row in +//! `u0` and the right half in `u1`, through a pair table as BC4's ([`Tables::pair_codes`]), +//! * lanes 7, 8 and 9 are the differences of red, green and blue: of colour 0 in `u0` and of +//! colour 1 in `u1`, modulo 32, 64 and 32, +//! * lanes 10 and 11 are the colour selectors as BC1's quadrants ([`Tables::quadrants`]): +//! lane 10 the top-left (`u0`) and top-right (`u1`) 2×2 texels, lane 11 the bottom ones. +//! +//! As for BC4, XCL has no source it can take for the three tables, so nothing calls this yet. + +use super::bc4::{back_reference, delta, selector_rows}; +use super::bc5::interleave; +use super::{decode_lanes, Error}; + +/// The constants of the BC3 rebuild that are not in a stream. +pub struct Tables { + /// The endpoints `[A0, A1, R0, G0, B0, R1, G1, B1]` of the blocks before a stream's first: + /// `history[256 - k]` is the block `k` before block 0 (k = 1..=255; entry 0 is never read). + /// `None`: not known. + pub history: [Option<[u8; 8]>; 256], + /// The alpha selectors of each pair symbol: bits 0–2 the left texel, 3–5 the right one. + pub pair_codes: [u8; 64], + /// The colour selectors of each quadrant symbol, 2 bits a texel: bits 0–1 the top-left + /// texel, 2–3 top-right, 4–5 bottom-left, 6–7 bottom-right. + pub quadrants: [u8; 256], +} + +/// The range of each endpoint, in the history's order. +const RANGE: [u16; 8] = [256, 256, 32, 64, 32, 32, 64, 32]; + +/// Unpack a BC3 stream to its `out_len` bytes of blocks. +pub fn decode(src: &[u8], out_len: usize, tables: &Tables) -> Result, Error> { + if out_len % 16 != 0 { + return Err(Error::OutputSize); + } + assemble(&decode_lanes(3, src, out_len)?, tables) +} + +/// The endpoints of a rebuilt block, in the history's order. +fn endpoints(block: &[u8]) -> [u8; 8] { + let c0 = u16::from_le_bytes([block[8], block[9]]); + let c1 = u16::from_le_bytes([block[10], block[11]]); + let rgb = |c: u16| [(c >> 11) as u8, (c >> 5 & 63) as u8, (c & 31) as u8]; + let [r0, g0, b0] = rgb(c0); + let [r1, g1, b1] = rgb(c1); + [block[0], block[1], r0, g0, b0, r1, g1, b1] +} + +/// The blocks of `symbols` (24 per block, in [`super::decode_lanes`]'s order). +pub fn assemble(symbols: &[u8], tables: &Tables) -> Result, Error> { + let blocks = symbols.len() / 24; + let mut out = Vec::new(); + out.try_reserve_exact(blocks * 16).map_err(|_| Error::OutputSize)?; + out.resize(blocks * 16, 0u8); + for (i, s) in symbols.chunks_exact(24).enumerate() { + let (u0, u1) = s.split_at(12); + if u0[1] != 0 || u1[1] != 0 { + return Err(Error::Lane1 { block: i }); + } + let predicted = match back_reference(interleave(u0[0], u1[0])) { + 0 => [128, 128, 0, 0, 0, 0, 0, 0], + d if d <= i => endpoints(&out[(i - d) * 16..]), + d => { + let slot = 256 + i - d; + tables.history[slot].ok_or(Error::History { block: i, slot })? + } + }; + let diffs = [u0[2], u1[2], u0[7], u0[8], u0[9], u1[7], u1[8], u1[9]]; + let e: [u16; 8] = std::array::from_fn(|k| (predicted[k] as u16 + delta(diffs[k]) as u16) % RANGE[k]); + let o = &mut out[i * 16..i * 16 + 16]; + o[0] = e[0] as u8; + o[1] = e[1] as u8; + let alpha = selector_rows((3..7).flat_map(|l| [u0[l], u1[l]]), &tables.pair_codes); + o[2..8].copy_from_slice(&alpha.to_le_bytes()[..6]); + o[8..10].copy_from_slice(&(e[2] << 11 | e[3] << 5 | e[4]).to_le_bytes()); + o[10..12].copy_from_slice(&(e[5] << 11 | e[6] << 5 | e[7]).to_le_bytes()); + let [tl, tr, bl, br] = [u0[10], u1[10], u0[11], u1[11]].map(|q| tables.quadrants[q as usize]); + // a row of the block is four texels, 2 bits each, the left one lowest + o[12] = (tl & 15) | (tr & 15) << 4; + o[13] = (tl >> 4) | (tr >> 4) << 4; + o[14] = (bl & 15) | (br & 15) << 4; + o[15] = (bl >> 4) | (br >> 4) << 4; + } + Ok(out) +} diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs index a0f2d428f..cf22dd44a 100644 --- a/crates/xcl/src/hle/bcpack/mod.rs +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -12,9 +12,10 @@ //! the stream ([`bc1::Tables`]). XCL has the estimates bcpack-rs made of them //! (`bc1_fitted.rs`), so its BC1 blocks are an approximation wherever an estimate is off. //! -//! * the rebuild of BC4 and BC5 blocks ([`bc4`], [`bc5`]), which also needs two tables of -//! constants each that are not in the stream ([`bc4::Tables`], [`bc5::Tables`]). XCL has no -//! source for them it can take, so nothing calls it and those requests are still refused. +//! * the rebuild of BC3, BC4 and BC5 blocks ([`bc3`], [`bc4`], [`bc5`]), which also needs +//! tables of constants that are not in the stream ([`bc3::Tables`], [`bc4::Tables`], +//! [`bc5::Tables`]). XCL has no source for them it can take, so nothing calls it and those +//! requests are still refused. //! //! What is not: the rebuild of the other formats. Their lanes decode, but how the symbols map //! to block bits is not published in a form XCL can use, so those requests are still refused. @@ -27,6 +28,7 @@ pub mod bc1; mod bc1_fitted; +pub mod bc3; pub mod bc4; pub mod bc5; mod lanes; diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index 8f86a359c..f51a65e6a 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -4,7 +4,7 @@ use super::lanes::{self, L}; use super::rans_tables::FREQ; -use super::{bc1, bc4, bc5, decode_lanes, lane_widths, Error}; +use super::{bc1, bc3, bc4, bc5, decode_lanes, lane_widths, Error}; /// The tables the fixtures' `.bc1` files were made with: history entry `slot` has the /// channels `(7 * slot + 13 * k) mod range`, and a quadrant symbol is its own selectors. @@ -35,9 +35,9 @@ fn by_unit(lane_major: &[u8], lanes: usize) -> Vec { (0..units * lanes).map(|i| lane_major[(i % lanes) * units + i / lanes]).collect() } -const FIXTURES: [&str; 16] = [ +const FIXTURES: [&str; 17] = [ "bc1-1-8", "bc1-2-0", "bc1-16-1", "bc1-16-9", "bc1-700-2", "bc1-8192-3", "bc3-16-1", "bc4-16-1", "bc5-16-1", "bc6-16-1", "bc7-2-0", "bc7-16-1", - "bc7-700-2", "bc7-8192-3", "bc4-300-4", "bc5-600-5", + "bc7-700-2", "bc7-8192-3", "bc4-300-4", "bc5-600-5", "bc3-600-6", ]; /// The symbols of the two 64 KiB fixtures, which ship without a `.lanes` file (`generate.py`). @@ -478,3 +478,66 @@ fn bc5_block_rebuild() { lane1[36 + 1] = 1; assert_eq!(bc5::assemble(&lane1, &tables), Err(Error::Lane1 { block: 1 })); } + +fn bc3_tables() -> bc3::Tables { + bc3::Tables { + history: std::array::from_fn(made_up_history), + pair_codes: made_up_pairs(), + quadrants: std::array::from_fn(|q| ((37 * q + 11) % 256) as u8), + } +} + +#[test] +fn bc3_fixture_decodes_to_its_blocks() { + let tables = bc3_tables(); + let bin = data("bc3-600-6.bin").unwrap(); + let want = data("bc3-600-6.bc3").unwrap(); + assert_eq!(bc3::decode(&bin, 300 * 16, &tables).as_deref(), Ok(&want[..])); + let lanes = data("bc3-600-6.lanes").unwrap(); + let d = |i: usize| bc4::back_reference(bc5::interleave(lanes[2 * i], lanes[2 * i + 1])); + let i = (0..300).find(|&i| d(i) > i).unwrap(); + let mut gap = bc3_tables(); + gap.history[256 + i - d(i)] = None; + assert_eq!(bc3::decode(&bin, 300 * 16, &gap), Err(Error::History { block: i, slot: 256 + i - d(i) })); + assert_eq!(bc3::decode(&bin, 300 * 16 - 8, &tables), Err(Error::OutputSize)); +} + +/// Two blocks by hand: every field, colour differences wrapping in their own range, and a +/// prediction from a rebuilt block's colours. +#[test] +fn bc3_block_rebuild() { + let mut tables = bc3_tables(); + tables.pair_codes = std::array::from_fn(|s| s as u8); + tables.quadrants = std::array::from_fn(|q| q as u8); + tables.history[255] = Some([200, 100, 31, 0, 5, 1, 63, 16]); + #[rustfmt::skip] + let symbols = [ + // block 0, u0: one block back (the history's last entry); A0 +1; alpha rows' left + // halves; R0 +1 (wraps to 0), G0 -1 (wraps to 63), B0 +0; top-left, bottom-left quadrants + 0, 0, 2, 0o01, 0o02, 0o03, 0o04, 2, 1, 0, 0x1B, 0xE4, + // u1: A1 -1; the rows' right halves; R1 -2 (wraps to 31), G1 +0, B1 +15; top-right, + // bottom-right quadrants + 1, 0, 1, 0o05, 0o06, 0o07, 0o10, 3, 0, 30, 0x55, 0xAA, + // block 1: one block back, nothing else + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let out = bc3::assemble(&symbols, &tables).unwrap(); + let alpha = 0o10_04_07_03_06_02_05_01u64.to_le_bytes(); + let c0 = (0u16 << 11 | 63 << 5 | 5).to_le_bytes(); + let c1 = (31u16 << 11 | 63 << 5 | 31).to_le_bytes(); + #[rustfmt::skip] + let block = [ + 201, 99, alpha[0], alpha[1], alpha[2], alpha[3], alpha[4], alpha[5], c0[0], c0[1], c1[0], c1[1], + // rows 0-1 from the top quadrants 0x1B | 0x55, rows 2-3 from 0xE4 | 0xAA + 0x5B, 0x51, 0xA4, 0xAE, + ]; + assert_eq!(out[..16], block); + let mut copy = block; + copy[2..8].fill(0); + copy[12..16].fill(0); + assert_eq!(out[16..32], copy); + let mut lane1 = symbols; + lane1[12 + 1] = 1; + assert_eq!(bc3::assemble(&lane1, &tables), Err(Error::Lane1 { block: 0 })); +} diff --git a/tests/data/bcpack/bc3-600-6.bc3 b/tests/data/bcpack/bc3-600-6.bc3 new file mode 100644 index 0000000000000000000000000000000000000000..fe7426dcb0445e364ac791345c9096a519df0028 GIT binary patch literal 4800 zcmV;x5!#LqM z5At!?vS{o3Clr6HB$*%$2t;LRZ2D!<-~ChTSDGKm3AYl^uHsJdhpYp7Tv;w$_pE4`D zsv^rYIQ75pPhpdWT-T_g5@W@%&#{c45q~`w+4e`{=FRo!1pGnG(eVwidSfkMV*0M1 zVnlX-sZSEGvB7DF7IGuBFI5x2ydDE9Lb~MR<{gbFz%Tvpmt)r^XVL{1y|indVZL$1 zusvbOWTi1sYaZx}$FO!7262?uJ{KTE**x45y9|@TGvCqZWL#vUt545socscZ&ogfH zr#bbaEP&SzARWHyU4b`9&{>zwwGAdXv$3xc*WFNth$3fU98BKdRtl$M+B~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l;I%$DrLhP?9wZIX0 zT|A~#zrVIWdv<4wmIIPYcNjKNdR>RfjLIAv{Iv6(20%a(<2<*0=d$!D_Nu2Ul#~}isS0G1XOTOLhzGW53NDLT{_f+j&J|DX%FEqBRq2&qjDWR`(NH3kro9A*8hgrCm-{_pSExvs&dxLSH+$Y=K*sO5uZAKDWq9wQvXddW z6BSgpS4Vb}8%qzqPU0e^;_v{v8nbQkT0e1(e76vl0r)T{cB@2hzr9@}n+sWRaW!Jm z;CB@~AYtVgl$fTIK9$ltc>~t8RZZS>?sbwFgR0EF2#8B^A5kq;vkWgNGceoQ~tgaN80|?3-Rw zTXIwbj0)DXXq9&x_&DGa7Kei3E8iIB?{T=>Gs5NGJI+ox1d0{CK$%q%C&&6VDMe$Bmu72Zd!5yr`&qrDq9FdgpZylmW(kk~LoVvV(p z7M-353M+&BJHPjQ!Zm%YCWnQ_D)PDWqw;RP!D$*ILbIOb^YZADl@4Jc`Z?m{$FRDv MaFl`Tzg` literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc3-600-6.lanes b/tests/data/bcpack/bc3-600-6.lanes new file mode 100644 index 0000000000000000000000000000000000000000..bbed5e3b58b7abe0c70facc2483b12672eac77a1 GIT binary patch literal 7200 zcmeHLXB!sPwVmF3@ALNFdw(sc0TdMwytasVRk(^08%8V$Atph%iwNQ4JbmVr4O;y4Ckd6I=Ng5yyDfC)Mn zQ3T8K1kdvb!;>6EqYObYJW2u_hypN8^B{&00Lw!>9=stqg@7;&@*D&p5E^_4KroKy zID&^rnxsL9APAo2f&q?$C`E%H7DS7}48rjc0?`19pd`ZJIKrY74lo$SZ~%kgG!aZ7 z35J=N74$u?}(g*-h5D#z!MBqs9O`HjK zLm(uGaWD!4C>(5y=ds}T0L2m%Leex2kSN6B5XP_w0tUD;!Qx<72n<0mMpGz`qBz2H zFv4LpLIslm2=E*Q0tC!ZFpVHI&j1L_(Lq)Sh=&;r4Pc~$06`q!2^6FNj0{i%36c)- z0MRIo@;J`~8DfL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~)|L>3Y@7w&*lEYhWU-HF`%O-7E_4K{x&s+F9e$$A*ZoX${`tQGzm%ao2S9)Kf zrR;G>=Dsn@&z!IUf4VWlAHO6q;IS?dGdaA^?q?pV z!-pO?aLd)7UNw69p8B#WcZ_*a-S_#SU2DRR+&XhK0Y7zL{pH(^5tY&No*(!A$v6JE zTEiACia#gLqz@kb=gTWUzWwB7w~XI;>i(D4P2NsEy62Kpf4%C_2ghDI>iwDjz2d7Y zu8!1xb@l@**DU`)xSia1?kVwqy>asLo7Rn)@!-By>FXw5a7JX=kJn%GRs8F7Hjl8k zubIBa-Fd`Og*Uh`-l@q6zw%>O6x@CK#lQ&#{ z#9ib3Syg`4wSVBY9=#Y@%YQNU$luK}T-n%^V)cC93S)2Ii2Ti~6T_z#JwAP&H1dg;4`1+R^2Hz4 zU)uWWrMaJ6$c;bmjOXviJ{@}qUFJ^Mw+(2$dFkZeWW0^LkG)~?dyKW|VG}=R?JJ|I zLv>yD;2TrtFKO-nfZKiMwy*Ad`OYJ|v1_jSZ0GUFyj3TKUU)k7{!Q<8GjA;WUp{_c A@c;k- literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/generate.py b/tests/data/bcpack/generate.py index ac385e5c6..0d50e527a 100644 --- a/tests/data/bcpack/generate.py +++ b/tests/data/bcpack/generate.py @@ -211,6 +211,37 @@ def assemble_bc5(symbols): return bytes(raw) +def made_up_quadrant(q): + return (37 * q + 11) % 256 + + +def assemble_bc3(symbols): + blocks = [] + raw = bytearray() + units = list(zip(*symbols)) + ranges = (256, 256, 32, 64, 32, 32, 64, 32) + for i in range(len(units) // 2): + a, b = units[2*i], units[2*i + 1] + ref = sum((a[0] >> k & 1) << (2*k) | (b[0] >> k & 1) << (2*k + 1) for k in range(4)) + d = 255 - ref // 2 if ref & 1 else ref // 2 + predictor = ([128, 128, 0, 0, 0, 0, 0, 0] if d == 0 else + blocks[i-d] if i >= d else made_up_history((i-d) % 256, 8)) + diffs = (a[2], b[2], a[7], a[8], a[9], b[7], b[8], b[9]) + ends = [(p + (~(v >> 1) if v & 1 else v >> 1)) % m for p, v, m in zip(predictor, diffs, ranges)] + blocks.append(ends) + raw.extend(bytes(ends[:2]) + pair_selectors([u[3 + y] for y in range(4) for u in (a, b)])) + for r, g, bl in (ends[2:5], ends[5:]): + raw.extend(struct.pack('> (2 * (2*(y%2) + x%2)) & 3) << (2 * (4*y + x)) + raw.extend(struct.pack('