diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 4afc9f29d..fd42e6a9e 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -10,6 +10,9 @@ 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, 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/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/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/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/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..cf22dd44a --- /dev/null +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -0,0 +1,153 @@ +//! 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, +//! * 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. +//! +//! * 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. +//! +//! Nothing here was compared with what a console writes for the same input: the entropy stage +//! 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; +pub mod bc3; +pub mod bc4; +pub mod bc5; +mod lanes; +mod rans_tables; + +/// Why a stream was not unpacked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// 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, + /// 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 }, + /// 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 { + /// 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", + Error::Lane1 { .. } => "lane 1", + Error::History { .. } => "unknown history", + } + } +} + +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"), + 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}"), + } + } +} + +/// 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) +} + +/// 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/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..f51a65e6a --- /dev/null +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -0,0 +1,543 @@ +//! 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::{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. +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() +} + +/// `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; 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", "bc3-600-6", +]; + +/// 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}"); + } +} + +#[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() { + 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| { + 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}"); + } + 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); + let _ = super::decode(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())); +} + +/// 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 })); + } +} + +/// 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 })); +} + +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 })); +} + +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/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/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/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/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.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-1-8.bin b/tests/data/bcpack/bc1-1-8.bin new file mode 100644 index 000000000..950507501 Binary files /dev/null and b/tests/data/bcpack/bc1-1-8.bin differ diff --git a/tests/data/bcpack/bc1-1-8.lanes b/tests/data/bcpack/bc1-1-8.lanes new file mode 100644 index 000000000..ccac41a29 Binary files /dev/null and b/tests/data/bcpack/bc1-1-8.lanes differ diff --git a/tests/data/bcpack/bc1-16-1.bc1 b/tests/data/bcpack/bc1-16-1.bc1 new file mode 100644 index 000000000..224f45bab Binary files /dev/null and b/tests/data/bcpack/bc1-16-1.bc1 differ diff --git a/tests/data/bcpack/bc1-16-1.bin b/tests/data/bcpack/bc1-16-1.bin new file mode 100644 index 000000000..8201430b2 Binary files /dev/null and b/tests/data/bcpack/bc1-16-1.bin differ diff --git a/tests/data/bcpack/bc1-16-1.lanes b/tests/data/bcpack/bc1-16-1.lanes new file mode 100644 index 000000000..92a74dd01 Binary files /dev/null and b/tests/data/bcpack/bc1-16-1.lanes differ 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Ï}µÉî·)®éˆå= 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, 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 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)) + 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('> (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) + + +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) + + +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('