diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index e2f7ec0d0..19e0830a7 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -10,6 +10,8 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | [FFmpeg](https://ffmpeg.org/) | LGPL-2.1+ | XMA1/XMA2 decoder and tables (`crates/xcl/src/hle/xma2/`) – after `libavcodec/wmaprodec.c`, `wmaprodata.h`, `wma.c`, `sinewin_tablegen.h`, `libavutil/float_dsp.c`, `tx_template.c` | port to safe Rust with annotation | | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | +| [silicon-rans](https://github.com/microsoft/silicon-rans) (Microsoft) | MIT | BCPack entropy stage: the rANS lane in `crates/xcl/src/hle/bcpack/lanes.rs` (after the `decoder` module of `mdu_minirans.v`) and its model tables in `hle/bcpack/rans_tables.rs` (generated by `scripts/gen_bcpack_tables.py` from the same file) | port to Rust with annotation; tables | +| [bcpack-decoder](https://github.com/Tim0219800/bcpack-decoder) (Tim0219800), [bcpack-rs](https://github.com/Ahmet-Dedeler/bcpack-rs) (Ahmet Dedeler) | MIT | no code; the BCPack stream layout, lane widths and byte feeder rule in `hle/bcpack/` follow their format notes (`docs/SPEC.md`, `docs/BCPACK_SPEC.md`) | specification | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/hle/bcpack/lanes.rs b/crates/xcl/src/hle/bcpack/lanes.rs new file mode 100644 index 000000000..54e45a8db --- /dev/null +++ b/crates/xcl/src/hle/bcpack/lanes.rs @@ -0,0 +1,352 @@ +//! The entropy stage of BCPack: a set of rANS decoders ("lanes") that share one byte stream. +//! +//! Every lane yields one symbol per 8 bytes of output. A lane's own bytes are a chain of +//! fragments, each a 2- or 3-byte header and its payload: +//! * byte 0: bits 0–3 the model `q`, bit 4 "reset the state when this fragment ends", bit 5 +//! "a third header byte follows", bits 6–7 `z`, by how many bits this fragment's symbols are +//! narrower than the lane's, +//! * the payload length: byte 1 plus 1, or with a third byte `(byte 2 << 8 | byte 1) + 257`; +//! it counts every byte the lane reads in the fragment, the first state bytes included. +//! +//! The state is 32 bits with the lower limit `L` = 2^24 and 16-bit probabilities; a byte is +//! shifted in while it is below `L`, a symbol leaves while it is above. A fragment's encoder +//! started at `L`, so a decoded fragment ends there, or at `L >> 8` / `L >> 16` when the +//! encoder dropped trailing zero bytes. +//! +//! Which lane gets which byte of the stream is decided clock by clock, as in the hardware: +//! * each lane holds one byte of input and one symbol of output; in a clock it first applies +//! its last symbol to the state and takes a byte, then reads a header byte or shifts the byte +//! in and decodes, +//! * the lanes that ask for a byte are served in lane order, eight bytes a clock at most; a +//! lane that asked and got none does nothing in that clock, +//! * a lane hands its symbol over only when its place in the symbol vector is free, and the +//! places are freed together when every lane has filled its own. A lane with a symbol it +//! cannot hand over does nothing either. +//! +//! The lane is a port of the `decoder` module of Microsoft's silicon-rans sample +//! (https://github.com/microsoft/silicon-rans, `mdu_minirans.v` at commit 2f6827d, Copyright (c) +//! Microsoft Corporation, MIT), made for XCL on 2026-11-23: same registers, same two phases, +//! same control states. The sample leaves the feeder and the symbol vector out; the two rules +//! above are from the public format notes of bcpack-decoder +//! (https://github.com/Tim0219800/bcpack-decoder, `docs/SPEC.md`) and bcpack-rs +//! (https://github.com/Ahmet-Dedeler/bcpack-rs, `docs/BCPACK_SPEC.md`), both MIT, which report +//! them as checked against retail streams; no code was taken from either. + +use super::rans_tables::FREQ; +use super::Error; + +/// The lower limit of the rANS state. +pub const L: u32 = 1 << 24; +/// Bytes the feeder hands out per clock. +const FEED_WINDOW: usize = 8; + +/// One of the 16 static models at one symbol width: the cumulative base and the per-symbol +/// frequency of each segment. Segment 0 is symbol 0, segment k >= 1 the symbols +/// `2^(k-1) .. 2^k`. Slot 0 belongs to no symbol: symbol 0 starts at slot 1. +#[derive(Clone, Copy)] +struct Model { + /// `base[k]` for the segments in use, 65536 for the rest + base: [u32; 10], + freq: [u32; 9], +} + +impl Model { + fn new(bits: usize, q: usize) -> Self { + let mut m = Model { base: [65536; 10], freq: [1; 9] }; + let mut at = 0u32; + for k in 0..=bits { + m.base[k] = at; + m.freq[k] = FREQ[bits - 1][q][k] as u32; + at += m.freq[k] * if k < 2 { 1 } else { 1 << (k - 1) }; + } + m + } + + /// The symbol of slot `cf` (1..=65535). + fn symbol(&self, cf: u32) -> u32 { + let mut seg = 0; + for k in 1..9 { + seg += (cf >= self.base[k]) as usize; + } + ((1u32 << seg) >> 1) + (cf - self.base[seg]) / self.freq[seg] + } + + /// The state after `sym` left state `x`. + fn advance(&self, x: u32, sym: u32) -> u32 { + let seg = (32 - sym.leading_zeros()) as usize; + let cfa = self.base[seg] + self.freq[seg] * (sym - ((1u32 << seg) >> 1)); + let (f, cf) = if cfa == 0 { (self.freq[seg] - 1, 1) } else { (self.freq[seg], cfa) }; + f.wrapping_mul(x >> 16).wrapping_add(x & 0xFFFF).wrapping_sub(cf) + } +} + +/// Where a fragment's decoding may end: the state its encoder started from, less the zero +/// bytes (two at most) the encoder's first symbol pushed out and the encoder did not store. +fn is_end_state(x: u32) -> bool { + x == L || x == L >> 8 || x == L >> 16 +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Ctrl { + Hdr0, + Hdr1, + Hdr2, + Processing, + /// the fragment's bytes are all in the state; symbols still leave + Draining, + Done, +} + +struct Lane { + /// the lane's symbol width + bits: u8, + ctrl: Ctrl, + input_buf: u8, + input_buf_full: bool, + sym: u32, + sym_buf_full: bool, + /// its place in the symbol vector is taken + slot_full: bool, + input_remaining: u32, + output_remaining: u32, + /// the state after the last symbol was applied + p0: u32, + /// the state the symbol in `sym` was read from + p1: u32, + hdr3: bool, + flush: bool, + q: u8, + model: Model, + stalled: bool, +} + +/// Decode the lanes of one stream: `widths[i]` is lane i's symbol width in bits (1..=8), +/// `units` the number of symbols every lane holds. The symbols come back unit by unit +/// (`symbols[unit * lanes + lane]`), with the number of bytes of `src` the lanes read. +pub(super) fn decode(src: &[u8], widths: &[u8], units: usize) -> Result<(Vec, usize), Error> { + let mut pos = 0; + let symbols = run(widths, units, |_| { + let b = src.get(pos).copied(); + pos += b.is_some() as usize; + b + })?; + Ok((symbols, pos)) +} + +/// [`decode`] with the stream as a function: the next byte, for the lane that gets it. +pub(super) fn run(widths: &[u8], units: usize, mut next: impl FnMut(usize) -> Option) -> Result, Error> { + let n = widths.len(); + assert!(n > 0 && widths.iter().all(|w| (1..=8).contains(w))); + if units == 0 { + return Ok(Vec::new()); + } + if units > u32::MAX as usize { + return Err(Error::OutputSize); + } + // grows with the units the stream really yields: the size a request names costs nothing + let mut symbols: Vec = Vec::new(); + let mut lanes: Vec = widths + .iter() + .map(|&bits| Lane { + bits, + ctrl: Ctrl::Hdr0, + input_buf: 0, + input_buf_full: false, + sym: 0, + sym_buf_full: false, + slot_full: false, + input_remaining: 0, + output_remaining: units as u32, + p0: 0, + p1: 0, + hdr3: false, + flush: false, + q: 0, + model: Model::new(bits as usize, 0), + stalled: false, + }) + .collect(); + let mut released = 0usize; + + // a lane is done when it has its symbols and has read its last fragment to the end + while lanes.iter().any(|l| l.ctrl != Ctrl::Done || l.sym_buf_full) { + let mut progress = false; + + // phase 0: the feeder fills input buffers, a lane applies its symbol and hands it over + let mut served = 0; + for (i, l) in lanes.iter_mut().enumerate() { + let blocked_on_output = l.sym_buf_full && l.slot_full; + let need = !l.input_buf_full + && match l.ctrl { + Ctrl::Hdr0 | Ctrl::Hdr1 | Ctrl::Hdr2 => true, + Ctrl::Processing => l.input_remaining > 0, + Ctrl::Draining | Ctrl::Done => false, + }; + let mut fed = None; + if need && !blocked_on_output && served < FEED_WINDOW { + // the stream never grows: a lane that waits for a byte past its end waits forever + let Some(b) = next(i) else { return Err(Error::Truncated { lane: i }) }; + fed = Some(b); + served += 1; + } + l.stalled = blocked_on_output || (need && fed.is_none()); + if l.stalled { + continue; + } + if matches!(l.ctrl, Ctrl::Processing | Ctrl::Draining) { + let p0 = if l.sym_buf_full { l.model.advance(l.p1, l.sym) } else { l.p1 }; + progress |= p0 != l.p0; + l.p0 = p0; + } + if let Some(b) = fed { + l.input_buf = b; + l.input_buf_full = true; + progress = true; + } + if l.sym_buf_full { + // the lane's last symbol leaves a state its encoder started from + let done = units - l.output_remaining as usize; + if l.output_remaining == 0 { + if !is_end_state(l.model.advance(l.p1, l.sym)) { + return Err(Error::EndState { lane: i }); + } + } + if symbols.len() < done * n { + symbols.try_reserve(n).map_err(|_| Error::OutputSize)?; + symbols.resize(done * n, 0); + } + symbols[(done - 1) * n + i] = l.sym as u8; + l.sym_buf_full = false; + l.slot_full = true; + progress = true; + } + } + + // phase 1: header bytes, or a byte into the state and a symbol out of it + for (i, l) in lanes.iter_mut().enumerate() { + if l.stalled { + continue; + } + match l.ctrl { + Ctrl::Hdr0 => { + if l.input_buf_full { + let b = l.input_buf; + l.input_buf_full = false; + l.input_remaining = 0; + l.q = b & 15; + l.flush = b & 0x10 != 0; + l.hdr3 = b & 0x20 != 0; + let z = b >> 6; + if z >= l.bits { + return Err(Error::Width { lane: i }); + } + l.model = Model::new((l.bits - z) as usize, l.q as usize); + l.ctrl = Ctrl::Hdr1; + progress = true; + } + } + Ctrl::Hdr1 => { + if l.input_buf_full { + l.input_buf_full = false; + if l.hdr3 { + l.input_remaining = l.input_buf as u32; + l.ctrl = Ctrl::Hdr2; + } else { + l.input_remaining = l.input_buf as u32 + 1; + l.ctrl = Ctrl::Processing; + } + progress = true; + } + } + Ctrl::Hdr2 => { + if l.input_buf_full { + l.input_buf_full = false; + l.input_remaining = ((l.input_buf as u32) << 8 | l.input_remaining) + 257; + l.ctrl = Ctrl::Processing; + progress = true; + } + } + Ctrl::Processing => { + let feed = l.p0 < L && l.input_remaining > 0 && l.input_buf_full; + let x = if feed { l.p0 << 8 | l.input_buf as u32 } else { l.p0 }; + let out = x > L && l.output_remaining > 0; + if out { + l.sym = l.model.symbol(x & 0xFFFF); + if x & 0xFFFF == 0 { + return Err(Error::Symbol { lane: i }); + } + l.output_remaining -= 1; + } + progress |= feed || out || x != l.p1; + l.p1 = x; + l.sym_buf_full = out; + if feed { + l.input_buf_full = false; + l.input_remaining -= 1; + } + if l.input_remaining == 0 { + progress = true; + if l.output_remaining == 0 { + l.ctrl = Ctrl::Done; + } else if x == L { + l.ctrl = Ctrl::Hdr0; + if l.flush { + l.p1 = 0; + } + } else { + l.ctrl = Ctrl::Draining; + } + } + } + Ctrl::Draining => { + let x = l.p0; + let out = x > L && l.output_remaining > 0; + if out { + l.sym = l.model.symbol(x & 0xFFFF); + if x & 0xFFFF == 0 { + return Err(Error::Symbol { lane: i }); + } + l.output_remaining -= 1; + } + progress |= out || x != l.p1; + l.p1 = x; + l.sym_buf_full = out; + if x <= L { + progress = true; + if l.output_remaining == 0 { + l.ctrl = Ctrl::Done; + } else { + l.ctrl = Ctrl::Hdr0; + if l.flush { + // The hardware drops whatever state is left here. A state that + // is thrown away took symbols with it unless it is where the + // fragment's encoder started, so anything else is damage. + if !is_end_state(x) { + return Err(Error::EndState { lane: i }); + } + l.p0 = 0; + l.p1 = 0; + } + } + } + } + Ctrl::Done => {} + } + } + + // the symbol vector leaves when every lane has put its symbol in + if lanes.iter().all(|l| l.slot_full) { + for l in lanes.iter_mut() { + l.slot_full = false; + } + released += 1; + progress = true; + } + if !progress { + // nothing moved in a whole clock, so nothing ever will + return Err(Error::Stuck); + } + } + debug_assert_eq!((released, symbols.len()), (units, units * n)); + Ok(symbols) +} diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs new file mode 100644 index 000000000..e35c2c062 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -0,0 +1,105 @@ +//! BCPack, the console's lossless packing of BCn texture blocks (`DSTORAGE_BCPACK_MODE`, the +//! DirectStorage stage between zlib and swizzle): a stream unpacks to plain BCn blocks. +//! +//! A stream has no header. The fields of the blocks are split over 12 or 16 rANS lanes, one +//! symbol per lane for every 8 bytes of output, and the lanes share the byte stream +//! (`lanes.rs`). The blocks are then rebuilt from the symbols; that part differs per format. +//! +//! What is here: the entropy stage for BC1, BC3, BC4, BC5, BC6H and BC7 ([`lane_widths`]); no +//! lane layout is published for BC2. Nothing calls it yet: DirectStorage still refuses every +//! request with a BCPack stage. +//! +//! What is not: the rebuild of blocks from the symbols, for any format. +//! +//! Nothing here was compared with what a console writes for the same input: the entropy stage +//! follows Microsoft's published decoder sample and the public format notes of bcpack-decoder +//! (Tim0219800) and bcpack-rs (Ahmet Dedeler), both MIT, whose authors report them as matching +//! retail streams. The tests check against streams built independently from those notes +//! (`tests/data/bcpack`), not against hardware output. + +mod lanes; +mod rans_tables; + +/// Why a stream was not unpacked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// no lane layout for this mode + Unsupported, + /// the output is not a whole number of blocks, or too large + OutputSize, + /// the stream ends before the lane has its bytes + Truncated { lane: usize }, + /// a fragment narrows the lane's symbols to nothing + Width { lane: usize }, + /// the state points at the slot no symbol has + Symbol { lane: usize }, + /// the lane's last symbol leaves a state no encoder starts from + EndState { lane: usize }, + /// the lanes wait for each other or for a byte their fragments do not have + Stuck, + /// bytes other than zero padding follow the stream + Trailing { consumed: usize }, +} + +impl Error { + /// The kind of failure, without its numbers. + pub fn kind(&self) -> &'static str { + match self { + Error::Unsupported => "unsupported", + Error::OutputSize => "output size", + Error::Truncated { .. } => "truncated", + Error::Width { .. } => "width", + Error::Symbol { .. } => "reserved slot", + Error::EndState { .. } => "end state", + Error::Stuck => "stuck", + Error::Trailing { .. } => "trailing data", + } + } +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + Error::Unsupported => write!(f, "no decoder for this mode"), + Error::OutputSize => write!(f, "the output size is not a whole number of blocks"), + Error::Truncated { lane } => write!(f, "the stream ends while lane {lane} waits for a byte"), + Error::Width { lane } => write!(f, "a fragment of lane {lane} narrows its symbols to nothing"), + Error::Symbol { lane } => write!(f, "lane {lane} reads the reserved slot"), + Error::EndState { lane } => write!(f, "lane {lane} ends in a state no encoder starts from"), + Error::Stuck => write!(f, "the lanes cannot go on"), + Error::Trailing { consumed } => write!(f, "data follows the stream's {consumed} bytes"), + } + } +} + +/// The symbol width of each lane of a `DSTORAGE_BCPACK_MODE` (1 BC1 … 7 BC7), in stream order. +/// Every lane holds one symbol per 8 bytes of output: one per BC1/BC4 block, two per 16-byte +/// block. +pub fn lane_widths(mode: u8) -> Option<&'static [u8]> { + Some(match mode { + 1 => &[8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8], + 3 => &[4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8], + 4 => &[8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6], + 5 => &[4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6], + 6 => &[4, 4, 8, 8, 8, 5, 5, 5, 6, 6, 6, 8, 8, 8, 8, 5], + 7 => &[4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5], + _ => return None, + }) +} + +/// The symbols of a stream that unpacks to `out_len` bytes, unit by unit +/// (`symbols[unit * lanes + lane]`). Zero padding may follow the stream. +pub fn decode_lanes(mode: u8, src: &[u8], out_len: usize) -> Result, Error> { + let widths = lane_widths(mode).ok_or(Error::Unsupported)?; + if out_len % 8 != 0 { + return Err(Error::OutputSize); + } + let (symbols, consumed) = lanes::decode(src, widths, out_len / 8)?; + if src[consumed..].iter().any(|&b| b != 0) { + return Err(Error::Trailing { consumed }); + } + Ok(symbols) +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/xcl/src/hle/bcpack/rans_tables.rs b/crates/xcl/src/hle/bcpack/rans_tables.rs new file mode 100644 index 000000000..7466a9c58 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/rans_tables.rs @@ -0,0 +1,161 @@ +// Generated by scripts/gen_bcpack_tables.py from Microsoft's silicon-rans sample (mdu_minirans.v, +// https://github.com/microsoft/silicon-rans commit 2f6827d): Copyright (c) Microsoft Corporation, MIT. +// `FREQ[bits - 1][q][segment]`: the frequency of each symbol of a segment, out of 65536. Segment 0 +// is symbol 0, segment k >= 1 is the symbols 2^(k-1) .. 2^k - 1. + +#![allow(clippy::unreadable_literal)] + +pub static FREQ: [[[u16; 9]; 16]; 8] = [ + // 1-bit alphabet + [ + [32768, 32768, 0, 0, 0, 0, 0, 0, 0], + [38761, 26775, 0, 0, 0, 0, 0, 0, 0], + [44484, 21052, 0, 0, 0, 0, 0, 0, 0], + [49818, 15718, 0, 0, 0, 0, 0, 0, 0], + [54623, 10913, 0, 0, 0, 0, 0, 0, 0], + [58721, 6815, 0, 0, 0, 0, 0, 0, 0], + [61911, 3625, 0, 0, 0, 0, 0, 0, 0], + [64036, 1500, 0, 0, 0, 0, 0, 0, 0], + [65121, 415, 0, 0, 0, 0, 0, 0, 0], + [65477, 59, 0, 0, 0, 0, 0, 0, 0], + [65534, 2, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + ], + // 2-bit alphabet + [ + [16384, 16384, 16384, 0, 0, 0, 0, 0, 0], + [21168, 17592, 13388, 0, 0, 0, 0, 0, 0], + [26354, 18130, 10526, 0, 0, 0, 0, 0, 0], + [31900, 17918, 7859, 0, 0, 0, 0, 0, 0], + [37750, 16874, 5456, 0, 0, 0, 0, 0, 0], + [43800, 14920, 3408, 0, 0, 0, 0, 0, 0], + [49850, 12062, 1812, 0, 0, 0, 0, 0, 0], + [55537, 8499, 750, 0, 0, 0, 0, 0, 0], + [60308, 4812, 208, 0, 0, 0, 0, 0, 0], + [63575, 1901, 30, 0, 0, 0, 0, 0, 0], + [65132, 402, 1, 0, 0, 0, 0, 0, 0], + [65511, 23, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + ], + // 3-bit alphabet + [ + [8192, 8192, 8192, 8192, 0, 0, 0, 0, 0], + [11073, 10095, 8796, 6694, 0, 0, 0, 0, 0], + [14406, 11948, 9065, 5263, 0, 0, 0, 0, 0], + [18234, 13666, 8958, 3930, 0, 0, 0, 0, 0], + [22624, 15126, 8437, 2728, 0, 0, 0, 0, 0], + [27657, 16143, 7460, 1704, 0, 0, 0, 0, 0], + [33414, 16436, 6031, 906, 0, 0, 0, 0, 0], + [39920, 15616, 4250, 375, 0, 0, 0, 0, 0], + [47024, 13284, 2406, 104, 0, 0, 0, 0, 0], + [54201, 9375, 950, 15, 0, 0, 0, 0, 0], + [60388, 4744, 200, 1, 0, 0, 0, 0, 0], + [64250, 1262, 10, 1, 0, 0, 0, 0, 0], + [65456, 74, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + ], + // 4-bit alphabet + [ + [4096, 4096, 4096, 4096, 4096, 0, 0, 0, 0], + [5665, 5407, 5048, 4398, 3347, 0, 0, 0, 0], + [7539, 6867, 5973, 4532, 2632, 0, 0, 0, 0], + [9773, 8461, 6833, 4479, 1965, 0, 0, 0, 0], + [12447, 10177, 7564, 4218, 1364, 0, 0, 0, 0], + [15679, 11977, 8072, 3730, 852, 0, 0, 0, 0], + [19640, 13774, 8217, 3016, 453, 0, 0, 0, 0], + [24559, 15361, 7808, 2124, 188, 0, 0, 0, 0], + [30704, 16320, 6642, 1203, 52, 0, 0, 0, 0], + [38280, 15920, 4688, 476, 7, 0, 0, 0, 0], + [47169, 13219, 2372, 99, 1, 0, 0, 0, 0], + [56354, 7896, 631, 4, 1, 0, 0, 0, 0], + [63248, 2208, 34, 1, 1, 0, 0, 0, 0], + [65465, 57, 1, 1, 1, 0, 0, 0, 0], + [65521, 1, 1, 1, 1, 0, 0, 0, 0], + [65521, 1, 1, 1, 1, 0, 0, 0, 0], + ], + // 5-bit alphabet + [ + [2048, 2048, 2048, 2048, 2048, 2048, 0, 0, 0], + [2865, 2799, 2704, 2524, 2200, 1673, 0, 0, 0], + [3858, 3682, 3434, 2986, 2266, 1316, 0, 0, 0], + [5063, 4709, 4230, 3418, 2240, 982, 0, 0, 0], + [6536, 5912, 5088, 3782, 2109, 682, 0, 0, 0], + [8366, 7314, 5988, 4036, 1865, 426, 0, 0, 0], + [10688, 8952, 6888, 4108, 1507, 227, 0, 0, 0], + [13713, 10847, 7680, 3904, 1062, 94, 0, 0, 0], + [17758, 12946, 8160, 3320, 602, 26, 0, 0, 0], + [23272, 15008, 7960, 2344, 237, 4, 0, 0, 0], + [30841, 16327, 6610, 1187, 48, 1, 0, 0, 0], + [41006, 15348, 3947, 316, 1, 1, 0, 0, 0], + [53291, 9957, 1104, 14, 1, 1, 0, 0, 0], + [63380, 2084, 22, 1, 1, 1, 0, 0, 0], + [65505, 1, 1, 1, 1, 1, 0, 0, 0], + [65505, 1, 1, 1, 1, 1, 0, 0, 0], + ], + // 6-bit alphabet + [ + [1024, 1024, 1024, 1024, 1024, 1024, 1024, 0, 0], + [1441, 1423, 1400, 1352, 1262, 1099, 837, 0, 0], + [1951, 1907, 1841, 1717, 1493, 1133, 658, 0, 0], + [2577, 2487, 2354, 2115, 1709, 1120, 491, 0, 0], + [3350, 3186, 2956, 2544, 1890, 1055, 341, 0, 0], + [4324, 4042, 3657, 2994, 2019, 932, 213, 0, 0], + [5581, 5107, 4476, 3444, 2055, 754, 113, 0, 0], + [7258, 6454, 5424, 3840, 1952, 531, 47, 0, 0], + [9579, 8179, 6473, 4080, 1660, 301, 13, 0, 0], + [12907, 10365, 7504, 3980, 1171, 119, 2, 0, 0], + [17852, 12988, 8164, 3304, 594, 23, 1, 0, 0], + [25441, 15565, 7673, 1974, 155, 1, 1, 0, 0], + [37208, 16084, 4978, 552, 4, 1, 1, 0, 0], + [53649, 9731, 1042, 4, 1, 1, 1, 0, 0], + [65147, 327, 1, 1, 1, 1, 1, 0, 0], + [65473, 1, 1, 1, 1, 1, 1, 0, 0], + ], + // 7-bit alphabet + [ + [512, 512, 512, 512, 512, 512, 512, 512, 0], + [722, 718, 712, 700, 676, 632, 550, 418, 0], + [981, 971, 952, 920, 858, 748, 566, 329, 0], + [1300, 1276, 1244, 1178, 1058, 854, 559, 246, 0], + [1696, 1654, 1593, 1478, 1272, 946, 526, 171, 0], + [2198, 2126, 2022, 1828, 1498, 1009, 467, 106, 0], + [2852, 2728, 2554, 2238, 1721, 1028, 376, 57, 0], + [3736, 3522, 3227, 2712, 1920, 977, 266, 23, 0], + [4979, 4601, 4090, 3236, 2040, 831, 151, 6, 0], + [6807, 6101, 5182, 3752, 1991, 586, 59, 1, 0], + [9634, 8218, 6494, 4082, 1652, 296, 11, 1, 0], + [14275, 11165, 7784, 3836, 988, 74, 1, 1, 0], + [22449, 14759, 8042, 2489, 272, 1, 1, 1, 0], + [37625, 16023, 4866, 509, 1, 1, 1, 1, 0], + [60485, 4663, 132, 1, 1, 1, 1, 1, 0], + [65409, 1, 1, 1, 1, 1, 1, 1, 0], + ], + // 8-bit alphabet + [ + [256, 256, 256, 256, 256, 256, 256, 256, 256], + [362, 360, 359, 356, 350, 338, 316, 275, 209], + [492, 488, 486, 476, 460, 429, 374, 284, 164], + [653, 647, 638, 622, 589, 529, 426, 280, 123], + [853, 843, 828, 796, 739, 636, 473, 264, 85], + [1108, 1090, 1063, 1011, 914, 748, 504, 234, 53], + [1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28], + [1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12], + [2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3], + [3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1], + [5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1], + [7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1], + [12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1], + [22767, 14857, 8012, 2432, 240, 1, 1, 1, 1], + [47343, 13141, 2332, 35, 1, 1, 1, 1, 1], + [65281, 1, 1, 1, 1, 1, 1, 1, 1], + ], +]; diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs new file mode 100644 index 000000000..ff82c01fa --- /dev/null +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -0,0 +1,266 @@ +//! Tests of the BCPack decoder on synthetic streams: the fixtures of `tests/data/bcpack` +//! (built by its `generate.py`, an encoder written from the format notes and not from this +//! decoder) and streams of the encoder below. None of them shows what a console would write. + +use super::lanes::{self, L}; +use super::rans_tables::FREQ; +use super::{decode_lanes, lane_widths, Error}; + +pub(crate) fn data(name: &str) -> Option> { + std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack").join(name)).ok() +} + +/// `bc--` → (mode, units) +fn fixture(stem: &str) -> (u8, usize) { + let mut p = stem.strip_prefix("bc").unwrap().split('-'); + (p.next().unwrap().parse().unwrap(), p.next().unwrap().parse().unwrap()) +} + +/// A `.lanes` file (all of lane 0, then lane 1 …) in the decoder's order. +fn by_unit(lane_major: &[u8], lanes: usize) -> Vec { + let units = lane_major.len() / lanes; + (0..units * lanes).map(|i| lane_major[(i % lanes) * units + i / lanes]).collect() +} + +const FIXTURES: [&str; 14] = [ + "bc1-1-8", "bc1-2-0", "bc1-16-1", "bc1-16-9", "bc1-700-2", "bc1-8192-3", "bc3-16-1", "bc4-16-1", "bc5-16-1", "bc6-16-1", "bc7-2-0", "bc7-16-1", + "bc7-700-2", "bc7-8192-3", +]; + +/// The symbols of the two 64 KiB fixtures, which ship without a `.lanes` file (`generate.py`). +pub(crate) fn large_fixture_symbols(mode: u8) -> Vec { + let n = lane_widths(mode).unwrap().len(); + let mut s = vec![0u8; 8192 * n]; + if mode == 1 { + for i in (0..8192).step_by(511) { + s[i * n + 2] = 30; + s[i * n + 8] = 5; + } + for i in (31..8192).step_by(31) { + s[i * n] = 2; + } + } + s +} + +#[test] +fn fixtures_decode_to_their_lanes() { + for stem in FIXTURES { + let (mode, units) = fixture(stem); + let n = lane_widths(mode).unwrap().len(); + let bin = data(&format!("{stem}.bin")).unwrap(); + let want = match data(&format!("{stem}.lanes")) { + Some(l) => by_unit(&l, n), + None => large_fixture_symbols(mode), + }; + assert_eq!(want.len(), units * n, "{stem}"); + // bc1-1-8 has states cut to fewer bytes than an encoder that starts at `L` can drop, + // which the hardware's decoder does not take either + if stem == "bc1-1-8" { + assert!(decode_lanes(mode, &bin, units * 8).is_err(), "{stem}"); + continue; + } + assert_eq!(decode_lanes(mode, &bin, units * 8).as_deref(), Ok(&want[..]), "{stem}"); + // zero padding after the stream is not part of it; anything else is + let mut padded = bin.clone(); + padded.extend([0; 37]); + assert_eq!(decode_lanes(mode, &padded, units * 8).as_deref(), Ok(&want[..]), "{stem} padded"); + padded.push(1); + assert_eq!(decode_lanes(mode, &padded, units * 8), Err(Error::Trailing { consumed: bin.len() }), "{stem}"); + } +} + +/// The 8-bit model 11 as US 11,234,023 prints it (its `base_table[8][12]`, counted from 1). +#[test] +fn model_matches_the_patent_excerpt() { + let base = [0u32, 7575, 14276, 25440, 41008, 56352, 64256, 65344, 65408]; + let freq = [7575u16, 6701, 5582, 3892, 1918, 494, 34, 1, 1]; + assert_eq!(FREQ[7][11], freq); + let mut at = 0; + for k in 0..9 { + assert_eq!(at, base[k]); + at += freq[k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }; + } + assert_eq!(at, 65536); + for (bits, per_q) in FREQ.iter().enumerate() { + for f in per_q { + let total: u32 = (0..9).map(|k| f[k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }).sum(); + assert_eq!(total, 65536); + assert!(f[..bits + 2].iter().all(|&v| v >= 1) && f[bits + 2..].iter().all(|&v| v == 0)); + } + } +} + +// --------------------------------------------------------------------------------------- +// a test encoder: any model, any fragment sizes +// --------------------------------------------------------------------------------------- + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) as u32 + } + fn below(&mut self, n: u32) -> u32 { + self.next() % n + } +} + +/// (frequency, first slot) of `sym` in model (`bits`, `q`). +fn slot(bits: usize, q: usize, sym: u32) -> (u32, u32) { + let seg = (32 - sym.leading_zeros()) as usize; + let base: u32 = (0..seg).map(|k| FREQ[bits - 1][q][k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }).sum(); + let f = FREQ[bits - 1][q][seg] as u32; + let cf = base + f * (sym - ((1u32 << seg) >> 1)); + if cf == 0 { + (f - 1, 1) + } else { + (f, cf) + } +} + +/// One flushed fragment: header, state, payload. `trim`: drop the zero bytes an encoder +/// that starts at `L` may drop (those its first symbol pushed out). +fn fragment(symbols: &[u8], lane_bits: usize, z: usize, q: usize, trim: bool) -> Vec { + let mut x = L; + let mut emitted = Vec::new(); + let mut droppable = 0; + for (k, &s) in symbols.iter().rev().enumerate() { + let (f, cf) = slot(lane_bits - z, q, s as u32); + while x >= f << 16 { + emitted.push(x as u8); + x >>= 8; + } + if k == 0 { + droppable = emitted.len(); + } + x = (x / f) << 16 | (x % f + cf); + } + let mut body = x.to_be_bytes().to_vec(); + body.extend(emitted.iter().rev()); + if trim { + body.truncate(body.len() - droppable); + } + let mode = (z << 6 | 0x10 | q) as u8; + let mut out = if body.len() <= 256 { + vec![mode, (body.len() - 1) as u8] + } else { + let n = body.len() - 257; + vec![mode | 0x20, n as u8, (n >> 8) as u8] + }; + out.extend(body); + out +} + +/// A stream of random symbols and fragments, with its symbols (the decoder's order). The +/// lanes' bytes are put in the order the decoder asks for them, so this checks the decoder +/// against the encoder's arithmetic and itself, not the byte order against anything. +fn random_stream(widths: &[u8], units: usize, rng: &mut Rng) -> (Vec, Vec) { + let n = widths.len(); + let mut symbols = vec![0u8; units * n]; + let mut queues: Vec> = Vec::new(); + for (l, &w) in widths.iter().enumerate() { + let mut bytes = Vec::new(); + let mut at = 0; + while at < units { + let longest = if rng.below(4) == 0 { 700 } else { 40 }; + let len = (1 + rng.below(longest) as usize).min(units - at); + let z = rng.below(4).min(w as u32 - 1) as usize; + let q = rng.below(16) as usize; + let bits = w as usize - z; + // the steeper models leave one slot to most symbols: keep those symbols rare + let frag: Vec = (0..len) + .map(|_| { + let top = if q >= 8 && rng.below(8) != 0 { 1u32 << bits.min(2) } else { 1 << bits }; + rng.below(top) as u8 + }) + .collect(); + for (k, &s) in frag.iter().enumerate() { + symbols[(at + k) * n + l] = s; + } + bytes.extend(fragment(&frag, w as usize, z, q, rng.below(2) == 0)); + at += len; + } + queues.push(bytes.into()); + } + let mut stream = Vec::new(); + let got = lanes::run(widths, units, |lane| { + let b = queues[lane].pop_front(); + stream.extend(b); + b + }) + .expect("the encoder's own fragments decode"); + assert_eq!(got, symbols); + assert!(queues.iter().all(|q| q.is_empty()), "every fragment was read to its end"); + (stream, symbols) +} + +#[test] +fn random_streams_round_trip_in_every_model() { + let mut rng = Rng(0x5EED); + let dump = std::env::var_os("XCL_BCPACK_DUMP").map(std::path::PathBuf::from); + for round in 0..60 { + for mode in [1u8, 3, 4, 5, 6, 7] { + let widths = lane_widths(mode).unwrap(); + let units = [1, 2, 7, 64, 300, 2048][round % 6] * if mode == 1 || mode == 4 { 1 } else { 2 }; + let (stream, symbols) = random_stream(widths, units, &mut rng); + assert_eq!(decode_lanes(mode, &stream, units * 8).as_deref(), Ok(&symbols[..]), "mode {mode} round {round}"); + // every byte of the stream is needed + assert!(decode_lanes(mode, &stream[..stream.len() - 1], units * 8).is_err()); + if let Some(dir) = &dump { + // for a comparison with other decoders: the stream and its lanes, lane by lane + let stem = dir.join(format!("r{round}-bc{mode}-{units}")); + let n = widths.len(); + let lane_major: Vec = (0..units * n).map(|i| symbols[(i % units) * n + i / units]).collect(); + std::fs::write(stem.with_extension("bin"), &stream).unwrap(); + std::fs::write(stem.with_extension("lanes"), lane_major).unwrap(); + } + } + } +} + +/// Damaged input ends in an answer, never a panic or a hang. (The answer can be other +/// symbols: a stream has no checksum, and under a uniform model any bytes are symbols.) +#[test] +fn damaged_streams_end_cleanly() { + let mut rng = Rng(7); + for stem in ["bc1-2-0", "bc1-16-1", "bc1-16-9", "bc7-16-1", "bc1-700-2", "bc7-700-2"] { + let (mode, units) = fixture(stem); + let bin = data(&format!("{stem}.bin")).unwrap(); + let check = |bytes: &[u8], units: usize| decode_lanes(mode, bytes, units * 8); + // every byte of a stream is some lane's: a shorter one is never whole + for cut in (0..bin.len()).step_by((bin.len() / 300).max(1)) { + assert!(check(&bin[..cut], units).is_err(), "{stem} cut at {cut}"); + } + for _ in 0..400 { + let mut b = bin.clone(); + let at = rng.below(b.len() as u32) as usize; + match rng.below(3) { + 0 => b[at] ^= 1 << rng.below(8), + 1 => b[at] = rng.next() as u8, + _ => { + b.remove(at); + } + } + let _ = check(&b, units); + } + // the wrong number of blocks, and a size that is no number of blocks + assert!(check(&bin, units + 1).is_err()); + assert!(check(&bin, units - 1).is_err()); + assert_eq!(decode_lanes(mode, &bin, units * 8 + 4), Err(Error::OutputSize)); + } + // noise, and headers that claim more than there is + for len in [0usize, 1, 2, 3, 47, 48, 64, 500, 5000] { + for _ in 0..40 { + let noise: Vec = (0..len).map(|_| rng.next() as u8).collect(); + for mode in [1u8, 7] { + let _ = decode_lanes(mode, &noise, 64 * 8); + } + } + } + assert!(decode_lanes(1, &[0xFF; 4096], 1 << 20).is_err()); + assert!(decode_lanes(7, &[0x00; 4096], 1 << 20).is_err()); + assert_eq!(decode_lanes(2, &[], 16), Err(Error::Unsupported)); + assert_eq!(decode_lanes(1, &[], 0), Ok(Vec::new())); +} diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index da0eafbd2..f64fa4855 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -11,6 +11,7 @@ use crate::config::Config; use crate::util::glob_match; pub mod acphal; +pub mod bcpack; pub mod d3d12_layout; pub mod d3d12x; pub mod dstorage; diff --git a/scripts/gen_bcpack_tables.py b/scripts/gen_bcpack_tables.py new file mode 100644 index 000000000..01874f749 --- /dev/null +++ b/scripts/gen_bcpack_tables.py @@ -0,0 +1,63 @@ +"""Generate crates/xcl/src/hle/bcpack/rans_tables.rs from Microsoft's silicon-rans sample +(MIT): the per-segment symbol frequencies of the 16 static models, for alphabets of 1 to 8 +bits. The cumulative bases are not stored: base[k + 1] = base[k] + freq[k] * symbols(k), which +this script checks against the sample's own `base_table`, and so are not the reciprocal tables +(`rf`, `rs`, `rn`): the decoder divides, and this script checks that the sample's reciprocal +path gives the same symbol for every slot of every model. + +usage: python scripts/gen_bcpack_tables.py +(https://github.com/microsoft/silicon-rans/blob/main/mdu_minirans.v, commit 2f6827d)""" +import io, os, re, sys + +src = io.open(sys.argv[1], encoding='utf-8').read() +OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'crates', 'xcl', 'src', 'hle', 'bcpack', 'rans_tables.rs') +WIDTHS, MODELS, SEGS = 8, 16, 9 # the sample has a 9-bit alphabet and a 10th segment as well; no BCPack lane is that wide + + +def table(name): + m = re.search(r'assign\s+' + name + r'\s*=\s*\'\{(.*?)\};\s*//\s*end\s+' + name, src, re.S) + rows = [[int(v) for v in r.split(',')] for r in re.findall(r"'\{\s*([0-9,\s]+?)\s*\}", m.group(1))] + assert len(rows) == 9 * 16 and all(len(r) == 10 for r in rows), name + return [rows[w * 16:(w + 1) * 16] for w in range(9)] + + +base, freq, rf, rs, rn = (table(n + '_table') for n in ('base', 'freq', 'rf', 'rs', 'rn')) + + +def symbols(seg): + return 1 if seg < 2 else 1 << (seg - 1) + + +for w in range(WIDTHS): + for q in range(MODELS): + b, f = base[w][q], freq[w][q] + nseg = w + 2 # segment 0 is symbol 0, segment k >= 1 is symbols [2^(k-1), 2^k) + acc = 0 + for k in range(nseg): + assert b[k] == acc and f[k] >= 1, (w, q, k) + acc += f[k] * symbols(k) + assert acc == 65536 and not any(f[nseg:]), (w, q) + # the sample's inverse (comparator chain, then a reciprocal multiply) is a division + for cf in range(65536): + seg = max((k for k in range(1, nseg) if cf >= b[k]), default=0) + steps = ((((cf - b[seg] + rn[w][q][seg]) & 0xFFFF) * rf[w][q][seg]) >> 15) >> rs[w][q][seg] + assert steps == (cf - b[seg]) // f[seg], (w, q, cf) + +out = io.open(OUT, 'w', encoding='utf-8', newline='\n') +out.write('''// Generated by scripts/gen_bcpack_tables.py from Microsoft's silicon-rans sample (mdu_minirans.v, +// https://github.com/microsoft/silicon-rans commit 2f6827d): Copyright (c) Microsoft Corporation, MIT. +// `FREQ[bits - 1][q][segment]`: the frequency of each symbol of a segment, out of 65536. Segment 0 +// is symbol 0, segment k >= 1 is the symbols 2^(k-1) .. 2^k - 1. + +#![allow(clippy::unreadable_literal)] + +''') +out.write(f'pub static FREQ: [[[u16; {SEGS}]; {MODELS}]; {WIDTHS}] = [\n') +for w in range(WIDTHS): + out.write(f' // {w + 1}-bit alphabet\n [\n') + for q in range(MODELS): + out.write(' [' + ', '.join(str(v) for v in freq[w][q][:SEGS]) + '],\n') + out.write(' ],\n') +out.write('];\n') +out.close() +print('wrote', os.path.normpath(OUT)) diff --git a/tests/data/bcpack/.gitattributes b/tests/data/bcpack/.gitattributes new file mode 100644 index 000000000..eb1e5257b --- /dev/null +++ b/tests/data/bcpack/.gitattributes @@ -0,0 +1,3 @@ +*.bin binary +*.lanes binary +*.bc1 binary diff --git a/tests/data/bcpack/bc1-1-8.bin b/tests/data/bcpack/bc1-1-8.bin new file mode 100644 index 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.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.bin b/tests/data/bcpack/bc1-16-9.bin new file mode 100644 index 000000000..2462981a1 Binary files /dev/null and b/tests/data/bcpack/bc1-16-9.bin differ diff --git a/tests/data/bcpack/bc1-16-9.lanes b/tests/data/bcpack/bc1-16-9.lanes new file mode 100644 index 000000000..bbba064ba Binary files /dev/null and b/tests/data/bcpack/bc1-16-9.lanes differ diff --git a/tests/data/bcpack/bc1-2-0.bin b/tests/data/bcpack/bc1-2-0.bin new file mode 100644 index 000000000..9583e4063 Binary files /dev/null and b/tests/data/bcpack/bc1-2-0.bin differ diff --git a/tests/data/bcpack/bc1-2-0.lanes b/tests/data/bcpack/bc1-2-0.lanes new file mode 100644 index 000000000..7067007a8 Binary files /dev/null and b/tests/data/bcpack/bc1-2-0.lanes differ diff --git a/tests/data/bcpack/bc1-700-2.bin b/tests/data/bcpack/bc1-700-2.bin new file mode 100644 index 000000000..b3470659e Binary files /dev/null and b/tests/data/bcpack/bc1-700-2.bin differ diff --git a/tests/data/bcpack/bc1-700-2.lanes b/tests/data/bcpack/bc1-700-2.lanes new file mode 100644 index 000000000..6eac67a55 Binary files /dev/null and b/tests/data/bcpack/bc1-700-2.lanes differ diff --git a/tests/data/bcpack/bc1-8192-3.bin b/tests/data/bcpack/bc1-8192-3.bin new file mode 100644 index 000000000..1bf0c4287 --- /dev/null +++ b/tests/data/bcpack/bc1-8192-3.bin @@ -0,0 +1,3 @@ +?%K6 66 6”‰¥��¥�¢‡ÿ×ÎÎ×ÎÌŽþ�  � !² ííZœ*GKK;””Kÿ‡‡”ŽŽ‡i²²Ž²Ga à } 2 # “ ¶ ÷ ¹ u Ì A ˜ g v ‡ Oœr º ‚ ‹ ³ Ù ß ¥  ² Ü} +Í ƒ � W eœ! ¬½$ ð ¸ tttt  { ž É   Ò 3 E ( ?  Y óœ@ Í þ «  · ò 3  ¤ v D ë  Çœ„y/ © ³ ½ � E © ® 2 ô«y µ Š 8 3 Ñ $ 0œ; ˜ ~ ¦ 5 ê ¯ à   = Û G P Î § úÜ×™ å ® ² R  … @ î $ ± A ¯ ·  é Ò ¹\ÿ   }  I , ° mÝ ” Ë â Y ˆ „ Ð ø ÜŽ» Ï b Z » Ò  ˆ 0 n ¿ Ç H A Õ  + ¯ünn ï I f Ü 0 ! o Þ õ < ê ± y  £<¬% è Í 0  º¶ ’ 3�‰‰‰‰ Õ  < ð ü i ÷ ¬ +N1   Œ _ ¨ ¢ Õ à � ¼ �  Ç É Œ ‰– A Z n  . ] j  ? Ç r  ¼ $ G q|‘~‚ W ñøã �Þ ª T ¤ ‚ » © W f ü { å XØË }  = ? ‘ Ý Ý z Í ø # É + é a 6 |áx � � œ ‡  ˆ  ¸ 9 ¢ Å ‹ ð Õ  \ No newline at end of file diff --git a/tests/data/bcpack/bc3-16-1.bin b/tests/data/bcpack/bc3-16-1.bin new file mode 100644 index 000000000..7090e9ccd Binary files /dev/null and b/tests/data/bcpack/bc3-16-1.bin differ diff --git a/tests/data/bcpack/bc3-16-1.lanes b/tests/data/bcpack/bc3-16-1.lanes new file mode 100644 index 000000000..21f601d74 Binary files /dev/null and b/tests/data/bcpack/bc3-16-1.lanes differ diff --git a/tests/data/bcpack/bc4-16-1.bin b/tests/data/bcpack/bc4-16-1.bin new file mode 100644 index 000000000..1801a52bb Binary files /dev/null and b/tests/data/bcpack/bc4-16-1.bin differ diff --git a/tests/data/bcpack/bc4-16-1.lanes b/tests/data/bcpack/bc4-16-1.lanes new file mode 100644 index 000000000..d10778ce7 Binary files /dev/null and b/tests/data/bcpack/bc4-16-1.lanes differ diff --git a/tests/data/bcpack/bc5-16-1.bin b/tests/data/bcpack/bc5-16-1.bin new file mode 100644 index 000000000..76fe7570c Binary files /dev/null and b/tests/data/bcpack/bc5-16-1.bin differ diff --git a/tests/data/bcpack/bc5-16-1.lanes b/tests/data/bcpack/bc5-16-1.lanes new file mode 100644 index 000000000..b99826baf Binary files /dev/null and b/tests/data/bcpack/bc5-16-1.lanes differ diff --git a/tests/data/bcpack/bc6-16-1.bin b/tests/data/bcpack/bc6-16-1.bin new file mode 100644 index 000000000..6a3a20490 Binary files /dev/null and b/tests/data/bcpack/bc6-16-1.bin differ diff --git a/tests/data/bcpack/bc6-16-1.lanes b/tests/data/bcpack/bc6-16-1.lanes new file mode 100644 index 000000000..02e458dac Binary files /dev/null and b/tests/data/bcpack/bc6-16-1.lanes differ diff --git a/tests/data/bcpack/bc7-16-1.bin b/tests/data/bcpack/bc7-16-1.bin new file mode 100644 index 000000000..43e4a405c Binary files /dev/null and b/tests/data/bcpack/bc7-16-1.bin differ diff --git a/tests/data/bcpack/bc7-16-1.lanes b/tests/data/bcpack/bc7-16-1.lanes new file mode 100644 index 000000000..850bc0d02 Binary files /dev/null and b/tests/data/bcpack/bc7-16-1.lanes differ diff --git a/tests/data/bcpack/bc7-2-0.bin b/tests/data/bcpack/bc7-2-0.bin new file mode 100644 index 000000000..83adbc9e0 Binary files /dev/null and b/tests/data/bcpack/bc7-2-0.bin differ diff --git a/tests/data/bcpack/bc7-2-0.lanes b/tests/data/bcpack/bc7-2-0.lanes new file mode 100644 index 000000000..1dbd8603d Binary files /dev/null and b/tests/data/bcpack/bc7-2-0.lanes differ diff --git a/tests/data/bcpack/bc7-700-2.bin b/tests/data/bcpack/bc7-700-2.bin new file mode 100644 index 000000000..2562254ab Binary files /dev/null and b/tests/data/bcpack/bc7-700-2.bin differ diff --git a/tests/data/bcpack/bc7-700-2.lanes b/tests/data/bcpack/bc7-700-2.lanes new file mode 100644 index 000000000..e16eece09 Binary files /dev/null and b/tests/data/bcpack/bc7-700-2.lanes differ diff --git a/tests/data/bcpack/bc7-8192-3.bin b/tests/data/bcpack/bc7-8192-3.bin new file mode 100644 index 000000000..c362eec97 --- /dev/null +++ b/tests/data/bcpack/bc7-8192-3.bin @@ -0,0 +1 @@ +KKKKKˆaa”””””òDD‡‡‡‡‡eÀÀŽŽŽŽŽD²²²²²‰ˆ6ò� KKKK6eÎ¥””””�D ×‡‡‡‡Î‰�ŽŽŽŽ í²²²²ttttttttt•• ‰‰‰‰‰‰‰‰‰ \ No newline at end of file diff --git a/tests/data/bcpack/generate.py b/tests/data/bcpack/generate.py new file mode 100644 index 000000000..18b738c6b --- /dev/null +++ b/tests/data/bcpack/generate.py @@ -0,0 +1,186 @@ +"""Generate synthetic q=0 and q=15 BCPack vectors using the encoder's byte counts. + +The multiplexer never decodes rANS. Each inverse step records the number +of bytes the forward step will need later. +""" + +import random +import struct +from collections import deque +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +BC1 = (8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8) +BC7 = (4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5) + + +WIDTHS = { + 1: BC1, + 3: (4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8), + 4: (8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), + 5: (4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), + 6: (4, 4, 8, 8, 8, 5, 5, 5, 6, 6, 6, 8, 8, 8, 8, 5), + 7: BC7, +} + + +def record_header(mode, body_size): + if body_size <= 256: + return bytes((mode, body_size - 1)) + return bytes((mode | 32,)) + struct.pack('= count << 16: + emitted.append(state & 255) + state >>= 8 + counts.append(len(emitted) - start) + whole, remainder = divmod(state, count) + state = (whole << 16) + lo + remainder + mode = 16 | model | (reduction << 6) + size = 4 + len(emitted) + state_bytes = state.to_bytes(4, 'big') + self.continuation = None + if carry and emitted: + # First record ends immediately after the initial state. Its first + # unfulfilled normalisation request starts the continuation header. + self.header = deque(bytes((mode & ~16, 3)) + state_bytes) + self.payload = deque() + self.continuation = (deque(record_header(mode, len(emitted))), + deque(reversed(emitted))) + elif trim: + assert len(symbols) == 1 and not any(emitted) + state_bytes = state_bytes.rstrip(b'\x00') + self.header = deque(record_header(mode, len(state_bytes)) + state_bytes) + self.payload = deque() + counts = [0] + else: + self.header = deque(record_header(mode, size) + state_bytes) + self.payload = deque(reversed(emitted)) + self.counts = deque(reversed(counts)) + self.buffered = False + self.owed = 0 + self.ahead = False + + def wants(self): + return self.header or (self.payload and not self.buffered + and (self.owed or not self.ahead)) + + def tick(self, served, stalled, out): + if self.header: + if served: + out.append(self.header.popleft()) + return + if served: + out.append(self.payload.popleft()) + self.buffered = True + if self.owed: + if self.buffered: + self.owed -= 1 + self.buffered = False + return + if self.counts and not (self.ahead or stalled): + self.owed = self.counts.popleft() + self.ahead = True + if self.buffered and self.owed: + self.buffered = False + self.owed -= 1 + + +def encode(symbols, widths, reductions, model=0, carry=False, trim=False): + lanes = [EncoderLane(*spec, model, carry, trim) for spec in zip(symbols, widths, reductions)] + out = bytearray() + while any(lane.header or lane.counts or lane.owed for lane in lanes): + wanted = [i for i, lane in enumerate(lanes) if lane.wants()] + for i, lane in enumerate(lanes): + lane.tick(i in wanted[:8], i in wanted[8:], out) + if lane.owed and lane.continuation: + lane.header, lane.payload = lane.continuation + lane.continuation = None + if all(lane.ahead for lane in lanes): + for lane in lanes: + lane.ahead = False + assert all(not lane.payload and not lane.buffered for lane in lanes) + return bytes(out) + + +def generate(mode, units, seed, reduced, **options): + widths = WIDTHS[mode] + rng = random.Random(seed) + reductions = [rng.randrange(4) if reduced else 0 for width in widths] + symbols = [[rng.randrange(1 << (width - reduction)) for _ in range(units)] + for width, reduction in zip(widths, reductions)] + if mode == 1: + symbols[1] = [0] * units + path = ROOT / f'bc{mode}-{units}-{seed}' + path.with_suffix('.bin').write_bytes(encode(symbols, widths, reductions, **options)) + path.with_suffix('.lanes').write_bytes(b''.join(map(bytes, symbols))) + return symbols, path + + +def seed_channels(slot): + return [(7 * slot + 13 * k) % (1 << w) for k, w in enumerate(BC1[2:8])] + + +def assemble(symbols): + blocks = [] + raw = bytearray() + for i, (ref, _, *fields) in enumerate(zip(*symbols)): + d = 255 - ref // 2 if ref & 1 else ref // 2 + predictor = ([0] * 6 if d == 0 else + blocks[i-d] if i >= d else seed_channels((i-d) % 256)) + channels = [] + for v, base, w in zip(fields, predictor, BC1[2:8]): + delta = ~(v >> 1) if v & 1 else v >> 1 + channels.append((base + delta) % (1 << w)) + blocks.append(channels) + for r, g, b in (channels[:3], channels[3:]): + raw.extend(struct.pack('> (2 * (2*(y%2) + x%2))) & 3 + indices |= px << (2 * (4*y + x)) + raw.extend(struct.pack('