From 3c5599595697f96bf11d1723f90d24b96db7aad5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:37:31 -0800 Subject: [PATCH 01/47] craft-testkit: fonts renames a test face's family and builds TrueType collections Add the fonts module. rename_family(bytes, from, to) replaces a family name of the same UTF-16 length in the family records (name IDs 1, 16 and 21) and in full names (ID 4) that are the name or start with it followed by a space, in UTF-16BE and ASCII Macintosh Roman records, and writes the name table checksum and head.checkSumAdjustment. collection(faces) builds a TTC 1.0 with each face's own tables, four-byte padding, file-relative offsets, zeroed checkSumAdjustment and checksums of the copied tables. Both return a FontError instead of panicking: names of different lengths, no family record holding the name, a face shorter than its table directory, tables or name strings out of range, shared name storage that a rename would change, a collection given as a face, and output past the 4 GiB that 32-bit offsets reach. The code comes from the rename and collection helpers in VectorCraft, DesignCraft and WordCraft font tests. Their tests need each app's font database and bundled fonts, so they stay in the apps; tests/fonts.rs tests the module on faces built in memory. --- crates/testkit/README.md | 19 ++ crates/testkit/src/fonts.rs | 498 ++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 7 + crates/testkit/tests/fonts.rs | 558 ++++++++++++++++++++++++++++++++++ 4 files changed, 1082 insertions(+) create mode 100644 crates/testkit/src/fonts.rs create mode 100644 crates/testkit/tests/fonts.rs diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..1e1a254e9f 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -78,11 +78,27 @@ fn no_std_instant_in_code_the_web_build_runs() { } ``` +## Test fonts + +The `fonts` module makes test fonts from font bytes the caller supplies. It reads no file and no environment variable, prints nothing, and builds for `wasm32-unknown-unknown`. + +- **`fonts::rename_family(bytes, from, to)`** returns a copy of one standalone face with the family name `from` replaced by `to`, which must have the same length in UTF-16 code units. It changes the family name records (name IDs 1, 16 and 21) whose value is `from`, and full names (ID 4) that are `from` or start with `from` and a space. At least one family record must hold `from`. It reads UTF-16BE and Macintosh Roman records, writes only ASCII names into Macintosh Roman records, leaves the PostScript name (ID 6), other names and other tables as they are, and writes the `name` table checksum and the `head` table's `checkSumAdjustment`. +- **`fonts::collection(faces)`** returns a TrueType collection (TTC 1.0) holding standalone faces. Each face gets its own copy of every table, tables start on four-byte boundaries, offsets count from the start of the collection, `checkSumAdjustment` is zero, and every table checksum matches the bytes in the collection. + +Both return a `fonts::FontError` instead of panicking: names of different lengths, a name that no family record holds, a face shorter than its table directory, a table or name string out of range, a collection given as a face, or output past the 4 GiB a collection's offsets reach. The layouts come from the OpenType font file and `name` table chapters: and . + +The tests that call the copies in VectorCraft, DesignCraft and WordCraft need each app's font database and its bundled fonts, so they stay in the apps. `tests/fonts.rs` tests the module on faces it assembles from bytes. + ## Origin | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `fonts` | storytold/vectorcraft, `rename` and `collection` | `crates/text/src/tests/sysfonts.rs` | `bada8e1710` | +| `fonts` | storytold/vectorcraft, `renamed` | `crates/testkit/src/fonts.rs` | `bada8e1710` | +| `fonts` | storytold/designcraft, the family renaming and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `8b169f8ee7` | +| `fonts` | storytold/wordcraft, `renamed_to` and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `f8c66d0692` | +| `fonts` | storytold/wordcraft, `renamed` | `crates/fonts/src/fontdb/user/tests.rs` | `f8c66d0692` | ## Migration @@ -90,3 +106,6 @@ fn no_std_instant_in_code_the_web_build_runs() { |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| VectorCraft | `fonts::rename_family`, `fonts::collection` | `crates/text/src/tests/sysfonts.rs` and `crates/testkit/src/fonts.rs` helpers | Not started | +| DesignCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` helpers | Not started | +| WordCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` and `crates/fonts/src/fontdb/user/tests.rs` helpers | Not started | diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs new file mode 100644 index 0000000000..7231980c7a --- /dev/null +++ b/crates/testkit/src/fonts.rs @@ -0,0 +1,498 @@ +//! Test fonts made from font bytes the caller supplies. +//! +//! [`rename_family`] gives one standalone face a family name of the same length, and [`collection`] +//! builds a TrueType collection (TTC) from standalone faces. Both read the structures they change as +//! the OpenType specification lays them out +//! ( and +//! ), and return a [`FontError`] +//! for input that does not fit them. Other tables are copied as they are and are not checked. +//! +//! The module reads no file and no environment variable, prints nothing, and builds for +//! `wasm32-unknown-unknown`. + +use std::fmt; +use std::ops::Range; + +/// Length of the sfnt header: version, `numTables`, `searchRange`, `entrySelector`, `rangeShift`. +const SFNT_HEADER: usize = 12; +/// Length of one table record: tag, checksum, offset, length. +const TABLE_RECORD: usize = 16; +/// Length of the `name` table header: version, count, `storageOffset`. +const NAME_HEADER: usize = 6; +/// Length of one name record. +const NAME_RECORD: usize = 12; +/// Length of one language-tag record of a version 1 `name` table. +const LANG_TAG_RECORD: usize = 4; +/// Offset of `checkSumAdjustment` in the `head` table. +const HEAD_ADJUSTMENT: usize = 8; +/// The value a standalone font's checksum and its `checkSumAdjustment` add up to. +const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA; +/// Name IDs that hold a family name: legacy (1), typographic (16) and WWS (21). +const FAMILY_IDS: [u16; 3] = [1, 16, 21]; +/// Name ID of the full font name, which starts with the family name. +const FULL_NAME_ID: u16 = 4; + +/// Why a face could not be renamed or collected. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FontError { + /// `from` and `to` have different lengths in UTF-16 code units. + UnequalLength, + /// `from` or `to` is empty. + InvalidName, + /// No family record of the face holds `from`. + NameNotFound, + /// The face has no `name` table. + MissingNameTable, + /// A structure the function reads is truncated, out of range or of an unknown version. + MalformedFont, + /// A matching Macintosh Roman record would need a name that is not ASCII. + UnsupportedEncoding, + /// A string the rename changes shares bytes with a string it keeps, or with a different replacement. + ConflictingNameStorage, + /// [`collection`] was given no faces. + EmptyCollection, + /// The input is a collection, or an sfnt version other than TrueType or CFF outlines. + UnsupportedFace, + /// The output would not fit in memory or in the 32-bit offsets of a collection. + OutputTooLarge, +} + +impl fmt::Display for FontError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::UnequalLength => "the old and new family names have different lengths", + Self::InvalidName => "a family name is empty", + Self::NameNotFound => "no family name record holds the old name", + Self::MissingNameTable => "the font has no name table", + Self::MalformedFont => "the font's table directory or name table is truncated or out of range", + Self::UnsupportedEncoding => "a Macintosh Roman name record can only take an ASCII name", + Self::ConflictingNameStorage => "a renamed string shares its bytes with a string that must not change", + Self::EmptyCollection => "a collection needs at least one face", + Self::UnsupportedFace => "the input is not a standalone TrueType or CFF face", + Self::OutputTooLarge => "the output is too large", + }) + } +} + +impl std::error::Error for FontError {} + +/// Returns a copy of `bytes`, one standalone face, with the family name `from` replaced by `to`. +/// +/// The records changed are the legacy, typographic and WWS family names (name IDs 1, 16 and 21) +/// whose whole value is `from`, and full names (name ID 4) that are `from` or start with `from` and a +/// space; at least one family record must hold `from`. Copyright, style, PostScript (ID 6) and every +/// other name keep their bytes. Records in UTF-16BE (platform 0, and platform 3 encodings 0, 1 and +/// 10) and Macintosh Roman (platform 1 encoding 0) are read, and only ASCII names are written into +/// Macintosh Roman records; records in other encodings are left as they are. The function then writes the +/// `name` table's checksum and the `head` table's `checkSumAdjustment`. +/// +/// # Errors +/// +/// [`FontError::InvalidName`] when a name is empty, [`FontError::UnequalLength`] when the names have +/// different UTF-16 lengths, [`FontError::NameNotFound`] when no family record holds `from`, +/// [`FontError::UnsupportedEncoding`] when a matching Macintosh Roman record would need non-ASCII +/// bytes, [`FontError::ConflictingNameStorage`] when a changed string shares bytes with a kept one, +/// [`FontError::MissingNameTable`], [`FontError::UnsupportedFace`] for a collection, and +/// [`FontError::MalformedFont`] when the directory, the `name` table or the `head` table is out of +/// range or of an unknown version, or when the `name` or `head` table shares bytes with the directory +/// or another table. +pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result, FontError> { + if from.is_empty() || to.is_empty() { + return Err(FontError::InvalidName); + } + if from.encode_utf16().count() != to.encode_utf16().count() { + return Err(FontError::UnequalLength); + } + let tables = directory(bytes)?; + let name = tables.iter().find(|t| &t.tag == b"name").ok_or(FontError::MissingNameTable)?; + let head = tables.iter().find(|t| &t.tag == b"head"); + if shares_bytes(&tables, name) || head.is_some_and(|head| shares_bytes(&tables, head)) { + return Err(FontError::MalformedFont); + } + if head.is_some_and(|head| head.length < HEAD_ADJUSTMENT + 4) { + return Err(FontError::MalformedFont); + } + let strings = name_strings(bytes, name)?; + let (edits, kept) = plan_edits(bytes, &strings, from, to)?; + check_kept(&edits, kept)?; + + let mut out = copy_of(bytes)?; + apply_edits(&mut out, name, &edits)?; + let name_sum = checksum(bytes_at(&out, name.offset, name.length)?); + put_u32(&mut out, name.record + 4, name_sum)?; + if let Some(head) = head { + let at = head.offset + HEAD_ADJUSTMENT; + put_u32(&mut out, at, 0)?; + let sum = checksum(&out); + put_u32(&mut out, at, CHECKSUM_TARGET.wrapping_sub(sum))?; + } + Ok(out) +} + +/// Returns a TrueType collection (TTC version 1.0) holding `faces`, each a standalone face, in order. +/// +/// Every face keeps its sfnt header and table order and gets its own copy of each table. Tables +/// start on four-byte boundaries with zero padding between them, offsets count from the start of the +/// collection, and each record keeps the table's unpadded length. Each `head` table's +/// `checkSumAdjustment` is set to zero, as a collection does not use it, and every table checksum is +/// computed from the bytes in the collection. +/// +/// # Errors +/// +/// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is +/// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or +/// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the +/// 4 GiB that its 32-bit offsets reach or cannot be allocated. +pub fn collection(faces: &[&[u8]]) -> Result, FontError> { + if faces.is_empty() { + return Err(FontError::EmptyCollection); + } + let directories = faces.iter().map(|face| directory(face)).collect::, _>>()?; + let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?; + let size = collection_size(&directories)?; + let mut out = Vec::new(); + out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?; + out.extend_from_slice(b"ttcf"); + out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + out.extend_from_slice(&count.to_be_bytes()); + out.resize(SFNT_HEADER + faces.len() * 4, 0); + for (index, (face, tables)) in faces.iter().zip(&directories).enumerate() { + let directory = offset32(out.len())?; + put_u32(&mut out, SFNT_HEADER + index * 4, directory)?; + write_face(&mut out, face, tables)?; + } + Ok(out) +} + +/// One table record of a face: where the record is and where its table is. +struct Table { + tag: [u8; 4], + /// Offset of the table record in the face. + record: usize, + offset: usize, + length: usize, +} + +/// Reads a standalone face's table directory, checking that every record and table lies in `face`. +fn directory(face: &[u8]) -> Result, FontError> { + let version = bytes_at(face, 0, 4)?; + if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { + return Err(FontError::UnsupportedFace); + } + let count = usize::from(u16_at(face, 4)?); + bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?; + let mut tables = Vec::with_capacity(count); + for index in 0..count { + let record = SFNT_HEADER + index * TABLE_RECORD; + let tag = <[u8; 4]>::try_from(bytes_at(face, record, 4)?).map_err(|_| FontError::MalformedFont)?; + let offset = usize_from(u32_at(face, record + 8)?)?; + let length = usize_from(u32_at(face, record + 12)?)?; + bytes_at(face, offset, length)?; + tables.push(Table { tag, record, offset, length }); + } + Ok(tables) +} + +/// Whether `table` shares bytes with the table directory or with another table of the face. +fn shares_bytes(tables: &[Table], table: &Table) -> bool { + let end = table.offset + table.length; + let overlaps = |start: usize, other_end: usize| start < end && table.offset < other_end; + overlaps(0, SFNT_HEADER + tables.len() * TABLE_RECORD) + || tables.iter().any(|other| other.record != table.record && overlaps(other.offset, other.offset + other.length)) +} + +/// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches. +fn collection_size(directories: &[Vec]) -> Result { + let mut size = u64::try_from(SFNT_HEADER + directories.len() * 4).map_err(|_| FontError::OutputTooLarge)?; + for tables in directories { + let directory = SFNT_HEADER + tables.len() * TABLE_RECORD; + size = size.checked_add(u64::try_from(directory).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; + for table in tables { + let padded = u64::try_from(table.length).map_err(|_| FontError::OutputTooLarge)?.div_ceil(4) * 4; + size = size.checked_add(padded).ok_or(FontError::OutputTooLarge)?; + } + } + if size > u64::from(u32::MAX) { + return Err(FontError::OutputTooLarge); + } + usize::try_from(size).map_err(|_| FontError::OutputTooLarge) +} + +/// Appends one face's directory and tables to a collection being built. +fn write_face(out: &mut Vec, face: &[u8], tables: &[Table]) -> Result<(), FontError> { + let directory = out.len(); + out.extend_from_slice(bytes_at(face, 0, SFNT_HEADER)?); + out.resize(directory + SFNT_HEADER + tables.len() * TABLE_RECORD, 0); + for (index, table) in tables.iter().enumerate() { + let start = out.len(); + out.extend_from_slice(bytes_at(face, table.offset, table.length)?); + if &table.tag == b"head" { + if table.length < HEAD_ADJUSTMENT + 4 { + return Err(FontError::MalformedFont); + } + put_u32(out, start + HEAD_ADJUSTMENT, 0)?; + } + let sum = checksum(bytes_at(out, start, table.length)?); + out.resize(out.len().div_ceil(4) * 4, 0); + let record = directory + SFNT_HEADER + index * TABLE_RECORD; + put_bytes(out, record, &table.tag)?; + put_u32(out, record + 4, sum)?; + put_u32(out, record + 8, offset32(start)?)?; + put_u32(out, record + 12, offset32(table.length)?)?; + } + Ok(()) +} + +/// How the bytes of a name record are encoded, as far as renaming reads them. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Encoding { + Utf16, + MacRoman, + Other, +} + +impl Encoding { + fn of(platform: u16, encoding: u16) -> Self { + match (platform, encoding) { + (0, _) | (3, 0 | 1 | 10) => Self::Utf16, + (1, 0) => Self::MacRoman, + _ => Self::Other, + } + } +} + +/// One string of the `name` table, with its range in the face. +struct NameString { + encoding: Encoding, + name_id: u16, + range: Range, +} + +/// The strings of a face's `name` table: the name records, then the language tags of version 1. +struct NameStrings { + names: Vec, + lang_tags: Vec>, +} + +/// Reads the name and language-tag records of `table`, checking every string lies in the table. +fn name_strings(face: &[u8], table: &Table) -> Result { + let data = bytes_at(face, table.offset, table.length)?; + let version = u16_at(data, 0)?; + if version > 1 { + return Err(FontError::MalformedFont); + } + let count = usize::from(u16_at(data, 2)?); + let storage = usize::from(u16_at(data, 4)?); + let records_end = NAME_HEADER + count * NAME_RECORD; + bytes_at(data, 0, records_end)?; + let mut header_end = records_end; + let mut lang_tag_records = 0; + if version == 1 { + lang_tag_records = usize::from(u16_at(data, records_end)?); + header_end = records_end + 2 + lang_tag_records * LANG_TAG_RECORD; + } + if storage < header_end || storage > data.len() { + return Err(FontError::MalformedFont); + } + let string = |at: usize| -> Result, FontError> { + let length = usize::from(u16_at(data, at)?); + let start = storage + usize::from(u16_at(data, at + 2)?); + bytes_at(data, start, length)?; + Ok(table.offset + start..table.offset + start + length) + }; + let mut names = Vec::with_capacity(count); + for index in 0..count { + let record = NAME_HEADER + index * NAME_RECORD; + let encoding = Encoding::of(u16_at(data, record)?, u16_at(data, record + 2)?); + let name_id = u16_at(data, record + 6)?; + names.push(NameString { encoding, name_id, range: string(record + 8)? }); + } + let mut lang_tags = Vec::with_capacity(lang_tag_records); + for index in 0..lang_tag_records { + lang_tags.push(string(records_end + 2 + index * LANG_TAG_RECORD)?); + } + Ok(NameStrings { names, lang_tags }) +} + +/// A string the rename writes: its range in the face and its new bytes. +struct Edit { + range: Range, + bytes: Vec, +} + +/// Works out the strings to rewrite and the ranges of the strings that must keep their bytes. +/// Refuses with [`FontError::NameNotFound`] when no family record (IDs 1, 16 and 21) holds `from`. +fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Result<(Vec, Vec>), FontError> { + let mut edits = Vec::new(); + let mut kept = strings.lang_tags.clone(); + let mut family_found = false; + for string in &strings.names { + let family = FAMILY_IDS.contains(&string.name_id); + let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; + let new = if family || string.name_id == FULL_NAME_ID { renamed(string, bytes, from, to)? } else { None }; + match new { + Some(new) => { + family_found |= family; + edits.push(Edit { range: string.range.clone(), bytes: new }); + } + None => kept.push(string.range.clone()), + } + } + if !family_found { + return Err(FontError::NameNotFound); + } + Ok((edits, kept)) +} + +/// The new bytes of a family or full-name string, or `None` when it does not hold `from`. +fn renamed(string: &NameString, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + let family = FAMILY_IDS.contains(&string.name_id); + let encoded = match string.encoding { + Encoding::Utf16 => renamed_utf16(family, bytes, from, to)?, + Encoding::MacRoman => renamed_mac_roman(family, bytes, from, to)?, + Encoding::Other => None, + }; + if encoded.as_ref().is_some_and(|encoded| encoded.len() != bytes.len()) { + return Err(FontError::UnequalLength); + } + Ok(encoded) +} + +/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and a space. +fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + let value = utf16_value(bytes)?; + let new = if family { + (value == from).then(|| to.to_owned()) + } else { + value.strip_prefix(from).filter(|rest| rest.is_empty() || rest.starts_with(' ')).map(|rest| format!("{to}{rest}")) + }; + Ok(new.map(|new| new.encode_utf16().flat_map(u16::to_be_bytes).collect())) +} + +/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, byte by byte; only ASCII names are written. +fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + if !from.is_ascii() { + return if mac_roman_may_hold(family, bytes, from) { Err(FontError::UnsupportedEncoding) } else { Ok(None) }; + } + let Some(rest) = bytes.strip_prefix(from.as_bytes()) else { + return Ok(None); + }; + if !(rest.is_empty() || (!family && rest.first() == Some(&b' '))) { + return Ok(None); + } + if !to.is_ascii() { + return Err(FontError::UnsupportedEncoding); + } + Ok(Some([to.as_bytes(), rest].concat())) +} + +/// Whether a Macintosh Roman string could hold a non-ASCII `from`. The encoding has one byte per +/// character and shares its ASCII range with Unicode, so a string that differs from `from` in length +/// or in an ASCII position cannot hold it. +fn mac_roman_may_hold(family: bool, bytes: &[u8], from: &str) -> bool { + let count = from.chars().count(); + let fits = bytes.len() == count || (!family && bytes.get(count) == Some(&b' ')); + fits && bytes.iter().zip(from.chars()).all(|(&byte, c)| !(byte.is_ascii() || c.is_ascii()) || char::from(byte) == c) +} + +/// Decodes a UTF-16BE string, refusing an odd length or an unpaired surrogate. +fn utf16_value(bytes: &[u8]) -> Result { + let (pairs, rest) = bytes.as_chunks::<2>(); + if !rest.is_empty() { + return Err(FontError::MalformedFont); + } + let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair)); + char::decode_utf16(units).collect::>().map_err(|_| FontError::MalformedFont) +} + +/// Refuses a rename whose strings overlap a string that keeps its bytes. +fn check_kept(edits: &[Edit], mut kept: Vec>) -> Result<(), FontError> { + kept.retain(|range| !range.is_empty()); + kept.sort_by_key(|range| range.start); + let mut merged: Vec> = Vec::with_capacity(kept.len()); + for range in kept { + match merged.last_mut() { + Some(last) if range.start <= last.end => last.end = last.end.max(range.end), + _ => merged.push(range), + } + } + for edit in edits { + let next = merged.partition_point(|range| range.end <= edit.range.start); + if merged.get(next).is_some_and(|range| range.start < edit.range.end) { + return Err(FontError::ConflictingNameStorage); + } + } + Ok(()) +} + +/// Writes the edits into `out`, refusing two edits that write different bytes to the same place. +fn apply_edits(out: &mut [u8], name: &Table, edits: &[Edit]) -> Result<(), FontError> { + let mut ranges: Vec<&Edit> = edits.iter().collect(); + ranges.sort_by_key(|edit| (edit.range.start, edit.range.end)); + ranges.dedup_by(|a, b| a.range == b.range && a.bytes == b.bytes); + let mut written = vec![false; name.length]; + for edit in ranges { + let target = out.get_mut(edit.range.clone()).ok_or(FontError::MalformedFont)?; + let start = edit.range.start.checked_sub(name.offset).ok_or(FontError::MalformedFont)?; + let marks = written.get_mut(start..start + edit.bytes.len()).ok_or(FontError::MalformedFont)?; + for ((byte, mark), &new) in target.iter_mut().zip(marks.iter_mut()).zip(&edit.bytes) { + if *mark && *byte != new { + return Err(FontError::ConflictingNameStorage); + } + *byte = new; + *mark = true; + } + } + Ok(()) +} + +/// The OpenType table checksum: the sum of big-endian 32-bit words, the last one padded with zeros. +fn checksum(data: &[u8]) -> u32 { + data.chunks(4).fold(0u32, |sum, chunk| { + let mut word = [0u8; 4]; + for (to, &from) in word.iter_mut().zip(chunk) { + *to = from; + } + sum.wrapping_add(u32::from_be_bytes(word)) + }) +} + +fn copy_of(bytes: &[u8]) -> Result, FontError> { + let mut out = Vec::new(); + out.try_reserve_exact(bytes.len()).map_err(|_| FontError::OutputTooLarge)?; + out.extend_from_slice(bytes); + Ok(out) +} + +fn bytes_at(data: &[u8], at: usize, length: usize) -> Result<&[u8], FontError> { + let end = at.checked_add(length).ok_or(FontError::MalformedFont)?; + data.get(at..end).ok_or(FontError::MalformedFont) +} + +fn u16_at(data: &[u8], at: usize) -> Result { + let bytes = <[u8; 2]>::try_from(bytes_at(data, at, 2)?).map_err(|_| FontError::MalformedFont)?; + Ok(u16::from_be_bytes(bytes)) +} + +fn u32_at(data: &[u8], at: usize) -> Result { + let bytes = <[u8; 4]>::try_from(bytes_at(data, at, 4)?).map_err(|_| FontError::MalformedFont)?; + Ok(u32::from_be_bytes(bytes)) +} + +fn put_bytes(data: &mut [u8], at: usize, bytes: &[u8]) -> Result<(), FontError> { + let end = at.checked_add(bytes.len()).ok_or(FontError::MalformedFont)?; + data.get_mut(at..end).ok_or(FontError::MalformedFont)?.copy_from_slice(bytes); + Ok(()) +} + +fn put_u32(data: &mut [u8], at: usize, value: u32) -> Result<(), FontError> { + put_bytes(data, at, &value.to_be_bytes()) +} + +fn usize_from(value: u32) -> Result { + usize::try_from(value).map_err(|_| FontError::MalformedFont) +} + +fn offset32(value: usize) -> Result { + u32::try_from(value).map_err(|_| FontError::OutputTooLarge) +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..fbf29767ce 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -24,7 +24,14 @@ //! They do **not** establish runtime correctness, protocol concurrency safety, or platform behavior //! under foreign host environments. They are lightweight syntactic regression gates designed to complement, //! rather than replace, platform integration tests and CI execution. +//! +//! ### Test fonts +//! +//! The [`fonts`] module makes test fonts from font bytes the caller supplies: +//! [`fonts::rename_family`] gives a face a family name of the same length, and +//! [`fonts::collection`] builds a TrueType collection from standalone faces. +pub mod fonts; pub mod guards; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs new file mode 100644 index 0000000000..f2722f11d3 --- /dev/null +++ b/crates/testkit/tests/fonts.rs @@ -0,0 +1,558 @@ +//! Tests of `craft_testkit::fonts` on faces assembled here from bytes. +//! +//! The helpers below read the output by the offsets the OpenType specification gives, without the +//! crate's own parser, so a test fails when a field is wrong even if the crate could read it back. + +use craft_testkit::fonts::{FontError, collection, rename_family}; + +const FROM: &str = "Source Sans 3"; +const TO: &str = "Sysfont Sans3"; +const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA; + +fn be16(data: &[u8], at: usize) -> u16 { + u16::from_be_bytes([data[at], data[at + 1]]) +} + +fn be32(data: &[u8], at: usize) -> u32 { + u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) +} + +fn set16(data: &mut [u8], at: usize, value: u16) { + data[at..at + 2].copy_from_slice(&value.to_be_bytes()); +} + +fn set32(data: &mut [u8], at: usize, value: u32) { + data[at..at + 4].copy_from_slice(&value.to_be_bytes()); +} + +/// The table checksum: big-endian 32-bit words added with wrapping, the last padded with zeros. +fn sum(data: &[u8]) -> u32 { + let mut total = 0u32; + let mut at = 0; + while at < data.len() { + let mut word = [0u8; 4]; + for (k, byte) in word.iter_mut().enumerate() { + if let Some(&b) = data.get(at + k) { + *byte = b; + } + } + total = total.wrapping_add(u32::from_be_bytes(word)); + at += 4; + } + total +} + +fn utf16(text: &str) -> Vec { + text.encode_utf16().flat_map(u16::to_be_bytes).collect() +} + +/// A name record: platform, encoding, name ID, and where its string is in storage. +struct Rec { + platform: u16, + encoding: u16, + name_id: u16, + offset: u16, + length: u16, +} + +/// A `name` table of `version` with the records as given, language tags as (length, offset), then storage. +fn name_table(version: u16, records: &[Rec], lang_tags: &[(u16, u16)], storage: &[u8]) -> Vec { + let mut header = 6 + 12 * records.len(); + if version == 1 { + header += 2 + 4 * lang_tags.len(); + } + let mut table = Vec::new(); + table.extend_from_slice(&version.to_be_bytes()); + table.extend_from_slice(&(records.len() as u16).to_be_bytes()); + table.extend_from_slice(&(header as u16).to_be_bytes()); + for rec in records { + for value in [rec.platform, rec.encoding, 0, rec.name_id, rec.length, rec.offset] { + table.extend_from_slice(&value.to_be_bytes()); + } + } + if version == 1 { + table.extend_from_slice(&(lang_tags.len() as u16).to_be_bytes()); + for &(length, offset) in lang_tags { + table.extend_from_slice(&length.to_be_bytes()); + table.extend_from_slice(&offset.to_be_bytes()); + } + } + table.extend_from_slice(storage); + table +} + +/// Name records with their strings stored one after another: (platform, encoding, name ID, bytes). +fn names(list: &[(u16, u16, u16, Vec)]) -> Vec { + let mut storage = Vec::new(); + let mut records = Vec::new(); + for (platform, encoding, name_id, bytes) in list { + records.push(Rec { platform: *platform, encoding: *encoding, name_id: *name_id, offset: storage.len() as u16, length: bytes.len() as u16 }); + storage.extend_from_slice(bytes); + } + name_table(0, &records, &[], &storage) +} + +/// A 54-byte `head` table whose `checkSumAdjustment` holds a stale value. +fn head() -> Vec { + let mut table = vec![0u8; 54]; + set32(&mut table, 0, 0x0001_0000); + set32(&mut table, 8, 0x1234_5678); + set32(&mut table, 12, 0x5F0F_3CF5); + set16(&mut table, 18, 1000); + table +} + +/// A standalone TrueType face holding `tables` in the order given, each on a four-byte boundary. +fn face(tables: &[(&[u8; 4], Vec)]) -> Vec { + let mut font = Vec::new(); + font.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + font.extend_from_slice(&(tables.len() as u16).to_be_bytes()); + font.extend_from_slice(&[0; 6]); + font.resize(12 + 16 * tables.len(), 0); + for (index, (tag, data)) in tables.iter().enumerate() { + let offset = font.len(); + font.extend_from_slice(data); + font.resize(font.len().div_ceil(4) * 4, 0); + let record = 12 + 16 * index; + font[record..record + 4].copy_from_slice(&tag[..]); + set32(&mut font, record + 4, sum(data)); + set32(&mut font, record + 8, offset as u32); + set32(&mut font, record + 12, data.len() as u32); + } + font +} + +fn family_face(list: &[(u16, u16, u16, Vec)]) -> Vec { + face(&[(b"head", head()), (b"name", names(list))]) +} + +/// A table of the face whose directory starts at `directory`: (record offset, table offset, length). +fn table_at(font: &[u8], directory: usize, tag: &[u8; 4]) -> (usize, usize, usize) { + let count = usize::from(be16(font, directory + 4)); + (0..count) + .map(|i| directory + 12 + 16 * i) + .find(|&record| &font[record..record + 4] == tag) + .map(|record| (record, be32(font, record + 8) as usize, be32(font, record + 12) as usize)) + .unwrap_or_else(|| panic!("no {} table", String::from_utf8_lossy(tag))) +} + +fn table(font: &[u8], tag: &[u8; 4]) -> (usize, usize, usize) { + table_at(font, 0, tag) +} + +/// Every name record of a standalone face: (platform, encoding, name ID, bytes). +fn strings(font: &[u8]) -> Vec<(u16, u16, u16, Vec)> { + let (_, at, _) = table(font, b"name"); + let count = usize::from(be16(font, at + 2)); + let storage = at + usize::from(be16(font, at + 4)); + (0..count) + .map(|i| { + let rec = at + 6 + 12 * i; + let start = storage + usize::from(be16(font, rec + 10)); + let end = start + usize::from(be16(font, rec + 8)); + (be16(font, rec), be16(font, rec + 2), be16(font, rec + 6), font[start..end].to_vec()) + }) + .collect() +} + +fn win(name_id: u16, text: &str) -> (u16, u16, u16, Vec) { + (3, 1, name_id, utf16(text)) +} + +fn mac(name_id: u16, bytes: &[u8]) -> (u16, u16, u16, Vec) { + (1, 0, name_id, bytes.to_vec()) +} + +#[test] +fn rename_handles_utf16_and_ascii() { + let font = family_face(&[win(1, FROM), (0, 3, 1, utf16(FROM)), mac(1, FROM.as_bytes()), win(16, FROM), win(21, FROM)]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(out.len(), font.len()); + assert_eq!(strings(&out), vec![win(1, TO), (0, 3, 1, utf16(TO)), mac(1, TO.as_bytes()), win(16, TO), win(21, TO)]); +} + +#[test] +fn rename_only_family_records() { + let list = [ + win(0, "Copyright 2026 the Source Sans 3 authors"), + win(1, FROM), + win(2, "Regular"), + win(6, "SourceSans3-Regular"), + win(13, "Source Sans 3 is licensed under the OFL"), + win(16, "Source Sans 3 Extra"), + ]; + let other = utf16(FROM); + let font = face(&[(b"head", head()), (b"name", names(&list)), (b"zzzz", other.clone())]); + let out = rename_family(&font, FROM, TO).unwrap(); + let mut want = list.to_vec(); + want[1] = win(1, TO); + assert_eq!(strings(&out), want); + let (_, at, length) = table(&out, b"zzzz"); + assert_eq!(&out[at..at + length], &other[..], "a table other than name keeps its bytes"); +} + +#[test] +fn rename_full_name_prefix_only() { + let list = + [win(1, FROM), win(4, "Source Sans 3 Bold"), (0, 3, 4, utf16("Source Sans 3Bold")), mac(4, b"My Source Sans 3"), mac(4, FROM.as_bytes())]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(4, "Sysfont Sans3 Bold"), list[2].clone(), list[3].clone(), mac(4, TO.as_bytes())]); +} + +#[test] +fn rename_rejects_non_ascii_mac_roman() { + let font = family_face(&[win(1, FROM), mac(1, FROM.as_bytes())]); + assert_eq!(rename_family(&font, FROM, "Sourcé Sans 3"), Err(FontError::UnsupportedEncoding)); + // "Café Sans 3" in Mac Roman, where é is 0x8E. + let font = family_face(&[win(1, "Café Sans 3"), mac(1, b"Caf\x8E Sans 3")]); + assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); +} + +#[test] +fn rename_keeps_unrelated_mac_roman_names() { + // Mac Roman 0x8E is "é". Neither Mac record can hold "Café Sans 3": one is shorter, and the other + // differs from it in an ASCII position. + let list = [win(1, "Café Sans 3"), mac(4, b"Autre \x8E"), mac(16, b"Caf\x8E Sans 4")]; + let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap(); + assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]); +} + +#[test] +fn rename_keeps_mac_roman_full_name_suffix() { + let list = [win(1, FROM), mac(4, b"Source Sans 3 Cr\x8Ame")]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), mac(4, b"Sysfont Sans3 Cr\x8Ame")]); +} + +#[test] +fn rename_requires_a_family_record() { + let font = family_face(&[win(1, "Other Family"), win(4, "Source Sans 3 Bold")]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::NameNotFound)); +} + +#[test] +fn rename_preserves_other_encodings() { + let list = [win(1, FROM), (3, 3, 1, utf16(FROM)), (1, 1, 1, FROM.as_bytes().to_vec()), (2, 1, 1, utf16(FROM))]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + let mut want = list.to_vec(); + want[0] = win(1, TO); + assert_eq!(strings(&out), want); +} + +#[test] +fn rename_rejects_odd_utf16() { + let mut odd = utf16(FROM); + odd.push(0); + let font = family_face(&[(3, 1, 1, odd)]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_surrogate() { + let font = family_face(&[(3, 1, 1, vec![0xD8, 0x00, 0x00, b'A']), win(16, FROM)]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_handles_shared_family_storage() { + let storage = utf16("Source Sans 3 Bold"); + let records = [ + Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 16, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 36 }, + ]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(16, TO), win(4, "Sysfont Sans3 Bold")]); +} + +#[test] +fn rename_rejects_shared_nonfamily_storage() { + let records = + [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, Rec { platform: 3, encoding: 1, name_id: 6, offset: 2, length: 10 }]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16(FROM)))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); +} + +#[test] +fn rename_updates_name_checksum() { + let font = family_face(&[win(1, FROM), win(2, "Regular")]); + let out = rename_family(&font, FROM, TO).unwrap(); + let (record, at, length) = table(&out, b"name"); + assert_eq!(be32(&out, record + 4), sum(&out[at..at + length])); + assert_ne!(be32(&out, record + 4), be32(&font, record + 4), "the renamed table has a new checksum"); +} + +#[test] +fn rename_updates_head_adjustment() { + let font = family_face(&[win(1, FROM)]); + let out = rename_family(&font, FROM, TO).unwrap(); + let (_, at, _) = table(&out, b"head"); + let mut zeroed = out.clone(); + set32(&mut zeroed, at + 8, 0); + assert_eq!(be32(&out, at + 8), CHECKSUM_TARGET.wrapping_sub(sum(&zeroed))); + assert_eq!(sum(&out), CHECKSUM_TARGET); +} + +#[test] +fn rename_format_one_preserves_language_tags() { + let mut storage = utf16(FROM); + storage.extend(utf16("en-US")); + let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }]; + let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(10, 26)], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO)]); + let (_, at, length) = table(&out, b"name"); + assert_eq!(&out[at + length - 10..at + length], &utf16("en-US")[..]); + assert_eq!(be16(&out, at + 18), 1, "the language-tag count stays"); +} + +#[test] +fn rename_keeps_language_tag_storage() { + let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }]; + let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(26, 0)], &utf16(FROM)))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); +} + +#[test] +fn rename_rejects_short_sfnt() { + assert_eq!(rename_family(&[], FROM, TO), Err(FontError::MalformedFont)); + assert_eq!(rename_family(&[0, 1, 0, 0, 0], FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_truncated_directory() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font[..12 + 16 + 8], FROM, TO), Err(FontError::MalformedFont)); + let mut many = font.clone(); + set16(&mut many, 4, 4000); + assert_eq!(rename_family(&many, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_collection() { + let font = family_face(&[win(1, FROM)]); + let ttc = collection(&[&font]).unwrap(); + assert_eq!(rename_family(&ttc, FROM, TO), Err(FontError::UnsupportedFace)); +} + +#[test] +fn rename_rejects_missing_name_table() { + let font = face(&[(b"head", head())]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MissingNameTable)); +} + +#[test] +fn rename_rejects_short_head() { + let font = face(&[(b"head", head()[..8].to_vec()), (b"name", names(&[win(1, FROM)]))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_name_storage() { + let font = family_face(&[win(1, FROM)]); + let (_, at, length) = table(&font, b"name"); + let mut beyond = font.clone(); + set16(&mut beyond, at + 4, length as u16 + 1); + assert_eq!(rename_family(&beyond, FROM, TO), Err(FontError::MalformedFont)); + let mut inside_header = font.clone(); + set16(&mut inside_header, at + 4, 6); + assert_eq!(rename_family(&inside_header, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_name_record_range() { + let font = family_face(&[win(1, FROM)]); + let (_, at, _) = table(&font, b"name"); + let mut long = font.clone(); + set16(&mut long, at + 6 + 8, 28); + assert_eq!(rename_family(&long, FROM, TO), Err(FontError::MalformedFont)); + let mut late = font; + set16(&mut late, at + 6 + 10, 2); + assert_eq!(rename_family(&late, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_name_table_sharing_bytes() { + let font = face(&[(b"head", head()), (b"name", names(&[win(1, FROM)])), (b"zzzz", vec![7; 8])]); + let (_, at, _) = table(&font, b"name"); + let (record, _, _) = table(&font, b"zzzz"); + let mut shared = font.clone(); + set32(&mut shared, record + 8, (at + 18) as u32); + assert_eq!(rename_family(&shared, FROM, TO), Err(FontError::MalformedFont)); + let (_, head_at, _) = table(&font, b"head"); + let mut under_head = font; + set32(&mut under_head, record + 8, (head_at + 8) as u32); + assert_eq!(rename_family(&under_head, FROM, TO), Err(FontError::MalformedFont), "checkSumAdjustment would land in zzzz"); +} + +#[test] +fn rename_rejects_unknown_name_format() { + let font = family_face(&[win(1, FROM)]); + let (_, at, _) = table(&font, b"name"); + let mut two = font; + set16(&mut two, at, 2); + assert_eq!(rename_family(&two, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_unequal_lengths() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font, FROM, "Other"), Err(FontError::UnequalLength)); +} + +#[test] +fn rename_rejects_unequal_utf16_lengths() { + // Both names are four bytes of UTF-8, but "𝐀" is two UTF-16 code units and "abcd" is four. + let font = family_face(&[win(1, "𝐀")]); + assert_eq!(rename_family(&font, "𝐀", "abcd"), Err(FontError::UnequalLength)); +} + +#[test] +fn rename_rejects_missing_family() { + let font = family_face(&[win(1, FROM), win(2, "Regular")]); + assert_eq!(rename_family(&font, "Source Sans 4", TO), Err(FontError::NameNotFound)); +} + +#[test] +fn rename_rejects_empty_names() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font, "", ""), Err(FontError::InvalidName)); + assert_eq!(rename_family(&font, FROM, ""), Err(FontError::InvalidName)); +} + +/// Two faces that differ in every table, with table lengths that are not multiples of four. +fn two_faces() -> (Vec, Vec) { + let a = face(&[(b"head", head()), (b"name", names(&[mac(1, b"Alpha")])), (b"zzzz", vec![1, 2, 3, 4, 5])]); + let mut other_head = head(); + set32(&mut other_head, 4, 0x0002_0000); + let b = face(&[(b"head", other_head), (b"name", names(&[mac(1, b"Beta")])), (b"zzzz", vec![9; 7])]); + (a, b) +} + +/// Each face's directory offset, read from the TTC header. +fn ttc_faces(ttc: &[u8]) -> Vec { + assert_eq!(&ttc[..4], b"ttcf"); + assert_eq!(be32(ttc, 4), 0x0001_0000); + (0..be32(ttc, 8) as usize).map(|i| be32(ttc, 12 + 4 * i) as usize).collect() +} + +/// Every table of a face in a collection: (tag, checksum, offset, length). +fn ttc_tables(ttc: &[u8], directory: usize) -> Vec<([u8; 4], u32, usize, usize)> { + (0..usize::from(be16(ttc, directory + 4))) + .map(|i| { + let r = directory + 12 + 16 * i; + (ttc[r..r + 4].try_into().unwrap(), be32(ttc, r + 4), be32(ttc, r + 8) as usize, be32(ttc, r + 12) as usize) + }) + .collect() +} + +#[test] +fn collection_offsets_are_file_relative() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + let faces = ttc_faces(&ttc); + assert_eq!(faces.len(), 2); + for (directory, input) in faces.into_iter().zip([&a, &b]) { + assert_eq!(&ttc[directory..directory + 12], &input[..12], "the sfnt header is copied"); + for (tag, _, offset, length) in ttc_tables(&ttc, directory) { + let (_, from, from_length) = table(input, &tag); + assert_eq!(length, from_length); + let mut want = input[from..from + from_length].to_vec(); + if &tag == b"head" { + set32(&mut want, 8, 0); + } + assert_eq!(&ttc[offset..offset + length], &want[..], "{} sits at its file offset", String::from_utf8_lossy(&tag)); + } + } +} + +#[test] +fn collection_pads_odd_faces() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + assert_eq!(ttc.len() % 4, 0); + for directory in ttc_faces(&ttc) { + assert_eq!(directory % 4, 0); + for (_, _, offset, length) in ttc_tables(&ttc, directory) { + assert_eq!(offset % 4, 0, "tables start on four-byte boundaries"); + let padded = length.div_ceil(4) * 4; + assert!(ttc[offset + length..offset + padded].iter().all(|&b| b == 0), "padding is zero"); + } + } + let lengths: Vec = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| t.3).collect(); + assert!(lengths.iter().any(|length| length % 4 != 0), "the fixture has unpadded lengths"); +} + +#[test] +fn collection_checksums_match_tables() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + for directory in ttc_faces(&ttc) { + for (tag, checksum, offset, length) in ttc_tables(&ttc, directory) { + assert_eq!(checksum, sum(&ttc[offset..offset + length])); + if &tag == b"head" { + assert_eq!(be32(&ttc, offset + 8), 0, "checkSumAdjustment is zero in a collection"); + } + } + } +} + +#[test] +fn collection_copies_tables() { + let (a, _) = two_faces(); + let ttc = collection(&[&a, &a]).unwrap(); + let mut ranges: Vec<(usize, usize)> = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| (t.2, t.2 + t.3)).collect(); + assert_eq!(ranges.len(), 6); + ranges.sort(); + assert!(ranges.windows(2).all(|pair| pair[0].1 <= pair[1].0), "each face has its own tables"); +} + +#[test] +fn collection_rejects_empty() { + assert_eq!(collection(&[]), Err(FontError::EmptyCollection)); +} + +#[test] +fn collection_rejects_nested_ttc() { + let (a, _) = two_faces(); + let ttc = collection(&[&a]).unwrap(); + assert_eq!(collection(&[&a, &ttc]), Err(FontError::UnsupportedFace)); +} + +#[test] +fn collection_rejects_short_directory() { + let (a, _) = two_faces(); + assert_eq!(collection(&[&a[..3]]), Err(FontError::MalformedFont)); + assert_eq!(collection(&[&a[..12 + 16 * 2]]), Err(FontError::MalformedFont)); + let mut many = a.clone(); + set16(&mut many, 4, 400); + assert_eq!(collection(&[&a, &many]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_out_of_range_table() { + let (a, _) = two_faces(); + let (record, _, _) = table(&a, b"zzzz"); + let mut late = a.clone(); + set32(&mut late, record + 8, a.len() as u32); + assert_eq!(collection(&[&late]), Err(FontError::MalformedFont)); + let mut long = a.clone(); + set32(&mut long, record + 12, u32::MAX); + assert_eq!(collection(&[&long]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_short_head() { + let font = face(&[(b"head", head()[..8].to_vec())]); + assert_eq!(collection(&[&font]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_offset_overflow() { + // 4,096 references to one face with a 1 MiB table add up to more than 4 GiB of output, which + // 32-bit offsets cannot address. The function refuses before allocating any of it. + let big = face(&[(b"zzzz", vec![0; 1 << 20])]); + let faces = vec![&big[..]; 4096]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} From 15cdfd8512bf88736f4f0077741911c96afcd851 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:26:23 -0800 Subject: [PATCH 02/47] craft-testkit: fonts reads Mac Roman names by character and rewrites only the family name rename_family compares a Macintosh Roman record with the family name character by character, using the Unicode mapping of Mac Roman, so a record whose non-ASCII letters differ from the name is left as it is instead of failing the rename with UnsupportedEncoding. A rename now writes only the bytes of the family name at the start of each matching string, and records that point at the same string are read once. A style name that shares the unchanged end of a full name keeps its bytes, and a name table with many records on one long string no longer allocates a copy of the string for each record. --- crates/testkit/src/fonts.rs | 163 ++++++++++++++++++++++------------ crates/testkit/tests/fonts.rs | 24 +++++ 2 files changed, 129 insertions(+), 58 deletions(-) diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index 7231980c7a..04345b66a2 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -10,6 +10,7 @@ //! The module reads no file and no environment variable, prints nothing, and builds for //! `wasm32-unknown-unknown`. +use std::collections::HashMap; use std::fmt; use std::ops::Range; @@ -47,7 +48,7 @@ pub enum FontError { MalformedFont, /// A matching Macintosh Roman record would need a name that is not ASCII. UnsupportedEncoding, - /// A string the rename changes shares bytes with a string it keeps, or with a different replacement. + /// Bytes the rename changes are shared with a string it keeps, or with a different replacement. ConflictingNameStorage, /// [`collection`] was given no faces. EmptyCollection, @@ -66,7 +67,7 @@ impl fmt::Display for FontError { Self::MissingNameTable => "the font has no name table", Self::MalformedFont => "the font's table directory or name table is truncated or out of range", Self::UnsupportedEncoding => "a Macintosh Roman name record can only take an ASCII name", - Self::ConflictingNameStorage => "a renamed string shares its bytes with a string that must not change", + Self::ConflictingNameStorage => "the bytes of a renamed family name are shared with a string that must not change", Self::EmptyCollection => "a collection needs at least one face", Self::UnsupportedFace => "the input is not a standalone TrueType or CFF face", Self::OutputTooLarge => "the output is too large", @@ -91,7 +92,7 @@ impl std::error::Error for FontError {} /// [`FontError::InvalidName`] when a name is empty, [`FontError::UnequalLength`] when the names have /// different UTF-16 lengths, [`FontError::NameNotFound`] when no family record holds `from`, /// [`FontError::UnsupportedEncoding`] when a matching Macintosh Roman record would need non-ASCII -/// bytes, [`FontError::ConflictingNameStorage`] when a changed string shares bytes with a kept one, +/// bytes, [`FontError::ConflictingNameStorage`] when changed bytes are shared with a kept string, /// [`FontError::MissingNameTable`], [`FontError::UnsupportedFace`] for a collection, and /// [`FontError::MalformedFont`] when the directory, the `name` table or the `head` table is out of /// range or of an unknown version, or when the `name` or `head` table shares bytes with the directory @@ -244,7 +245,7 @@ fn write_face(out: &mut Vec, face: &[u8], tables: &[Table]) -> Result<(), Fo } /// How the bytes of a name record are encoded, as far as renaming reads them. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Encoding { Utf16, MacRoman, @@ -314,28 +315,42 @@ fn name_strings(face: &[u8], table: &Table) -> Result { Ok(NameStrings { names, lang_tags }) } -/// A string the rename writes: its range in the face and its new bytes. +/// Bytes the rename writes: the range of the family name at the start of a string, and the new name. +/// The rest of the string keeps its bytes. struct Edit { range: Range, bytes: Vec, } -/// Works out the strings to rewrite and the ranges of the strings that must keep their bytes. +/// Works out the family names to rewrite and the ranges of the strings that must keep their bytes. /// Refuses with [`FontError::NameNotFound`] when no family record (IDs 1, 16 and 21) holds `from`. +/// Records that point at the same string are read once. fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Result<(Vec, Vec>), FontError> { let mut edits = Vec::new(); let mut kept = strings.lang_tags.clone(); let mut family_found = false; + let mut read: HashMap<(usize, usize, Encoding, bool), bool> = HashMap::new(); for string in &strings.names { let family = FAMILY_IDS.contains(&string.name_id); - let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; - let new = if family || string.name_id == FULL_NAME_ID { renamed(string, bytes, from, to)? } else { None }; - match new { - Some(new) => { - family_found |= family; - edits.push(Edit { range: string.range.clone(), bytes: new }); + if !family && string.name_id != FULL_NAME_ID { + kept.push(string.range.clone()); + continue; + } + let key = (string.range.start, string.range.end, string.encoding, family); + let edited = match read.get(&key) { + Some(&edited) => edited, + None => { + let edit = renamed(string, face, from, to)?; + let edited = edit.is_some(); + edits.extend(edit); + read.insert(key, edited); + edited } - None => kept.push(string.range.clone()), + }; + if edited { + family_found |= family; + } else { + kept.push(string.range.clone()); } } if !family_found { @@ -344,67 +359,99 @@ fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Resul Ok((edits, kept)) } -/// The new bytes of a family or full-name string, or `None` when it does not hold `from`. -fn renamed(string: &NameString, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { +/// The edit of a family or full-name string, or `None` when it does not hold `from`. +fn renamed(string: &NameString, face: &[u8], from: &str, to: &str) -> Result, FontError> { let family = FAMILY_IDS.contains(&string.name_id); - let encoded = match string.encoding { + let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; + let renamed = match string.encoding { Encoding::Utf16 => renamed_utf16(family, bytes, from, to)?, Encoding::MacRoman => renamed_mac_roman(family, bytes, from, to)?, Encoding::Other => None, }; - if encoded.as_ref().is_some_and(|encoded| encoded.len() != bytes.len()) { + let Some((old_length, new)) = renamed else { + return Ok(None); + }; + if new.len() != old_length { return Err(FontError::UnequalLength); } - Ok(encoded) + let start = string.range.start; + Ok(Some(Edit { range: start..start + old_length, bytes: new })) } -/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and a space. -fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { - let value = utf16_value(bytes)?; - let new = if family { - (value == from).then(|| to.to_owned()) - } else { - value.strip_prefix(from).filter(|rest| rest.is_empty() || rest.starts_with(' ')).map(|rest| format!("{to}{rest}")) - }; - Ok(new.map(|new| new.encode_utf16().flat_map(u16::to_be_bytes).collect())) -} - -/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, byte by byte; only ASCII names are written. -fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { - if !from.is_ascii() { - return if mac_roman_may_hold(family, bytes, from) { Err(FontError::UnsupportedEncoding) } else { Ok(None) }; - } - let Some(rest) = bytes.strip_prefix(from.as_bytes()) else { - return Ok(None); - }; - if !(rest.is_empty() || (!family && rest.first() == Some(&b' '))) { - return Ok(None); - } - if !to.is_ascii() { - return Err(FontError::UnsupportedEncoding); - } - Ok(Some([to.as_bytes(), rest].concat())) -} - -/// Whether a Macintosh Roman string could hold a non-ASCII `from`. The encoding has one byte per -/// character and shares its ASCII range with Unicode, so a string that differs from `from` in length -/// or in an ASCII position cannot hold it. -fn mac_roman_may_hold(family: bool, bytes: &[u8], from: &str) -> bool { - let count = from.chars().count(); - let fits = bytes.len() == count || (!family && bytes.get(count) == Some(&b' ')); - fits && bytes.iter().zip(from.chars()).all(|(&byte, c)| !(byte.is_ascii() || c.is_ascii()) || char::from(byte) == c) -} - -/// Decodes a UTF-16BE string, refusing an odd length or an unpaired surrogate. -fn utf16_value(bytes: &[u8]) -> Result { +/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and +/// a space. Returns the byte length of `from` in the string and the bytes of `to`. +fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result)>, FontError> { let (pairs, rest) = bytes.as_chunks::<2>(); if !rest.is_empty() { return Err(FontError::MalformedFont); } let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair)); - char::decode_utf16(units).collect::>().map_err(|_| FontError::MalformedFont) + if char::decode_utf16(units.clone()).any(|c| c.is_err()) { + return Err(FontError::MalformedFont); + } + let count = from.encode_utf16().count(); + if !units.clone().take(count).eq(from.encode_utf16()) { + return Ok(None); + } + match units.clone().nth(count) { + None => {} + Some(unit) if !family && unit == u16::from(b' ') => {} + Some(_) => return Ok(None), + } + Ok(Some((count * 2, to.encode_utf16().flat_map(u16::to_be_bytes).collect()))) } +/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, comparing its decoded characters +/// with `from`. Only ASCII names are written. +fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result)>, FontError> { + let count = from.chars().count(); + let Some(name) = bytes.get(..count) else { + return Ok(None); + }; + if !name.iter().map(|&byte| mac_roman_char(byte)).eq(from.chars()) { + return Ok(None); + } + match bytes.get(count) { + None => {} + Some(b' ') if !family => {} + Some(_) => return Ok(None), + } + if !from.is_ascii() || !to.is_ascii() { + return Err(FontError::UnsupportedEncoding); + } + Ok(Some((count, to.as_bytes().to_vec()))) +} + +/// The character a Macintosh Roman byte stands for. Bytes below 0x80 are ASCII; the others follow +/// the mapping at . +fn mac_roman_char(byte: u8) -> char { + match byte.checked_sub(0x80) { + None => char::from(byte), + Some(high) => MAC_ROMAN_HIGH.get(usize::from(high)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), + } +} + +/// The characters of Macintosh Roman bytes 0x80 to 0xFF. +#[rustfmt::skip] +const MAC_ROMAN_HIGH: [char; 128] = [ + '\u{00C4}', '\u{00C5}', '\u{00C7}', '\u{00C9}', '\u{00D1}', '\u{00D6}', '\u{00DC}', '\u{00E1}', + '\u{00E0}', '\u{00E2}', '\u{00E4}', '\u{00E3}', '\u{00E5}', '\u{00E7}', '\u{00E9}', '\u{00E8}', + '\u{00EA}', '\u{00EB}', '\u{00ED}', '\u{00EC}', '\u{00EE}', '\u{00EF}', '\u{00F1}', '\u{00F3}', + '\u{00F2}', '\u{00F4}', '\u{00F6}', '\u{00F5}', '\u{00FA}', '\u{00F9}', '\u{00FB}', '\u{00FC}', + '\u{2020}', '\u{00B0}', '\u{00A2}', '\u{00A3}', '\u{00A7}', '\u{2022}', '\u{00B6}', '\u{00DF}', + '\u{00AE}', '\u{00A9}', '\u{2122}', '\u{00B4}', '\u{00A8}', '\u{2260}', '\u{00C6}', '\u{00D8}', + '\u{221E}', '\u{00B1}', '\u{2264}', '\u{2265}', '\u{00A5}', '\u{00B5}', '\u{2202}', '\u{2211}', + '\u{220F}', '\u{03C0}', '\u{222B}', '\u{00AA}', '\u{00BA}', '\u{03A9}', '\u{00E6}', '\u{00F8}', + '\u{00BF}', '\u{00A1}', '\u{00AC}', '\u{221A}', '\u{0192}', '\u{2248}', '\u{2206}', '\u{00AB}', + '\u{00BB}', '\u{2026}', '\u{00A0}', '\u{00C0}', '\u{00C3}', '\u{00D5}', '\u{0152}', '\u{0153}', + '\u{2013}', '\u{2014}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{00F7}', '\u{25CA}', + '\u{00FF}', '\u{0178}', '\u{2044}', '\u{20AC}', '\u{2039}', '\u{203A}', '\u{FB01}', '\u{FB02}', + '\u{2021}', '\u{00B7}', '\u{201A}', '\u{201E}', '\u{2030}', '\u{00C2}', '\u{00CA}', '\u{00C1}', + '\u{00CB}', '\u{00C8}', '\u{00CD}', '\u{00CE}', '\u{00CF}', '\u{00CC}', '\u{00D3}', '\u{00D4}', + '\u{F8FF}', '\u{00D2}', '\u{00DA}', '\u{00DB}', '\u{00D9}', '\u{0131}', '\u{02C6}', '\u{02DC}', + '\u{00AF}', '\u{02D8}', '\u{02D9}', '\u{02DA}', '\u{00B8}', '\u{02DD}', '\u{02DB}', '\u{02C7}', +]; + /// Refuses a rename whose strings overlap a string that keeps its bytes. fn check_kept(edits: &[Edit], mut kept: Vec>) -> Result<(), FontError> { kept.retain(|range| !range.is_empty()); diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs index f2722f11d3..6ff688c7fa 100644 --- a/crates/testkit/tests/fonts.rs +++ b/crates/testkit/tests/fonts.rs @@ -206,6 +206,16 @@ fn rename_rejects_non_ascii_mac_roman() { // "Café Sans 3" in Mac Roman, where é is 0x8E. let font = family_face(&[win(1, "Café Sans 3"), mac(1, b"Caf\x8E Sans 3")]); assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); + let font = family_face(&[win(1, "Café Sans 3"), mac(4, b"Caf\x8E Sans 3 Bold")]); + assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); +} + +#[test] +fn rename_keeps_mac_roman_names_with_other_letters() { + // Mac Roman 0x80 is "Ä" and 0x8F is "è", so neither Mac record holds "Café Sans 3". + let list = [win(1, "Café Sans 3"), mac(1, b"Caf\x80 Sans 3"), mac(4, b"Caf\x8F Sans 3 Bold")]; + let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap(); + assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]); } #[test] @@ -274,6 +284,20 @@ fn rename_rejects_shared_nonfamily_storage() { assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); } +#[test] +fn rename_keeps_a_style_sharing_the_full_name_suffix() { + // The style name (ID 2) "Bold" is the last 8 bytes of the full name, which the rename does not change. + let storage = [utf16(FROM), utf16("Source Sans 3 Bold")].concat(); + let records = [ + Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 2, offset: 54, length: 8 }, + Rec { platform: 3, encoding: 1, name_id: 4, offset: 26, length: 36 }, + ]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]); +} + #[test] fn rename_updates_name_checksum() { let font = family_face(&[win(1, FROM), win(2, "Regular")]); From 7e243276880416fdd34cae02b5dfbb5efcf86d98 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:59:56 -0800 Subject: [PATCH 03/47] craft-xtask: add the display-name scanner for words the app lists `craft_xtask::names` reads the words an app lists in its Rust string literals (escapes decoded, test-only code skipped), the package description of a `Cargo.toml` and text files, and returns each finding with its path and line. The app passes the word list, the inputs, the literals and exceptions that may keep a word, and its allow marker. No app switches yet; the crate README lists the planned switches and the results that change for each app. --- crates/xtask/README.md | 93 +- crates/xtask/src/lib.rs | 3 + crates/xtask/src/names.rs | 1790 +++++++++++++++++++++++++++++++++++++ 3 files changed, 1885 insertions(+), 1 deletion(-) create mode 100644 crates/xtask/src/names.rs diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..2ae5c66e5a 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -7,6 +7,7 @@ The crate is native only and is a dependency of an app's `xtask` package only. | Module | Feature | Contents | |---|---|---| | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | +| `names` | always | `Policy`, `Input`, `scan`, `scan_source`, `literals`, `test_path`: the display-name scanner, which looks for the words an app lists in its string literals, `Cargo.toml` descriptions and text files | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | @@ -59,6 +60,86 @@ or file could not be opened or locked) or `Report` (the run passed but the repor written). A report that cannot be written after a failed run is printed to stderr, and the run keeps its `Step` error. +## Names + +The app owns its word list, the paths it scans, the literals and exceptions that may keep a word, +the marker, the command or test that runs the scan, and the message it prints. The library reads the +files and returns the findings: + +```rust,no_run +use std::path::Path; +use craft_xtask::names::{self, Input, Policy}; + +const BANNED: &[&str] = &["Amber Tool", "AzureKit"]; +const ALLOWED: &[&str] = &["AzureKit Design"]; +const POLICY: Policy<'static> = Policy { allowed: ALLOWED, ..Policy::new(BANNED) }; + +#[test] +fn production_display_names_stay_neutral() { + let base = Path::new(env!("CARGO_MANIFEST_DIR")); + let inputs = [Input::rust(Path::new("src")), Input::rust(Path::new("../engine/src/cmd"))]; + let found = names::scan(base, &inputs, &POLICY).unwrap(); + let list: Vec = found.iter().map(ToString::to_string).collect(); + assert!(list.is_empty(), "Banned display names:\n{}", list.join("\n")); +} +``` + +- `Input::rust` takes a Rust file or a folder, which is read recursively for `.rs` files that + `Policy::skip` keeps, given their path below the folder (`test_path` by default: `tests.rs`, + `*_tests.rs` and files under a `tests` folder). Links to folders are not followed. A file input + is read whatever its name. +- `Input::manifest` reads the values at the key paths `package.description` and + `workspace.package.description` of a `Cargo.toml`: the table header (`[package]`, + `[workspace.package]`) joined with the key, which may be bare, quoted or dotted. Headers and keys + inside strings and arrays do not count, and a key inside an inline table is not read. A + `description` under any other table, or before the first header, is not read. A TOML string, + single-line or multi-line, is decoded, and a comment after it is not read; any other value is + read as the rest of its line. `Input::text` reads every line of a text file, and + `Input::text_mark_above` also lets a `#` line with the marker exempt the line below it. Inputs + must not include binary files. +- In Rust, the scanner reads `"…"` and `r"…"` literals with any number of `#`, decodes every escape + (`\n`, `\x7A`, `\u{…}`, a backslash before a line break) and reads CRLF as LF. `b"…"`, `br"…"`, + `c"…"` and `cr"…"` are read when `Policy::literals` asks for them. Comments, character, byte and + lifetime tokens, and the rest of a module after `#![cfg(test)]` are skipped. So is the code under + `#[cfg(test)]`, comments in the attribute included: a `const`, `static` or `let` up to its `;`, + another item up to the `}` that closes it or the `;` that ends it, and a field, argument, arm or + statement up to its `,` or `;`. A block expression (a block, a macro's braces, a labeled block, or + `if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as + an arm's expression after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` + branches. When a method call, field or `?` follows that `}`, it runs up to its `,` or `;` + instead. Other `cfg` expressions and macros are not evaluated. A source the lexer cannot read + (an unterminated literal or comment, an unknown escape, unbalanced delimiters) is an error. +- A word matches as a whole word: the characters next to it are not letters, digits or `_`, in any + script. `MatchCase::Exact` compares characters exactly, and `MatchCase::AsciiInsensitive` ignores + the case of ASCII letters. `allowed` and `exceptions` exempt a whole decoded literal or + description or trimmed text line, never part of one. +- In Rust, the marker counts only inside a comment on a line the literal spans. In a manifest it + counts anywhere on a line the description spans, and in a text file anywhere on the line. +- `scan` reads each file once, in path order, and returns the findings in path order, then source + order, then the order of `banned`. A `Finding` has the path, the first line of the literal or + description, the word, the decoded text or text line and the kind; its `Display` text is + `path:line: "word" in "text"`. `scan_source` scans one source already in memory, and + `literals` returns a source's literals. +- `names::Error` is `Policy` (no banned words, an empty word or an empty marker), `Io` (with the + path), `InvalidUtf8`, `FileTooLarge`, `TotalTooLarge`, `TooDeep`, `Conflict` (a file given as two + kinds of input) or `Syntax` (with the path and line). `DEFAULT_LIMITS` is 8 MiB per file, 512 MiB + per scan and folders 64 deep; a file over the limit is rejected before it is read. + +The source copies differ in a few rules. An app that switches lists the results that change: + +- The eight `display_names.rs` tests compare exactly (`MatchCase::Exact`), read byte and C strings + like other strings, skip only `#[cfg(test)] mod` (GridCraft skips any `#[cfg(test)]` item up to + its `}` or `;`), pass `\x` and `\u{…}` through undecoded, can take the quote in `'\"'` as the + start of a string (LightCraft, FigCraft, PhotoCraft), follow folder links, skip a file root named + like a test file, and stop with a panic on a file they cannot read (FigCraft returns the error). + Each finds more or less here accordingly. +- VectorCraft's `brands` check compares ASCII letters without case (`MatchCase::AsciiInsensitive`) + and reads byte and C strings (`Literals`). It also takes a non-ASCII letter or `_` next to a word + as a word boundary, takes its marker anywhere on a line, literals included, reads an escape as a + space, reads manifest lines that start with `description` as they are (comments included, one + line of a multi-line value), and skips a file it cannot read. +- PhotoCraft's check of its locale catalogs stays in the app. + ## Lock `RunOptions::with_lock(LockConfig::new(dir, slots, owner_label))` takes one of `slots` lock files in @@ -98,7 +179,15 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | -| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| `names`: the literal lexer, whole-word matching, allowed literals, the tree walk and the tests `production_display_names_stay_neutral`, `guard_distinguishes_labels_from_identifiers_and_comments`, `guard_scans_production_after_test_only_items`, `guard_skips_escaped_character_literals`, `guard_decodes_whitespace_escapes` | CADCraft `crates/ui-egui/tests/display_names.rs` at [8e69890](https://github.com/storytold/cadcraft/blob/8e6989022398ff5f79adaab77d19fdd7137591f3/crates/ui-egui/tests/display_names.rs) and DeckCraft at [b0c77eb](https://github.com/storytold/deckcraft/blob/b0c77ebd6a6fe6c9037cfbe1c8a7f397304b2205/crates/ui-egui/tests/display_names.rs) | +| `names`: the test `guard_scans_after_escaped_character_literals` | AniCraft `crates/engine/tests/display_names.rs` at [3435e98](https://github.com/storytold/anicraft/blob/3435e9868150312e54694c0a70082609b2fe8573/crates/engine/tests/display_names.rs) | +| `names`: read errors returned, and the test `source_read_failures_are_reported` | FigCraft `crates/mcp/tests/display_names.rs` at [bad07e4](https://github.com/storytold/figcraft/blob/bad07e4433240cad046589129c084bd2fc36f097/crates/mcp/tests/display_names.rs) | +| `names`: the tests `guard_scans_production_after_test_only_items_and_parses_raw_labels`, `guard_skips_escaped_character_literals_without_hiding_labels`, and `exceptions` for a group-label prefix | WordCraft `crates/ui-egui/tests/display_names.rs` at [323cf78](https://github.com/storytold/wordcraft/blob/323cf78232ff3c07f9dbb7989ed729d5851c9773/crates/ui-egui/tests/display_names.rs) | +| `names`: `exceptions` for a message prefix | LightCraft `crates/ui-egui/tests/display_names.rs` at [6b2b7e6](https://github.com/storytold/lightcraft/blob/6b2b7e6d1117e683a1701568e56f979d061e4699/crates/ui-egui/tests/display_names.rs) | +| `names`: a single file as a root | GridCraft `crates/ui-egui/tests/display_names.rs` at [f204433](https://github.com/storytold/gridcraft/blob/f2044337c7e195bdf6bec1b3914937a3dd386749/crates/ui-egui/tests/display_names.rs) | +| `names`: allowed literals | PhotoCraft `crates/ui-egui/tests/display_names.rs` at [d6557b9](https://github.com/storytold/photocraft/blob/d6557b9a8b40f0542a99e7382ec2b5250548e27b/crates/ui-egui/tests/display_names.rs) | +| `names`: `MatchCase::AsciiInsensitive`, manifest descriptions, text files, the marker and the line above it, the literal's first line, and the tests `rust_literals_skip_comments_identifiers_tests_and_marked_lines`, `whole_words_only`, `docs_packaging_and_manifests`, `scope`, `injected_strings_fail_the_gate`, `the_tree_is_clean` | VectorCraft `xtask/src/brands.rs` at [107078a](https://github.com/storytold/vectorcraft/blob/107078ad10870f8a8fdeade9bd5627a3eea34a67/xtask/src/brands.rs) | +| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `names`, the full escape decoder, byte and C strings as an option, every `#[cfg(test)]` item form and `#![cfg(test)]`, the syntax errors, the marker only in comments, word boundaries in every script, the limits, the sorted findings and the skipped folder links | written here | ## Migration @@ -107,6 +196,8 @@ No app uses this crate yet. | App | Status | |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | +| AniCraft, CADCraft, DeckCraft, FigCraft, GridCraft, LightCraft, PhotoCraft, WordCraft | Planned: the lexer and matcher of `display_names.rs` move to `names`, with `MatchCase::Exact`. `BANNED`, `ALLOWED`, `ROOTS`, the prefix exceptions (LightCraft, WordCraft), PhotoCraft's catalog test and the tests named after them stay in the app. | +| VectorCraft | Planned: `cargo xtask brands` calls `names::scan` with `MatchCase::AsciiInsensitive`, byte and C strings, `brand-ok` and its desktop entry as `Input::text_mark_above`. The word list, the file selection from `git ls-files` and the message stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..7abdc46b08 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -9,6 +9,8 @@ //! - [`runner`]: the gate's step runner. [`runner::run_steps`] runs the steps in order, stops at the //! first failure and prints the `ok`, `FAIL` and `skip` summary. [`runner::root`], //! [`runner::cargo`], [`runner::run`] and [`runner::nextest_or_test`] build and run the commands. +//! - [`names`]: the display-name scanner. [`names::scan`] looks for the words an app lists in its +//! Rust string literals, `Cargo.toml` descriptions and text files, and returns what it finds. //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. @@ -37,6 +39,7 @@ #[cfg(feature = "lock")] pub mod lock; +pub mod names; #[cfg(feature = "report")] pub mod report; pub mod runner; diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs new file mode 100644 index 0000000000..57d4f89de8 --- /dev/null +++ b/crates/xtask/src/names.rs @@ -0,0 +1,1790 @@ +//! The display-name scanner: words an app must not show users, looked for in the text users read. +//! +//! The app supplies the words, the files and folders to read, the literals that may keep a word, +//! and the marker that exempts a line. The library reads: +//! +//! - [`Kind::Rust`]: the string literals of Rust sources, with escapes decoded, outside comments and +//! test-only code. A folder is read recursively for `.rs` files. +//! - [`Kind::Manifest`]: the package descriptions of a `Cargo.toml`. +//! - [`Kind::Text`] and [`Kind::TextMarkAbove`]: every line of a text file. +//! +//! It returns the [`Finding`]s; the app prints them and decides the exit status. The scan is +//! lexical: it does not resolve macros or evaluate `cfg` expressions other than `cfg(test)`, and it +//! cannot tell whether a literal is shown. It never starts a process or calls git. + +use std::collections::HashSet; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +/// The limits [`Policy::new`] sets: 8 MiB per file, 512 MiB in all, folders 64 deep. +pub const DEFAULT_LIMITS: Limits = Limits { max_file_bytes: 8 << 20, max_total_bytes: 512 << 20, max_depth: 64 }; + +/// How a banned word is compared with the text. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MatchCase { + /// Character for character. + Exact, + /// ASCII letters compare without case; other characters compare exactly. + AsciiInsensitive, +} + +/// Which Rust literal forms besides `"…"` and `r"…"` are read. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Literals { + /// `b"…"` and `br"…"`. + pub byte_strings: bool, + /// `c"…"` and `cr"…"`. + pub c_strings: bool, +} + +/// Bounds on what [`scan`] reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest file read, in bytes. + pub max_file_bytes: u64, + /// The most bytes read by one scan, across all files. + pub max_total_bytes: u64, + /// The deepest folder read below a [`Kind::Rust`] folder input. + pub max_depth: usize, +} + +/// The app's rules for one scan. +#[derive(Clone, Copy)] +pub struct Policy<'a> { + /// The words users must not see. A word matches only as a whole word: the characters next to it + /// are not letters, digits or `_`. + pub banned: &'a [&'a str], + /// How the words are compared. + pub case: MatchCase, + /// Whole literals (or text lines, trimmed) that may keep a banned word. + pub allowed: &'a [&'a str], + /// Functions that return `true` for a whole literal or trimmed text line that may keep a banned + /// word. + pub exceptions: &'a [fn(&str) -> bool], + /// A marker that exempts a line. In Rust it counts only inside a comment on a line the literal + /// spans; in a text file it counts anywhere on the line, and in [`Kind::TextMarkAbove`] files also + /// on a `#` line just above. + pub allow_marker: Option<&'a str>, + /// The optional Rust literal forms. + pub literals: Literals, + /// Returns `true` for a Rust file in a folder input to leave out, given its path below that + /// folder. [`test_path`] is the default. A file input is read whatever this returns. + pub skip: fn(&Path) -> bool, + /// Bounds on what is read. + pub limits: Limits, +} + +impl<'a> Policy<'a> { + /// A policy with these banned words, exact comparison, no allowed literals, exceptions or + /// marker, only `"…"` and `r"…"` literals, [`test_path`] and [`DEFAULT_LIMITS`]. + pub const fn new(banned: &'a [&'a str]) -> Self { + Policy { + banned, + case: MatchCase::Exact, + allowed: &[], + exceptions: &[], + allow_marker: None, + literals: Literals { byte_strings: false, c_strings: false }, + skip: test_path, + limits: DEFAULT_LIMITS, + } + } + + /// The banned words in `text`, in the order of [`Policy::banned`]. Empty when `text` is allowed + /// or an exception returns `true` for it. + pub fn words_in(&self, text: &str) -> Vec<&'a str> { + if self.allowed.contains(&text) || self.exceptions.iter().any(|exempt| exempt(text)) { + return Vec::new(); + } + self.banned.iter().copied().filter(|word| contains_word(text, word, self.case)).collect() + } + + fn validate(&self) -> Result<(), Error> { + if self.banned.is_empty() { + return Err(Error::Policy("the list of banned words is empty")); + } + if self.banned.iter().any(|word| word.trim().is_empty()) { + return Err(Error::Policy("a banned word is empty")); + } + if self.allow_marker.is_some_and(|marker| marker.trim().is_empty()) { + return Err(Error::Policy("the allow marker is empty")); + } + if self.limits.max_file_bytes == 0 || self.limits.max_total_bytes == 0 { + return Err(Error::Policy("a byte limit is zero")); + } + Ok(()) + } +} + +/// The apps' rule for test code: a file named `tests.rs` or ending in `_tests.rs`, or a file under +/// a folder named `tests`. +pub fn test_path(path: &Path) -> bool { + let file = path.file_name().map(|name| name.to_string_lossy()).unwrap_or_default(); + file == "tests.rs" || file.ends_with("_tests.rs") || path.parent().is_some_and(|dir| dir.components().any(|part| part.as_os_str() == "tests")) +} + +/// What a path holds and how it is read. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Kind { + /// A Rust file, or a folder whose `.rs` files are read. + Rust, + /// A `Cargo.toml`, whose `package.description` and `workspace.package.description` values are + /// read, decoded when they are TOML strings. + Manifest, + /// A text file, every line. + Text, + /// A text file whose comments take whole `#` lines (a desktop entry): a `#` line with the marker + /// also exempts the line below it. + TextMarkAbove, +} + +/// One path to scan, relative to the base folder [`scan`] takes, or absolute. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Input<'a> { + /// How the path is read. + pub kind: Kind, + /// The file or, for [`Kind::Rust`], folder. + pub path: &'a Path, +} + +impl<'a> Input<'a> { + /// A Rust file or folder. + pub fn rust(path: &'a Path) -> Self { + Input { kind: Kind::Rust, path } + } + + /// A `Cargo.toml`. + pub fn manifest(path: &'a Path) -> Self { + Input { kind: Kind::Manifest, path } + } + + /// A text file. + pub fn text(path: &'a Path) -> Self { + Input { kind: Kind::Text, path } + } + + /// A text file whose `#` lines can mark the line below them. + pub fn text_mark_above(path: &'a Path) -> Self { + Input { kind: Kind::TextMarkAbove, path } + } +} + +/// A banned word found in a file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Finding { + /// The file, as the input named it, joined with the path below a folder input. + pub path: PathBuf, + /// The 1-based line the literal starts on, or the text line. + pub line: usize, + /// The banned word, as [`Policy::banned`] lists it. + pub word: String, + /// The decoded literal or description, or the trimmed text line. + pub text: String, + /// How the file was read. + pub kind: Kind, +} + +impl fmt::Display for Finding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}:{}: {:?} in {:?}", self.path.display(), self.line, self.word, self.text) + } +} + +/// A Rust source the scanner cannot read as tokens. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SyntaxError { + /// The 1-based line the problem starts on. + pub line: usize, + /// What is wrong. + pub message: &'static str, +} + +impl fmt::Display for SyntaxError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "line {}: {}", self.line, self.message) + } +} + +/// Why a scan did not finish. +#[derive(Debug)] +pub enum Error { + /// The policy cannot be used. + Policy(&'static str), + /// A file or folder could not be read. + Io { + /// The path, as reported. + path: PathBuf, + /// The cause. + source: io::Error, + }, + /// A file is not UTF-8. + InvalidUtf8 { + /// The path, as reported. + path: PathBuf, + }, + /// A file is larger than [`Limits::max_file_bytes`]. + FileTooLarge { + /// The path, as reported. + path: PathBuf, + /// The limit, in bytes. + limit: u64, + }, + /// Reading this file took the scan past [`Limits::max_total_bytes`]. + TotalTooLarge { + /// The path, as reported. + path: PathBuf, + /// The limit, in bytes. + limit: u64, + }, + /// A folder is deeper than [`Limits::max_depth`]. + TooDeep { + /// The path, as reported. + path: PathBuf, + /// The limit. + limit: usize, + }, + /// A file is given as two kinds of input. + Conflict { + /// The path, as reported. + path: PathBuf, + }, + /// A Rust source could not be read as tokens. + Syntax { + /// The path, as reported. + path: PathBuf, + /// Where and what. + error: SyntaxError, + }, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Policy(m) => write!(f, "policy: {m}"), + Error::Io { path, source } => write!(f, "{}: {source}", path.display()), + Error::InvalidUtf8 { path } => write!(f, "{}: not UTF-8", path.display()), + Error::FileTooLarge { path, limit } => write!(f, "{}: larger than {limit} bytes", path.display()), + Error::TotalTooLarge { path, limit } => write!(f, "{}: the scan read more than {limit} bytes", path.display()), + Error::TooDeep { path, limit } => write!(f, "{}: more than {limit} folders deep", path.display()), + Error::Conflict { path } => write!(f, "{}: given as two kinds of input", path.display()), + Error::Syntax { path, error } => write!(f, "{}: {error}", path.display()), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for String { + fn from(e: Error) -> Self { + e.to_string() + } +} + +/// Every finding in `inputs`, read from `base`. Files are read once each, in path order, and the +/// findings come in path order, then in source order, then in the order of [`Policy::banned`]. +/// +/// A [`Kind::Rust`] folder is read recursively for `.rs` files that [`Policy::skip`] keeps; links to +/// folders are not followed. A file input is read whatever its name. Every error stops the scan: a +/// missing input, a file that cannot be read, is not UTF-8 or is over a limit, and a Rust source the +/// lexer cannot read. Inputs must not include binary files. +pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result, Error> { + policy.validate()?; + let mut files = Vec::new(); + for input in inputs { + if input.kind == Kind::Rust { + collect_rust(base, input.path, policy, &mut files)?; + } else { + files.push((input.path.to_path_buf(), input.kind)); + } + } + files.sort(); + files.dedup(); + if let Some(pair) = files.windows(2).find(|pair| pair[0].0 == pair[1].0) { + return Err(Error::Conflict { path: pair[0].0.clone() }); + } + let mut total = 0; + let mut findings = Vec::new(); + for (path, kind) in &files { + let source = read_limited(&base.join(path), path, &policy.limits, &mut total)?; + findings.extend(scan_source(path, &source, *kind, policy)?); + } + Ok(findings) +} + +/// The findings in one source that is already in memory. `path` is only reported. A +/// [`Kind::Rust`] source is a single file here. +pub fn scan_source(path: &Path, source: &str, kind: Kind, policy: &Policy<'_>) -> Result, Error> { + policy.validate()?; + let finding = + |line: usize, word: &str, text: &str| Finding { path: path.to_path_buf(), line, word: word.to_string(), text: text.to_string(), kind }; + let mut out = Vec::new(); + if kind == Kind::Rust { + let lexed = lex(source, policy.literals, policy.allow_marker).map_err(|error| Error::Syntax { path: path.to_path_buf(), error })?; + for lit in &lexed.literals { + if (lit.first_line..=lit.last_line).any(|line| lexed.marked_lines.contains(&line)) { + continue; + } + out.extend(policy.words_in(&lit.text).into_iter().map(|word| finding(lit.first_line, word, &lit.text))); + } + return Ok(out); + } + let lines: Vec<&str> = source.lines().collect(); + let marked = |line: &str| policy.allow_marker.is_some_and(|marker| line.contains(marker)); + if kind == Kind::Manifest { + for (first, last, text) in descriptions(source) { + if lines.get(first - 1..last.min(lines.len())).is_some_and(|span| span.iter().any(|line| marked(line))) { + continue; + } + out.extend(policy.words_in(&text).into_iter().map(|word| finding(first, word, &text))); + } + return Ok(out); + } + for (i, line) in lines.iter().enumerate() { + let above = i.checked_sub(1).and_then(|j| lines.get(j)).is_some_and(|l| l.trim_start().starts_with('#') && marked(l)); + if marked(line) || (kind == Kind::TextMarkAbove && above) { + continue; + } + let text = line.trim(); + out.extend(policy.words_in(text).into_iter().map(|word| finding(i + 1, word, text))); + } + Ok(out) +} + +/// The package descriptions of a `Cargo.toml`, the values at the key paths `package.description` +/// and `workspace.package.description`: the 1-based first and last line of each, and its text. A +/// TOML string is decoded; any other value is the rest of its line, trimmed. Table headers count +/// outside strings and arrays; keys inside inline tables are not read. +fn descriptions(source: &str) -> Vec<(usize, usize, String)> { + let mut out = Vec::new(); + let (mut offset, mut number, mut resume, mut depth) = (0, 0, 0, 0); + // The current table's key path, or `None` under an array of tables or an unreadable header. + let mut table = Some(Vec::new()); + for line in source.split_inclusive('\n') { + let start = offset; + offset += line.len(); + number += 1; + if start < resume { + continue; + } + let top = depth == 0; + resume = toml_line_end(source, start, line.len(), &mut depth); + if !top { + continue; + } + // A byte order mark may start the file. + let body = if start == 0 { line.strip_prefix('\u{feff}').unwrap_or(line) } else { line }; + let trimmed = body.trim_start_matches([' ', '\t']); + if trimmed.starts_with('[') { + table = toml_header(trimmed); + depth = 0; + continue; + } + let Some((key, value)) = toml_key(body).and_then(|(key, rest)| Some((key, rest.strip_prefix('=')?.trim_start()))) else { + continue; + }; + let path: Vec<&str> = table.iter().flatten().chain(&key).map(String::as_str).collect(); + if table.is_none() || !matches!(path.as_slice(), ["package", "description"] | ["workspace", "package", "description"]) { + continue; + } + let at = start + line.len() - value.len(); + let (text, len) = toml_string(source.get(at..).unwrap_or_default()).unwrap_or_else(|| (value.trim().to_string(), value.trim_end().len())); + resume = resume.max(at + len); + let last = number + source.get(at..at + len).unwrap_or_default().matches('\n').count(); + out.push((number, last, text)); + } + out +} + +/// The key path of a TOML table header (`[a.b]`) at the start of `line`, or `None` for an array of +/// tables (`[[a.b]]`) or a header that cannot be read. +fn toml_header(line: &str) -> Option> { + let (parts, rest) = toml_key(line.strip_prefix('[').filter(|rest| !rest.starts_with('['))?)?; + let rest = rest.strip_prefix(']')?.trim_start_matches([' ', '\t']); + (rest.is_empty() || rest.starts_with(['#', '\r', '\n'])).then_some(parts) +} + +/// The parts of the TOML key (bare, quoted or dotted) at the start of `text`, after any spaces, and +/// the text after the key and the spaces that follow it. +fn toml_key(text: &str) -> Option<(Vec, &str)> { + let mut parts = Vec::new(); + let mut rest = text; + loop { + rest = rest.trim_start_matches([' ', '\t']); + if rest.starts_with("\"\"\"") || rest.starts_with("'''") { + return None; + } + let len = if rest.starts_with(['"', '\'']) { + let (part, len) = toml_string(rest)?; + parts.push(part); + len + } else { + let len = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-').len(); + parts.push(rest.get(..len).filter(|part| !part.is_empty())?.to_string()); + len + }; + rest = rest.get(len..)?.trim_start_matches([' ', '\t']); + match rest.strip_prefix('.') { + Some(after) => rest = after, + None => return Some((parts, rest)), + } + } +} + +/// The end of the TOML line of `len` bytes at `start`, or past the last string that starts on it, +/// so that the later lines of a multi-line string are not read as keys. `depth` counts the arrays +/// and inline tables open after the line, outside strings and comments. +fn toml_line_end(source: &str, start: usize, len: usize, depth: &mut usize) -> usize { + let (mut at, mut end) = (start, start + len); + while at < end { + let Some(c) = source.get(at..).and_then(|rest| rest.chars().next()) else { break }; + match c { + '#' => break, + '[' | '{' => { + *depth += 1; + at += 1; + } + ']' | '}' => { + *depth = depth.saturating_sub(1); + at += 1; + } + '"' | '\'' => match toml_string(source.get(at..).unwrap_or_default()) { + Some((_, string)) => { + at += string; + if at > end { + // The string closes on a later line: read the rest of that line too. + end = source.get(at..).and_then(|rest| rest.find('\n')).map_or(source.len(), |i| at + i + 1); + } + } + None => break, + }, + _ => at += c.len_utf8(), + } + } + end +} + +/// The TOML string at the start of `value`, decoded, and its length in bytes. `None` when `value` +/// does not start with a complete, valid string. +fn toml_string(value: &str) -> Option<(String, usize)> { + let delim = ["\"\"\"", "'''", "\"", "'"].into_iter().find(|d| value.starts_with(d))?; + let (basic, multi) = (delim.starts_with('"'), delim.len() == 3); + let mut at = delim.len(); + if multi { + let after = value.get(at..)?; + at += if after.starts_with("\r\n") { 2 } else { usize::from(after.starts_with('\n')) }; + } + let mut text = String::new(); + loop { + let rest = value.get(at..)?; + let c = rest.chars().next()?; + if rest.starts_with(delim) { + if !multi { + return Some((text, at + 1)); + } + // Up to two quotes just before the closing three belong to the text. + let extra = rest.chars().take_while(|&q| q == c).count().saturating_sub(3).min(2); + text.extend(std::iter::repeat_n(c, extra)); + return Some((text, at + extra + 3)); + } + match c { + '\\' if basic => at = toml_escape(value, at + 1, multi, &mut text)?, + '\n' if !multi => return None, + '\r' if rest.starts_with("\r\n") => at += 1, + _ => { + text.push(c); + at += c.len_utf8(); + } + } + } +} + +/// The escape after a backslash at `at` in a TOML basic string, decoded into `text`, and the index +/// after it. +fn toml_escape(value: &str, at: usize, multi: bool, text: &mut String) -> Option { + let rest = value.get(at..)?; + let c = rest.chars().next()?; + let simple = match c { + 'b' => Some('\u{8}'), + 't' => Some('\t'), + 'n' => Some('\n'), + 'f' => Some('\u{c}'), + 'r' => Some('\r'), + 'e' => Some('\u{1b}'), + '"' | '\\' => Some(c), + _ => None, + }; + if let Some(decoded) = simple { + text.push(decoded); + return Some(at + 1); + } + let digits = match c { + 'x' => 2, + 'u' => 4, + 'U' => 8, + _ => 0, + }; + if digits > 0 { + let hex = rest.get(1..1 + digits).filter(|hex| hex.chars().all(|h| h.is_ascii_hexdigit()))?; + text.push(u32::from_str_radix(hex, 16).ok().and_then(char::from_u32)?); + return Some(at + 1 + digits); + } + // A backslash at the end of a line in a multi-line string: the line break and the whitespace + // after it are left out. + if multi && rest.trim_start_matches([' ', '\t']).starts_with(['\n', '\r']) { + return Some(at + rest.len() - rest.trim_start_matches([' ', '\t', '\n', '\r']).len()); + } + None +} + +/// A Rust string literal. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Literal { + /// The 1-based line of its opening quote. + pub first_line: usize, + /// The 1-based line of its closing quote. + pub last_line: usize, + /// Its text, with escapes decoded (not in raw literals) and CRLF read as LF. + pub text: String, +} + +/// The string literals of a Rust source outside comments and test-only code, in source order. +/// +/// Test-only code is the code under `#[cfg(test)]` and the rest of a module that starts with +/// `#![cfg(test)]`. Under `#[cfg(test)]`, a `const`, `static` or `let` runs up to its `;`, another +/// item up to its closing `}` or its `;`, and a field, argument, arm or statement up to its `,` or +/// `;`. A block expression (a block, a macro's braces, a labeled block, or `if`, `match`, `loop`, +/// `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as an arm's expression +/// after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` branches. When a method +/// call, field or `?` follows that `}`, it runs up to its `,` or `;` instead. Character, byte and +/// lifetime tokens are read, so a quote in them does not start a string. +pub fn literals(source: &str, kinds: Literals) -> Result, SyntaxError> { + lex(source, kinds, None).map(|lexed| lexed.literals) +} + +fn contains_word(text: &str, word: &str, case: MatchCase) -> bool { + match case { + MatchCase::Exact => text.match_indices(word).any(|(at, _)| whole_word(text, at, word.len())), + MatchCase::AsciiInsensitive => { + let lower = text.to_ascii_lowercase(); + let word = word.to_ascii_lowercase(); + lower.match_indices(&word).any(|(at, _)| whole_word(text, at, word.len())) + } + } +} + +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn whole_word(text: &str, at: usize, len: usize) -> bool { + let before = text.get(..at).and_then(|s| s.chars().next_back()); + let after = text.get(at + len..).and_then(|s| s.chars().next()); + !before.is_some_and(is_word) && !after.is_some_and(is_word) +} + +fn io_error(path: &Path) -> impl FnOnce(io::Error) -> Error + '_ { + move |source| Error::Io { path: path.to_path_buf(), source } +} + +fn collect_rust(base: &Path, path: &Path, policy: &Policy<'_>, out: &mut Vec<(PathBuf, Kind)>) -> Result<(), Error> { + let meta = fs::metadata(base.join(path)).map_err(io_error(path))?; + if meta.is_dir() { + walk(base, path, path, policy, 0, out) + } else { + out.push((path.to_path_buf(), Kind::Rust)); + Ok(()) + } +} + +fn walk(base: &Path, input: &Path, dir: &Path, policy: &Policy<'_>, depth: usize, out: &mut Vec<(PathBuf, Kind)>) -> Result<(), Error> { + if depth > policy.limits.max_depth { + return Err(Error::TooDeep { path: dir.to_path_buf(), limit: policy.limits.max_depth }); + } + let mut entries = fs::read_dir(base.join(dir)).and_then(|entries| entries.collect::>>()).map_err(io_error(dir))?; + entries.sort_by_key(fs::DirEntry::file_name); + for entry in entries { + let path = dir.join(entry.file_name()); + let file_type = entry.file_type().map_err(io_error(&path))?; + if file_type.is_dir() { + walk(base, input, &path, policy, depth + 1, out)?; + continue; + } + if !path.extension().is_some_and(|ext| ext == "rs") || (policy.skip)(path.strip_prefix(input).unwrap_or(&path)) { + continue; + } + // A link to a folder is not followed; a link to a file is read like the file. + let is_file = if file_type.is_symlink() { fs::metadata(base.join(&path)).map_err(io_error(&path))?.is_file() } else { file_type.is_file() }; + if is_file { + out.push((path, Kind::Rust)); + } + } + Ok(()) +} + +fn read_limited(full: &Path, path: &Path, limits: &Limits, total: &mut u64) -> Result { + let file = File::open(full).map_err(io_error(path))?; + let len = file.metadata().map_err(io_error(path))?.len(); + if len > limits.max_file_bytes { + return Err(Error::FileTooLarge { path: path.to_path_buf(), limit: limits.max_file_bytes }); + } + let mut bytes = Vec::with_capacity(usize::try_from(len).unwrap_or(0)); + file.take(limits.max_file_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(io_error(path))?; + let read = u64::try_from(bytes.len()).unwrap_or(u64::MAX); + if read > limits.max_file_bytes { + return Err(Error::FileTooLarge { path: path.to_path_buf(), limit: limits.max_file_bytes }); + } + *total = total.saturating_add(read); + if *total > limits.max_total_bytes { + return Err(Error::TotalTooLarge { path: path.to_path_buf(), limit: limits.max_total_bytes }); + } + let mut text = String::from_utf8(bytes).map_err(|_| Error::InvalidUtf8 { path: path.to_path_buf() })?; + if text.starts_with('\u{feff}') { + text.remove(0); + } + Ok(text) +} + +struct Lexed { + literals: Vec, + marked_lines: HashSet, +} + +/// The literal forms, which differ in the escapes they take and in whether the scan reads them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Form { + Str, + Char, + Byte, + C, +} + +/// The keywords that start an item, whose header can hold commas. +const ITEM_KEYWORDS: &[&str] = + &["const", "enum", "extern", "fn", "impl", "let", "macro_rules", "mod", "static", "struct", "trait", "type", "union", "use"]; + +/// The keywords of items that end at their `;`, whatever braces their value holds. +const SEMICOLON_KEYWORDS: &[&str] = &["const", "let", "static"]; + +/// The keywords that start an expression ending at the `}` of its block (or of its last `else`). +const BLOCK_KEYWORDS: &[&str] = &["async", "const", "for", "if", "loop", "match", "unsafe", "while"]; + +/// Test-only code being skipped. +#[derive(Debug, Clone, Copy)] +enum TestRegion { + /// An item, field, argument, arm or statement under `#[cfg(test)]`, at this delimiter depth. + /// `start` is the index where its code (or an arm's expression, after `=>`) starts; `opened` is + /// set once its first `{` is read, `item` once an item keyword (`fn`, `impl`, `mod`…) is read, + /// and `semi` while the last such keyword is `const`, `let` or `static`, whose items end at their + /// `;`. Without an item keyword, `block` is set when that first `{` starts a block expression (a + /// block, a macro's braces, or `if`, `match`, `loop` and the like), which ends at its `}` unless + /// an `else` follows. A `.` or `?` after that `}` clears `block`, so the expression ends at its + /// `;` or `,`. + Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool }, + /// The rest of the module that `#![cfg(test)]` starts, at this delimiter depth. + Inner { level: usize }, +} + +struct Lexer<'s> { + chars: Vec, + at: usize, + line: usize, + kinds: Literals, + marker: Option<&'s str>, + /// Open delimiters and the line of each. + delims: Vec<(char, usize)>, + test: Option, + out: Lexed, +} + +fn lex(source: &str, kinds: Literals, marker: Option<&str>) -> Result { + let mut lexer = Lexer { + chars: source.chars().collect(), + at: 0, + line: 1, + kinds, + marker, + delims: Vec::new(), + test: None, + out: Lexed { literals: Vec::new(), marked_lines: HashSet::new() }, + }; + lexer.run()?; + Ok(lexer.out) +} + +impl Lexer<'_> { + fn peek(&self, ahead: usize) -> Option { + self.chars.get(self.at + ahead).copied() + } + + fn next(&mut self) -> Option { + let c = self.peek(0)?; + self.at += 1; + Some(c) + } + + fn error(line: usize, message: &'static str) -> SyntaxError { + SyntaxError { line, message } + } + + fn run(&mut self) -> Result<(), SyntaxError> { + while let Some(c) = self.peek(0) { + match c { + '\n' => { + self.line += 1; + self.at += 1; + } + '/' if self.peek(1) == Some('/') => self.line_comment(), + '/' if self.peek(1) == Some('*') => self.block_comment()?, + '"' => { + self.at += 1; + self.string(Form::Str)?; + } + '\'' => self.quote(Form::Char)?, + '#' => self.hash(), + '{' | '(' | '[' => self.open(c), + '}' | ')' | ']' => self.close(c)?, + ';' => self.item_end(false), + ',' => self.item_end(true), + '=' if self.peek(1) == Some('>') => self.arrow(), + c if c.is_ascii_digit() => self.number(), + c if is_word(c) => self.word()?, + _ => self.at += 1, + } + } + match self.delims.last() { + Some(&(_, line)) => Err(Self::error(line, "unclosed delimiter")), + None => Ok(()), + } + } + + fn comment_text(&mut self, first: usize, start: usize) { + if let Some(marker) = self.marker { + let text: String = self.chars.get(start..self.at).unwrap_or_default().iter().collect(); + let marked = text.split('\n').enumerate().filter(|(_, line)| line.contains(marker)); + self.out.marked_lines.extend(marked.map(|(i, _)| first + i)); + } + } + + fn line_comment(&mut self) { + let start = self.at; + while self.peek(0).is_some_and(|c| c != '\n') { + self.at += 1; + } + self.comment_text(self.line, start); + } + + fn block_comment(&mut self) -> Result<(), SyntaxError> { + let (first, start) = (self.line, self.at); + self.at += 2; + let mut depth = 1_usize; + while depth > 0 { + match (self.next(), self.peek(0)) { + (None, _) => return Err(Self::error(first, "unterminated block comment")), + (Some('/'), Some('*')) => { + self.at += 1; + depth += 1; + } + (Some('*'), Some('/')) => { + self.at += 1; + depth -= 1; + } + (Some('\n'), _) => self.line += 1, + _ => {} + } + } + self.comment_text(first, start); + Ok(()) + } + + fn reads(&self, form: Form) -> bool { + match form { + Form::Str => true, + Form::Byte => self.kinds.byte_strings, + Form::C => self.kinds.c_strings, + Form::Char => false, + } + } + + fn push(&mut self, first: usize, text: String, form: Form) { + if self.reads(form) && self.test.is_none() { + self.out.literals.push(Literal { first_line: first, last_line: self.line, text }); + } + } + + /// A `"…"` body after its opening quote. + fn string(&mut self, form: Form) -> Result<(), SyntaxError> { + let first = self.line; + let mut text = String::new(); + loop { + match self.next() { + None => return Err(Self::error(first, "unterminated string literal")), + Some('"') => break, + Some('\\') => self.escape(form, &mut text, first)?, + Some('\r') if self.peek(0) == Some('\n') => {} + Some('\n') => { + self.line += 1; + text.push('\n'); + } + Some(c) => text.push(c), + } + } + self.push(first, text, form); + Ok(()) + } + + /// The escape after a backslash, decoded into `text`. + fn escape(&mut self, form: Form, text: &mut String, first: usize) -> Result<(), SyntaxError> { + let decoded = match self.next() { + None => return Err(Self::error(first, "unterminated escape")), + Some('n') => '\n', + Some('r') => '\r', + Some('t') => '\t', + Some('0') => '\0', + Some(c @ ('\\' | '\'' | '"')) => c, + Some('x') => self.hex_escape(form)?, + Some('u') if form != Form::Byte => self.unicode_escape()?, + Some('\n') if form != Form::Char => { + self.continuation(); + return Ok(()); + } + Some('\r') if form != Form::Char && self.peek(0) == Some('\n') => { + self.at += 1; + self.continuation(); + return Ok(()); + } + Some(_) => return Err(Self::error(self.line, "unknown character escape")), + }; + text.push(decoded); + Ok(()) + } + + /// A backslash before a line break: the break and the whitespace after it are left out. + fn continuation(&mut self) { + self.line += 1; + while let Some(c @ (' ' | '\t' | '\n' | '\r')) = self.peek(0) { + self.line += usize::from(c == '\n'); + self.at += 1; + } + } + + fn hex_escape(&mut self, form: Form) -> Result { + let digits = (self.peek(0).and_then(|c| c.to_digit(16)), self.peek(1).and_then(|c| c.to_digit(16))); + let (Some(high), Some(low)) = digits else { + return Err(Self::error(self.line, "a \\x escape needs two hex digits")); + }; + self.at += 2; + let value = high * 16 + low; + match (value, form) { + (0..=0x7f, _) => Ok(char::from_u32(value).unwrap_or(char::REPLACEMENT_CHARACTER)), + (_, Form::Byte | Form::C) => Ok(char::REPLACEMENT_CHARACTER), + _ => Err(Self::error(self.line, "a \\x escape above 0x7F")), + } + } + + fn unicode_escape(&mut self) -> Result { + let bad = Self::error(self.line, "an invalid \\u{...} escape"); + if self.next() != Some('{') || self.peek(0) == Some('_') { + return Err(bad); + } + let (mut value, mut digits) = (0_u32, 0_usize); + loop { + match self.next() { + Some('}') => break, + Some('_') => {} + Some(c) if digits < 6 => { + value = value * 16 + c.to_digit(16).ok_or_else(|| bad.clone())?; + digits += 1; + } + _ => return Err(bad), + } + } + if digits == 0 { + return Err(bad); + } + char::from_u32(value).ok_or(bad) + } + + /// A quote: a character or byte literal, or the start of a lifetime or label. + fn quote(&mut self, form: Form) -> Result<(), SyntaxError> { + match (self.peek(1), self.peek(2)) { + (Some('\\'), _) => { + let first = self.line; + self.at += 2; + self.escape(form, &mut String::new(), first)?; + if self.next() != Some('\'') { + return Err(Self::error(first, "unterminated character literal")); + } + } + (Some(c), Some('\'')) if c != '\'' && c != '\n' => self.at += 3, + _ => self.at += 1, + } + Ok(()) + } + + fn number(&mut self) { + while self.peek(0).is_some_and(is_word) { + self.at += 1; + } + } + + /// An identifier, or the prefix of a byte, C or raw literal. + fn word(&mut self) -> Result<(), SyntaxError> { + let start = self.at; + self.number(); + let word: String = self.chars.get(start..self.at).unwrap_or_default().iter().collect(); + // `const { .. }` is a block expression, not an item. + let const_block = word == "const" && self.chars.get(self.skip_space(self.at)) == Some(&'{'); + if let Some(TestRegion::Item { level, opened: false, item, semi, .. }) = &mut self.test + && *level == self.delims.len() + && ITEM_KEYWORDS.contains(&word.as_str()) + && !const_block + { + *item = true; + *semi = SEMICOLON_KEYWORDS.contains(&word.as_str()); + } + match (word.as_str(), self.peek(0)) { + ("b", Some('\'')) => self.quote(Form::Byte), + ("b", Some('"')) => { + self.at += 1; + self.string(Form::Byte) + } + ("c", Some('"')) => { + self.at += 1; + self.string(Form::C) + } + ("r", Some('"' | '#')) => self.raw(Form::Str), + ("br", Some('"' | '#')) => self.raw(Form::Byte), + ("cr", Some('"' | '#')) => self.raw(Form::C), + _ => Ok(()), + } + } + + /// A raw literal after its `r`, or a raw identifier (`r#name`), which is left to the caller. + fn raw(&mut self, form: Form) -> Result<(), SyntaxError> { + let hashes = self.chars.get(self.at..).unwrap_or_default().iter().take_while(|&&c| c == '#').count(); + if self.peek(hashes) != Some('"') { + return Ok(()); + } + let first = self.line; + self.at += hashes + 1; + let mut text = String::new(); + loop { + match self.next() { + None => return Err(Self::error(first, "unterminated raw string literal")), + Some('"') if (0..hashes).all(|n| self.peek(n) == Some('#')) => break, + Some('\r') if self.peek(0) == Some('\n') => {} + Some(c) => { + self.line += usize::from(c == '\n'); + text.push(c); + } + } + } + self.at += hashes; + self.push(first, text, form); + Ok(()) + } + + /// The index after the whitespace and comments at `at`. + fn skip_space(&self, mut at: usize) -> usize { + loop { + match (self.chars.get(at), self.chars.get(at + 1)) { + (Some(c), _) if c.is_whitespace() => at += 1, + (Some('/'), Some('/')) => { + while self.chars.get(at).is_some_and(|&c| c != '\n') { + at += 1; + } + } + (Some('/'), Some('*')) => { + let mut depth = 0_usize; + loop { + match (self.chars.get(at), self.chars.get(at + 1)) { + (None, _) => return at, + (Some('/'), Some('*')) => { + depth += 1; + at += 2; + } + (Some('*'), Some('/')) => { + depth -= 1; + at += 2; + if depth == 0 { + break; + } + } + _ => at += 1, + } + } + } + _ => return at, + } + } + } + + /// The end of a `#[cfg(test)]` or `#![cfg(test)]` attribute at the current `#`, and whether it + /// is the inner form. + fn cfg_test_end(&self) -> Option<(usize, bool)> { + let mut at = self.at + 1; + let inner = self.chars.get(at) == Some(&'!'); + at += usize::from(inner); + for token in ["[", "cfg", "(", "test", ")", "]"] { + at = self.skip_space(at); + let end = at + token.chars().count(); + if !self.chars.get(at..end).is_some_and(|got| got.iter().copied().eq(token.chars())) { + return None; + } + if token.starts_with(is_word) && self.chars.get(end).is_some_and(|&c| is_word(c)) { + return None; + } + at = end; + } + Some((at, inner)) + } + + fn hash(&mut self) { + let Some((end, inner)) = self.cfg_test_end() else { + self.at += 1; + return; + }; + let skipped = self.chars.get(self.at..end).unwrap_or_default(); + self.line += skipped.iter().filter(|&&c| c == '\n').count(); + self.at = end; + if self.test.is_none() { + let level = self.delims.len(); + self.test = Some(if inner { + TestRegion::Inner { level } + } else { + TestRegion::Item { level, start: end, opened: false, item: false, semi: false, block: false } + }); + } + } + + /// A `=>` at the level of a test-only arm: its expression starts after it. + fn arrow(&mut self) { + self.at += 2; + if let Some(TestRegion::Item { level, item: false, .. }) = self.test + && level == self.delims.len() + { + self.test = Some(TestRegion::Item { level, start: self.at, opened: false, item: false, semi: false, block: false }); + } + } + + /// Whether the code at `start` is a block expression whose first `{` is at the current index: + /// the block itself, a macro's braces, a labeled block or loop, or a block keyword's expression. + /// Outer attributes before it are passed over. + fn starts_block(&self, start: usize) -> bool { + let mut at = self.skip_space(start); + while self.chars.get(at) == Some(&'#') { + at = self.skip_space(at + 1); + if self.chars.get(at) != Some(&'[') { + return false; + } + let mut depth = 0_usize; + loop { + match self.chars.get(at) { + None => return false, + Some('[') => depth += 1, + Some(']') => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + at += 1; + } + at = self.skip_space(at + 1); + } + at == self.at || self.chars.get(at) == Some(&'\'') || BLOCK_KEYWORDS.contains(&self.word_at(at).as_str()) || self.macro_braces(at) + } + + /// Whether the code at `at` is a macro path, `!` and the `{` at the current index. + fn macro_braces(&self, mut at: usize) -> bool { + if self.chars.get(at..at + 2) == Some(&[':', ':'][..]) { + at = self.skip_space(at + 2); + } + loop { + let len = self.word_at(at).chars().count(); + if len == 0 { + return false; + } + at = self.skip_space(at + len); + if self.chars.get(at..at + 2) != Some(&[':', ':'][..]) { + break; + } + at = self.skip_space(at + 2); + } + self.chars.get(at) == Some(&'!') && self.skip_space(at + 1) == self.at + } + + fn word_at(&self, at: usize) -> String { + self.chars.get(at..).unwrap_or_default().iter().take_while(|&&c| is_word(c)).collect() + } + + fn open(&mut self, c: char) { + if let Some(TestRegion::Item { level, start, opened: false, item, semi, .. }) = self.test + && level == self.delims.len() + && c == '{' + { + let block = !item && self.starts_block(start); + self.test = Some(TestRegion::Item { level, start, opened: true, item, semi, block }); + } + self.delims.push((c, self.line)); + self.at += 1; + } + + fn close(&mut self, c: char) -> Result<(), SyntaxError> { + let expected = match self.delims.pop() { + Some(('{', _)) => '}', + Some(('(', _)) => ')', + Some(_) => ']', + None => return Err(Self::error(self.line, "unmatched closing delimiter")), + }; + if c != expected { + return Err(Self::error(self.line, "mismatched closing delimiter")); + } + self.at += 1; + let depth = self.delims.len(); + let ends = match self.test { + Some(TestRegion::Item { level, start, opened, item, semi, block }) => { + let block_end = opened && depth == level && c == '}'; + if block_end && !item && block && self.postfix_follows() { + // A method call, field or `?` continues the expression to its `;` or `,`. + self.test = Some(TestRegion::Item { level, start, opened, item, semi, block: false }); + false + } else { + depth < level || (block_end && if item { !semi } else { block && self.word_at(self.skip_space(self.at)) != "else" }) + } + } + Some(TestRegion::Inner { level }) => depth < level, + None => false, + }; + if ends { + self.test = None; + } + Ok(()) + } + + /// Whether a `?` or a `.` (not `..`) follows the current index, past whitespace and comments. + fn postfix_follows(&self) -> bool { + let at = self.skip_space(self.at); + match self.chars.get(at) { + Some('?') => true, + Some('.') => self.chars.get(at + 1) != Some(&'.'), + _ => false, + } + } + + /// A `;` ends a test-only statement, or an item that has no body or ends at its `;`, and a `,` + /// inside a delimiter ends a test-only field, argument or arm. A `,` in an item's header + /// (`impl`, a `where` clause) does not. + fn item_end(&mut self, comma: bool) { + if let Some(TestRegion::Item { level, opened, item, semi, .. }) = self.test + && level == self.delims.len() + && if comma { level > 0 && !item } else { !item || !opened || semi } + { + self.test = None; + } + self.at += 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BANNED: &[&str] = &["Amber Tool", "AzureKit", "BlueCore"]; + const ALLOWED: &[&str] = &["AzureKit Design"]; + const POLICY: Policy<'static> = Policy { allowed: ALLOWED, ..Policy::new(BANNED) }; + + fn banned_display(text: &str) -> bool { + !POLICY.words_in(text).is_empty() + } + + fn literals(source: &str) -> Vec { + super::literals(source, Literals::default()).unwrap().into_iter().map(|lit| lit.text).collect() + } + + fn write(dir: &Path, path: &str, text: &str) { + let path = dir.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + + fn hits(findings: &[Finding]) -> Vec<(String, usize, &str)> { + findings.iter().map(|f| (f.path.to_string_lossy().replace('\\', "/"), f.line, f.word.as_str())).collect() + } + + #[test] + fn production_display_names_stay_neutral() { + let dir = tempfile::tempdir().unwrap(); + let base = dir.path().join("crates/ui"); + write(&base, "src/lib.rs", "pub const LABEL: &str = \"Open\";\n#[cfg(test)]\nmod tests { const S: &str = \"AzureKit\"; }\n"); + write(&base, "src/tests.rs", "const S: &str = \"AzureKit\";\n"); + write(&base, "src/panel_tests.rs", "const S: &str = \"BlueCore\";\n"); + write(&base, "src/tests/helper.rs", "const S: &str = \"Amber Tool\";\n"); + write(&base, "src/notes.txt", "AzureKit\n"); + write(dir.path(), "crates/engine/src/cmd/file.rs", "pub const DESIGN: &str = \"AzureKit Design\";\n"); + let roots = [Path::new("src"), Path::new("../engine/src/cmd")]; + let inputs: Vec> = roots.iter().map(|root| Input::rust(root)).collect(); + let found = scan(&base, &inputs, &POLICY).unwrap(); + assert!(found.is_empty(), "{found:#?}"); + } + + #[test] + fn guard_distinguishes_labels_from_identifiers_and_comments() { + for name in BANNED { + assert!(banned_display(name), "{name}"); + } + for name in ALLOWED { + assert!(!banned_display(name), "{name}"); + } + assert!(!banned_display("filter.azureKit")); + assert!(!banned_display("tool.guidedBlueCore")); + assert!(!banned_display("insert.amberTool")); + assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]); + assert_eq!(literals("r#\"raw label\"#"), ["raw label"]); + } + + #[test] + fn guard_scans_production_after_test_only_items() { + let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"live label"#; } + "###; + assert_eq!(literals(source), ["live label"]); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]); + } + + #[test] + fn guard_skips_escaped_character_literals() { + assert_eq!(literals(r#"let q = '\"'; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\''; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\\'; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\u{22}'; "label""#), ["label"]); + } + + #[test] + fn guard_decodes_whitespace_escapes() { + assert_eq!(literals(r#""one\ntwo\tthree\rfour\0""#), ["one\ntwo\tthree\rfour\0"]); + assert_eq!(literals("\"joined\\\n label\""), ["joinedlabel"]); + for name in BANNED { + let source = format!("\"\\t{name}\\n\""); + assert!(literals(&source).iter().any(|label| banned_display(label))); + } + } + + #[test] + fn guard_scans_after_escaped_character_literals() { + let source = r###"let a = '\"'; let b = '\''; let c = '\\'; + let d = '\u{22}'; let e = '\x22'; + let label = "Amber Tool"; + fn lifetime<'a>(value: &'a str) { 'outer: loop { break 'outer; } let _ = "BlueCore"; } + "###; + assert_eq!(literals(source), ["Amber Tool", "BlueCore"]); + } + + #[test] + fn guard_scans_production_after_test_only_items_and_parses_raw_labels() { + let source = r###"#[cfg(test)] mod tests { let _ = "AzureKit"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"BlueCore"#; } + "###; + assert_eq!(literals(source), ["BlueCore"]); + assert!(literals(source).iter().any(|label| banned_display(label))); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"AzureKit\"; }"), ["AzureKit"]); + } + + #[test] + fn guard_skips_escaped_character_literals_without_hiding_labels() { + let source = r#"let quote = '\"'; let label = "BlueCore"; // "ignored""#; + assert_eq!(literals(source), ["BlueCore"]); + assert!(literals(source).iter().any(|label| banned_display(label))); + assert_eq!(literals(r#"let quote = '\"'; // "BlueCore""#), Vec::::new()); + } + + #[test] + fn source_read_failures_are_reported() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "src/lib.rs", "const S: &str = \"Open\";\n"); + // A file cannot be read as a folder, and a missing root is an error, not an empty scan. + for root in ["src/lib.rs/not-a-folder.rs", "missing"] { + let err = scan(dir.path(), &[Input::rust(Path::new(root))], &POLICY).unwrap_err(); + assert!(matches!(err, Error::Io { .. }), "{root}: {err}"); + } + let err = scan(dir.path(), &[Input::text(Path::new("missing.txt"))], &POLICY).unwrap_err(); + assert!(matches!(err, Error::Io { .. }), "{err}"); + } + + const DENY: &[&str] = &["azurekit", "bluecore", "copperline", "dunemark", "emberly", "fernwave", "glintpad"]; + const VECTOR: Policy<'static> = Policy { + case: MatchCase::AsciiInsensitive, + allow_marker: Some("name-ok"), + literals: Literals { byte_strings: true, c_strings: true }, + ..Policy::new(DENY) + }; + + fn rust_hits(src: &str) -> Vec<(usize, &str)> { + let found = scan_source(Path::new("lib.rs"), src, Kind::Rust, &VECTOR).unwrap(); + found.iter().map(|f| (f.line, DENY.iter().copied().find(|w| *w == f.word).unwrap())).collect() + } + + #[test] + fn rust_literals_skip_comments_identifiers_tests_and_marked_lines() { + let src = r##"// BlueCore in a comment +/// AzureKit in a doc comment +/* block AzureKit /* nested */ Copperline */ +fn f() { let a = "Made for BlueCore users"; let k = "copyEmberly"; let q = '"'; let l: &'static str = r#"raw "Dunemark" text"#; } +const OLD: &str = "BlueCore Defaults"; // name-ok: legacy alias +fn g() -> &'static str { "line\nEMBERLY" } +#[cfg(test)] +mod tests { + fn t() { let x = "AzureKit"; if true { let y = "Copperline"; } } +} +#[cfg(test)] +mod other; +fn h() { let s = b"Fernwave"; let m = "multi +line Glintpad"; } +"##; + assert_eq!(rust_hits(src), [(4, "bluecore"), (4, "dunemark"), (6, "emberly"), (13, "fernwave"), (13, "glintpad")]); + let lits = super::literals(src, VECTOR.literals).unwrap(); + let multi = lits.iter().find(|l| l.text.contains("Glintpad")).unwrap(); + assert_eq!((multi.first_line, multi.last_line), (13, 14)); + } + + #[test] + fn whole_words_only() { + assert_eq!(VECTOR.words_in("AzureKit's app"), ["azurekit"]); + assert_eq!(VECTOR.words_in("an BLUECORE-style UI"), ["bluecore"]); + assert!(VECTOR.words_in("bluecores bluecoreish copyEmberly emberlyMode").is_empty()); + } + + #[test] + fn docs_packaging_and_manifests() { + let scan = |text: &str, kind: Kind| -> Vec<(usize, String)> { + scan_source(Path::new("f"), text, kind, &VECTOR).unwrap().into_iter().map(|f| (f.line, f.word)).collect() + }; + let one = |line: usize, word: &str| vec![(line, word.to_string())]; + assert_eq!(scan("Keywords=vector;bluecore;\n", Kind::Text), one(1, "bluecore")); + assert_eq!(scan("Like AzureKit apps\nnot here: AzureKit # name-ok\n", Kind::Text), one(1, "azurekit")); + let desktop = "# shared type (name-ok)\nMimeType=application/bluecore;\n# a comment\nMimeType=application/bluecore;\n"; + assert_eq!(scan(desktop, Kind::TextMarkAbove), one(4, "bluecore"), "a `#` line marks the line below it only"); + assert_eq!( + scan(desktop, Kind::Text), + [(2, "bluecore".to_string()), (4, "bluecore".to_string())], + "only mark-above files take a mark from above" + ); + assert_eq!(scan("x = 1 # name-ok\nBlueCore\n", Kind::TextMarkAbove), one(2, "bluecore"), "a code line's comment marks that line only"); + let manifest = "[package]\nname = \"azurekit-thing\"\ndescription = \"BlueCore-style UI\"\n"; + assert_eq!(scan(manifest, Kind::Manifest), one(3, "bluecore")); + let multi = + "[package]\ndescription = \"\"\"\nA BlueCore\n-style UI\"\"\"\nkeywords = [\"azurekit\"]\ndescription = '''one line''' # azurekit\n"; + assert_eq!(scan(multi, Kind::Manifest), one(2, "bluecore"), "a multi-line value is read whole; a comment is not read"); + assert_eq!(scan("[package]\ndescription = '''\nAzureKit'''\nname = \"bluecore\"\n", Kind::Manifest), one(2, "azurekit")); + let escaped = "[package]\ndescription = \"\"\"say \\\"\"\" and\nBlueCore \\\\\"\"\"\nname = \"azurekit\"\n"; + assert_eq!(scan(escaped, Kind::Manifest), one(2, "bluecore"), "an escaped quote does not close the description"); + assert_eq!( + scan("[package]\ndescription = \"Blue\\u0043ore and Azure\\U0000004Bit\"\n", Kind::Manifest), + [(2, "azurekit".to_string()), (2, "bluecore".to_string())] + ); + assert_eq!(scan("[package]\ndescription = \"\"\"Blue\\\n Core\"\"\"\n", Kind::Manifest), one(2, "bluecore")); + assert!(scan("[package]\ndescription = \"Neutral\" # BlueCore\ndescriptions = \"AzureKit\"\n", Kind::Manifest).is_empty()); + let notes = "[package]\nnotes = \"\"\"\n[dependencies]\ndescription = \"BlueCore\"\n\"\"\" # \"\"\"\nquoted = 'a \"\"\" b'\ndescription = \"AzureKit\"\n"; + assert_eq!(scan(notes, Kind::Manifest), one(7, "azurekit"), "lines inside another key's string are not keys or headers"); + let keys = "package.description = 'BlueCore'\n[package]\n\"description\" = \"AzureKit\"\n'description'='Copperline'\n# description = \"Dunemark\"\nother.description = \"Emberly\"\n"; + assert_eq!(scan(keys, Kind::Manifest), [(1, "bluecore".to_string()), (3, "azurekit".to_string()), (4, "copperline".to_string())]); + let marked = + "[package]\ndescription = \"\"\"\nBlueCore long\n\"\"\" # name-ok\nname = \"y\"\n[workspace.package]\ndescription = \"BlueCore\"\n"; + assert_eq!(scan(marked, Kind::Manifest), one(7, "bluecore"), "a marker on any line of the value counts"); + let text = scan_source(Path::new("Cargo.toml"), "[package]\ndescription = '''\nBlueCore\nstyle'''\n", Kind::Manifest, &VECTOR).unwrap(); + assert_eq!(text[0].text, "BlueCore\nstyle"); + } + + #[test] + fn only_package_descriptions_are_read() { + let scan = |text: &str| -> Vec<(usize, String)> { + scan_source(Path::new("Cargo.toml"), text, Kind::Manifest, &VECTOR).unwrap().into_iter().map(|f| (f.line, f.word)).collect() + }; + let other = "description = \"Glintpad\"\n[dependencies.foo]\ndescription = \"BlueCore\"\n[package.metadata.x]\ndescription = \"AzureKit\"\n\ + [[bin]]\ndescription = \"Copperline\"\n[[package]]\ndescription = \"Copperline\"\n[package]\nmetadata.description = \"Dunemark\"\n\ + dependencies = { description = \"Dunemark\" }\n[workspace]\ndescription = \"Emberly\"\n"; + assert!(scan(other).is_empty(), "{:?}", scan(other)); + assert_eq!(scan("\u{feff}[package]\ndescription = \"BlueCore\"\n"), [(2, "bluecore".to_string())], "a byte order mark is skipped"); + assert_eq!(scan("\u{feff}package.description = \"AzureKit\"\n"), [(1, "azurekit".to_string())]); + let tables = "[ \"package\" ] # x\ndescription = \"BlueCore\"\n[dependencies.foo]\nx = [\n [\"package\"]\n]\ndescription = \"AzureKit\"\n\ + [workspace . 'package']\ndescription = \"Fernwave\"\n[dependencies]\nworkspace.package.description = \"Emberly\"\n\ + y = [ \"\"\"\n]\n\"\"\", ]\n[package]\ndescription = \"Glintpad\"\n"; + assert_eq!( + scan(tables), + [(2, "bluecore".to_string()), (9, "fernwave".to_string()), (16, "glintpad".to_string())], + "a line inside an array is not a header, and an array closed after a multi-line string is closed" + ); + } + + #[test] + fn scope() { + for (path, test) in [ + ("src/cmd/file.rs", false), + ("src/tests_file.rs", false), + ("src/text_tests.rs", true), + ("src/cms/tests.rs", true), + ("tests/command_sweep.rs", true), + ("src/tests/helper.rs", true), + ("../engine/tests/a.rs", true), + ] { + assert_eq!(test_path(Path::new(path)), test, "{path}"); + } + let dir = tempfile::tempdir().unwrap(); + for file in ["src/a.rs", "src/b.txt", "src/c.rs.bak", "src/d/e.rs", "src/tests/f.rs", "src/g_tests.rs"] { + write(dir.path(), file, "\"AzureKit\"\n"); + } + let found = scan(dir.path(), &[Input::rust(Path::new("src"))], &POLICY).unwrap(); + assert_eq!(hits(&found), [("src/a.rs".to_string(), 1, "AzureKit"), ("src/d/e.rs".to_string(), 1, "AzureKit")]); + let named = scan(dir.path(), &[Input::rust(Path::new("src/g_tests.rs"))], &POLICY).unwrap(); + assert_eq!(hits(&named), [("src/g_tests.rs".to_string(), 1, "AzureKit")], "a file input is read whatever its name"); + write(dir.path(), "tests/app/src/lib.rs", "\"AzureKit\"\n"); + let below = scan(dir.path(), &[Input::rust(Path::new("tests/app/src"))], &POLICY).unwrap(); + assert_eq!(hits(&below), [("tests/app/src/lib.rs".to_string(), 1, "AzureKit")], "folders above the input do not count"); + } + + #[test] + fn injected_strings_fail_the_gate() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "crates/x/src/lib.rs", "pub const LABEL: &str = \"Export for BlueCore\"; // a comment: AzureKit\n"); + write(root, "crates/x/Cargo.toml", "[package]\nname = \"x\"\ndescription = \"A Copperline-style crate\"\n"); + write(root, "docs/x.md", "Works like Copperline.\n"); + write(root, "docs/x.txt", "Works like Copperline.\n"); + write(root, "packaging/x.desktop", "Keywords=vector;bluecore;\n"); + let marked = "# shared type (name-ok)\nMimeType=application/bluecore;\n"; + write(root, "packaging/linux/app.desktop", marked); + write(root, "packaging/x.yaml", marked); + write(root, "README.md", "AzureKit trademark notice\n"); + let path = Path::new; + let inputs = [ + Input::rust(path("crates")), + Input::manifest(path("crates/x/Cargo.toml")), + Input::text(path("docs/x.txt")), + Input::text(path("packaging/x.desktop")), + Input::text_mark_above(path("packaging/linux/app.desktop")), + Input::text(path("packaging/x.yaml")), + ]; + let found = scan(root, &inputs, &VECTOR).unwrap(); + let expected = [ + ("crates/x/Cargo.toml", 3, "copperline"), + ("crates/x/src/lib.rs", 1, "bluecore"), + ("docs/x.txt", 1, "copperline"), + ("packaging/x.desktop", 1, "bluecore"), + ("packaging/x.yaml", 2, "bluecore"), + ]; + assert_eq!(hits(&found), expected.map(|(p, l, w)| (p.to_string(), l, w))); + } + + #[test] + fn the_tree_is_clean() { + // This crate's own sources hold none of the synthetic words outside their tests, and the + // lexer reads every one of them. + let base = Path::new(env!("CARGO_MANIFEST_DIR")); + let found = scan(base, &[Input::rust(Path::new("src"))], &VECTOR).unwrap(); + assert!(found.is_empty(), "{found:#?}"); + } + + #[test] + fn escapes_are_decoded_before_matching() { + for source in [r#""A\x7AureKit""#, r#""A\u{7A}ureKit""#, r#""A\u{7_A}ureKit""#, r#""Azure\u{4B}it""#] { + assert_eq!(literals(source), ["AzureKit"], "{source}"); + } + assert_eq!(literals(r#""Blue\x43ore""#), ["BlueCore"]); + // A continuation leaves out the line break and the indentation, and adds no space. + assert_eq!(literals("\"Blue\\\n Core\""), ["BlueCore"]); + assert_eq!(literals("\"Blue\\\r\n\tCore\""), ["BlueCore"]); + assert_eq!(literals(r#""say \"BlueCore\" \\ ok""#), [r#"say "BlueCore" \ ok"#]); + } + + #[test] + fn test_only_items_of_every_form_are_skipped() { + let source = r#"#[cfg(test)] pub mod t { const S: &str = "AzureKit"; } +#[cfg(test)] fn f() { let _ = "AzureKit"; } +#[cfg(test)] const C: &str = "AzureKit"; +#[cfg(test)] static D: [&str; 2] = ["AzureKit", "AzureKit"]; +#[cfg(test)] +#[allow(dead_code)] +fn g() -> [u8; 2] { let _ = "AzureKit"; [0, 1] } +# [ cfg ( test ) ] mod spaced { "AzureKit"; } +struct S { #[cfg(test)] probe: &'static str, label: &'static str } +fn h() { let s = S { #[cfg(test)] probe: "AzureKit", label: "one" }; } +#[cfg(test)] mod declared; +mod generic { + #[cfg(test)] + impl Probe for Pair where A: Clone, B: Copy { fn p() { let _ = "AzureKit"; } } +} +mod inner { + #![cfg(test)] + fn i() { let _ = "AzureKit"; } +} +#[cfg(test)] const PICK: &str = if true { "AzureKit" } else { "AzureKit" }; +#[cfg(/* a reason */ test)] const NOTED: &str = "AzureKit"; +#[cfg( // a reason + test)] const NOTED_LINE: &str = "AzureKit"; +#[cfg(test)] const fn k() -> u8 { 1 } +#[cfg(not(test))] const E: &str = "two"; +#[cfg(tests)] const F: &str = "three"; +fn live() { let _ = "four"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four"]); + assert_eq!(literals("#![cfg(test)]\nfn a() { \"AzureKit\"; }\nfn b() { \"AzureKit\"; }\n"), Vec::::new()); + } + + #[test] + fn test_only_arms_and_statements_end_after_their_last_block() { + let source = r#"fn pick(x: u8, c: bool) -> &'static str { + match x { + #[cfg(test)] 0 => if c { "AzureKit" } else { "AzureKit" }, + #[cfg(test)] 1 => if c { "AzureKit" } else if !c { "AzureKit" } else { "AzureKit" } + #[cfg(test)] 2 => { "AzureKit" } + 3 => "one", + #[cfg(test)] 4 => Probe { a: "AzureKit" }.label("AzureKit"), + #[cfg(test)] Probe { a: 5 } => "AzureKit", + #[cfg(test)] 6 => match c { true => "AzureKit", false => "AzureKit" } + #[cfg(test)] #[allow(unused)] 7 => unsafe { "AzureKit" } + _ => "two", + } +} +fn statements(c: bool) { + #[cfg(test)] if c { "AzureKit"; } else { "AzureKit"; } + let _ = "three"; + #[cfg(test)] { "AzureKit"; } + #[cfg(test)] probe! { "AzureKit" } + #[cfg(test)] crate::probe! /* noted */ { "AzureKit" } + let _ = "four"; + #[cfg(test)] Probe { a: "AzureKit" }.run("AzureKit"); + #[cfg(test)] 'outer: loop { "AzureKit"; } + #[cfg(test)] const { "AzureKit"; } + let _ = "five"; +} +fn tail() -> Probe { + #[cfg(test)] Probe { a: "AzureKit" }.with("AzureKit") +} +fn after() { let _ = "six"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six"]); + } + + #[test] + fn test_only_blocks_keep_their_method_calls_and_question_marks() { + let source = r#"fn statements(c: bool) -> Result<(), Probe> { + #[cfg(test)] { "x" }.replace("x", "AzureKit"); + let _ = "one"; + #[cfg(test)] unsafe { probe("x") }?; + #[cfg(test)] unsafe { probe("x") }?.with("AzureKit"); + let _ = "two"; + #[cfg(test)] { "x" } /* noted */ .replace("x", "AzureKit"); + #[cfg(test)] { "x" } // noted + .replace("x", "AzureKit"); + #[cfg(test)] match c { _ => probe("x") }?.with("AzureKit"); + #[cfg(test)] probe! { "x" }.with("AzureKit"); + #[cfg(test)] { (1, "x") }.0.with("AzureKit"); + let _ = "three"; + #[cfg(test)] { "AzureKit"; } + ..; + let _ = "four"; + Ok(()) +} +fn pick(x: u8, c: bool) -> String { + match x { + #[cfg(test)] 8 => if c { "x" } else { "y" }.to_string().replace("x", "AzureKit"), + 9 => "five".into(), + #[cfg(test)] 10 => { "x" }.replace("x", "AzureKit"), + _ => "six".into(), + } +} +fn tail() -> String { + #[cfg(test)] { "x" }.replace("x", "AzureKit") +} +fn after() { let _ = "seven"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six", "seven"]); + } + + #[test] + fn the_marker_counts_only_in_a_comment() { + let policy = Policy { allow_marker: Some("name-ok"), ..POLICY }; + let rust = |src: &str| scan_source(Path::new("lib.rs"), src, Kind::Rust, &policy).unwrap().len(); + assert_eq!(rust("let label = \"AzureKit name-ok\";"), 1); + assert_eq!(rust("let label = \"AzureKit\"; // name-ok: compatibility"), 0); + assert_eq!(rust("let label = \"AzureKit\"; /* name-ok */"), 0); + assert_eq!(rust("/* name-ok */ let label = \"AzureKit\";"), 0); + assert_eq!(rust("/* name-ok\n */ let label = \"AzureKit\";"), 1, "a block comment marks only its lines that hold the marker"); + assert_eq!(rust("/* a\n b name-ok */ let label = \"AzureKit\";"), 0); + assert_eq!(rust("/* a\n\n name-ok */ let label = \"AzureKit\";"), 0, "the marker's line is the comment's third"); + assert_eq!(rust("/* a\n name-ok\n */ let label = \"AzureKit\nx\";"), 1); + assert_eq!(rust("let a = \"name-ok\"; let b = \"AzureKit\";"), 1); + assert_eq!(rust("// name-ok\nlet label = \"AzureKit\";"), 1, "the line above does not count in Rust"); + assert_eq!(rust("let label = \"Azure\nKit\nAzureKit\"; // name-ok"), 0, "a mark on any line of the literal counts"); + } + + #[test] + fn letters_of_any_script_are_part_of_a_word() { + for policy in [POLICY, Policy { case: MatchCase::AsciiInsensitive, ..POLICY }] { + assert!(policy.words_in("éAzureKit").is_empty()); + assert!(policy.words_in("AzureKitß").is_empty()); + assert!(policy.words_in("AzureKit_2").is_empty()); + assert_eq!(policy.words_in("é AzureKit, é"), ["AzureKit"]); + } + } + + #[test] + fn case_follows_the_policy() { + assert!(POLICY.words_in("azurekit").is_empty()); + assert_eq!(Policy { case: MatchCase::AsciiInsensitive, ..POLICY }.words_in("azureKIT and amber TOOL"), ["Amber Tool", "AzureKit"]); + } + + #[test] + fn allowed_literals_and_exceptions_match_whole_text() { + fn group(text: &str) -> bool { + text.strip_prefix("AzureKit Design › ").is_some_and(|rest| !banned_display(rest)) + } + let policy = Policy { exceptions: &[group], ..POLICY }; + assert!(policy.words_in("AzureKit Design").is_empty()); + assert_eq!(policy.words_in("AzureKit Design extra"), ["AzureKit"]); + assert!(policy.words_in("AzureKit Design › Layout").is_empty()); + assert_eq!(policy.words_in("AzureKit Design › BlueCore Styles"), ["AzureKit", "BlueCore"]); + } + + #[test] + fn byte_and_c_strings_are_read_only_when_asked() { + let source = r##"let a = b"AzureKit"; let b = br#"AzureKit"#; let c = c"BlueCore"; let d = cr"BlueCore"; let e = b'"'; let f = b'\xFF'; let g = r#"plain"#;"##; + assert_eq!(literals(source), ["plain"]); + let bytes = super::literals(source, Literals { byte_strings: true, c_strings: false }).unwrap(); + assert_eq!(bytes.iter().map(|l| l.text.as_str()).collect::>(), ["AzureKit", "AzureKit", "plain"]); + let both = super::literals(source, Literals { byte_strings: true, c_strings: true }).unwrap(); + assert_eq!(both.len(), 5); + assert_eq!(literals("let r#type = 1; let s = \"BlueCore\";"), ["BlueCore"]); + } + + #[test] + fn raw_strings_close_at_the_same_number_of_hashes() { + assert_eq!(literals(r###"r##"a "# b"## "next""###), [r##"a "# b"##, "next"]); + assert_eq!(literals(r#"r"\x41""#), [r"\x41"]); + } + + #[test] + fn malformed_source_is_an_error() { + for (source, line) in [ + ("let a = \"open", 1), + ("\n let a = r#\"open\"", 2), + ("/* /* */", 1), + ("fn f() { }}", 1), + ("fn f() {\n", 1), + ("fn f( ]", 1), + (r#""\q""#, 1), + (r#""\x80""#, 1), + (r#""\x4""#, 1), + (r#""\u{D800}""#, 1), + (r#""\u{1234567}""#, 1), + (r#""\u{}""#, 1), + (r"let c = '\q';", 1), + (r"let c = '\n", 1), + ] { + let err = super::literals(source, Literals::default()).unwrap_err(); + assert_eq!(err.line, line, "{source}: {err}"); + } + let err = scan_source(Path::new("bad.rs"), "\"open", Kind::Rust, &POLICY).unwrap_err(); + assert!(matches!(err, Error::Syntax { .. }), "{err}"); + } + + #[test] + fn lines_count_crlf_and_words_at_literal_edges() { + let src = "fn a() {}\r\n\r\nconst A: &str = \"AzureKit\";\r\nconst B: &str = \"x\r\ny BlueCore\";\r\n"; + let found = scan_source(Path::new("lib.rs"), src, Kind::Rust, &POLICY).unwrap(); + assert_eq!(found.iter().map(|f| (f.line, f.word.as_str())).collect::>(), [(3, "AzureKit"), (4, "BlueCore")]); + assert_eq!(found[1].text, "x\ny BlueCore"); + let text = scan_source(Path::new("a.txt"), "one\r\nBlueCore\r\n", Kind::Text, &POLICY).unwrap(); + assert_eq!((text[0].line, text[0].text.as_str()), (2, "BlueCore")); + } + + #[test] + fn unreadable_and_oversized_inputs_are_errors() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + fs::create_dir_all(root.join("bad")).unwrap(); + fs::write(root.join("bad/lib.rs"), b"const S: &str = \"\xff\";").unwrap(); + let err = scan(root, &[Input::rust(Path::new("bad"))], &POLICY).unwrap_err(); + assert!(matches!(err, Error::InvalidUtf8 { .. }), "{err}"); + + write(root, "big/lib.rs", &"/* */".repeat(40)); + let small = Policy { limits: Limits { max_file_bytes: 199, ..DEFAULT_LIMITS }, ..POLICY }; + let err = scan(root, &[Input::rust(Path::new("big"))], &small).unwrap_err(); + assert!(matches!(err, Error::FileTooLarge { limit: 199, .. }), "{err}"); + let exact = Policy { limits: Limits { max_file_bytes: 200, ..DEFAULT_LIMITS }, ..POLICY }; + assert!(scan(root, &[Input::rust(Path::new("big"))], &exact).unwrap().is_empty()); + + write(root, "two/a.rs", "\"one\""); + write(root, "two/b.rs", "\"two\""); + let total = Policy { limits: Limits { max_total_bytes: 9, ..DEFAULT_LIMITS }, ..POLICY }; + let err = scan(root, &[Input::rust(Path::new("two"))], &total).unwrap_err(); + assert!(matches!(&err, Error::TotalTooLarge { path, .. } if path.ends_with("b.rs")), "{err}"); + + write(root, "deep/a/b/c/lib.rs", "\"one\""); + let shallow = Policy { limits: Limits { max_depth: 2, ..DEFAULT_LIMITS }, ..POLICY }; + let err = scan(root, &[Input::rust(Path::new("deep"))], &shallow).unwrap_err(); + assert!(matches!(err, Error::TooDeep { limit: 2, .. }), "{err}"); + let enough = Policy { limits: Limits { max_depth: 3, ..DEFAULT_LIMITS }, ..POLICY }; + assert!(scan(root, &[Input::rust(Path::new("deep"))], &enough).unwrap().is_empty()); + } + + #[cfg(unix)] + #[test] + fn folder_links_are_not_followed() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "outside/lib.rs", "\"AzureKit\""); + write(root, "src/lib.rs", "\"BlueCore\""); + std::os::unix::fs::symlink(root.join("outside"), root.join("src/linked")).unwrap(); + std::os::unix::fs::symlink(root.join("outside/lib.rs"), root.join("src/file_link.rs")).unwrap(); + std::os::unix::fs::symlink(root.join("gone"), root.join("src/dangling.txt")).unwrap(); + std::os::unix::fs::symlink(root.join("gone"), root.join("src/tests.rs")).unwrap(); + let found = scan(root, &[Input::rust(Path::new("src"))], &POLICY).unwrap(); + assert_eq!(hits(&found), [("src/file_link.rs".to_string(), 1, "AzureKit"), ("src/lib.rs".to_string(), 1, "BlueCore")]); + } + + #[test] + fn findings_are_sorted_and_files_read_once() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "src/b.rs", "\"BlueCore\"\n\"AzureKit BlueCore Amber Tool\""); + write(root, "src/a.rs", "\"AzureKit\""); + let src = Path::new("src"); + let inputs = [Input::rust(Path::new("src/b.rs")), Input::rust(src), Input::rust(src)]; + let found = scan(root, &inputs, &POLICY).unwrap(); + let expected = [ + ("src/a.rs", 1, "AzureKit"), + ("src/b.rs", 1, "BlueCore"), + ("src/b.rs", 2, "Amber Tool"), + ("src/b.rs", 2, "AzureKit"), + ("src/b.rs", 2, "BlueCore"), + ]; + assert_eq!(hits(&found), expected.map(|(p, l, w)| (p.to_string(), l, w))); + assert_eq!(found[0].to_string(), format!("{}:1: \"AzureKit\" in \"AzureKit\"", Path::new("src").join("a.rs").display())); + let twice = [Input::rust(src), Input::text(Path::new("src/a.rs"))]; + let err = scan(root, &twice, &POLICY).unwrap_err(); + assert!(matches!(&err, Error::Conflict { path } if path.ends_with("a.rs")), "{err}"); + } + + #[test] + fn policies_that_match_nothing_are_errors() { + let empty: &[&str] = &[]; + for policy in [Policy::new(empty), Policy::new(&["AzureKit", " "]), Policy { allow_marker: Some(""), ..POLICY }] { + let err = scan_source(Path::new("f"), "", Kind::Text, &policy).unwrap_err(); + assert!(matches!(err, Error::Policy(_)), "{err}"); + } + } +} From 6701acfcf1f13757f4485755722dc27d97fe57c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:03:39 -0800 Subject: [PATCH 04/47] craft-testkit: bound collection and use-path allocations and fix guard edge cases - fonts::collection counts the table directories from each face's numTables before reading any record, then adds the tables one face at a time, so oversized input returns OutputTooLarge without keeping a directory for every face. - fonts::rename_family keeps the rest of each renamed full name, so a family name stored inside that suffix is refused with ConflictingNameStorage. - The guards read `use<...>` as a capturing bound, not a declaration, and keep use paths of at most eight segments, so a long prefix shared by many names is not copied into each. - std_instant finds the modules of a file that a #[path] attribute names next to that file, separately from a plain load of the same file. - predefined_quit reports ::quit. - wgsl_float_literals ends line comments and counts lines at every WGSL line break, and skips digits inside Unicode identifiers. --- crates/testkit/README.md | 2 +- crates/testkit/src/fonts.rs | 59 ++++++--- crates/testkit/src/guards.rs | 233 +++++++++++++++++++++++---------- crates/testkit/tests/fonts.rs | 34 +++++ crates/testkit/tests/guards.rs | 68 ++++++++++ 5 files changed, 303 insertions(+), 93 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 1e1a254e9f..fd2c621ec7 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -6,7 +6,7 @@ Source-level platform regression guards and verification utilities for the Craft `craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications: -1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. +1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::`, in the qualified form `::quit`, and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. 2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value, rounded to `f64`, exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. A literal that exceeds the maximum by less than `f64` precision rounds to the maximum and is not reported. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. `f32::MAX` can be written as the hex float `0x1.fffffep+127f`, which equals it, or as the decimal `3.4028234663852886e38`, which rounds to it. 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index 04345b66a2..cfc3096a0c 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -143,24 +143,26 @@ pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result, Font /// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is /// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or /// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the -/// 4 GiB that its 32-bit offsets reach or cannot be allocated. +/// 4 GiB that its 32-bit offsets reach or cannot be allocated. The headers and table directories are +/// counted from each face's `numTables` before any table record is read, so faces whose directories +/// alone pass 4 GiB return [`FontError::OutputTooLarge`] even when a table record is out of range. pub fn collection(faces: &[&[u8]]) -> Result, FontError> { if faces.is_empty() { return Err(FontError::EmptyCollection); } - let directories = faces.iter().map(|face| directory(face)).collect::, _>>()?; let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?; - let size = collection_size(&directories)?; + let size = collection_size(faces)?; let mut out = Vec::new(); out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?; out.extend_from_slice(b"ttcf"); out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); out.extend_from_slice(&count.to_be_bytes()); out.resize(SFNT_HEADER + faces.len() * 4, 0); - for (index, (face, tables)) in faces.iter().zip(&directories).enumerate() { + for (index, face) in faces.iter().enumerate() { + let tables = directory(face)?; let directory = offset32(out.len())?; put_u32(&mut out, SFNT_HEADER + index * 4, directory)?; - write_face(&mut out, face, tables)?; + write_face(&mut out, face, &tables)?; } Ok(out) } @@ -176,11 +178,7 @@ struct Table { /// Reads a standalone face's table directory, checking that every record and table lies in `face`. fn directory(face: &[u8]) -> Result, FontError> { - let version = bytes_at(face, 0, 4)?; - if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { - return Err(FontError::UnsupportedFace); - } - let count = usize::from(u16_at(face, 4)?); + let count = table_count(face)?; bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?; let mut tables = Vec::with_capacity(count); for index in 0..count { @@ -194,6 +192,15 @@ fn directory(face: &[u8]) -> Result, FontError> { Ok(tables) } +/// Reads a standalone face's sfnt version and `numTables`, without reading the table records. +fn table_count(face: &[u8]) -> Result { + let version = bytes_at(face, 0, 4)?; + if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { + return Err(FontError::UnsupportedFace); + } + Ok(usize::from(u16_at(face, 4)?)) +} + /// Whether `table` shares bytes with the table directory or with another table of the face. fn shares_bytes(tables: &[Table], table: &Table) -> bool { let end = table.offset + table.length; @@ -203,18 +210,24 @@ fn shares_bytes(tables: &[Table], table: &Table) -> bool { } /// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches. -fn collection_size(directories: &[Vec
]) -> Result { - let mut size = u64::try_from(SFNT_HEADER + directories.len() * 4).map_err(|_| FontError::OutputTooLarge)?; - for tables in directories { - let directory = SFNT_HEADER + tables.len() * TABLE_RECORD; - size = size.checked_add(u64::try_from(directory).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; - for table in tables { - let padded = u64::try_from(table.length).map_err(|_| FontError::OutputTooLarge)?.div_ceil(4) * 4; - size = size.checked_add(padded).ok_or(FontError::OutputTooLarge)?; - } +/// +/// The headers and table directories are added up first, from each face's `numTables` alone, so that +/// input whose directories already pass the limit is refused before any table record is read. The +/// tables are then added one face at a time, and no face's directory is kept. +fn collection_size(faces: &[&[u8]]) -> Result { + let add = |size: u64, bytes: usize| -> Result { + let size = size.checked_add(u64::try_from(bytes).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; + if size > u64::from(u32::MAX) { Err(FontError::OutputTooLarge) } else { Ok(size) } + }; + let mut size = add(0, SFNT_HEADER)?; + size = add(size, faces.len().checked_mul(4).ok_or(FontError::OutputTooLarge)?)?; + for face in faces { + size = add(size, SFNT_HEADER + table_count(face)? * TABLE_RECORD)?; } - if size > u64::from(u32::MAX) { - return Err(FontError::OutputTooLarge); + for face in faces { + for table in directory(face)? { + size = add(size, table.length.div_ceil(4).checked_mul(4).ok_or(FontError::OutputTooLarge)?)?; + } } usize::try_from(size).map_err(|_| FontError::OutputTooLarge) } @@ -342,6 +355,10 @@ fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Resul None => { let edit = renamed(string, face, from, to)?; let edited = edit.is_some(); + if let Some(edit) = &edit { + // The rest of a full name, after the family name, must keep its bytes. + kept.push(edit.range.end..string.range.end); + } edits.extend(edit); read.insert(key, edited); edited diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 77006af6f3..8a68eb0b72 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -114,6 +114,11 @@ impl AsFileSource for &(&str, String) { /// read as far as this depth, so hostile nesting cannot exhaust the stack. const MAX_NESTING: usize = 64; +/// The most segments of a `use` path that [`use_leaves`] keeps. The guards compare paths of at most +/// three segments, so a leaf with a longer path is left out, and a long prefix shared by many leaves +/// is not copied into each of them. +const MAX_USE_PATH: usize = 8; + /// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text /// except string contents, which `cfg` predicates compare. #[derive(Debug, Clone, PartialEq, Eq)] @@ -344,6 +349,29 @@ fn then_path(toks: &[Token], i: usize, name: impl Fn(&str) -> bool) -> bool { && toks.get(i + 2).is_some_and(|t| matches!(&t.kind, Kind::Ident(s) if name(s))) } +/// Whether the path that ends at `toks[i]` starts right after the `<` of a qualified path, as in +/// `::quit`, rather than after the `<` of generic arguments (`Vec::new`, +/// `f::`). +fn opens_qualified_path(toks: &[Token], i: usize) -> bool { + let mut start = i; + while start >= 2 && toks[start - 1].is_punct(':') && toks[start - 2].is_punct(':') { + if start >= 3 && matches!(toks[start - 3].kind, Kind::Ident(_)) { + start -= 3; + } else { + start -= 2; + break; + } + } + start >= 1 + && toks[start - 1].is_punct('<') + && match start.checked_sub(2).map(|j| &toks[j].kind) { + None => true, + Some(Kind::Ident(s)) => KEYWORDS.contains(&s.as_str()), + Some(Kind::Punct(c)) => !matches!(*c, ':' | '>'), + Some(_) => false, + } +} + /// One name a `use` declaration brings into scope. #[derive(Debug)] struct UseLeaf { @@ -361,7 +389,8 @@ fn use_leaves(toks: &[Token]) -> Vec { let mut leaves = Vec::new(); let mut i = 0; while i < toks.len() { - if toks[i].is_ident("use") && !continues_a_path(toks, i) { + // `use<...>` is a precise capturing bound on `impl Trait`, not a `use` declaration. + if toks[i].is_ident("use") && !continues_a_path(toks, i) && !toks.get(i + 1).is_some_and(|t| t.is_punct('<')) { let start = i; let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); let mut pos = i + 1; @@ -389,24 +418,30 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta *pos += 2; continue; } - let mut path = prefix.clone(); - if name != "self" { - path.push(name.clone()); - } - let mut bound = path.last().cloned(); - if toks.get(*pos).is_some_and(|t| t.is_ident("as")) - && let Some(Kind::Ident(alias)) = toks.get(*pos + 1).map(|t| &t.kind) - { - bound = Some(alias.clone()); - *pos += 2; - } - if let Some(bound) = bound.filter(|b| b != "_") { - out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + let length = prefix.len() + usize::from(name != "self"); + let alias = match (toks.get(*pos), toks.get(*pos + 1).map(|t| &t.kind)) { + (Some(t), Some(Kind::Ident(alias))) if t.is_ident("as") => { + *pos += 2; + Some(alias) + } + _ => None, + }; + if length <= MAX_USE_PATH { + let mut path = prefix.clone(); + if name != "self" { + path.push(name.clone()); + } + let bound = alias.cloned().or_else(|| path.last().cloned()); + if let Some(bound) = bound.filter(|b| b != "_") { + out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + } } break; } Kind::Punct('*') => { - out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + if prefix.len() <= MAX_USE_PATH { + out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + } *pos += 1; break; } @@ -797,19 +832,20 @@ fn join_path(parent: &str, child: &str) -> String { /// The paths, normalized, where the module `decl` declared in the file at `parent` (normalized) can be. /// -/// The modules of `lib.rs`, `main.rs` and `mod.rs` are in the file's folder, and those of any other file -/// are in the folder named after its stem. Each inline module around the declaration adds a folder named +/// The modules of `lib.rs`, `main.rs` and `mod.rs`, and with `path_loaded`, of a file that a `#[path]` +/// attribute names, are in the file's folder, and those of any other file are in the folder named after +/// its stem. Each inline module around the declaration adds a folder named /// after it, or with a `path` attribute, moves to that path relative to the current folder (without the /// stem folder). The module is then `.rs` or `/mod.rs` there, or with a `path` attribute, that /// path relative to the current folder, again without the stem folder. -fn module_files(parent: &str, decl: &ModDecl) -> Vec { +fn module_files(parent: &str, decl: &ModDecl, path_loaded: bool) -> Vec { let (dir, file) = match parent.rsplit_once('/') { Some(("", file)) => ("/", file), Some(split) => split, None => ("", parent), }; let mut folder = dir.to_string(); - let mut stem = (!matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); + let mut stem = (!path_loaded && !matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); for inline in &decl.inline { if let Some(attr) = &inline.path_attribute { folder = join_path(&folder, attr); @@ -839,67 +875,88 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { for (i, path) in paths.iter().enumerate() { index.entry(path.as_str()).or_default().push(i); } - // The files each declaration names, in the order of `decls`. - let children: Vec)>> = decls - .iter() - .enumerate() - .map(|(parent, file_decls)| { - file_decls - .iter() - .map(|decl| { - let files = - module_files(&paths[parent], decl).iter().flat_map(|c| index.get(c.as_str()).into_iter().flatten().copied()).collect(); - (decl.native, files) - }) - .collect() + // rustc reads a file that a `#[path]` attribute names as if it were a `mod.rs`, so the modules it + // declares are in its own folder rather than its stem folder. Each file is therefore two nodes: node + // `2 * file` for the file loaded by a plain `mod name;` (or as a crate root), and node `2 * file + 1` + // for the file loaded through a `#[path]` attribute. Each node lists the nodes its declarations name, + // with whether the declaration is in a native-only item. + let edges: Vec> = (0..paths.len() * 2) + .map(|node| { + let (parent, path_loaded) = (node / 2, node % 2 == 1); + let mut targets = Vec::new(); + for decl in &decls[parent] { + let by_path = usize::from(decl.module.path_attribute.is_some()); + for candidate in module_files(&paths[parent], decl, path_loaded) { + for &j in index.get(candidate.as_str()).into_iter().flatten() { + targets.push((decl.native, 2 * j + by_path)); + } + } + } + targets }) .collect(); + // The nodes that are loaded: a file that no loaded node names is a crate root, loaded plainly, and a + // node is loaded when a loaded node names it. Every file starts out loaded plainly, and the set is + // narrowed until it stops changing, or after `MAX_MODULE_ROUNDS` rounds. + let mut loaded: Vec = (0..paths.len() * 2).map(|node| node % 2 == 0).collect(); + let mut named = vec![false; paths.len()]; + for _ in 0..MAX_MODULE_ROUNDS { + let mut reached = vec![false; paths.len() * 2]; + for (node, targets) in edges.iter().enumerate() { + if loaded[node] { + for &(_, target) in targets { + reached[target] = true; + } + } + } + named = (0..paths.len()).map(|j| reached[2 * j] || reached[2 * j + 1]).collect(); + let next: Vec = (0..paths.len() * 2).map(|node| reached[node] || (node % 2 == 0 && !named[node / 2])).collect(); + if next == loaded { + break; + } + loaded = next; + } + // Files the web build compiles: crate roots, and every file a declaration outside a native-only item // of such a file names. - let mut named = vec![false; paths.len()]; - for (_, files) in children.iter().flatten() { - for &j in files { - named[j] = true; - } - } - let mut web = vec![false; paths.len()]; - let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).collect(); - for &j in &queue { - web[j] = true; + let mut web = vec![false; paths.len() * 2]; + let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).map(|j| 2 * j).collect(); + for &node in &queue { + web[node] = true; } while let Some(parent) = queue.pop() { - for (_, files) in children[parent].iter().filter(|(is_native, _)| !is_native) { - for &j in files { - if !web[j] { - web[j] = true; - queue.push(j); - } + for &(_, target) in edges[parent].iter().filter(|(is_native, _)| !is_native) { + if !web[target] { + web[target] = true; + queue.push(target); } } } - // Files a native-only declaration names, and their descendants. - let mut native = vec![false; paths.len()]; - let mut mark = |files: &[usize], queue: &mut Vec| { - for &j in files { - if !native[j] { - native[j] = true; - queue.push(j); - } + // Files a native-only declaration of a loaded node names, and their descendants. + let mut native = vec![false; paths.len() * 2]; + let starts = edges.iter().enumerate().filter(|&(node, _)| loaded[node]).flat_map(|(_, targets)| targets.iter()); + for &(_, target) in starts.filter(|(is_native, _)| *is_native) { + if !native[target] { + native[target] = true; + queue.push(target); } - }; - for (_, files) in children.iter().flatten().filter(|(is_native, _)| *is_native) { - mark(files, &mut queue); } while let Some(parent) = queue.pop() { - for (_, files) in &children[parent] { - mark(files, &mut queue); + for &(_, target) in &edges[parent] { + if !native[target] { + native[target] = true; + queue.push(target); + } } } - native.iter().zip(&web).map(|(&n, &w)| n && !w).collect() + (0..paths.len()).map(|j| (native[2 * j] || native[2 * j + 1]) && !web[2 * j] && !web[2 * j + 1]).collect() } +/// The most rounds [`native_only_files`] spends narrowing the set of loaded files. +const MAX_MODULE_ROUNDS: usize = 16; + /// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { if lines.is_empty() { @@ -919,7 +976,8 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. /// /// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace -/// or line breaks around `::` do not hide a call. It also follows a `use` that renames muda's type +/// or line breaks around `::` do not hide a call. A qualified path such as `::quit` +/// is reported too. It also follows a `use` that renames muda's type /// (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's /// `PredefinedMenuItem` is not followed. Each finding names the line where the /// type's name starts, once per line, in line order. @@ -943,7 +1001,10 @@ where for (i, tok) in toks.iter().enumerate() { let Kind::Ident(name) = &tok.kind else { continue }; let named = name == "PredefinedMenuItem" || (aliases.contains(name) && !continues_a_path(&toks, i)); - if named && then_path(&toks, i + 1, |s| s == "quit" || s == "Quit") { + let quit = |at: usize| then_path(&toks, at, |s| s == "quit" || s == "Quit"); + // `::quit`, a qualified path to the same function. + let qualified = || toks.get(i + 1).is_some_and(|t| t.is_punct('>')) && quit(i + 2) && opens_qualified_path(&toks, i); + if named && (quit(i + 1) || qualified()) { lines.insert(tok.line); } } @@ -974,8 +1035,8 @@ where /// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the /// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside /// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or -/// `name/mod.rs` next to `lib.rs`, `main.rs` or `mod.rs`, and in the folder named after any other file's -/// stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration +/// `name/mod.rs` next to `lib.rs`, `main.rs`, `mod.rs` or a file that a `#[path]` attribute names, and in +/// the folder named after any other file's stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration /// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way /// (for example all from one `rust_sources` call), and a crate root other than `lib.rs` or `main.rs` /// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline @@ -1050,7 +1111,11 @@ where findings } -/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, keeping line breaks. +/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, and write each WGSL line break as +/// `\n`: line feed, vertical tab, form feed, carriage return, carriage return and line feed as one +/// break, next line (U+0085), line separator (U+2028) and paragraph separator (U+2029) +/// (). A line comment ends at any of them, and `str::lines` +/// then counts lines the way WGSL does. fn mask_wgsl_comments(code: &str) -> String { let chars: Vec = code.chars().collect(); let len = chars.len(); @@ -1061,10 +1126,15 @@ fn mask_wgsl_comments(code: &str) -> String { while i < len { let c = chars[i]; let next = chars.get(i + 1).copied(); - if c == '\n' { + let line_break = match c { + '\r' if next == Some('\n') => 2, + '\n' | '\u{000B}' | '\u{000C}' | '\r' | '\u{0085}' | '\u{2028}' | '\u{2029}' => 1, + _ => 0, + }; + if line_break > 0 { in_line = false; out.push('\n'); - i += 1; + i += line_break; } else if in_line { out.push(' '); i += 1; @@ -1183,7 +1253,9 @@ fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { /// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats /// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and /// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. -/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. +/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. A `//` comment +/// ends at any WGSL line break, a lone carriage return included, and finding lines count every one of them. +/// * **Identifiers**: digits inside an identifier, `π1e39` included, are not a literal. pub fn wgsl_float_literals(wgsl: &str) -> Vec { wgsl_float_literals_in([("", wgsl)]) } @@ -1205,7 +1277,14 @@ where let mut i = 0; while i < code.len() { let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); - let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + // Outside comments, a character that is not ASCII and not blankspace (U+200E, U+200F) is part of an + // identifier, as in `π1e39`. + let word_before = digit_or_dot + && i > 0 + && (code[i - 1].is_ascii_alphanumeric() + || code[i - 1] == b'_' + || code[i - 1] == b'.' + || (!code[i - 1].is_ascii() && !line[..i].ends_with(['\u{200E}', '\u{200F}']))); if !digit_or_dot || word_before { i += 1; continue; @@ -1392,3 +1471,15 @@ pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> files.sort_by(|a, b| a.0.cmp(&b.0)); Ok(files) } + +#[cfg(test)] +mod tests { + use super::{MAX_USE_PATH, lex_rust, use_leaves}; + + #[test] + fn use_leaves_keep_no_path_longer_than_the_limit() { + let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); + let paths: Vec> = use_leaves(&lex_rust(&source)).into_iter().map(|leaf| leaf.path).collect(); + assert_eq!(paths, vec![vec!["a"; MAX_USE_PATH], vec!["std", "time", "Instant"], vec!["std", "time"]]); + } +} diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs index 6ff688c7fa..56e20b79ac 100644 --- a/crates/testkit/tests/fonts.rs +++ b/crates/testkit/tests/fonts.rs @@ -298,6 +298,16 @@ fn rename_keeps_a_style_sharing_the_full_name_suffix() { assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]); } +#[test] +fn rename_rejects_a_family_name_in_the_full_name_suffix() { + // The full name "A A" is stored once, and the family name (ID 1) is its last "A". Renaming the + // family would change the full name's suffix " A". + let records = + [Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 6 }, Rec { platform: 3, encoding: 1, name_id: 1, offset: 4, length: 2 }]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16("A A")))]); + assert_eq!(rename_family(&font, "A", "B"), Err(FontError::ConflictingNameStorage)); +} + #[test] fn rename_updates_name_checksum() { let font = family_face(&[win(1, FROM), win(2, "Regular")]); @@ -580,3 +590,27 @@ fn collection_rejects_offset_overflow() { let faces = vec![&big[..]; 4096]; assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); } + +#[test] +fn collection_rejects_directories_past_the_offset_limit() { + // 65,536 references to one face with 4,096 empty tables: the table directories alone take more + // than 4 GiB. The function refuses without keeping a directory for every face. + let tables: Vec<(&[u8; 4], Vec)> = (0..4096).map(|_| (b"zzzz", Vec::new())).collect(); + let many = face(&tables); + let faces = vec![&many[..]; 65536]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} + +#[test] +fn collection_counts_directories_before_reading_records() { + // The same number of directories, each with every table record out of range. The size limit is + // found from the faces' table counts before any table record is read. + let mut directory = vec![0u8; 12 + 16 * 4096]; + set32(&mut directory, 0, 0x0001_0000); + set16(&mut directory, 4, 4096); + for index in 0..4096 { + set32(&mut directory, 12 + 16 * index + 8, u32::MAX); + } + let faces = vec![&directory[..]; 65536]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 169fdd5734..e568422645 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -412,6 +412,21 @@ fn menu() { assert!(predefined_quit([("src/menu.rs", other_crate)]).is_empty()); } +#[test] +fn predefined_quit_reports_a_qualified_path() { + let source = r#" +use muda::PredefinedMenuItem as Item; +fn menu() { + let a = ::quit(None); + let b = < PredefinedMenuItem >::quit(None); + let c = ::quit(None); + let d = Vec::::quit(None); + let e = Wrapper::quit(None); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 6]); +} + #[test] fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { let source = r#" @@ -566,6 +581,12 @@ use std::time::{ assert_eq!(findings[0].text, "Instant"); } +#[test] +fn std_instant_reads_a_use_after_a_precise_capturing_bound() { + let source = "fn clock() -> impl Fn() + use<> {\n use std::{time::Instant};\n || { let _ = Instant::now(); }\n}\n"; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![2]); +} + #[test] fn std_instant_does_not_count_brace_character_literals_as_braces() { let source = r#" @@ -601,6 +622,15 @@ fn deeply_nested_use_groups_and_cfg_predicates_do_not_exhaust_the_stack() { assert_eq!(lines(&std_instant([("src/shallow.rs", shallow)])), vec![1]); } +#[test] +fn a_long_use_path_shared_by_many_names_is_read_without_copying_it_to_each() { + // 10,000 path segments shared by 10,000 names, followed by a `use` the guard reports. + let names: Vec = (0..10_000).map(|n| format!("x{n}")).collect(); + let source = format!("use {}{{{}}};\nuse std::time::Instant;\n", "a::".repeat(10_000), names.join(", ")); + assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]); + assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty()); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } @@ -733,6 +763,28 @@ mod platform { assert_eq!(finding_paths(&std_instant(files)), vec!["src/a/native.rs", "src/a/native/clock.rs"]); } +#[test] +fn std_instant_finds_the_modules_of_a_path_attribute_file_next_to_it() { + let lib = r#" +#[cfg(not(target_arch = "wasm32"))] +#[path = "platform/native.rs"] +mod native; +"#; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform/native.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/web.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/web.rs"]); +} + +#[test] +fn std_instant_resolves_a_file_loaded_both_plainly_and_by_path_attribute_once_for_each() { + // `platform.rs` is a web module, and a native-only `#[path]` declaration loads it again. Its + // `mod clock;` is `src/platform/clock.rs` for the first and `src/clock.rs` for the second. + let lib = "mod platform;\n#[cfg(unix)]\n#[path = \"platform.rs\"]\nmod native;\n"; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/clock.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/platform/clock.rs"]); +} + #[test] fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() { let lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(70), "}\n".repeat(70)); @@ -807,6 +859,22 @@ fn wgsl_half_floats_use_the_f16_range() { assert_eq!(findings[0].text, "70000.0"); } +#[test] +fn wgsl_line_comments_end_and_lines_count_at_every_line_break() { + let shader = "// note\rconst A: f32 = 4e38;\r\nconst B: f32 = 5e38;\n// x\u{2028}const C: f32 = 6e38;\u{2029}const D: f32 = 7e38;\u{000B}// y\u{0085}const E: f32 = 8e38;\u{000C}const F: f32 = 9e38;"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2, 3, 5, 6, 8, 9]); + assert_eq!(findings[0].text, "4e38"); +} + +#[test] +fn wgsl_digits_inside_unicode_identifiers_are_not_literals() { + let shader = "const π1e39 = 1.0;\nconst é2e40: f32 = 2.0;\nconst A: f32 =\u{200E}1e39;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![3]); + assert_eq!(findings[0].text, "1e39"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn test_rust_sources_filtering() { From ba866e1e45aa27a2dad6624c1f534632c3529a05 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Sat, 7 Nov 2026 08:37:23 -0500 Subject: [PATCH 05/47] craft-gpu: add the GPU job traits and the shared providers. This carries over crates/gpu, crates/gpu-wgpu, crates/gpu-null, and crates/gpu-providers from the cut-down #160 branch, with minimal workspace wiring. None of these crates names a vendor or any app. craft-gpu defines GpuJob and ProviderRegistry. craft-gpu-null is an in-memory context for tests. craft-gpu-providers holds the shared craft.* WGSL providers. craft-gpu-wgpu is the wgpu backend, native and WebGPU. --- Cargo.toml | 7 ++ crates/gpu-null/Cargo.toml | 13 +++ crates/gpu-null/src/lib.rs | 46 ++++++++++ crates/gpu-providers/Cargo.toml | 16 ++++ crates/gpu-providers/src/composite.rs | 69 ++++++++++++++ crates/gpu-providers/src/echo.rs | 18 ++++ crates/gpu-providers/src/lib.rs | 33 +++++++ crates/gpu-providers/src/mask.rs | 35 +++++++ crates/gpu-providers/src/noop.rs | 14 +++ crates/gpu-providers/src/params.rs | 13 +++ crates/gpu-providers/src/readback.rs | 38 ++++++++ crates/gpu-providers/src/tests.rs | 127 ++++++++++++++++++++++++++ crates/gpu-wgpu/Cargo.toml | 31 +++++++ crates/gpu-wgpu/src/lib.rs | 89 ++++++++++++++++++ crates/gpu/Cargo.toml | 17 ++++ crates/gpu/src/caps.rs | 23 +++++ crates/gpu/src/chunk.rs | 11 +++ crates/gpu/src/context.rs | 23 +++++ crates/gpu/src/error.rs | 14 +++ crates/gpu/src/job.rs | 28 ++++++ crates/gpu/src/lib.rs | 27 ++++++ crates/gpu/src/provider.rs | 8 ++ crates/gpu/src/readback.rs | 50 ++++++++++ crates/gpu/src/registry.rs | 39 ++++++++ crates/gpu/src/tests.rs | 69 ++++++++++++++ docs/gpu-backends.md | 14 +++ docs/gpu-providers.md | 14 +++ 27 files changed, 886 insertions(+) create mode 100644 crates/gpu-null/Cargo.toml create mode 100644 crates/gpu-null/src/lib.rs create mode 100644 crates/gpu-providers/Cargo.toml create mode 100644 crates/gpu-providers/src/composite.rs create mode 100644 crates/gpu-providers/src/echo.rs create mode 100644 crates/gpu-providers/src/lib.rs create mode 100644 crates/gpu-providers/src/mask.rs create mode 100644 crates/gpu-providers/src/noop.rs create mode 100644 crates/gpu-providers/src/params.rs create mode 100644 crates/gpu-providers/src/readback.rs create mode 100644 crates/gpu-providers/src/tests.rs create mode 100644 crates/gpu-wgpu/Cargo.toml create mode 100644 crates/gpu-wgpu/src/lib.rs create mode 100644 crates/gpu/Cargo.toml create mode 100644 crates/gpu/src/caps.rs create mode 100644 crates/gpu/src/chunk.rs create mode 100644 crates/gpu/src/context.rs create mode 100644 crates/gpu/src/error.rs create mode 100644 crates/gpu/src/job.rs create mode 100644 crates/gpu/src/lib.rs create mode 100644 crates/gpu/src/provider.rs create mode 100644 crates/gpu/src/readback.rs create mode 100644 crates/gpu/src/registry.rs create mode 100644 crates/gpu/src/tests.rs create mode 100644 docs/gpu-backends.md create mode 100644 docs/gpu-providers.md diff --git a/Cargo.toml b/Cargo.toml index bd08fa725e..2a7dcfa648 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -91,6 +91,10 @@ craft-html = { path = "crates/html" } craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } +craft-gpu = { path = "crates/gpu" } +craft-gpu-null = { path = "crates/gpu-null" } +craft-gpu-providers = { path = "crates/gpu-providers" } +craft-gpu-wgpu = { path = "crates/gpu-wgpu" } craft-i18n = { path = "crates/i18n" } craft-idml = { path = "crates/idml" } craft-indd = { path = "crates/indd" } @@ -193,6 +197,9 @@ proptest = "1" encoding_rs = "0.8" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } +# Foundation crates for craft-gpu-wgpu. The versions match the ones the app repos already pin. +pollster = "0.4" +wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] } [workspace.lints.rust] unsafe_code = "forbid" diff --git a/crates/gpu-null/Cargo.toml b/crates/gpu-null/Cargo.toml new file mode 100644 index 0000000000..adb907597f --- /dev/null +++ b/crates/gpu-null/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-gpu-null" +description = "In-memory GpuContext for CI and headless tests" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs new file mode 100644 index 0000000000..66925b4901 --- /dev/null +++ b/crates/gpu-null/src/lib.rs @@ -0,0 +1,46 @@ +//! CPU-only [`GpuContext`](craft_gpu::GpuContext) for tests and CI. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; + +/// In-memory buffer store; no GPU hardware required. +pub struct NullContext { + caps: DeviceCaps, + worker_kind: WorkerKind, + buffers: Vec>, +} + +impl NullContext { + pub fn new(worker_kind: WorkerKind) -> Self { + Self { + caps: DeviceCaps { backend_name: "null".into(), device_name: "null".into(), ..DeviceCaps::default() }, + worker_kind, + buffers: Vec::new(), + } + } +} + +impl GpuContext for NullContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + self.worker_kind + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.buffers.push(bytes.to_vec()); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { + self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } +} diff --git a/crates/gpu-providers/Cargo.toml b/crates/gpu-providers/Cargo.toml new file mode 100644 index 0000000000..b581b81123 --- /dev/null +++ b/crates/gpu-providers/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-gpu-providers" +description = "Shared GpuProvider implementations (composite, readback, …) — no app deps" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } + +[dev-dependencies] +craft-gpu-null = { workspace = true } diff --git a/crates/gpu-providers/src/composite.rs b/crates/gpu-providers/src/composite.rs new file mode 100644 index 0000000000..aeda3ead04 --- /dev/null +++ b/crates/gpu-providers/src/composite.rs @@ -0,0 +1,69 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +use crate::params::parse_u32; + +/// CPU stand-in for FilmCraft `composite.wgsl` Normal/Dissolve premultiplied "over" until WGSL runs on wgpu. +pub struct PremulCompositeProvider; + +impl GpuProvider for PremulCompositeProvider { + fn id(&self) -> &'static str { + "craft.composite.premul" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize; + let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize; + let len = width.saturating_mul(height).saturating_mul(4); + let (dst_h, src_h) = match job.inputs.as_slice() { + [a, b] => (a, b), + [a] => (a, a), + _ => { + return Err(GpuFault::InvalidJob("craft.composite.premul expects one or two RGBA8 inputs (backdrop, layer)".into())); + } + }; + let dst_bytes = ctx.read_buffer(*dst_h)?; + let src_bytes = ctx.read_buffer(*src_h)?; + if dst_bytes.len() < len || src_bytes.len() < len { + return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into())); + } + let mut out = vec![0u8; len]; + for px in 0..width.saturating_mul(height) { + let i = px * 4; + let mut dst = straight_to_premul([dst_bytes[i], dst_bytes[i + 1], dst_bytes[i + 2], dst_bytes[i + 3]]); + let src = straight_to_premul([src_bytes[i], src_bytes[i + 1], src_bytes[i + 2], src_bytes[i + 3]]); + premul_over(&mut dst, src); + let straight = premul_to_straight(dst); + out[i..i + 4].copy_from_slice(&straight); + } + let handle = ctx.upload_buffer("craft.composite.premul.out", &out)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} + +/// Premultiplied `src` over premultiplied `dst` (`filmcraft_render` / `composite.wgsl` Normal path). +fn premul_over(dst: &mut [f32; 4], src: [f32; 4]) { + let k = 1.0 - src[3]; + for c in 0..4 { + dst[c] = src[c] + dst[c] * k; + } +} + +fn straight_to_premul(p: [u8; 4]) -> [f32; 4] { + let a = f32::from(p[3]) / 255.0; + let s = a / 255.0; + [f32::from(p[0]) * s, f32::from(p[1]) * s, f32::from(p[2]) * s, a] +} + +fn premul_to_straight(p: [f32; 4]) -> [u8; 4] { + let a = p[3].clamp(0.0, 1.0); + if a <= f32::EPSILON { + return [0, 0, 0, 0]; + } + let inv = 255.0 / a; + [ + (p[0] * inv).round().clamp(0.0, 255.0) as u8, + (p[1] * inv).round().clamp(0.0, 255.0) as u8, + (p[2] * inv).round().clamp(0.0, 255.0) as u8, + (a * 255.0).round().clamp(0.0, 255.0) as u8, + ] +} diff --git a/crates/gpu-providers/src/echo.rs b/crates/gpu-providers/src/echo.rs new file mode 100644 index 0000000000..2fb356ceb3 --- /dev/null +++ b/crates/gpu-providers/src/echo.rs @@ -0,0 +1,18 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// Concatenates job params with bytes from the first input handle (shared test / debug provider). +pub struct EchoProvider; + +impl GpuProvider for EchoProvider { + fn id(&self) -> &'static str { + "craft.test.echo" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let mut data = job.params.0.clone(); + if let Some(&h) = job.inputs.first() { + data.extend_from_slice(&ctx.read_buffer(h)?); + } + Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: Some(data) }) + } +} diff --git a/crates/gpu-providers/src/lib.rs b/crates/gpu-providers/src/lib.rs new file mode 100644 index 0000000000..c310a6c4f1 --- /dev/null +++ b/crates/gpu-providers/src/lib.rs @@ -0,0 +1,33 @@ +//! Generic GPU providers extracted from app crates over time (craft-libs#7). + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod composite; +mod echo; +mod mask; +mod noop; +mod params; +mod readback; + +#[cfg(test)] +mod tests; + +use craft_gpu::{GpuProvider, ProviderRegistry}; + +pub use composite::PremulCompositeProvider; +pub use echo::EchoProvider; +pub use mask::MaskProvider; +pub use noop::NoopProvider; +pub use readback::ReadbackProvider; + +/// Default shared providers for worker/runtime init (`craft.*` ids only). +pub fn register_all() -> Vec> { + vec![Box::new(NoopProvider), Box::new(EchoProvider), Box::new(MaskProvider), Box::new(PremulCompositeProvider), Box::new(ReadbackProvider)] +} + +/// Register [`register_all`] providers into an existing registry. +pub fn register_all_into(registry: &mut ProviderRegistry) { + for provider in register_all() { + registry.register(provider); + } +} diff --git a/crates/gpu-providers/src/mask.rs b/crates/gpu-providers/src/mask.rs new file mode 100644 index 0000000000..41957c1f7b --- /dev/null +++ b/crates/gpu-providers/src/mask.rs @@ -0,0 +1,35 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +use crate::params::parse_u32; + +/// CPU stand-in for FilmCraft mask composite until WGSL runs on wgpu. +pub struct MaskProvider; + +impl GpuProvider for MaskProvider { + fn id(&self) -> &'static str { + "craft.mask" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize; + let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize; + let len = width.saturating_mul(height).saturating_mul(4); + let (base, mask) = match job.inputs.as_slice() { + [a, b] => (a, b), + [a] => (a, a), + _ => return Err(GpuFault::InvalidJob("craft.mask expects one or two RGBA inputs".into())), + }; + let base_bytes = ctx.read_buffer(*base)?; + let mask_bytes = ctx.read_buffer(*mask)?; + if base_bytes.len() < len || mask_bytes.len() < len { + return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into())); + } + let mut out = vec![0u8; len]; + for i in 0..len { + let m = mask_bytes[i]; + out[i] = ((u16::from(base_bytes[i]) * u16::from(m)) / 255) as u8; + } + let handle = ctx.upload_buffer("craft.mask.out", &out)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} diff --git a/crates/gpu-providers/src/noop.rs b/crates/gpu-providers/src/noop.rs new file mode 100644 index 0000000000..4ce8aef91a --- /dev/null +++ b/crates/gpu-providers/src/noop.rs @@ -0,0 +1,14 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// No-op dispatch for wiring tests; shared readback/composite providers live in sibling modules. +pub struct NoopProvider; + +impl GpuProvider for NoopProvider { + fn id(&self) -> &'static str { + "craft.noop" + } + + fn run(&self, _ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: None }) + } +} diff --git a/crates/gpu-providers/src/params.rs b/crates/gpu-providers/src/params.rs new file mode 100644 index 0000000000..2327aa3efa --- /dev/null +++ b/crates/gpu-providers/src/params.rs @@ -0,0 +1,13 @@ +use craft_gpu::GpuJobParams; + +pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option { + let bytes = params.0.as_slice(); + let start = bytes.windows(prefix.len()).position(|w| w == prefix)? + prefix.len(); + let rest = &bytes[start..]; + let end = rest.iter().position(|&b| b == b',' || b == b';').unwrap_or(rest.len()); + std::str::from_utf8(&rest[..end]).ok()?.parse().ok() +} + +pub(crate) fn params_contain(params: &GpuJobParams, needle: &[u8]) -> bool { + params.0.windows(needle.len()).any(|w| w == needle) +} diff --git a/crates/gpu-providers/src/readback.rs b/crates/gpu-providers/src/readback.rs new file mode 100644 index 0000000000..fb27f798ca --- /dev/null +++ b/crates/gpu-providers/src/readback.rs @@ -0,0 +1,38 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, chunk_buffer, f16_rgba_to_f32_bytes}; + +use crate::params::{params_contain, parse_u32}; + +/// CPU stand-in for accumulator/output readback (`read_accumulator` / `read_output` in FilmCraft gpu) until wgpu maps buffers. +pub struct ReadbackProvider; + +impl GpuProvider for ReadbackProvider { + fn id(&self) -> &'static str { + "craft.readback" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(0); + let height = parse_u32(&job.params, b"h:").unwrap_or(0); + let input = job.inputs.first().copied().ok_or_else(|| GpuFault::InvalidJob("craft.readback expects one input buffer".into()))?; + let raw = ctx.read_buffer(input)?; + let caps = ctx.caps(); + let _chunks = chunk_buffer(&caps, &raw)?; + + let out_bytes = if params_contain(&job.params, b"fmt:u8") { + let need = usize::try_from(width.saturating_mul(height).saturating_mul(4)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; + if need == 0 || raw.len() < need { + return Err(GpuFault::InvalidJob("rgba8 readback shorter than w*h*4".into())); + } + raw[..need].to_vec() + } else { + let need = usize::try_from(width.saturating_mul(height).saturating_mul(8)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; + if need == 0 || raw.len() < need { + return Err(GpuFault::InvalidJob("f16 rgba readback shorter than w*h*8".into())); + } + f16_rgba_to_f32_bytes(&raw[..need]).map_err(|len| GpuFault::InvalidJob(format!("f16 rgba length {len} not multiple of 8")))? + }; + + let handle = ctx.upload_buffer("craft.readback.out", &out_bytes)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} diff --git a/crates/gpu-providers/src/tests.rs b/crates/gpu-providers/src/tests.rs new file mode 100644 index 0000000000..b996ca57b2 --- /dev/null +++ b/crates/gpu-providers/src/tests.rs @@ -0,0 +1,127 @@ +#![allow(clippy::expect_used)] + +use craft_gpu::{GpuContext, GpuJob, GpuJobParams, ProviderRegistry, WorkerKind, f16_to_f32, f16_to_f32_fast}; +use craft_gpu_null::NullContext; + +use crate::{EchoProvider, MaskProvider, NoopProvider, PremulCompositeProvider, ReadbackProvider, register_all, register_all_into}; + +#[test] +fn noop_provider_registered_by_id() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(NoopProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("noop dispatch"); + assert!(out.data.is_none()); +} + +#[test] +fn echo_provider_concatenates_params_and_first_input() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(EchoProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let h = ctx.upload_buffer("in", b"xy").expect("upload_buffer in test"); + let job = GpuJob { provider_id: "craft.test.echo".into(), params: GpuJobParams(b"a".to_vec()), inputs: vec![h], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("echo dispatch"); + assert_eq!(out.data.as_deref(), Some(b"axy".as_slice())); +} + +#[test] +fn register_all_lists_shared_providers() { + let ids: Vec<_> = register_all().iter().map(|p| p.id()).collect(); + assert_eq!(ids, vec!["craft.noop", "craft.test.echo", "craft.mask", "craft.composite.premul", "craft.readback",]); +} + +#[test] +fn gpu_providers_cargo_has_no_app_deps() { + let manifest = include_str!("../Cargo.toml"); + for line in manifest.lines() { + let t = line.trim(); + assert!( + !(t.starts_with("effectcraft") || t.starts_with("filmcraft") || t.contains("effectcraft-") || t.contains("filmcraft-")), + "forbidden app dependency line: {t}" + ); + } +} + +#[test] +fn mask_provider_multiplies_rgba_by_mask_on_cpu() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(MaskProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let base = ctx.upload_buffer("base", &[255u8, 0, 0, 255, 100, 100, 100, 255]).expect("upload base"); + let mask = ctx.upload_buffer("mask", &[128u8, 255, 255, 255, 0, 255, 255, 255]).expect("upload mask"); + let job = + craft_gpu::GpuJob { provider_id: "craft.mask".into(), params: GpuJobParams(b"w:1,h:2".to_vec()), inputs: vec![base, mask], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("mask dispatch"); + let handle = out.outputs[0]; + let bytes = ctx.read_buffer(handle).expect("read mask out"); + assert_eq!(bytes[0], 128); + assert_eq!(bytes[4], 0); +} + +#[test] +fn premul_composite_over_on_cpu() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(PremulCompositeProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + // backdrop: green opaque; layer: half-alpha blue + let dst = ctx.upload_buffer("dst", &[0, 255, 0, 255]).expect("upload dst"); + let src = ctx.upload_buffer("src", &[0, 0, 255, 128]).expect("upload src"); + let job = + GpuJob { provider_id: "craft.composite.premul".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![dst, src], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("premul composite"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read out"); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], 127); + assert_eq!(bytes[2], 128); + assert_eq!(bytes[3], 255); +} + +#[test] +fn readback_decodes_f16_rgba_to_f32() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(ReadbackProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let h = half_float_one(); + let mut raw = Vec::new(); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&0u16.to_le_bytes()); + let inp = ctx.upload_buffer("accum", &raw).expect("upload f16"); + let job = GpuJob { provider_id: "craft.readback".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![inp], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("readback"); + let decoded = ctx.read_buffer(out.outputs[0]).expect("read f32 out"); + assert_eq!(decoded.len(), 16); + let r = f32::from_le_bytes(decoded[0..4].try_into().expect("r")); + assert!((r - 1.0).abs() < 1e-3); + assert_eq!(f16_to_f32(h), f16_to_f32_fast(h)); +} + +fn half_float_one() -> u16 { + f32_to_f16(1.0) +} + +fn f32_to_f16(v: f32) -> u16 { + let bits = v.to_bits(); + let sign = ((bits >> 31) & 1) as u16; + let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let mant = bits & 0x007f_ffff; + if exp <= 0 { + return sign << 15; + } + if exp >= 0x1f { + return (sign << 15) | 0x7c00; + } + (sign << 15) | ((exp as u16) << 10) | ((mant >> 13) as u16) +} + +#[test] +fn register_all_into_populates_registry() { + let mut registry = ProviderRegistry::new(); + register_all_into(&mut registry); + let mut ctx = NullContext::new(WorkerKind::SharedWorker); + let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + registry.dispatch(&mut ctx, &job).expect("noop via register_all_into"); +} diff --git a/crates/gpu-wgpu/Cargo.toml b/crates/gpu-wgpu/Cargo.toml new file mode 100644 index 0000000000..4f2c9ae5b2 --- /dev/null +++ b/crates/gpu-wgpu/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "craft-gpu-wgpu" +description = "craft-gpu backend using wgpu (WebGPU on wasm32, native APIs on desktop)" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true, optional = true } +wgpu = { workspace = true } + +[features] +default = [] +adapter-probe = ["dep:pollster"] +native-vulkan = ["wgpu/vulkan"] +native-dx12 = ["wgpu/dx12"] +native-metal = ["wgpu/metal"] +native-gles = ["wgpu/gles"] + +[dev-dependencies] +pollster = { workspace = true } diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs new file mode 100644 index 0000000000..91aa8cc19b --- /dev/null +++ b/crates/gpu-wgpu/src/lib.rs @@ -0,0 +1,89 @@ +//! wgpu-backed [`GpuContext`](craft_gpu::GpuContext). +//! +//! WebGPU on `wasm32`; native APIs when backend features are enabled. Adapter probing is +//! optional on native via the `adapter-probe` feature (pollster). + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; + +fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { + DeviceCaps { backend_name: backend_name.into(), device_name: device_name.into(), ..DeviceCaps::default() } +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +fn probe_caps_native() -> DeviceCaps { + let instance = wgpu::Instance::default(); + let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { + Ok(adapter) => adapter, + Err(_) => return probe_fallback("wgpu", "no-adapter"), + }; + let info = adapter.get_info(); + let limits = adapter.limits(); + DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name, + max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, + max_buffer_size: limits.max_buffer_size, + max_texture_dimension_2d: limits.max_texture_dimension_2d, + } +} + +/// Report device limits when an adapter is available; otherwise conservative defaults. +pub fn probe_caps() -> DeviceCaps { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + { + return probe_caps_native(); + } + + #[cfg(all(not(target_arch = "wasm32"), not(feature = "adapter-probe")))] + { + probe_fallback("wgpu", "probe-not-run") + } + + #[cfg(target_arch = "wasm32")] + { + probe_fallback("webgpu", "browser") + } +} + +/// wgpu-backed context; buffer IO uses staging until full device wiring lands (craft-libs#6). +pub struct WgpuContext { + caps: DeviceCaps, + worker_kind: WorkerKind, + staging: Vec>, +} + +impl WgpuContext { + pub fn new(worker_kind: WorkerKind) -> Self { + Self { caps: probe_caps(), worker_kind, staging: Vec::new() } + } + + pub fn with_caps(worker_kind: WorkerKind, caps: DeviceCaps) -> Self { + Self { caps, worker_kind, staging: Vec::new() } + } +} + +impl GpuContext for WgpuContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + self.worker_kind + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.staging.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.staging.push(bytes.to_vec()); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.staging.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { + self.staging.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } +} diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml new file mode 100644 index 0000000000..3928ad8bee --- /dev/null +++ b/crates/gpu/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-gpu" +description = "Provider-neutral GPU traits, GpuJob envelope, and registry (no vendor IO)" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs new file mode 100644 index 0000000000..ae63a43ab2 --- /dev/null +++ b/crates/gpu/src/caps.rs @@ -0,0 +1,23 @@ +use serde::{Deserialize, Serialize}; + +/// Limits and labels reported to Settings UI and worker RPC (`GpuCaps`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeviceCaps { + pub backend_name: String, + pub device_name: String, + pub max_storage_buffer_binding_size: u64, + pub max_buffer_size: u64, + pub max_texture_dimension_2d: u32, +} + +impl Default for DeviceCaps { + fn default() -> Self { + Self { + backend_name: "null".into(), + device_name: "null".into(), + max_storage_buffer_binding_size: 128 * 1024 * 1024, + max_buffer_size: 256 * 1024 * 1024, + max_texture_dimension_2d: 8192, + } + } +} diff --git a/crates/gpu/src/chunk.rs b/crates/gpu/src/chunk.rs new file mode 100644 index 0000000000..6246377773 --- /dev/null +++ b/crates/gpu/src/chunk.rs @@ -0,0 +1,11 @@ +use crate::{DeviceCaps, GpuFault}; + +/// Split `data` into contiguous slices no larger than [`DeviceCaps::max_storage_buffer_binding_size`]. +pub fn chunk_buffer<'a>(caps: &DeviceCaps, data: &'a [u8]) -> Result, GpuFault> { + let max = usize::try_from(caps.max_storage_buffer_binding_size) + .map_err(|_| GpuFault::Operation("max_storage_buffer_binding_size exceeds host address space".into()))?; + if max == 0 { + return Err(GpuFault::Operation("max_storage_buffer_binding_size must be non-zero".into())); + } + Ok(data.chunks(max).collect()) +} diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs new file mode 100644 index 0000000000..8d565e3441 --- /dev/null +++ b/crates/gpu/src/context.rs @@ -0,0 +1,23 @@ +use crate::{DeviceCaps, GpuFault, HandleId}; + +/// Where the context was created (main thread vs worker). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WorkerKind { + Main, + DedicatedWorker, + SharedWorker, +} + +/// Device/queue abstraction implemented by `craft-gpu-wgpu` and `craft-gpu-null`. +pub trait GpuContext { + fn caps(&self) -> DeviceCaps; + + fn worker_kind(&self) -> WorkerKind; + + /// Register an opaque buffer blob; returns a handle for job graphs. + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result; + + fn buffer_len(&self, handle: HandleId) -> Result; + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault>; +} diff --git a/crates/gpu/src/error.rs b/crates/gpu/src/error.rs new file mode 100644 index 0000000000..2a44f4b6a0 --- /dev/null +++ b/crates/gpu/src/error.rs @@ -0,0 +1,14 @@ +use thiserror::Error; + +/// Neutral GPU failure (no wgpu/WebGPU types cross this boundary). +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum GpuFault { + #[error("provider not registered: {0}")] + UnknownProvider(String), + #[error("invalid job: {0}")] + InvalidJob(String), + #[error("device unavailable: {0}")] + DeviceUnavailable(String), + #[error("operation failed: {0}")] + Operation(String), +} diff --git a/crates/gpu/src/job.rs b/crates/gpu/src/job.rs new file mode 100644 index 0000000000..5f822b6f6f --- /dev/null +++ b/crates/gpu/src/job.rs @@ -0,0 +1,28 @@ +use serde::{Deserialize, Serialize}; + +/// Opaque resource handle in a job graph (resolved in the active [`GpuContext`](crate::GpuContext)). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct HandleId(pub u32); + +/// Stable provider name (`craft.readback`, `effectcraft.compositor.frame`, …). +pub type ProviderId = String; + +/// Versioned parameter blob; schema owned by the provider crate, not craft-gpu. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJobParams(pub Vec); + +/// Serializable work unit for generic worker dispatch. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJob { + pub provider_id: ProviderId, + pub params: GpuJobParams, + pub inputs: Vec, + pub outputs: Vec, +} + +/// Result handles or side-channel bytes (provider-defined interpretation). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJobOutcome { + pub outputs: Vec, + pub data: Option>, +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs new file mode 100644 index 0000000000..bf4993f30e --- /dev/null +++ b/crates/gpu/src/lib.rs @@ -0,0 +1,27 @@ +//! GPU traits, job envelope, and provider registry for Craft apps and the web runtime. +//! +//! Application crates register [`GpuProvider`] implementations; generic hosts dispatch +//! [`GpuJob`] values by [`ProviderId`] without importing app project types. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod caps; +mod chunk; +mod context; +mod error; +mod job; +mod provider; +mod readback; +mod registry; + +#[cfg(test)] +mod tests; + +pub use caps::DeviceCaps; +pub use chunk::chunk_buffer; +pub use context::{GpuContext, WorkerKind}; +pub use error::GpuFault; +pub use job::{GpuJob, GpuJobOutcome, GpuJobParams, HandleId}; +pub use provider::GpuProvider; +pub use readback::{f16_rgba_to_f32_bytes, f16_to_f32, f16_to_f32_fast}; +pub use registry::ProviderRegistry; diff --git a/crates/gpu/src/provider.rs b/crates/gpu/src/provider.rs new file mode 100644 index 0000000000..677351f579 --- /dev/null +++ b/crates/gpu/src/provider.rs @@ -0,0 +1,8 @@ +use crate::{GpuContext, GpuFault, GpuJob, GpuJobOutcome}; + +/// One GPU operation family. App and generic providers implement this trait. +pub trait GpuProvider { + fn id(&self) -> &'static str; + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result; +} diff --git a/crates/gpu/src/readback.rs b/crates/gpu/src/readback.rs new file mode 100644 index 0000000000..ad02afbe88 --- /dev/null +++ b/crates/gpu/src/readback.rs @@ -0,0 +1,50 @@ +/// IEEE half → f32 (FilmCraft `filmcraft_gpu::f16_to_f32`), for decoding `Rgba16Float` readbacks. +pub fn f16_to_f32(h: u16) -> f32 { + let sign = ((h & 0x8000) as u32) << 16; + let exp = ((h >> 10) & 0x1f) as u32; + let mant = (h & 0x03ff) as u32; + let bits = match exp { + 0 => { + if mant == 0 { + sign + } else { + let b = 31 - mant.leading_zeros(); + let frac = (mant ^ (1 << b)) << (23 - b); + sign | ((103 + b) << 23) | frac + } + } + 0x1f => sign | 0x7f80_0000 | (mant << 13), + _ => sign | ((exp + 112) << 23) | (mant << 13), + }; + f32::from_bits(bits) +} + +/// [`f16_to_f32`] with a fast path for normal numbers and zeros; subnormals and non-finite values use [`f16_to_f32`]. +#[inline] +pub fn f16_to_f32_fast(h: u16) -> f32 { + let u = u32::from(h); + let sign = (u & 0x8000) << 16; + let abs = u & 0x7fff; + if (0x0400..0x7c00).contains(&abs) { + f32::from_bits(sign | ((abs + (112 << 10)) << 13)) + } else if abs == 0 { + f32::from_bits(sign) + } else { + f16_to_f32(h) + } +} + +/// Expand little-endian RGBA f16 texels to RGBA f32 (row-major, no padding). +pub fn f16_rgba_to_f32_bytes(src: &[u8]) -> Result, usize> { + if !src.len().is_multiple_of(8) { + return Err(src.len()); + } + let mut out = Vec::with_capacity(src.len() * 2); + for chunk in src.as_chunks::<8>().0 { + for pair in chunk.as_chunks::<2>().0 { + let v = f16_to_f32_fast(u16::from_le_bytes(*pair)); + out.extend_from_slice(&v.to_le_bytes()); + } + } + Ok(out) +} diff --git a/crates/gpu/src/registry.rs b/crates/gpu/src/registry.rs new file mode 100644 index 0000000000..9a970da8ba --- /dev/null +++ b/crates/gpu/src/registry.rs @@ -0,0 +1,39 @@ +use crate::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// Lookup table filled at worker/app init. Generic runtime code only talks to this. +pub struct ProviderRegistry { + providers: Vec>, +} + +impl Default for ProviderRegistry { + fn default() -> Self { + Self::new() + } +} + +impl ProviderRegistry { + pub fn new() -> Self { + Self { providers: Vec::new() } + } + + pub fn register(&mut self, provider: Box) { + self.providers.push(provider); + } + + pub fn dispatch(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + for provider in &self.providers { + if provider.id() == job.provider_id { + return provider.run(ctx, job); + } + } + Err(GpuFault::UnknownProvider(job.provider_id.clone())) + } + + pub fn dispatch_batch(&self, ctx: &mut dyn GpuContext, jobs: &[GpuJob]) -> Result, GpuFault> { + let mut out = Vec::with_capacity(jobs.len()); + for job in jobs { + out.push(self.dispatch(ctx, job)?); + } + Ok(out) + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs new file mode 100644 index 0000000000..411f64311a --- /dev/null +++ b/crates/gpu/src/tests.rs @@ -0,0 +1,69 @@ +#![allow(clippy::expect_used)] + +use crate::{ + DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, WorkerKind, chunk_buffer, f16_rgba_to_f32_bytes, f16_to_f32, + f16_to_f32_fast, +}; + +struct MemContext { + caps: DeviceCaps, + buffers: Vec>, +} + +impl GpuContext for MemContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + WorkerKind::Main + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.buffers.push(bytes.to_vec()); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { + self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } +} + +#[test] +fn unknown_provider_is_fault() { + let registry = ProviderRegistry::new(); + let mut ctx = MemContext { caps: DeviceCaps::default(), buffers: Vec::new() }; + let job = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + assert!(matches!(registry.dispatch(&mut ctx, &job), Err(GpuFault::UnknownProvider(_)))); +} + +#[test] +fn f16_to_f32_matches_fast_for_one() { + let h = 0x3c00u16; + assert!((f16_to_f32(h) - 1.0).abs() < 1e-6); + assert_eq!(f16_to_f32(h).to_bits(), f16_to_f32_fast(h).to_bits()); +} + +#[test] +fn f16_rgba_to_f32_bytes_expands_texels() { + let src = 0x3c00u16.to_le_bytes(); + let mut raw = Vec::new(); + for _ in 0..4 { + raw.extend_from_slice(&src); + } + let out = f16_rgba_to_f32_bytes(&raw).expect("decode"); + assert_eq!(out.len(), 16); + assert!((f32::from_le_bytes(out[0..4].try_into().expect("le")) - 1.0).abs() < 1e-6); +} + +#[test] +fn chunk_buffer_splits_on_storage_binding_limit() { + let caps = DeviceCaps { max_storage_buffer_binding_size: 4, ..DeviceCaps::default() }; + let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer"); + assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]); +} diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md new file mode 100644 index 0000000000..1e7a383cd0 --- /dev/null +++ b/docs/gpu-backends.md @@ -0,0 +1,14 @@ +# GPU backends + +| Crate | Role | +|-------|------| +| `craft-gpu` | Traits, `GpuJob`, `ProviderRegistry` | +| `craft-gpu-wgpu` | wgpu → WebGPU (wasm) / Vulkan·DX12·Metal (native) | +| `craft-gpu-null` | In-memory context for CI | + +Feature flags on `craft-gpu-wgpu`: + +- `adapter-probe` — native only; uses pollster to `request_adapter` and fill real [`DeviceCaps`](../crates/gpu/src/caps.rs) (falls back when no GPU, e.g. CI). +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. + +On `wasm32`, wgpu is built with the `webgpu` feature; caps probing stays browser-default until async init lands in the worker. diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md new file mode 100644 index 0000000000..33e5a021e9 --- /dev/null +++ b/docs/gpu-providers.md @@ -0,0 +1,14 @@ +# GPU providers + +Provider ids: + +- `craft.*` — shared ops in **craft-gpu-providers** (no app crate deps) +- `craft.noop`, `craft.test.echo`, `craft.mask`, `craft.composite.premul`, `craft.readback` — registered by [`register_all()`](../crates/gpu-providers/src/lib.rs) for worker/runtime init + - `craft.mask` — CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu + - `craft.composite.premul` — CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu + - `craft.readback` — CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** +- `{app}.*` — registered by application wasm at init + +Generic worker code must only call `ProviderRegistry::dispatch` — never import app gpu crates. + +Dependency lint: **craft-gpu-providers** must not depend on `effectcraft-*`, `filmcraft-*`, or `*-engine`. From f731e52528090126acb7fa884d64b42b9baa8d3c Mon Sep 17 00:00:00 2001 From: William Dunn Date: Tue, 10 Nov 2026 19:08:19 -0500 Subject: [PATCH 06/47] craft-gpu: real device wiring, device loss and async readback (RFC-0022) Addresses skylartaylor's review gate on #663 at 138f7b2. RFC-0022 has merged since that review. This follows its acceptance requirements. WgpuContext now requests a real device. DeviceCaps comes from that device, reflecting the limits and features actually enabled on it. Buffers are real wgpu::Buffer values when a device exists. The no-adapter case still degrades to the same staging behavior as craft-gpu-null. The RFC defines that case explicitly as the no-adapter path. Device loss is registered via set_device_lost_callback. It surfaces as GpuFault::DeviceLost. It never surfaces as a panic. The recovery is stated on GpuContext's trait docs. GpuContext::read_buffer is no longer a required method. The primitives are request_read and poll_reads. That mirrors craft-worker-host's own HostMessage::GpuJobs to WorkerMessage::GpuBatchDone split one level down. read_buffer stays as a default blocking convenience. It resolves immediately on the null and staging paths. Native wgpu blocks on Device::poll(wait_indefinitely). On wasm32 it returns GpuFault::Operation, since a blocking wait there would freeze the one thread map_async's own callback needs to run on. crates/gpu-wgpu/src/tests.rs adds a real-backend suite, gated on adapter-probe plus non-wasm32. It runs upload, readback and device-loss tests against a real WgpuContext. It also runs three craft-gpu-providers CPU-stand-in providers against that same real WgpuContext. It skips with a clear message when no adapter is present. Verified against lavapipe with mesa-vulkan-drivers, using --features adapter-probe,native-vulkan: every test passes. That run first caught a real wgpu panic on buffer lengths that are not a multiple of 4, COPY_BUFFER_ALIGNMENT. The fix pads real buffers transparently. Every caller still sees exact, unpadded bytes. docs/gpu-backends.md and docs/gpu-providers.md are updated to match, including named consumers (the runtime slice first, then EffectCraft and FilmCraft) and a device-ownership note for when egui's wgpu renderer is also running. --- crates/gpu-null/src/lib.rs | 50 ++++- crates/gpu-wgpu/Cargo.toml | 4 + crates/gpu-wgpu/src/lib.rs | 377 +++++++++++++++++++++++++++++++++-- crates/gpu-wgpu/src/tests.rs | 152 ++++++++++++++ crates/gpu/src/caps.rs | 13 ++ crates/gpu/src/context.rs | 73 ++++++- crates/gpu/src/error.rs | 6 + crates/gpu/src/lib.rs | 2 +- crates/gpu/src/tests.rs | 37 +++- docs/gpu-backends.md | 53 ++++- docs/gpu-providers.md | 4 + 11 files changed, 740 insertions(+), 31 deletions(-) create mode 100644 crates/gpu-wgpu/src/tests.rs diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index 66925b4901..b28fdf80b2 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -2,13 +2,18 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind}; -/// In-memory buffer store; no GPU hardware required. +/// In-memory buffer store; no GPU hardware required. Reads resolve synchronously (there is +/// nothing to wait for), so [`request_read`](GpuContext::request_read) and +/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially, and the default +/// [`read_buffer`](GpuContext::read_buffer) never loops more than once. pub struct NullContext { caps: DeviceCaps, worker_kind: WorkerKind, buffers: Vec>, + next_request: u64, + ready: Vec, } impl NullContext { @@ -17,6 +22,8 @@ impl NullContext { caps: DeviceCaps { backend_name: "null".into(), device_name: "null".into(), ..DeviceCaps::default() }, worker_kind, buffers: Vec::new(), + next_request: 0, + ready: Vec::new(), } } } @@ -40,7 +47,42 @@ impl GpuContext for NullContext { self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { - self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + fn request_read(&mut self, handle: HandleId) -> Result { + let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let request = ReadRequest(self.next_request); + self.next_request = self.next_request.wrapping_add(1); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) + } + + fn poll_reads(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } +} + +#[cfg(test)] +mod tests { + use craft_gpu::GpuContext; + + use super::NullContext; + use craft_gpu::WorkerKind; + + #[test] + fn request_read_then_poll_reads_delivers_the_same_bytes_as_read_buffer() { + let mut ctx = NullContext::new(WorkerKind::Main); + let handle = ctx.upload_buffer("in", b"abc").expect("upload_buffer"); + let request = ctx.request_read(handle).expect("request_read"); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1); + assert_eq!(outcomes[0].request, request); + assert_eq!(outcomes[0].handle, handle); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"abc".as_slice())); + } + + #[test] + fn read_buffer_default_still_works() { + let mut ctx = NullContext::new(WorkerKind::SharedWorker); + let handle = ctx.upload_buffer("in", b"xyz").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"xyz".to_vec()); } } diff --git a/crates/gpu-wgpu/Cargo.toml b/crates/gpu-wgpu/Cargo.toml index 4f2c9ae5b2..ecf45c62f0 100644 --- a/crates/gpu-wgpu/Cargo.toml +++ b/crates/gpu-wgpu/Cargo.toml @@ -29,3 +29,7 @@ native-gles = ["wgpu/gles"] [dev-dependencies] pollster = { workspace = true } +# Real-backend test (crates/gpu-wgpu/src/tests.rs): dispatches craft-gpu-providers' CPU-stand-in +# providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance +# requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu). +craft-gpu-providers = { workspace = true } diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 91aa8cc19b..009fd1e4b4 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -1,11 +1,28 @@ //! wgpu-backed [`GpuContext`](craft_gpu::GpuContext). //! -//! WebGPU on `wasm32`; native APIs when backend features are enabled. Adapter probing is -//! optional on native via the `adapter-probe` feature (pollster). +//! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe` +//! feature (native only, pollster) and at least one `native-*` backend feature, +//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device +//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's +//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present, +//! or on `wasm32` where real device creation needs the async worker-init path noted in +//! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as +//! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context); +//! that is RFC-0022's defined no-adapter path, not an error. +//! +//! Readback is asynchronous end to end (`request_read` + `poll_reads`), because WebGPU can only +//! map a buffer that way. Native, with a real device, drives it with `Buffer::map_async` plus +//! `Device::poll`. The blocking `read_buffer` convenience (see +//! [`GpuContext`](craft_gpu::GpuContext)'s trait docs) blocks efficiently on native by polling +//! the device while it waits; on `wasm32` it instead returns a fault, since blocking there would +//! freeze the one thread the map's own completion callback needs to run on. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind}; + +#[cfg(test)] +mod tests; fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { DeviceCaps { backend_name: backend_name.into(), device_name: device_name.into(), ..DeviceCaps::default() } @@ -13,7 +30,7 @@ fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] fn probe_caps_native() -> DeviceCaps { - let instance = wgpu::Instance::default(); + let instance = native::instance(); let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { Ok(adapter) => adapter, Err(_) => return probe_fallback("wgpu", "no-adapter"), @@ -26,14 +43,18 @@ fn probe_caps_native() -> DeviceCaps { max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, max_buffer_size: limits.max_buffer_size, max_texture_dimension_2d: limits.max_texture_dimension_2d, + features: Vec::new(), } } -/// Report device limits when an adapter is available; otherwise conservative defaults. +/// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This +/// is the quick, device-free probe for UI surfaces that want a number before any context exists +/// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted +/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists. pub fn probe_caps() -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] { - return probe_caps_native(); + probe_caps_native() } #[cfg(all(not(target_arch = "wasm32"), not(feature = "adapter-probe")))] @@ -47,20 +68,201 @@ pub fn probe_caps() -> DeviceCaps { } } -/// wgpu-backed context; buffer IO uses staging until full device wiring lands (craft-libs#6). +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +mod native { + use std::sync::{Arc, Mutex}; + + use craft_gpu::{DeviceCaps, GpuFault}; + + use crate::{Backing, DeviceBacking}; + + /// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu + /// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this + /// as real compute providers land, and it degrades gracefully regardless: see + /// [`create_device`]. + const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty(); + + /// An instance over whichever native backends were compiled in (`native-vulkan`, + /// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the + /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in CI. + /// `new_without_display_handle` because this context never has a window (no surface is ever + /// requested); FilmCraft's own off-screen export device uses the same constructor for the + /// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). + pub(crate) fn instance() -> wgpu::Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + if let Some(backends) = wgpu::Backends::from_env() { + desc.backends = backends; + } + wgpu::Instance::new(desc) + } + + /// Request a real device. `None` on the defined no-adapter path (no usable adapter): the + /// caller degrades to the staging backing, identical in shape to `craft-gpu-null`. + /// + /// Never panics: `required_features` is intersected with what the adapter actually + /// advertises, and `required_limits` is set to the adapter's own limits (never more), so + /// `request_device`'s documented panics ("features/limits not supported by this adapter") + /// cannot trigger here. + pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> { + let instance = instance(); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let features = DESIRED_FEATURES & adapter.features(); + let limits = adapter.limits(); + let desc = + wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() }; + let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?; + + let lost = Arc::new(Mutex::new(None)); + { + let lost = Arc::clone(&lost); + device.set_device_lost_callback(move |reason, message| { + if let Ok(mut slot) = lost.lock() { + *slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}"))); + } + }); + } + + let info = device.adapter_info(); + let device_limits = device.limits(); + let caps = DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name, + max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size, + max_buffer_size: device_limits.max_buffer_size, + max_texture_dimension_2d: device_limits.max_texture_dimension_2d, + features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), + }; + let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); + Some((caps, backing)) + } +} + +/// No real device: buffers live on the host, exactly like `craft-gpu-null`. RFC-0022's defined +/// degrade path for "no adapter" (feature off, no GPU present, or the `wasm32` async-init gap). +#[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] +enum Backing { + Staging(Vec>), +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +enum Backing { + Staging(Vec>), + /// A real device. `DeviceCaps` was built from it, not from the adapter it came from. + Device(DeviceBacking), +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +struct DeviceBacking { + device: wgpu::Device, + queue: wgpu::Queue, + /// Each buffer paired with its true, caller-given byte length. wgpu requires every buffer + /// with copy usage to be sized in multiples of [`COPY_ALIGN`]; the buffer itself is padded to + /// that, but callers (`buffer_len`, `request_read`'s returned bytes) see the true length, + /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. + buffers: Vec<(wgpu::Buffer, u64)>, + /// Set by the device-lost callback registered in [`native::create_device`]; checked before + /// every call that would otherwise touch the (now invalid) device. + lost: std::sync::Arc>>, + pending: Vec, +} + +/// wgpu's `COPY_BUFFER_ALIGNMENT`: every buffer with copy usage, and every `write_buffer` / +/// `copy_buffer_to_buffer` size, must be a multiple of this (4 bytes). Uploading or reading back +/// a buffer length that doesn't land on this boundary (`b"xy"`, two bytes) is a validation error +/// on native wgpu, surfaced as a panic from inside `wgpu-core`'s own uncaptured-error path unless +/// padded first; `craft-gpu-null`'s plain `Vec` has no such constraint, so this padding is +/// purely an artifact of the real backend, kept invisible to every caller of this crate. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +const COPY_ALIGN: u64 = 4; + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +struct PendingRead { + request: ReadRequest, + handle: HandleId, + staging: wgpu::Buffer, + /// True length to truncate the mapped (padded) bytes back down to. + true_len: u64, + state: std::sync::Arc>>>, +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +fn resolve_pending(pending: PendingRead) -> ReadOutcome { + let PendingRead { request, handle, staging, true_len, state } = pending; + let result = match state.lock() { + Ok(mut guard) => match guard.take() { + Some(Ok(())) => match staging.get_mapped_range(0..true_len.next_multiple_of(COPY_ALIGN)) { + Ok(view) => { + let mut bytes = view.to_vec(); + drop(view); + staging.unmap(); + bytes.truncate(usize::try_from(true_len).unwrap_or(usize::MAX)); + Ok(bytes) + } + Err(err) => Err(GpuFault::Operation(err.to_string())), + }, + Some(Err(message)) => Err(GpuFault::Operation(message)), + None => Err(GpuFault::Operation("read_buffer: map_async callback has not run yet".into())), + }, + Err(_) => Err(GpuFault::Operation("read_buffer: map state lock poisoned".into())), + }; + ReadOutcome { request, handle, result } +} + +/// wgpu-backed context. See the module docs for the real-device-vs-staging split. pub struct WgpuContext { caps: DeviceCaps, worker_kind: WorkerKind, - staging: Vec>, + backing: Backing, + next_request: u64, + ready: Vec, } impl WgpuContext { pub fn new(worker_kind: WorkerKind) -> Self { - Self { caps: probe_caps(), worker_kind, staging: Vec::new() } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + { + if let Some((caps, backing)) = native::create_device() { + return Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }; + } + } + Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } + /// Force the staging (no-device) path with caller-supplied caps. For tests, and for callers + /// that intentionally want the portable path (FilmCraft's `?webgl` / `?nogpuworkers`, per + /// `docs/pilot-filmcraft.md`) rather than a real device's own caps. pub fn with_caps(worker_kind: WorkerKind, caps: DeviceCaps) -> Self { - Self { caps, worker_kind, staging: Vec::new() } + Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } + } + + /// True when this context holds a real device (`request_device` succeeded), false on the + /// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of + /// implying a device that was never created; tests use it to skip rather than fail when the + /// host genuinely has no usable adapter (see `crates/gpu-wgpu/src/tests.rs`). + pub fn has_device(&self) -> bool { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if matches!(self.backing, Backing::Device(_)) { + return true; + } + false + } + + /// True once the device has reported loss. Every [`DeviceCaps`] read before this point is + /// stale; see [`GpuContext`]'s trait docs for the recovery this context expects. + pub fn is_device_lost(&self) -> bool { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.lost.lock().map(|g| g.is_some()).unwrap_or(false); + } + false + } + + fn take_lost_fault(&self) -> Option { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.lost.lock().ok().and_then(|g| g.clone()); + } + None } } @@ -73,17 +275,158 @@ impl GpuContext for WgpuContext { self.worker_kind } - fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { - let id = HandleId(u32::try_from(self.staging.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); - self.staging.push(bytes.to_vec()); - Ok(id) + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))] + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + if bytes.is_empty() { + return Err(GpuFault::InvalidJob("upload_buffer: bytes must be non-empty".into())); + } + match &mut self.backing { + Backing::Staging(buffers) => { + let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; + buffers.push(bytes.to_vec()); + Ok(HandleId(id)) + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + let true_len = bytes.len() as u64; + let padded_len = true_len.next_multiple_of(COPY_ALIGN); + let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: padded_len, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + if padded_len == true_len { + d.queue.write_buffer(&buffer, 0, bytes); + } else { + let mut padded = bytes.to_vec(); + padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); + d.queue.write_buffer(&buffer, 0, &padded); + } + let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; + d.buffers.push((buffer, true_len)); + Ok(HandleId(id)) + } + } } fn buffer_len(&self, handle: HandleId) -> Result { - self.staging.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + match &self.backing { + Backing::Staging(buffers) => buffers.get(handle.0 as usize).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())), + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then(|(_, true_len)| { + usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) + }) + } + } } - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { - self.staging.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + fn request_read(&mut self, handle: HandleId) -> Result { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + match &mut self.backing { + Backing::Staging(buffers) => { + let bytes = buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + let (buffer, true_len) = d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let true_len = *true_len; + let copy_len = true_len.next_multiple_of(COPY_ALIGN); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("craft-gpu-wgpu.read-staging"), + size: copy_len, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); + encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); + d.queue.submit(Some(encoder.finish())); + let state = std::sync::Arc::new(std::sync::Mutex::new(None)); + { + let state = std::sync::Arc::clone(&state); + staging.map_async(wgpu::MapMode::Read, 0..copy_len, move |result| { + if let Ok(mut slot) = state.lock() { + *slot = Some(result.map_err(|e| e.to_string())); + } + }); + } + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + d.pending.push(PendingRead { request, handle, staging, true_len, state }); + Ok(request) + } + } + } + + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_mut))] + fn poll_reads(&mut self) -> Vec { + let mut outcomes = std::mem::take(&mut self.ready); + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &mut self.backing { + if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) { + outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) })); + return outcomes; + } + let _ = d.device.poll(wgpu::PollType::Poll); + let mut remaining = Vec::with_capacity(d.pending.len()); + for pending in d.pending.drain(..) { + let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false); + if is_ready { + outcomes.push(resolve_pending(pending)); + } else { + remaining.push(pending); + } + } + d.pending = remaining; + } + outcomes + } + + #[cfg(not(target_arch = "wasm32"))] + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + loop { + for outcome in self.poll_reads() { + if outcome.request == request { + return outcome.result; + } + } + // Block on the GPU between polls instead of busy-spinning the CPU. A no-op when + // `backing` is `Staging` (nothing to wait for; the request already resolved above) + // or when wgpu is itself WebGPU under the hood, which self-polls. + #[cfg(feature = "adapter-probe")] + if let Backing::Device(d) = &self.backing { + let _ = d.device.poll(wgpu::PollType::wait_indefinitely()); + } + } + } + + /// WebGPU can only map a buffer asynchronously, and `wasm32` is single-threaded: blocking + /// here would stop the only thread the browser needs to run `map_async`'s own completion + /// callback on, hanging the tab instead of returning. Callers on this target drive + /// [`request_read`](GpuContext::request_read) and [`poll_reads`](GpuContext::poll_reads) + /// directly from the worker's message loop; see `docs/gpu-backends.md`. + #[cfg(target_arch = "wasm32")] + fn read_buffer(&mut self, _handle: HandleId) -> Result, GpuFault> { + Err(GpuFault::Operation( + "read_buffer is not supported on wasm32/WebGPU: it can only map asynchronously. Use request_read + poll_reads from the worker's \ + message loop instead." + .into(), + )) } } diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs new file mode 100644 index 0000000000..0ea49d5dfc --- /dev/null +++ b/crates/gpu-wgpu/src/tests.rs @@ -0,0 +1,152 @@ +#![allow(clippy::expect_used)] + +//! RFC-0022 acceptance requirement 2: real backends beside the null one. `craft-gpu-null` stays +//! mandatory for every consumer (it cannot validate shader compilation, resource rules, or +//! numerical results), so these tests run representative jobs on a real wgpu device when one is +//! available, and skip loudly rather than failing the suite when the host genuinely has none +//! (`cargo test` without `--features adapter-probe,native-vulkan` already exercises the masked +//! path: no adapter is ever requested, and every context here falls back to the staging path, +//! same shape as `craft-gpu-null`). +//! +//! Tolerance: every job below is byte/structural equality, not a numeric comparison with slack. +//! That is honest for what runs today: no provider dispatches a real WGSL compute job yet +//! (`craft-gpu-providers` ships CPU stand-ins by design; see `docs/gpu-providers.md`), so the only +//! thing a real device adds over the null one here is the upload → real `wgpu::Buffer` → copy → +//! `map_async` → read round trip itself. A provider that dispatches actual WGSL will need a +//! stated numeric tolerance of its own when it lands; this suite is not that provider. + +use craft_gpu::{GpuContext, GpuJob, GpuJobParams, GpuProvider, WorkerKind}; +use craft_gpu_providers::{EchoProvider, PremulCompositeProvider, ReadbackProvider}; + +use crate::WgpuContext; + +/// A real device if this host has one; otherwise `None` with a loud, honest message instead of a +/// failed assertion. Call at the top of every test in this module. +fn real_context_or_skip(test_name: &str) -> Option { + let ctx = WgpuContext::new(WorkerKind::Main); + if ctx.has_device() { + return Some(ctx); + } + eprintln!( + "SKIP {test_name}: no real wgpu device in this environment (no backend feature compiled \ + in, or `request_adapter` found nothing). This is RFC-0022's defined no-adapter path, not \ + a failure; craft-gpu-null already covers the portable contract. Run with \ + `--features adapter-probe,native-vulkan` against a Vulkan adapter (a software one, such \ + as lavapipe/llvmpipe via mesa-vulkan-drivers, is enough) to exercise this suite for real." + ); + None +} + +#[test] +fn real_device_reports_a_non_null_backend_and_empty_features_it_actually_requested() { + let Some(ctx) = real_context_or_skip("real_device_reports_a_non_null_backend_and_empty_features_it_actually_requested") else { + return; + }; + let caps = ctx.caps(); + assert_ne!(caps.backend_name, "null", "a real device must not report the null backend name"); + assert_ne!(caps.device_name, "no-adapter", "has_device() was true; caps must not be the no-adapter fallback"); + assert_ne!(caps.device_name, "probe-not-run", "has_device() was true; caps must not be the probe-skipped fallback"); + // This context asks the device for no features yet (no provider dispatches real WGSL): the + // device reports exactly what was requested, per `Device::features`' own contract, so this is + // device-truth agreeing with an intentionally empty request, not an unprobed default. + assert!(caps.features.is_empty(), "no feature was requested, so none should be reported enabled: {:?}", caps.features); +} + +#[test] +fn real_device_upload_and_async_readback_round_trips_bytes_exactly() { + let Some(mut ctx) = real_context_or_skip("real_device_upload_and_async_readback_round_trips_bytes_exactly") else { + return; + }; + let payload: Vec = (0..256u32).map(|b| b as u8).collect(); + let handle = ctx.upload_buffer("round-trip", &payload).expect("upload_buffer on a real device"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), payload.len()); + + // Exercise request_read + poll_reads directly (the primitive every backend implements), + // not just the read_buffer convenience, so the async shape itself is under test. + let request = ctx.request_read(handle).expect("request_read"); + let mut got = None; + // Non-blocking poll_reads() in a bounded loop, exercising the exact primitive a worker's own + // message/poll loop would call; read_buffer_convenience (a separate test) covers the blocking + // path. The bound is generous for a software rasterizer on a 256-byte buffer, never relying + // on wall-clock sleeps. + for _ in 0..1_000_000 { + if let Some(outcome) = ctx.poll_reads().into_iter().find(|o| o.request == request) { + got = Some(outcome.result.expect("map_async + Device::poll round trip")); + break; + } + } + assert_eq!(got.expect("the real device never completed the mapped read within the bounded poll loop"), payload); +} + +#[test] +fn real_device_read_buffer_convenience_blocks_to_completion() { + let Some(mut ctx) = real_context_or_skip("real_device_read_buffer_convenience_blocks_to_completion") else { + return; + }; + let handle = ctx.upload_buffer("blocking-read", b"craft-gpu-wgpu").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"craft-gpu-wgpu".to_vec()); +} + +/// RFC-0022 requirement 2's "representative jobs": the same `craft-gpu-providers` CPU stand-ins +/// `craft-runtime` dispatches against the null context in CI also run, unmodified, against a +/// real device, through the same `&mut dyn GpuContext` seam. +#[test] +fn shared_providers_run_against_a_real_device_through_the_same_seam_as_the_null_context() { + let Some(mut ctx) = real_context_or_skip("shared_providers_run_against_a_real_device_through_the_same_seam_as_the_null_context") else { + return; + }; + + let echo = EchoProvider; + let input = ctx.upload_buffer("echo-in", b"xy").expect("upload_buffer"); + let job = GpuJob { provider_id: "craft.test.echo".into(), params: GpuJobParams(b"a".to_vec()), inputs: vec![input], outputs: vec![] }; + let out = echo.run(&mut ctx, &job).expect("craft.test.echo on a real device"); + assert_eq!(out.data.as_deref(), Some(b"axy".as_slice())); + + let composite = PremulCompositeProvider; + let dst = ctx.upload_buffer("dst", &[0, 255, 0, 255]).expect("upload dst"); + let src = ctx.upload_buffer("src", &[0, 0, 255, 128]).expect("upload src"); + let job = + GpuJob { provider_id: "craft.composite.premul".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![dst, src], outputs: vec![] }; + let out = composite.run(&mut ctx, &job).expect("craft.composite.premul on a real device"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read composite output off a real device"); + assert_eq!(bytes, vec![0, 127, 128, 255]); + + let readback = ReadbackProvider; + let rgba = ctx.upload_buffer("rgba", &[10, 20, 30, 40]).expect("upload rgba"); + let job = GpuJob { provider_id: "craft.readback".into(), params: GpuJobParams(b"w:1,h:1,fmt:u8".to_vec()), inputs: vec![rgba], outputs: vec![] }; + let out = readback.run(&mut ctx, &job).expect("craft.readback fmt:u8 on a real device"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read readback output off a real device"); + assert_eq!(bytes, vec![10, 20, 30, 40]); +} + +/// RFC-0022 requirement 1's device-loss half: a stated fault, not a panic, and a documented +/// recovery. `Backing`/`DeviceBacking` are crate-private, so this test reaches `ctx.backing` +/// directly to force the one cause it can trigger deterministically (`device.destroy()`) rather +/// than waiting on a real driver reset. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +#[test] +fn device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls() { + use craft_gpu::GpuFault; + + use crate::Backing; + + let Some(mut ctx) = real_context_or_skip("device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls") else { + return; + }; + assert!(!ctx.is_device_lost(), "a freshly created device must not already report loss"); + + if let Backing::Device(d) = &ctx.backing { + d.device.destroy(); + // The lost closure can run during destroy() or on the next poll, depending on backend; + // give it the chance either way. + let _ = d.device.poll(wgpu::PollType::Poll); + } + + // poll_reads() is the other place the trait docs promise this surfaces, for a caller that + // polls instead of issuing a buffer call first. + let _ = ctx.poll_reads(); + assert!(ctx.is_device_lost(), "device.destroy() must surface through is_device_lost(), per the GpuContext trait docs"); + + let after = ctx.upload_buffer("after-loss", b"x"); + assert!(matches!(after, Err(GpuFault::DeviceLost(_))), "a call after device loss must return GpuFault::DeviceLost, got {after:?}"); +} diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs index ae63a43ab2..75dcf173d0 100644 --- a/crates/gpu/src/caps.rs +++ b/crates/gpu/src/caps.rs @@ -1,6 +1,13 @@ use serde::{Deserialize, Serialize}; /// Limits and labels reported to Settings UI and worker RPC (`GpuCaps`). +/// +/// Per RFC-0022's acceptance requirements, a backend that has a device fills every field here +/// from that created device, never from the adapter it was created on: an adapter advertises more +/// than a device may grant (`required_features`/`required_limits` at `request_device` time narrow +/// both). `craft-gpu-wgpu` reports [`Default`]-shaped conservative values only on the defined +/// no-adapter path (no GPU present, the feature compiled out, or the `wasm32` worker-init gap +/// described in `docs/gpu-backends.md`), never as a stand-in for a real device's own caps. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct DeviceCaps { pub backend_name: String, @@ -8,6 +15,11 @@ pub struct DeviceCaps { pub max_storage_buffer_binding_size: u64, pub max_buffer_size: u64, pub max_texture_dimension_2d: u32, + /// Feature names actually enabled on the created device (`wgpu::Features::iter_names` on + /// native wgpu), empty on backends with no device. A fast path gates on membership here, + /// never on what the adapter merely advertised. + #[serde(default)] + pub features: Vec, } impl Default for DeviceCaps { @@ -18,6 +30,7 @@ impl Default for DeviceCaps { max_storage_buffer_binding_size: 128 * 1024 * 1024, max_buffer_size: 256 * 1024 * 1024, max_texture_dimension_2d: 8192, + features: Vec::new(), } } } diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 8d565e3441..df0d5e308a 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -8,7 +8,55 @@ pub enum WorkerKind { SharedWorker, } +/// Opaque in-flight readback request handed out by [`GpuContext::request_read`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ReadRequest(pub u64); + +/// One completed (or failed) readback, delivered by [`GpuContext::poll_reads`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReadOutcome { + pub request: ReadRequest, + pub handle: HandleId, + pub result: Result, GpuFault>, +} + /// Device/queue abstraction implemented by `craft-gpu-wgpu` and `craft-gpu-null`. +/// +/// ## Device loss +/// +/// A context can lose its device at any time: a driver reset, OS-level eviction under memory +/// pressure, or an explicit `device.destroy()`. Device loss is a fault, not a panic. It surfaces +/// through [`GpuFault::DeviceLost`] from the next call that would otherwise touch the device, and +/// also through [`poll_reads`](Self::poll_reads), so a host's event loop can observe it even +/// between buffer calls. Once a context has reported [`GpuFault::DeviceLost`], every +/// [`DeviceCaps`] it reported before that point is stale. The consumer's recovery, per RFC-0022, +/// is one of: +/// +/// - fall back to the portable path (a [`DeviceCaps`]-gated path with no fast-path features, or a +/// different, CPU-backed [`GpuContext`]) for the rest of the session, or +/// - re-acquire a device, meaning construct a fresh [`GpuContext`], and re-probe +/// [`caps`](Self::caps) before resuming GPU jobs. +/// +/// No backend here supports continuing to dispatch jobs against a context that has already +/// reported device loss, using caps read before the loss. +/// +/// ## Readback +/// +/// [`read_buffer`](Self::read_buffer) is a blocking convenience built on +/// [`request_read`](Self::request_read) and [`poll_reads`](Self::poll_reads): those two are the +/// primitives every backend implements directly, because WebGPU (and therefore native wgpu's +/// `buffer.map_async`) can only map a buffer asynchronously. The completion is delivered the same +/// way a `GpuJob` batch's outcome is delivered to a worker's host: queued, then collected on a +/// later poll, analogous to `craft-worker-host`'s `HostMessage::GpuJobs` being answered later by +/// `WorkerMessage::GpuBatchDone`. +/// +/// A backend that can honestly block (the null context, which never has anything to wait for; +/// native wgpu driving `Device::poll` itself) uses `read_buffer`'s default body. A backend that +/// cannot honestly block without freezing its single thread (WebGPU on `wasm32`, where a map +/// completes only via the browser's own event loop) overrides `read_buffer` to return +/// [`GpuFault::Operation`] instead of deadlocking; callers there must drive `request_read` and +/// `poll_reads` from the worker's own message loop. See `docs/gpu-backends.md` for which backend +/// does which. pub trait GpuContext { fn caps(&self) -> DeviceCaps; @@ -19,5 +67,28 @@ pub trait GpuContext { fn buffer_len(&self, handle: HandleId) -> Result; - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault>; + /// Queue an asynchronous readback of `handle`. Completion is delivered by + /// [`poll_reads`](Self::poll_reads). + fn request_read(&mut self, handle: HandleId) -> Result; + + /// Drain every read completed (or failed) since the last call. Also where a device-lost + /// fault surfaces for callers that are polling rather than issuing buffer calls. A context + /// that resolves reads synchronously (the null context; native wgpu with no device) may + /// resolve a request on the very next call after [`request_read`](Self::request_read). + fn poll_reads(&mut self) -> Vec; + + /// Blocking convenience for callers that need bytes now, such as the CPU-stand-in providers + /// in `craft-gpu-providers`. The default drains [`request_read`](Self::request_read) and + /// [`poll_reads`](Self::poll_reads) in a loop; see the trait docs for which backends honestly + /// support blocking here and which override this to fail instead of hanging. + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + loop { + for outcome in self.poll_reads() { + if outcome.request == request { + return outcome.result; + } + } + } + } } diff --git a/crates/gpu/src/error.rs b/crates/gpu/src/error.rs index 2a44f4b6a0..794611efb9 100644 --- a/crates/gpu/src/error.rs +++ b/crates/gpu/src/error.rs @@ -9,6 +9,12 @@ pub enum GpuFault { InvalidJob(String), #[error("device unavailable: {0}")] DeviceUnavailable(String), + /// The device was lost (driver reset, OS eviction, explicit `destroy()`) after it was + /// created. Every [`crate::DeviceCaps`] read before this point is stale: per + /// [`crate::GpuContext`]'s trait docs, fall back to the portable path or re-acquire a device + /// and re-probe caps. Never keep dispatching jobs against a context that reported this. + #[error("device lost: {0}")] + DeviceLost(String), #[error("operation failed: {0}")] Operation(String), } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index bf4993f30e..58ba45ebd0 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -19,7 +19,7 @@ mod tests; pub use caps::DeviceCaps; pub use chunk::chunk_buffer; -pub use context::{GpuContext, WorkerKind}; +pub use context::{GpuContext, ReadOutcome, ReadRequest, WorkerKind}; pub use error::GpuFault; pub use job::{GpuJob, GpuJobOutcome, GpuJobParams, HandleId}; pub use provider::GpuProvider; diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 411f64311a..56ea34e109 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1,13 +1,15 @@ #![allow(clippy::expect_used)] use crate::{ - DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, WorkerKind, chunk_buffer, f16_rgba_to_f32_bytes, f16_to_f32, - f16_to_f32_fast, + DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind, chunk_buffer, + f16_rgba_to_f32_bytes, f16_to_f32, f16_to_f32_fast, }; struct MemContext { caps: DeviceCaps, buffers: Vec>, + next_request: u64, + ready: Vec, } impl GpuContext for MemContext { @@ -29,19 +31,44 @@ impl GpuContext for MemContext { self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { - self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + fn request_read(&mut self, handle: HandleId) -> Result { + let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let request = ReadRequest(self.next_request); + self.next_request = self.next_request.wrapping_add(1); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) } + + fn poll_reads(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } +} + +fn mem_context() -> MemContext { + MemContext { caps: DeviceCaps::default(), buffers: Vec::new(), next_request: 0, ready: Vec::new() } } #[test] fn unknown_provider_is_fault() { let registry = ProviderRegistry::new(); - let mut ctx = MemContext { caps: DeviceCaps::default(), buffers: Vec::new() }; + let mut ctx = mem_context(); let job = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; assert!(matches!(registry.dispatch(&mut ctx, &job), Err(GpuFault::UnknownProvider(_)))); } +#[test] +fn read_buffer_default_resolves_against_request_read_and_poll_reads() { + let mut ctx = mem_context(); + let handle = ctx.upload_buffer("in", b"hello").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"hello".to_vec()); +} + +#[test] +fn request_read_on_bad_handle_is_invalid_job() { + let mut ctx = mem_context(); + assert!(matches!(ctx.request_read(HandleId(99)), Err(GpuFault::InvalidJob(_)))); +} + #[test] fn f16_to_f32_matches_fast_for_one() { let h = 0x3c00u16; diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md index 1e7a383cd0..35527d5b0b 100644 --- a/docs/gpu-backends.md +++ b/docs/gpu-backends.md @@ -8,7 +8,54 @@ Feature flags on `craft-gpu-wgpu`: -- `adapter-probe` — native only; uses pollster to `request_adapter` and fill real [`DeviceCaps`](../crates/gpu/src/caps.rs) (falls back when no GPU, e.g. CI). -- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. +- `adapter-probe` — native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. -On `wasm32`, wgpu is built with the `webgpu` feature; caps probing stays browser-default until async init lands in the worker. +## Real device, device-truth caps (RFC-0022 requirement 1) + +With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device`, not just `request_adapter`. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing — no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. + +Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`), not a `Vec>` staged on the host. + +**The no-adapter path is still defined, not an error.** Without a usable adapter — `adapter-probe` off, no backend feature on, no GPU present, or on `wasm32` (see below) — `WgpuContext` degrades to the same in-memory staging behavior as `craft-gpu-null`. `WgpuContext::has_device()` tells a caller which path it got; `probe_caps()` (no context) stays the quick, adapter-only, advisory estimate it always was. + +**`wasm32` gap, acknowledged, not hidden.** RFC-0022 itself describes browser capability probing moving "from static defaults to real adapter queries once async initialization lands in the worker" — that landing hasn't happened yet. `request_adapter`/`request_device` are JS promises; driving them synchronously the way `pollster::block_on` does natively isn't available on `wasm32`, and wiring the async worker-init path is a larger, separate piece of work. Until then, `WgpuContext` on `wasm32` reports the same conservative, adapter-free defaults it always has. This is the RFC's own acknowledged follow-up, not new scope invented for this PR. + +## Device loss (RFC-0022 requirement 1) + +`WgpuContext` registers `Device::set_device_lost_callback` when it creates a real device. Loss (a driver reset, OS-level eviction, or an explicit `destroy()`) surfaces as `GpuFault::DeviceLost`, from the next buffer call and from `poll_reads()`, never as a panic. + +Once a context has reported `GpuFault::DeviceLost`, every `DeviceCaps` it reported before that point is stale. The stated recovery, per the trait docs on [`GpuContext`](../crates/gpu/src/context.rs): + +1. fall back to the portable path for the rest of the session, or +2. construct a fresh `GpuContext` and re-probe `caps()` before resuming GPU jobs. + +No backend here supports continuing to dispatch jobs against a context that already reported loss, using caps read before it. + +## Async readback (RFC-0022 requirement 3) + +`GpuContext::read_buffer` used to be synchronous. WebGPU can only map a buffer asynchronously (`map_async`), so the trait's real primitives are now `request_read` (queue a readback, get a `ReadRequest`) and `poll_reads` (drain completions). This mirrors `craft-worker-host`'s own async shape: a `HostMessage::GpuJobs { batch_id, .. }` is answered later by `WorkerMessage::GpuBatchDone { batch_id, outcomes }`, not inline; `request_read`/`poll_reads` is the same split one level down, for one buffer instead of one job batch. + +`read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`): + +- `craft-gpu-null`: resolves every request immediately — nothing to wait for. +- `craft-gpu-wgpu`, native, with a real device: blocks by calling `Device::poll(PollType::wait_indefinitely())` between polls, so it waits on the GPU instead of busy-spinning the CPU. +- `craft-gpu-wgpu`, native, staging path (no device): resolves immediately, same as the null context. +- `craft-gpu-wgpu`, `wasm32`: **returns `GpuFault::Operation`, not bytes.** `wasm32` is single-threaded; blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab, not return. A caller there must drive `request_read` + `poll_reads` from the worker's own message loop instead of calling `read_buffer`. + +**Known follow-up on `craft-libs#662`.** That branch's `RuntimeContext` wrapper (`crates/runtime/src/runtime.rs`) implements `GpuContext` by matching on its `Null`/`Wgpu` variants, including an explicit `read_buffer` arm. When #662 rebases past this PR, that block needs two added match arms (`request_read`, `poll_reads`) delegating to each inner context the same way the existing methods do, and its own `read_buffer` arm can simply be deleted in favor of the trait's default (or kept, delegating the same way). No logic in `craft-worker-host` or the runtime facade changes: `HostMessage::GpuJobs` still dispatches a whole batch synchronously today, same as before this PR. + +## Named consumers (RFC-0022's "what this RFC decides") + +- **First: the runtime slice**, `craft-libs#662` (`craft-worker-host`, the worker-host executing `GpuJob` batches; `craft-runtime`, the facade `RuntimeBuilder`/`Runtime` build on top of `GpuContext`). +- **Second: the render-path apps**, EffectCraft and FilmCraft. Neither has adopted these crates yet (see `docs/pilot-effectcraft.md`, `docs/pilot-filmcraft.md`); both already carry their own hand-rolled wgpu code today: + - **FilmCraft** (`storytold/filmcraft`, `crates/gpu` = `filmcraft-gpu`): a monitor/preview `GpuCompositor` over `composite.wgsl`, `mask.rs`/`mask.wgsl`, `lut.rs`/`lut.wgsl`, `transition.rs`/`transition.wgsl`, plus its own adapter-selection policy (`adapter.rs`, see device ownership below) and a separate off-screen `ExportRenderer`. The pilot doc orders `craft.mask`, `craft.lut`, `craft.transition`, then `craft.composite`/`craft.readback` as the extraction sequence into `craft-gpu-providers`. + - **EffectCraft** (`storytold/effectcraft`, `apps/effectcraft-web`): its own `store.rs`/`persist.rs`/`diskcache.rs` and dedicated-worker GPU dispatch (`worker.rs`, `frames.rs`); app-specific jobs route through `effectcraft.*` provider ids once it adopts `craft-runtime`, with the shared `craft.*` ids from this slice used alongside them. + +## Device ownership, when egui's wgpu renderer is also running + +The question that decides whether a render-path app can adopt `WgpuContext` as-is: who owns the `Device`/`Queue` when egui (via `eframe`/`egui-wgpu`) is also drawing? + +**FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created — one device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. + +`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor — it does not change `GpuContext`'s trait shape — but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md index 33e5a021e9..0705b9124f 100644 --- a/docs/gpu-providers.md +++ b/docs/gpu-providers.md @@ -12,3 +12,7 @@ Provider ids: Generic worker code must only call `ProviderRegistry::dispatch` — never import app gpu crates. Dependency lint: **craft-gpu-providers** must not depend on `effectcraft-*`, `filmcraft-*`, or `*-engine`. + +## Readback is async underneath; these providers don't see it + +`GpuContext::read_buffer`, the method every provider above calls, is a blocking convenience over the trait's real primitives, `request_read` + `poll_reads` (see [gpu-backends.md](./gpu-backends.md)). Nothing in this crate changed for that: `craft-gpu-null` still resolves `read_buffer` immediately, and `craft-gpu-wgpu`'s native path now does too, by blocking on the device between polls instead of staging in a plain `Vec>`. `crates/gpu-wgpu/src/tests.rs` runs these same providers (`craft.test.echo`, `craft.composite.premul`, `craft.readback`) against a real `WgpuContext`, not just the null one, when a real adapter is available (RFC-0022 requirement 2). A provider dispatching a real WGSL job will be the one that actually needs the non-blocking `request_read`/`poll_reads` shape directly, since on `wasm32` `read_buffer` itself returns a fault rather than blocking. From 1ccaafb7ab7564af30341324601ce8071002541a Mon Sep 17 00:00:00 2001 From: William Dunn Date: Tue, 10 Nov 2026 21:20:50 -0500 Subject: [PATCH 07/47] craft-gpu: buffer-size guards, empty-buffer parity, read_buffer keeps other completions Answers the six findings in CodeRabbit review 5852678306 on PR #663. upload_buffer on the device path refuses a padded size past the device's max_buffer_size with GpuFault::InvalidJob before creating the buffer. request_read guards its staging copy the same way. An oversized request used to reach wgpu as a validation error on the device's error scope. Empty buffers are accepted everywhere, matching craft-gpu-null and the documented staging parity. The device path resolves an empty readback immediately (wgpu refuses an empty map range). The blanket InvalidJob on empty upload bytes is gone. read_buffer no longer eats completions that belong to another outstanding request. The wgpu override re-queues them for the next poll_reads. The null context gains an override that takes only its own completion. The trait's default-body contract is documented: with the default body, do not interleave read_buffer with an outstanding request_read. ReadbackProvider validates the storage-binding cap directly. The old chunk_buffer call allocated a Vec of slices only to drop it. parse_u32 and params_contain refuse an empty prefix or needle. windows(0) panics and the crate's rule is never to crash. The manifest guard test now also rejects *-engine dependency lines, per docs/gpu-providers.md. --- crates/gpu-null/src/lib.rs | 35 +++++++++++++++++- crates/gpu-providers/src/params.rs | 6 ++- crates/gpu-providers/src/readback.rs | 10 +++-- crates/gpu-providers/src/tests.rs | 15 +++++++- crates/gpu-wgpu/src/lib.rs | 36 ++++++++++++++++-- crates/gpu-wgpu/src/tests.rs | 55 ++++++++++++++++++++++++++++ crates/gpu/src/context.rs | 6 +++ 7 files changed, 152 insertions(+), 11 deletions(-) diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index b28fdf80b2..f5c6dbb188 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -6,8 +6,10 @@ use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadReq /// In-memory buffer store; no GPU hardware required. Reads resolve synchronously (there is /// nothing to wait for), so [`request_read`](GpuContext::request_read) and -/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially, and the default -/// [`read_buffer`](GpuContext::read_buffer) never loops more than once. +/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially. +/// [`read_buffer`](GpuContext::read_buffer) is overridden to take only its own completion, +/// leaving completions for other outstanding requests queued for the next +/// [`poll_reads`](GpuContext::poll_reads). pub struct NullContext { caps: DeviceCaps, worker_kind: WorkerKind, @@ -58,6 +60,14 @@ impl GpuContext for NullContext { fn poll_reads(&mut self) -> Vec { std::mem::take(&mut self.ready) } + + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + match self.ready.iter().position(|o| o.request == request) { + Some(i) => self.ready.remove(i).result, + None => Err(GpuFault::Operation("request_read did not resolve synchronously".into())), + } + } } #[cfg(test)] @@ -85,4 +95,25 @@ mod tests { let handle = ctx.upload_buffer("in", b"xyz").expect("upload_buffer"); assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"xyz".to_vec()); } + + #[test] + fn read_buffer_keeps_another_outstanding_requests_completion_queued() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1, "a's completion must survive b's read_buffer"); + assert_eq!(outcomes[0].request, request_a); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); + } + + #[test] + fn an_empty_buffer_uploads_and_reads_back_empty() { + let mut ctx = NullContext::new(WorkerKind::Main); + let handle = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); + } } diff --git a/crates/gpu-providers/src/params.rs b/crates/gpu-providers/src/params.rs index 2327aa3efa..7571897dfe 100644 --- a/crates/gpu-providers/src/params.rs +++ b/crates/gpu-providers/src/params.rs @@ -1,6 +1,10 @@ use craft_gpu::GpuJobParams; pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option { + // `windows(0)` panics; an empty prefix is a caller bug, answered with None, not a crash. + if prefix.is_empty() { + return None; + } let bytes = params.0.as_slice(); let start = bytes.windows(prefix.len()).position(|w| w == prefix)? + prefix.len(); let rest = &bytes[start..]; @@ -9,5 +13,5 @@ pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option { } pub(crate) fn params_contain(params: &GpuJobParams, needle: &[u8]) -> bool { - params.0.windows(needle.len()).any(|w| w == needle) + !needle.is_empty() && params.0.windows(needle.len()).any(|w| w == needle) } diff --git a/crates/gpu-providers/src/readback.rs b/crates/gpu-providers/src/readback.rs index fb27f798ca..1428fba588 100644 --- a/crates/gpu-providers/src/readback.rs +++ b/crates/gpu-providers/src/readback.rs @@ -1,4 +1,4 @@ -use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, chunk_buffer, f16_rgba_to_f32_bytes}; +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, f16_rgba_to_f32_bytes}; use crate::params::{params_contain, parse_u32}; @@ -15,8 +15,12 @@ impl GpuProvider for ReadbackProvider { let height = parse_u32(&job.params, b"h:").unwrap_or(0); let input = job.inputs.first().copied().ok_or_else(|| GpuFault::InvalidJob("craft.readback expects one input buffer".into()))?; let raw = ctx.read_buffer(input)?; - let caps = ctx.caps(); - let _chunks = chunk_buffer(&caps, &raw)?; + // A real GPU provider binds the input as a storage buffer. Refuse a caps report no + // device path could satisfy, instead of pretending this stand-in's readback would have + // worked there. + if ctx.caps().max_storage_buffer_binding_size == 0 { + return Err(GpuFault::Operation("max_storage_buffer_binding_size must be non-zero".into())); + } let out_bytes = if params_contain(&job.params, b"fmt:u8") { let need = usize::try_from(width.saturating_mul(height).saturating_mul(4)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; diff --git a/crates/gpu-providers/src/tests.rs b/crates/gpu-providers/src/tests.rs index b996ca57b2..650ae22e62 100644 --- a/crates/gpu-providers/src/tests.rs +++ b/crates/gpu-providers/src/tests.rs @@ -38,12 +38,25 @@ fn gpu_providers_cargo_has_no_app_deps() { for line in manifest.lines() { let t = line.trim(); assert!( - !(t.starts_with("effectcraft") || t.starts_with("filmcraft") || t.contains("effectcraft-") || t.contains("filmcraft-")), + !(t.starts_with("effectcraft") + || t.starts_with("filmcraft") + || t.contains("effectcraft-") + || t.contains("filmcraft-") + || t.contains("-engine =") + || t.contains("-engine.") + || t.contains("-engine\"")), "forbidden app dependency line: {t}" ); } } +#[test] +fn empty_param_prefix_and_needle_are_refused_not_a_panic() { + let params = GpuJobParams(b"w:3,h:2".to_vec()); + assert_eq!(crate::params::parse_u32(¶ms, b""), None); + assert!(!crate::params::params_contain(¶ms, b"")); +} + #[test] fn mask_provider_multiplies_rgba_by_mask_on_cpu() { let mut registry = ProviderRegistry::new(); diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 009fd1e4b4..cdc1343b75 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -280,9 +280,6 @@ impl GpuContext for WgpuContext { if let Some(fault) = self.take_lost_fault() { return Err(fault); } - if bytes.is_empty() { - return Err(GpuFault::InvalidJob("upload_buffer: bytes must be non-empty".into())); - } match &mut self.backing { Backing::Staging(buffers) => { let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; @@ -293,6 +290,12 @@ impl GpuContext for WgpuContext { Backing::Device(d) => { let true_len = bytes.len() as u64; let padded_len = true_len.next_multiple_of(COPY_ALIGN); + if padded_len > self.caps.max_buffer_size { + return Err(GpuFault::InvalidJob(format!( + "upload_buffer: {true_len} bytes (padded to {padded_len}) exceeds the device's max_buffer_size {}", + self.caps.max_buffer_size + ))); + } let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, @@ -345,7 +348,22 @@ impl GpuContext for WgpuContext { Backing::Device(d) => { let (buffer, true_len) = d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let true_len = *true_len; + if true_len == 0 { + // An empty buffer has nothing to copy or map (wgpu refuses an empty map + // range); resolve it immediately, same as the staging path. + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + self.ready.push(ReadOutcome { request, handle, result: Ok(Vec::new()) }); + return Ok(request); + } let copy_len = true_len.next_multiple_of(COPY_ALIGN); + if copy_len > self.caps.max_buffer_size { + return Err(GpuFault::Operation(format!( + "request_read: staging copy of {copy_len} bytes exceeds the device's max_buffer_size {}", + self.caps.max_buffer_size + ))); + } let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, @@ -401,11 +419,21 @@ impl GpuContext for WgpuContext { fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { let request = self.request_read(handle)?; loop { + let mut matched = None; + let mut others = Vec::new(); for outcome in self.poll_reads() { if outcome.request == request { - return outcome.result; + matched = Some(outcome.result); + } else { + others.push(outcome); } } + // Completions belonging to other outstanding requests go back on the queue for the + // caller's next poll_reads instead of being dropped. + self.ready.extend(others); + if let Some(result) = matched { + return result; + } // Block on the GPU between polls instead of busy-spinning the CPU. A no-op when // `backing` is `Staging` (nothing to wait for; the request already resolved above) // or when wgpu is itself WebGPU under the hood, which self-polls. diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 0ea49d5dfc..0199168e9b 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -150,3 +150,58 @@ fn device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls() { let after = ctx.upload_buffer("after-loss", b"x"); assert!(matches!(after, Err(GpuFault::DeviceLost(_))), "a call after device loss must return GpuFault::DeviceLost, got {after:?}"); } + +/// The staging path promises "same shape as `craft-gpu-null`": an empty upload is accepted and +/// reads back empty rather than being refused. +#[test] +fn staging_path_accepts_an_empty_buffer_and_reads_it_back_empty() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let handle = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); +} + +/// `read_buffer` must not eat completions that belong to another outstanding `request_read`. +#[test] +fn staging_read_buffer_keeps_another_outstanding_requests_completion_queued() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1, "a's completion must survive b's read_buffer"); + assert_eq!(outcomes[0].request, request_a); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); +} + +/// Same two guarantees on a real device: empty buffers round-trip (the readback resolves without +/// mapping, since wgpu refuses an empty map range) and `read_buffer` re-queues completions that +/// belong to another outstanding request. +#[test] +fn real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging() { + let Some(mut ctx) = real_context_or_skip("real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging") else { + return; + }; + let empty = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(empty).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(empty).expect("read_buffer empty"), Vec::::new()); + + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let mut seen_a = false; + for _ in 0..1000 { + for outcome in ctx.poll_reads() { + if outcome.request == request_a { + assert_eq!(outcome.result.as_deref(), Ok(b"aa".as_slice())); + seen_a = true; + } + } + if seen_a { + break; + } + } + assert!(seen_a, "a's completion must still arrive through poll_reads after b's read_buffer"); +} diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index df0d5e308a..3d27a465ae 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -81,6 +81,12 @@ pub trait GpuContext { /// in `craft-gpu-providers`. The default drains [`request_read`](Self::request_read) and /// [`poll_reads`](Self::poll_reads) in a loop; see the trait docs for which backends honestly /// support blocking here and which override this to fail instead of hanging. + /// + /// The default body has nowhere to put completions that belong to other requests, so it + /// drops them: with the default body, never call this while another + /// [`request_read`](Self::request_read) is outstanding. A backend that stores completions + /// overrides this to put the other requests' outcomes back for the next + /// [`poll_reads`](Self::poll_reads); both bundled backends do. fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { let request = self.request_read(handle)?; loop { From 9c25dd40c0001655590a3b72f56ffb221927add6 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 11:27:29 -0500 Subject: [PATCH 08/47] craft-gpu: per-job batch results, wasm staging reads resolve Two findings CodeRabbit raised against the carried copy on PR 662, fixed here where the crates live. dispatch_batch now answers per job in input order. The old first-failure abort discarded outcomes earlier providers had already produced, leaving the caller nothing to reply with and no way to name the jobs worth retrying. A job fed by a failed predecessor fails honestly on its own bad handles. On wasm32 read_buffer now serves the staging backing, whose reads resolve synchronously. The backing on that target is always staging today. The refusal remains for a read that did not resolve synchronously, guarding the future wasm device backing where blocking would hang the tab. --- crates/gpu-wgpu/src/lib.rs | 30 +++++++++++++++++++----------- crates/gpu/src/registry.rs | 12 ++++++------ crates/gpu/src/tests.rs | 24 ++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 17 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index cdc1343b75..2dfd5e15dc 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -444,17 +444,25 @@ impl GpuContext for WgpuContext { } } - /// WebGPU can only map a buffer asynchronously, and `wasm32` is single-threaded: blocking - /// here would stop the only thread the browser needs to run `map_async`'s own completion - /// callback on, hanging the tab instead of returning. Callers on this target drive - /// [`request_read`](GpuContext::request_read) and [`poll_reads`](GpuContext::poll_reads) - /// directly from the worker's message loop; see `docs/gpu-backends.md`. + /// On `wasm32` the backing is always the in-memory staging store today (real device + /// creation needs the async worker-init path and does not exist on this target yet), and a + /// staging read resolves synchronously, so serving it blocks nothing. The refusal below + /// guards the future wasm device backing: WebGPU can only map a buffer asynchronously, and + /// `wasm32` is single-threaded, so blocking on a real device would stop the only thread the + /// browser needs to run `map_async`'s own completion callback on, hanging the tab. Callers + /// on a device backing drive [`request_read`](GpuContext::request_read) and + /// [`poll_reads`](GpuContext::poll_reads) from the worker's message loop instead; see + /// `docs/gpu-backends.md`. #[cfg(target_arch = "wasm32")] - fn read_buffer(&mut self, _handle: HandleId) -> Result, GpuFault> { - Err(GpuFault::Operation( - "read_buffer is not supported on wasm32/WebGPU: it can only map asynchronously. Use request_read + poll_reads from the worker's \ - message loop instead." - .into(), - )) + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + match self.ready.iter().position(|o| o.request == request) { + Some(i) => self.ready.remove(i).result, + None => Err(GpuFault::Operation( + "read_buffer on wasm32: the read did not resolve synchronously. Use request_read + poll_reads from the worker's message loop \ + instead." + .into(), + )), + } } } diff --git a/crates/gpu/src/registry.rs b/crates/gpu/src/registry.rs index 9a970da8ba..5e9d978dea 100644 --- a/crates/gpu/src/registry.rs +++ b/crates/gpu/src/registry.rs @@ -29,11 +29,11 @@ impl ProviderRegistry { Err(GpuFault::UnknownProvider(job.provider_id.clone())) } - pub fn dispatch_batch(&self, ctx: &mut dyn GpuContext, jobs: &[GpuJob]) -> Result, GpuFault> { - let mut out = Vec::with_capacity(jobs.len()); - for job in jobs { - out.push(self.dispatch(ctx, job)?); - } - Ok(out) + /// Run every job in order and answer per job, in input order. A later job's failure never + /// discards outcomes earlier providers already produced: the caller replies per job and can + /// retry exactly the failed ones. A job whose inputs came from a failed earlier job fails + /// honestly on its own bad handles. + pub fn dispatch_batch(&self, ctx: &mut dyn GpuContext, jobs: &[GpuJob]) -> Vec> { + jobs.iter().map(|job| self.dispatch(ctx, job)).collect() } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 56ea34e109..0bf86ae1bf 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -56,6 +56,30 @@ fn unknown_provider_is_fault() { assert!(matches!(registry.dispatch(&mut ctx, &job), Err(GpuFault::UnknownProvider(_)))); } +#[test] +fn dispatch_batch_keeps_completed_outcomes_when_a_later_job_fails() { + struct Echo; + impl crate::GpuProvider for Echo { + fn id(&self) -> &'static str { + "test.echo" + } + fn run(&self, _ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + Ok(crate::GpuJobOutcome { outputs: vec![], data: Some(job.params.0.clone()) }) + } + } + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(Echo)); + let mut ctx = mem_context(); + let ok = GpuJob { provider_id: "test.echo".into(), params: GpuJobParams(b"first".to_vec()), inputs: vec![], outputs: vec![] }; + let bad = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + let ok2 = GpuJob { provider_id: "test.echo".into(), params: GpuJobParams(b"third".to_vec()), inputs: vec![], outputs: vec![] }; + let results = registry.dispatch_batch(&mut ctx, &[ok, bad, ok2]); + assert_eq!(results.len(), 3, "one entry per job, in input order"); + assert_eq!(results[0].as_ref().expect("first job succeeded").data.as_deref(), Some(b"first".as_slice())); + assert!(matches!(results[1], Err(GpuFault::UnknownProvider(_)))); + assert_eq!(results[2].as_ref().expect("job after the failure still ran").data.as_deref(), Some(b"third".as_slice())); +} + #[test] fn read_buffer_default_resolves_against_request_read_and_poll_reads() { let mut ctx = mem_context(); From a0951756a22865b8de325fd06890d3fba8cf9d7a Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:00:20 -0500 Subject: [PATCH 09/47] Add free_buffer and device_status to GpuContext. Two CodeRabbit findings against crates/gpu-wgpu, both answered at the trait level since craft-gpu-null has the exact same gap. free_buffer (lib.rs:313). Every upload_buffer call added an entry to a backend's buffer table. So did every output buffer a provider's job created. Nothing ever removed one. Repeated jobs retained memory for the whole lifetime of a context. The new required method releases a buffer's resources. A freed handle behaves as invalid afterward, the same fault an unknown handle already produces. device_status (lib.rs:401). poll_reads can only attach a device-lost fault to a read it has something to attach it to. A caller whose event loop only polls, with nothing pending when loss happens, could never observe it. The new method, default Ok(()), covers that gap directly; a backend with no concept of device loss needs no override. MemContext in this crate's own tests gets the same free_buffer shape as craft-gpu-null, to keep it compiling under the new required method. --- crates/gpu/src/context.rs | 25 +++++++++++++++++++++++++ crates/gpu/src/tests.rs | 17 +++++++++++++---- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 3d27a465ae..22ca694e49 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -75,8 +75,33 @@ pub trait GpuContext { /// fault surfaces for callers that are polling rather than issuing buffer calls. A context /// that resolves reads synchronously (the null context; native wgpu with no device) may /// resolve a request on the very next call after [`request_read`](Self::request_read). + /// + /// This can only attach a device-lost fault to a read it has something to attach it to: when + /// nothing is outstanding, there is no [`ReadOutcome`] to fabricate one onto. A caller whose + /// event loop only polls, with no buffer calls and no outstanding read, uses + /// [`device_status`](Self::device_status) for that gap. fn poll_reads(&mut self) -> Vec; + /// Device loss observable independent of any specific read or buffer call, covering the gap + /// [`poll_reads`](Self::poll_reads) has when nothing is outstanding to attach the fault to. + /// The default is `Ok(())`: correct for any backend with no concept of device loss (the null + /// context; the staging/no-device path here). A backend that can lose a device overrides + /// this to report it. + fn device_status(&self) -> Result<(), GpuFault> { + Ok(()) + } + + /// Release a previously uploaded buffer's resources. A no-op, not an error, for a handle + /// that is already invalid or was already freed: callers are never required to track + /// whether they already freed one. A freed handle behaves as invalid afterward (the same + /// fault a never-issued handle would produce) from every other method on this trait. + /// + /// Without this, a backend's buffer table -- and the memory behind it -- can only ever grow + /// for the context's lifetime: every `upload_buffer`, and every output buffer a provider's + /// job creates, adds an entry nothing removes. Repeated jobs then retain GPU (or host, for + /// the null context) memory long after every caller is done with every handle it created. + fn free_buffer(&mut self, handle: HandleId); + /// Blocking convenience for callers that need bytes now, such as the CPU-stand-in providers /// in `craft-gpu-providers`. The default drains [`request_read`](Self::request_read) and /// [`poll_reads`](Self::poll_reads) in a loop; see the trait docs for which backends honestly diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0bf86ae1bf..40ac0583c1 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -7,7 +7,9 @@ use crate::{ struct MemContext { caps: DeviceCaps, - buffers: Vec>, + /// `None` means freed (or never allocated): handles are stable indices, so a freed slot + /// cannot simply be removed without shifting every later handle's index. + buffers: Vec>>, next_request: u64, ready: Vec, } @@ -23,16 +25,17 @@ impl GpuContext for MemContext { fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); - self.buffers.push(bytes.to_vec()); + self.buffers.push(Some(bytes.to_vec())); Ok(id) } fn buffer_len(&self, handle: HandleId) -> Result { - self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); @@ -42,6 +45,12 @@ impl GpuContext for MemContext { fn poll_reads(&mut self) -> Vec { std::mem::take(&mut self.ready) } + + fn free_buffer(&mut self, handle: HandleId) { + if let Some(slot) = self.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } } fn mem_context() -> MemContext { From 5b33ccf51353b1df600ddf80166c952dec811a6c Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:00:52 -0500 Subject: [PATCH 10/47] Implement free_buffer for NullContext. buffers moves from Vec> to Vec>>. A handle is a stable index. Freeing a slot replaces it with None. Removing it instead would shift every later handle's index out from under its caller. buffer_len and request_read now reject a freed index the same way they already reject one that never existed. Two new tests. One frees a handle and checks another's index and bytes stay untouched. One frees a handle twice, and a handle that never existed, and confirms both are a harmless no-op. --- crates/gpu-null/src/lib.rs | 50 +++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index f5c6dbb188..8a880a6a55 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -13,7 +13,9 @@ use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadReq pub struct NullContext { caps: DeviceCaps, worker_kind: WorkerKind, - buffers: Vec>, + /// `None` means freed (or never allocated): handles are stable indices into this Vec, so a + /// freed slot cannot simply be removed without shifting every later handle's index. + buffers: Vec>>, next_request: u64, ready: Vec, } @@ -41,16 +43,17 @@ impl GpuContext for NullContext { fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); - self.buffers.push(bytes.to_vec()); + self.buffers.push(Some(bytes.to_vec())); Ok(id) } fn buffer_len(&self, handle: HandleId) -> Result { - self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); @@ -68,14 +71,21 @@ impl GpuContext for NullContext { None => Err(GpuFault::Operation("request_read did not resolve synchronously".into())), } } + + /// Replaces the slot with `None` rather than removing it: handles are stable indices, and + /// removing would shift every later handle's index out from under its caller. + fn free_buffer(&mut self, handle: HandleId) { + if let Some(slot) = self.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } } #[cfg(test)] mod tests { - use craft_gpu::GpuContext; + use craft_gpu::{GpuContext, GpuFault, HandleId, WorkerKind}; use super::NullContext; - use craft_gpu::WorkerKind; #[test] fn request_read_then_poll_reads_delivers_the_same_bytes_as_read_buffer() { @@ -116,4 +126,32 @@ mod tests { assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); } + + /// CodeRabbit finding on gpu-wgpu/src/lib.rs:313: nothing released an uploaded buffer's + /// resources, so a backend's buffer table could only ever grow. free_buffer must actually + /// reclaim the payload and make the handle behave as invalid afterward, not just forget it + /// exists while still holding its bytes. + #[test] + fn free_buffer_invalidates_the_handle_and_does_not_shift_other_handles() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(GpuFault::InvalidJob(_))), "a freed handle must behave as invalid"); + assert_eq!(ctx.buffer_len(b).expect("b must be unaffected by freeing a"), 2); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec(), "b's own index must not have shifted"); + } + + /// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not + /// expected to track whether they already freed one. + #[test] + fn free_buffer_is_a_harmless_no_op_when_repeated_or_given_an_unknown_handle() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + ctx.free_buffer(a); + ctx.free_buffer(a); // already freed + ctx.free_buffer(HandleId(999)); // never existed + } } From 4aefc2dbbac9d606283c7bfa8516a01221dd3e55 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:01:51 -0500 Subject: [PATCH 11/47] Fix the no-device caps fallback, capture allocation failures, free buffers. Four CodeRabbit findings against this crate. The no-device fallback in WgpuContext::new called probe_caps() again on request_device failure (lib.rs:228). A second, successful adapter query would then report the adapter's advertised limits as if they came from a granted device, for a context that holds none. It now falls back to the plain, fixed caps probe_caps's own doc comment already promises for that case. Allocation failures during buffer creation used to reach wgpu's default uncaptured-error handler (lib.rs:299). That handler panics. The size check already in place only catches a request past the device's advertised maximum. It says nothing about whether the device can actually allocate that many bytes right now. An error scope around both the output-buffer and the read-staging-buffer creation converts a failure into a GpuFault instead. free_buffer for WgpuContext (lib.rs:313) matches the Option-wrapped shape just added to craft-gpu-null. Both backings, staging and real device, release a buffer's resources and make the handle behave as invalid afterward, without shifting any other handle's index. device_status for WgpuContext (lib.rs:401) reports device loss through the trait method just added to GpuContext. A caller that only polls can now observe loss even with nothing pending. New tests cover the fixed fallback value and a regression check that the new allocation error scope does not misfire on an ordinary allocation. They also cover free_buffer on both the staging and the real-device path. One more covers device_status observing a destroyed device with nothing outstanding. A genuine out-of-memory condition is not reliably reproducible in CI; the allocation-failure test is the honest half of that fix this can run. --- crates/gpu-wgpu/src/lib.rs | 97 ++++++++++++++++++++++++++++++------ crates/gpu-wgpu/src/tests.rs | 97 ++++++++++++++++++++++++++++++++++++ 2 files changed, 180 insertions(+), 14 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 2dfd5e15dc..efbe432e9a 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -139,14 +139,16 @@ mod native { /// No real device: buffers live on the host, exactly like `craft-gpu-null`. RFC-0022's defined /// degrade path for "no adapter" (feature off, no GPU present, or the `wasm32` async-init gap). +/// Each slot is `None` once freed (or never allocated): handles are stable indices, so a freed +/// slot cannot simply be removed without shifting every later handle's index. #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] enum Backing { - Staging(Vec>), + Staging(Vec>>), } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] enum Backing { - Staging(Vec>), + Staging(Vec>>), /// A real device. `DeviceCaps` was built from it, not from the adapter it came from. Device(DeviceBacking), } @@ -158,8 +160,9 @@ struct DeviceBacking { /// Each buffer paired with its true, caller-given byte length. wgpu requires every buffer /// with copy usage to be sized in multiples of [`COPY_ALIGN`]; the buffer itself is padded to /// that, but callers (`buffer_len`, `request_read`'s returned bytes) see the true length, - /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. - buffers: Vec<(wgpu::Buffer, u64)>, + /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None` + /// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting. + buffers: Vec>, /// Set by the device-lost callback registered in [`native::create_device`]; checked before /// every call that would otherwise touch the (now invalid) device. lost: std::sync::Arc>>, @@ -224,7 +227,20 @@ impl WgpuContext { if let Some((caps, backing)) = native::create_device() { return Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }; } + // request_adapter and/or request_device failed: fall back to the conservative + // fallback, never probe_caps(). probe_caps() would re-query the adapter here, and a + // second, successful adapter query would report the adapter's advertised limits as + // if they came from a granted device -- the exact thing probe_caps's own doc comment + // says caps() must never do for a context with no device. + return Self { + caps: probe_fallback("wgpu", "no-device"), + worker_kind, + backing: Backing::Staging(Vec::new()), + next_request: 0, + ready: Vec::new(), + }; } + #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } @@ -283,7 +299,7 @@ impl GpuContext for WgpuContext { match &mut self.backing { Backing::Staging(buffers) => { let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; - buffers.push(bytes.to_vec()); + buffers.push(Some(bytes.to_vec())); Ok(HandleId(id)) } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] @@ -296,6 +312,13 @@ impl GpuContext for WgpuContext { self.caps.max_buffer_size ))); } + // The size check above only catches a request past the device's advertised + // maximum; it proves nothing about whether the device can actually allocate + // padded_len bytes right now (free VRAM varies). wgpu 30.0.1 sends an allocation + // failure to the default uncaptured-error handler, which panics, unless a scope + // captures it first. An error scope converts that into a value this can return + // as a GpuFault instead of taking the worker down with it. + d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, @@ -309,8 +332,11 @@ impl GpuContext for WgpuContext { padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); d.queue.write_buffer(&buffer, 0, &padded); } + if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error: {err}"))); + } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; - d.buffers.push((buffer, true_len)); + d.buffers.push(Some((buffer, true_len))); Ok(HandleId(id)) } } @@ -321,13 +347,18 @@ impl GpuContext for WgpuContext { return Err(fault); } match &self.backing { - Backing::Staging(buffers) => buffers.get(handle.0 as usize).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())), - #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] - Backing::Device(d) => { - d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then(|(_, true_len)| { - usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) - }) + Backing::Staging(buffers) => { + buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => d + .buffers + .get(handle.0 as usize) + .and_then(Option::as_ref) + .ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + .and_then(|(_, true_len)| { + usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) + }), } } @@ -337,7 +368,8 @@ impl GpuContext for WgpuContext { } match &mut self.backing { Backing::Staging(buffers) => { - let bytes = buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = + buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let id = self.next_request; self.next_request = self.next_request.wrapping_add(1); let request = ReadRequest(id); @@ -346,7 +378,8 @@ impl GpuContext for WgpuContext { } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] Backing::Device(d) => { - let (buffer, true_len) = d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let (buffer, true_len) = + d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let true_len = *true_len; if true_len == 0 { // An empty buffer has nothing to copy or map (wgpu refuses an empty map @@ -364,6 +397,10 @@ impl GpuContext for WgpuContext { self.caps.max_buffer_size ))); } + // Same reasoning as upload_buffer's error scope: an allocation failure for the + // read-staging buffer must become a GpuFault, not reach the default + // uncaptured-error handler and panic. + d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, @@ -373,6 +410,9 @@ impl GpuContext for WgpuContext { let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); + if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error: {err}"))); + } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); { let state = std::sync::Arc::clone(&state); @@ -391,6 +431,35 @@ impl GpuContext for WgpuContext { } } + /// Replaces the slot with `None` rather than removing it: handles are stable indices, and + /// removing would shift every later handle's index out from under its caller. Dropping a + /// `Some((wgpu::Buffer, _))` here releases that buffer's GPU-side allocation. + fn free_buffer(&mut self, handle: HandleId) { + match &mut self.backing { + Backing::Staging(buffers) => { + if let Some(slot) = buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + if let Some(slot) = d.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } + } + } + + /// Covers the gap `poll_reads` has when nothing is pending: that method can only attach a + /// device-lost fault to a read it has something to attach it to, so a caller whose event + /// loop only polls, with no outstanding read, could never observe loss through it alone. + fn device_status(&self) -> Result<(), GpuFault> { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + Ok(()) + } + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_mut))] fn poll_reads(&mut self) -> Vec { let mut outcomes = std::mem::take(&mut self.ready); diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 0199168e9b..787be45797 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -175,6 +175,103 @@ fn staging_read_buffer_keeps_another_outstanding_requests_completion_queued() { assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); } +/// CodeRabbit finding on lib.rs:228: if `request_adapter` succeeds but `request_device` fails, +/// the fallback must be the conservative fixed value, never a second, successful `probe_caps()` +/// adapter query -- which would report the adapter's advertised limits as if they came from a +/// granted device, for a context that holds none. Forcing `request_device` itself to fail is +/// hardware-dependent and not reliably reproducible in CI, so this tests the fallback value +/// `WgpuContext::new` falls back to directly: it must be the plain, fixed value, never one that +/// looks like a real probe result. +#[test] +fn the_no_device_fallback_caps_are_the_plain_fixed_value_not_a_probe_result() { + let caps = crate::probe_fallback("wgpu", "no-device"); + assert_eq!(caps.backend_name, "wgpu"); + assert_eq!(caps.device_name, "no-device"); + assert_eq!(caps, craft_gpu::DeviceCaps { backend_name: "wgpu".into(), device_name: "no-device".into(), ..craft_gpu::DeviceCaps::default() }); +} + +/// CodeRabbit finding on lib.rs:299: an allocation failure used to be able to reach wgpu's +/// default uncaptured-error handler, which panics. An error scope around buffer creation now +/// converts that into a `GpuFault` instead. A genuine out-of-memory condition is not reliably +/// reproducible in CI (it depends on how much free VRAM the host actually has), so this is the +/// regression half: the added error scope must not misfire on an entirely ordinary allocation. +#[test] +fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { + let Some(mut ctx) = real_context_or_skip("upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place") else { + return; + }; + let handle = ctx.upload_buffer("scope-regression", b"ok").expect("a normal allocation must not report a false allocation error"); + assert_eq!(ctx.read_buffer(handle).expect("read back"), b"ok".to_vec()); +} + +/// CodeRabbit finding on lib.rs:313: nothing released an uploaded buffer's resources, so the +/// buffer table (and the GPU memory behind it) could only ever grow. free_buffer must actually +/// make the handle behave as invalid afterward, and must not disturb any other handle's index. +#[test] +fn staging_free_buffer_invalidates_the_handle_without_shifting_others() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(craft_gpu::GpuFault::InvalidJob(_))), "a freed handle must behave as invalid"); + assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); +} + +/// The same guarantee on a real device: freeing one handle must not disturb another's index or +/// its own buffer. +#[test] +fn real_device_free_buffer_invalidates_the_handle_without_shifting_others() { + let Some(mut ctx) = real_context_or_skip("real_device_free_buffer_invalidates_the_handle_without_shifting_others") else { + return; + }; + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(craft_gpu::GpuFault::InvalidJob(_))), "a freed handle must behave as invalid on a real device too"); + assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); +} + +/// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not expected +/// to track whether they already freed one. +#[test] +fn free_buffer_is_a_harmless_no_op_when_repeated_or_given_an_unknown_handle() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + ctx.free_buffer(a); + ctx.free_buffer(a); + ctx.free_buffer(craft_gpu::HandleId(999)); +} + +/// CodeRabbit finding on lib.rs:401: `poll_reads` can only attach a device-lost fault to a read +/// it has something to attach it to, so a caller whose event loop only polls, with nothing +/// outstanding, could never observe loss through it alone. `device_status` covers exactly that +/// gap: it is checked here with no buffer call and no pending read at all after the device is +/// destroyed. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +#[test] +fn device_status_surfaces_loss_even_with_nothing_pending() { + use craft_gpu::GpuFault; + + use crate::Backing; + + let Some(mut ctx) = real_context_or_skip("device_status_surfaces_loss_even_with_nothing_pending") else { + return; + }; + assert_eq!(ctx.device_status(), Ok(()), "a freshly created device must not already report loss"); + + if let Backing::Device(d) = &ctx.backing { + d.device.destroy(); + let _ = d.device.poll(wgpu::PollType::Poll); + } + + // No upload_buffer, no request_read, no poll_reads: device_status() alone must observe it. + assert!(matches!(ctx.device_status(), Err(GpuFault::DeviceLost(_))), "device.destroy() must surface through device_status() alone"); +} + /// Same two guarantees on a real device: empty buffers round-trip (the readback resolves without /// mapping, since wgpu refuses an empty map range) and `read_buffer` re-queues completions that /// belong to another outstanding request. From 8c0a33605bc61a225f66dc4e11d3df733b0a8b0b Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:07:37 -0500 Subject: [PATCH 12/47] Fix the error-scope API call and run cargo fmt. wgpu 30.0.1's Device has no pop_error_scope method. push_error_scope returns an ErrorScopeGuard. pop() lives on that guard. Keep the guard from push_error_scope and call pop() on it. Also drops an unneeded mut on a test binding that never mutates its context. Also runs cargo fmt on the lines the Option-wrapped buffer changes touched. --- crates/gpu-null/src/lib.rs | 3 +-- crates/gpu-wgpu/src/lib.rs | 21 +++++++++------------ crates/gpu-wgpu/src/tests.rs | 2 +- crates/gpu/src/tests.rs | 3 +-- 4 files changed, 12 insertions(+), 17 deletions(-) diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index 8a880a6a55..a1992e4743 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -52,8 +52,7 @@ impl GpuContext for NullContext { } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = - self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index efbe432e9a..b7849d7c4d 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -318,7 +318,7 @@ impl GpuContext for WgpuContext { // failure to the default uncaptured-error handler, which panics, unless a scope // captures it first. An error scope converts that into a value this can return // as a GpuFault instead of taking the worker down with it. - d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, @@ -332,7 +332,7 @@ impl GpuContext for WgpuContext { padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); d.queue.write_buffer(&buffer, 0, &padded); } - if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + if let Some(err) = pollster::block_on(error_scope.pop()) { return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error: {err}"))); } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; @@ -351,14 +351,11 @@ impl GpuContext for WgpuContext { buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] - Backing::Device(d) => d - .buffers - .get(handle.0 as usize) - .and_then(Option::as_ref) - .ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) - .and_then(|(_, true_len)| { - usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) - }), + Backing::Device(d) => { + d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then( + |(_, true_len)| usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())), + ) + } } } @@ -400,7 +397,7 @@ impl GpuContext for WgpuContext { // Same reasoning as upload_buffer's error scope: an allocation failure for the // read-staging buffer must become a GpuFault, not reach the default // uncaptured-error handler and panic. - d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, @@ -410,7 +407,7 @@ impl GpuContext for WgpuContext { let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); - if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + if let Some(err) = pollster::block_on(error_scope.pop()) { return Err(GpuFault::Operation(format!("request_read: device reported an allocation error: {err}"))); } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 787be45797..e681f1fec4 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -258,7 +258,7 @@ fn device_status_surfaces_loss_even_with_nothing_pending() { use crate::Backing; - let Some(mut ctx) = real_context_or_skip("device_status_surfaces_loss_even_with_nothing_pending") else { + let Some(ctx) = real_context_or_skip("device_status_surfaces_loss_even_with_nothing_pending") else { return; }; assert_eq!(ctx.device_status(), Ok(()), "a freshly created device must not already report loss"); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 40ac0583c1..528b2e587d 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -34,8 +34,7 @@ impl GpuContext for MemContext { } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = - self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); From 406b20e14e727f21eca526936f301b89049dc448 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:09:25 -0500 Subject: [PATCH 13/47] Drop a needless return clippy flagged in the adapter-probe lane. The fallback branch in WgpuContext::new is the function's own tail expression once the real-device branch above it has already returned early. The explicit return on it was redundant. --- crates/gpu-wgpu/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index b7849d7c4d..6f2df7a0da 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -232,13 +232,13 @@ impl WgpuContext { // second, successful adapter query would report the adapter's advertised limits as // if they came from a granted device -- the exact thing probe_caps's own doc comment // says caps() must never do for a context with no device. - return Self { + Self { caps: probe_fallback("wgpu", "no-device"), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new(), - }; + } } #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } From c4beee98038e459677466621b148c35e9e2ff287 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:10:52 -0500 Subject: [PATCH 14/47] Run cargo fmt on the no-device fallback branch. --- crates/gpu-wgpu/src/lib.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 6f2df7a0da..948f145b6a 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -232,13 +232,7 @@ impl WgpuContext { // second, successful adapter query would report the adapter's advertised limits as // if they came from a granted device -- the exact thing probe_caps's own doc comment // says caps() must never do for a context with no device. - Self { - caps: probe_fallback("wgpu", "no-device"), - worker_kind, - backing: Backing::Staging(Vec::new()), - next_request: 0, - ready: Vec::new(), - } + Self { caps: probe_fallback("wgpu", "no-device"), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } From 64b1c2f4aa18861eea89a8d4bfea1c1da36190f4 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 17:16:32 -0500 Subject: [PATCH 15/47] Pop the OOM scope before the call that would misuse a failed buffer. upload_buffer popped its scope only after write_buffer. request_read popped its scope only after the copy and its submission. A buffer that failed to create is invalid. Using an invalid buffer raises a VALIDATION error that an OutOfMemory-only scope never catches. The default uncaptured-error handler still panicked on a failed create even with the scope in place. Pop right after create_buffer in both paths and return before the buffer is used again, with a separate scope around the later write or copy. write_buffer only queues its copy into wgpu's PendingWrites. An upload with no following submission kept the destination and staging buffers alive inside wgpu-core until some other submit happened. upload_buffer now flushes with an empty queue.submit right after its own write_buffer call. A free_buffer right after an upload can now actually release the allocation. --- crates/gpu-wgpu/src/lib.rs | 47 +++++++++++++++++++++----- crates/gpu-wgpu/src/tests.rs | 64 +++++++++++++++++++++++++++++++++++- 2 files changed, 101 insertions(+), 10 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 948f145b6a..fb9dd8b7fb 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -310,15 +310,26 @@ impl GpuContext for WgpuContext { // maximum; it proves nothing about whether the device can actually allocate // padded_len bytes right now (free VRAM varies). wgpu 30.0.1 sends an allocation // failure to the default uncaptured-error handler, which panics, unless a scope - // captures it first. An error scope converts that into a value this can return - // as a GpuFault instead of taking the worker down with it. - let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + // captures it first. Pop this scope immediately, before write_buffer below ever + // touches `buffer`: a buffer that failed to create is invalid, and writing to an + // invalid buffer raises its own VALIDATION error, a kind this OutOfMemory-only + // scope does not catch, so it must reach the default handler and panic regardless + // of when this scope is popped. Checking right here is what keeps that from + // happening at all. + let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + if let Some(err) = pollster::block_on(create_scope.pop()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}"))); + } + // write_buffer makes its own staging allocation to carry `bytes` to the device, a + // second allocation that can also run out of memory; it gets its own scope rather + // than reusing the one already closed above. + let write_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); if padded_len == true_len { d.queue.write_buffer(&buffer, 0, bytes); } else { @@ -326,8 +337,16 @@ impl GpuContext for WgpuContext { padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); d.queue.write_buffer(&buffer, 0, &padded); } - if let Some(err) = pollster::block_on(error_scope.pop()) { - return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error: {err}"))); + // write_buffer only records the copy into wgpu's PendingWrites; wgpu-core flushes + // that queue at the sooner of the caller's next real command-buffer submission or + // the next map_async on an affected buffer, and keeps the buffer named by the + // write alive internally until then. Without a submission here, a free_buffer + // right after this call could never actually release the GPU allocation behind + // it, since nothing would ever flush PendingWrites to let it go. An empty submit + // is still a submission as far as that flush is concerned, so it is enough. + d.queue.submit(std::iter::empty()); + if let Some(err) = pollster::block_on(write_scope.pop()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}"))); } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; d.buffers.push(Some((buffer, true_len))); @@ -390,19 +409,29 @@ impl GpuContext for WgpuContext { } // Same reasoning as upload_buffer's error scope: an allocation failure for the // read-staging buffer must become a GpuFault, not reach the default - // uncaptured-error handler and panic. - let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + // uncaptured-error handler and panic. Pop immediately, before copy_buffer_to_buffer + // below ever names `staging` as a copy destination: a staging buffer that failed + // to create is invalid, and copying into an invalid buffer raises its own + // VALIDATION error, a kind this OutOfMemory-only scope does not catch, so it must + // reach the default handler and panic regardless of when this scope is popped. + let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + if let Some(err) = pollster::block_on(create_scope.pop()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}"))); + } + // The copy and its submission get their own scope rather than reusing the one + // already closed above, same split as upload_buffer's create vs. write. + let copy_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); - if let Some(err) = pollster::block_on(error_scope.pop()) { - return Err(GpuFault::Operation(format!("request_read: device reported an allocation error: {err}"))); + if let Some(err) = pollster::block_on(copy_scope.pop()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}"))); } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); { diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index e681f1fec4..29b4bd0227 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -194,7 +194,9 @@ fn the_no_device_fallback_caps_are_the_plain_fixed_value_not_a_probe_result() { /// default uncaptured-error handler, which panics. An error scope around buffer creation now /// converts that into a `GpuFault` instead. A genuine out-of-memory condition is not reliably /// reproducible in CI (it depends on how much free VRAM the host actually has), so this is the -/// regression half: the added error scope must not misfire on an entirely ordinary allocation. +/// regression half: the added error scope must not misfire on an entirely ordinary allocation, +/// across both the create scope and the write scope that now follows it (see the next doc +/// comment for why those are two separate scopes rather than one spanning both calls). #[test] fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { let Some(mut ctx) = real_context_or_skip("upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place") else { @@ -204,6 +206,44 @@ fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { assert_eq!(ctx.read_buffer(handle).expect("read back"), b"ok".to_vec()); } +/// CodeRabbit finding on lib.rs:329 (upload_buffer) and lib.rs:404 (request_read): the original +/// code popped its single error scope only after write_buffer (respectively, after the copy and +/// its submission), so a failed create_buffer would leave an invalid buffer in play across the +/// later call that used it. write_buffer against an invalid buffer raises a VALIDATION error, a +/// kind the OutOfMemory-only scope never catches, so it would reach wgpu's default +/// uncaptured-error handler and panic there instead of surfacing as a `GpuFault` -- the same +/// crash the scope was added to prevent in the first place. +/// +/// A genuine allocation failure is not reliably reproducible in CI (it depends on how much free +/// VRAM/host memory lavapipe actually has to give), so this cannot be a runtime test that forces +/// `create_buffer` to fail and then observes `write_buffer` never ran. What can be verified +/// honestly, and is verified here, is the ordering itself: `upload_buffer`'s source now pops the +/// create scope and returns on error strictly before it pushes the write scope or calls +/// `write_buffer`, and `request_read`'s source pops the staging-buffer create scope and returns +/// on error strictly before it creates the copy encoder or calls `queue.submit`. Both orderings +/// are asserted directly against the source text below rather than left as an unverified claim in +/// a comment; the success-path test above is the runtime half, proving the added scope split does +/// not misfire on the ordinary case. +#[test] +fn a_failed_allocation_scope_pop_is_ordered_strictly_before_the_call_that_would_use_the_buffer() { + let source = include_str!("lib.rs"); + let upload_create_pop = source.find("create_scope.pop()").expect("upload_buffer must pop a create scope"); + let upload_write_scope_push = + source.find("let write_scope = d.device.push_error_scope").expect("upload_buffer must push a separate write scope"); + assert!( + upload_create_pop < upload_write_scope_push, + "upload_buffer must check the create scope's result before it ever pushes the write scope or calls write_buffer" + ); + + let read_create_pop = + source.rfind("device reported an allocation error creating the staging buffer").expect("request_read must pop a create scope"); + let read_copy_scope_push = source.rfind("let copy_scope = d.device.push_error_scope").expect("request_read must push a separate copy scope"); + assert!( + read_create_pop < read_copy_scope_push, + "request_read must check the staging-buffer create scope's result before it ever pushes the copy scope or touches the encoder" + ); +} + /// CodeRabbit finding on lib.rs:313: nothing released an uploaded buffer's resources, so the /// buffer table (and the GPU memory behind it) could only ever grow. free_buffer must actually /// make the handle behave as invalid afterward, and must not disturb any other handle's index. @@ -235,6 +275,28 @@ fn real_device_free_buffer_invalidates_the_handle_without_shifting_others() { assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); } +/// CodeRabbit finding on lib.rs:438: `queue.write_buffer` only records its copy in wgpu's +/// PendingWrites; without some submission to flush that queue, wgpu-core keeps the destination +/// buffer (and the staging buffer `write_buffer` made internally) alive on its own, so repeated +/// upload_buffer/free_buffer cycles would retain GPU allocations with nothing ever releasing +/// them. `upload_buffer` now flushes with an empty `queue.submit` right after its own +/// write_buffer call. This cannot assert freed VRAM directly (wgpu exposes no such counter), so +/// it instead proves the behavioral guarantee this fix is actually for: many upload/free cycles +/// in a row complete without panicking and without ever running out of handles, which is exactly +/// what an unbounded, unflushed retention would eventually threaten on a long-lived worker. +#[test] +fn real_device_upload_and_free_many_cycles_in_a_row_does_not_panic_or_leak_a_growing_table() { + let Some(mut ctx) = real_context_or_skip("real_device_upload_and_free_many_cycles_in_a_row_does_not_panic_or_leak_a_growing_table") else { + return; + }; + for i in 0..256u32 { + let bytes = i.to_le_bytes(); + let handle = ctx.upload_buffer("cycle", &bytes).expect("each upload in the cycle must succeed"); + assert_eq!(ctx.read_buffer(handle).expect("read back this cycle's buffer"), bytes.to_vec()); + ctx.free_buffer(handle); + } +} + /// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not expected /// to track whether they already freed one. #[test] From ca3f6ff1becbcba795717e79be35ef439b394939 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 17:23:19 -0500 Subject: [PATCH 16/47] Run cargo fmt on the new ordering test. --- crates/gpu-wgpu/src/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 29b4bd0227..a4d31c4e39 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -228,8 +228,7 @@ fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { fn a_failed_allocation_scope_pop_is_ordered_strictly_before_the_call_that_would_use_the_buffer() { let source = include_str!("lib.rs"); let upload_create_pop = source.find("create_scope.pop()").expect("upload_buffer must pop a create scope"); - let upload_write_scope_push = - source.find("let write_scope = d.device.push_error_scope").expect("upload_buffer must push a separate write scope"); + let upload_write_scope_push = source.find("let write_scope = d.device.push_error_scope").expect("upload_buffer must push a separate write scope"); assert!( upload_create_pop < upload_write_scope_push, "upload_buffer must check the create scope's result before it ever pushes the write scope or calls write_buffer" From dd2e729f97e77ecf49af359ab91ae6c507e89759 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 18:09:06 -0500 Subject: [PATCH 17/47] craft-gpu-wgpu: correct the crate docs on wasm32 read_buffer The staging backing serves wasm32 reads synchronously since the staging-reads fix. Only a read that did not complete synchronously faults. The crate-level summary still described the old unconditional fault. --- Cargo.lock | 34 ++++++++++++++++++++++++++++++++++ crates/gpu-wgpu/src/lib.rs | 6 ++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 60b7f73401..cecd879879 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1871,6 +1871,40 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-gpu-null" +version = "0.1.0" +dependencies = [ + "craft-gpu", +] + +[[package]] +name = "craft-gpu-providers" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-null", +] + +[[package]] +name = "craft-gpu-wgpu" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-providers", + "pollster 0.4.0", + "wgpu", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index fb9dd8b7fb..4d0e290354 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -14,8 +14,10 @@ //! map a buffer that way. Native, with a real device, drives it with `Buffer::map_async` plus //! `Device::poll`. The blocking `read_buffer` convenience (see //! [`GpuContext`](craft_gpu::GpuContext)'s trait docs) blocks efficiently on native by polling -//! the device while it waits; on `wasm32` it instead returns a fault, since blocking there would -//! freeze the one thread the map's own completion callback needs to run on. +//! the device while it waits. On `wasm32` the backing is always the in-memory staging store +//! today, whose reads complete synchronously, and `read_buffer` serves them; only a read that +//! did not complete synchronously returns a fault there, since blocking would freeze the one +//! thread a real map's completion callback would need to run on. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] From dbfa4892571ef23175ebce05b30d74be32085588 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Thu, 12 Nov 2026 16:36:29 -0500 Subject: [PATCH 18/47] craft-gpu: sync the docs with the implemented readback behavior Review asked for three corrections. The backends doc, the providers doc and the trait docs now state that both bundled backends override read_buffer's default body and that wasm32 serves the staging read, with a fault only for a read that did not resolve synchronously. The runtime follow-up paragraph now records that #662 consumed it. The software Vulkan container run is described as local testing. Hosted CI coverage and the pilot consumers' browser and hardware validation remain their own requirements. Em dashes swept from both docs per the house writing rules. --- crates/gpu-wgpu/src/lib.rs | 2 +- crates/gpu-wgpu/src/tests.rs | 4 +++- crates/gpu/src/context.rs | 25 ++++++++++++++----------- docs/gpu-backends.md | 26 +++++++++++++------------- docs/gpu-providers.md | 16 ++++++++-------- 5 files changed, 39 insertions(+), 34 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 4d0e290354..9a6364f4ee 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -86,7 +86,7 @@ mod native { /// An instance over whichever native backends were compiled in (`native-vulkan`, /// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the - /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in CI. + /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane. /// `new_without_display_handle` because this context never has a window (no surface is ever /// requested); FilmCraft's own off-screen export device uses the same constructor for the /// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index a4d31c4e39..6f0b74f88e 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -3,7 +3,9 @@ //! RFC-0022 acceptance requirement 2: real backends beside the null one. `craft-gpu-null` stays //! mandatory for every consumer (it cannot validate shader compilation, resource rules, or //! numerical results), so these tests run representative jobs on a real wgpu device when one is -//! available, and skip loudly rather than failing the suite when the host genuinely has none +//! available. Runs against a software Vulkan adapter in a local container are local testing, not +//! hosted CI coverage: hosted lanes and the pilot consumers' browser and hardware validation +//! remain their own, separate requirements. The suite skips loudly when the host has no adapter //! (`cargo test` without `--features adapter-probe,native-vulkan` already exercises the masked //! path: no adapter is ever requested, and every context here falls back to the staging path, //! same shape as `craft-gpu-null`). diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 22ca694e49..8d8ccb0a24 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -25,10 +25,10 @@ pub struct ReadOutcome { /// ## Device loss /// /// A context can lose its device at any time: a driver reset, OS-level eviction under memory -/// pressure, or an explicit `device.destroy()`. Device loss is a fault, not a panic. It surfaces -/// through [`GpuFault::DeviceLost`] from the next call that would otherwise touch the device, and -/// also through [`poll_reads`](Self::poll_reads), so a host's event loop can observe it even -/// between buffer calls. Once a context has reported [`GpuFault::DeviceLost`], every +/// pressure, or an explicit `device.destroy()`. Device loss surfaces as a fault and never panics. It arrives +/// through [`GpuFault::DeviceLost`] from the next call that would otherwise touch the device. +/// It also arrives through [`poll_reads`](Self::poll_reads), letting a host's event loop observe +/// it even between buffer calls. Once a context has reported [`GpuFault::DeviceLost`], every /// [`DeviceCaps`] it reported before that point is stale. The consumer's recovery, per RFC-0022, /// is one of: /// @@ -50,13 +50,16 @@ pub struct ReadOutcome { /// later poll, analogous to `craft-worker-host`'s `HostMessage::GpuJobs` being answered later by /// `WorkerMessage::GpuBatchDone`. /// -/// A backend that can honestly block (the null context, which never has anything to wait for; -/// native wgpu driving `Device::poll` itself) uses `read_buffer`'s default body. A backend that -/// cannot honestly block without freezing its single thread (WebGPU on `wasm32`, where a map -/// completes only via the browser's own event loop) overrides `read_buffer` to return -/// [`GpuFault::Operation`] instead of deadlocking; callers there must drive `request_read` and -/// `poll_reads` from the worker's own message loop. See `docs/gpu-backends.md` for which backend -/// does which. +/// Both bundled backends override `read_buffer`'s default body, since the default has nowhere +/// to put completions belonging to other outstanding requests: the null context takes only its +/// own completion, and the wgpu context re-queues the others while blocking efficiently on a +/// native device. On `wasm32` the wgpu context's only backing today is the in-memory staging +/// store, whose reads resolve synchronously and are served; only a read that did not resolve +/// synchronously returns [`GpuFault::Operation`] there, the refusal a future real device backing +/// will need, because a map on that target completes only via the browser's own event loop and +/// blocking for it would freeze the one thread that loop runs on. Callers on such a backing +/// drive `request_read` and `poll_reads` from the worker's own message loop. See +/// `docs/gpu-backends.md` for which backend does which. pub trait GpuContext { fn caps(&self) -> DeviceCaps; diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md index 35527d5b0b..6e2246e918 100644 --- a/docs/gpu-backends.md +++ b/docs/gpu-backends.md @@ -8,18 +8,18 @@ Feature flags on `craft-gpu-wgpu`: -- `adapter-probe` — native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). -- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. +- `adapter-probe`: native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles`: enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. ## Real device, device-truth caps (RFC-0022 requirement 1) -With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device`, not just `request_adapter`. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing — no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. +With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device` after `request_adapter`, creating a real device. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing, since no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. -Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`), not a `Vec>` staged on the host. +Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-staged `Vec>` form survives only on the no-device path. -**The no-adapter path is still defined, not an error.** Without a usable adapter — `adapter-probe` off, no backend feature on, no GPU present, or on `wasm32` (see below) — `WgpuContext` degrades to the same in-memory staging behavior as `craft-gpu-null`. `WgpuContext::has_device()` tells a caller which path it got; `probe_caps()` (no context) stays the quick, adapter-only, advisory estimate it always was. +**The no-adapter path is still a defined path.** Without a usable adapter (`adapter-probe` off, no backend feature on, no GPU present, or `wasm32`, see below), `WgpuContext` degrades to the same in-memory staging behavior as `craft-gpu-null`. `WgpuContext::has_device()` tells a caller which path it got; `probe_caps()` (no context) stays the quick, adapter-only, advisory estimate it always was. -**`wasm32` gap, acknowledged, not hidden.** RFC-0022 itself describes browser capability probing moving "from static defaults to real adapter queries once async initialization lands in the worker" — that landing hasn't happened yet. `request_adapter`/`request_device` are JS promises; driving them synchronously the way `pollster::block_on` does natively isn't available on `wasm32`, and wiring the async worker-init path is a larger, separate piece of work. Until then, `WgpuContext` on `wasm32` reports the same conservative, adapter-free defaults it always has. This is the RFC's own acknowledged follow-up, not new scope invented for this PR. +**`wasm32` gap, acknowledged, not hidden.** RFC-0022 itself describes browser capability probing moving "from static defaults to real adapter queries once async initialization lands in the worker". That landing hasn't happened yet. `request_adapter`/`request_device` are JS promises. Driving them synchronously the way `pollster::block_on` does natively is unavailable on `wasm32`. Wiring the async worker-init path is a larger, separate piece of work. Until then, `WgpuContext` on `wasm32` reports the same conservative, adapter-free defaults it always has. This is the RFC's own acknowledged follow-up, not new scope invented for this PR. ## Device loss (RFC-0022 requirement 1) @@ -36,14 +36,14 @@ No backend here supports continuing to dispatch jobs against a context that alre `GpuContext::read_buffer` used to be synchronous. WebGPU can only map a buffer asynchronously (`map_async`), so the trait's real primitives are now `request_read` (queue a readback, get a `ReadRequest`) and `poll_reads` (drain completions). This mirrors `craft-worker-host`'s own async shape: a `HostMessage::GpuJobs { batch_id, .. }` is answered later by `WorkerMessage::GpuBatchDone { batch_id, outcomes }`, not inline; `request_read`/`poll_reads` is the same split one level down, for one buffer instead of one job batch. -`read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`): +`read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`). Both bundled backends override that default body. The default has nowhere to put completions belonging to other outstanding requests. The overrides keep those queued for the next `poll_reads`: -- `craft-gpu-null`: resolves every request immediately — nothing to wait for. -- `craft-gpu-wgpu`, native, with a real device: blocks by calling `Device::poll(PollType::wait_indefinitely())` between polls, so it waits on the GPU instead of busy-spinning the CPU. +- `craft-gpu-null`: overrides to take only its own completion; every request resolves immediately, with nothing to wait for. +- `craft-gpu-wgpu`, native, with a real device: overrides to block by calling `Device::poll(PollType::wait_indefinitely())` between polls. It waits on the GPU without busy-spinning the CPU, re-queuing other requests' completions. - `craft-gpu-wgpu`, native, staging path (no device): resolves immediately, same as the null context. -- `craft-gpu-wgpu`, `wasm32`: **returns `GpuFault::Operation`, not bytes.** `wasm32` is single-threaded; blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab, not return. A caller there must drive `request_read` + `poll_reads` from the worker's own message loop instead of calling `read_buffer`. +- `craft-gpu-wgpu`, `wasm32`: **serves the staging read.** The only backing on this target today is the in-memory staging store, since real device creation needs the async worker-init path that has not landed. Staging reads resolve synchronously. `read_buffer` returns their bytes. Only a read that did not resolve synchronously returns `GpuFault::Operation`. That refusal will matter once a real device backing exists there: `wasm32` is single-threaded and blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab. A caller on a future device backing must drive `request_read` + `poll_reads` from the worker's own message loop. -**Known follow-up on `craft-libs#662`.** That branch's `RuntimeContext` wrapper (`crates/runtime/src/runtime.rs`) implements `GpuContext` by matching on its `Null`/`Wgpu` variants, including an explicit `read_buffer` arm. When #662 rebases past this PR, that block needs two added match arms (`request_read`, `poll_reads`) delegating to each inner context the same way the existing methods do, and its own `read_buffer` arm can simply be deleted in favor of the trait's default (or kept, delegating the same way). No logic in `craft-worker-host` or the runtime facade changes: `HostMessage::GpuJobs` still dispatches a whole batch synchronously today, same as before this PR. +**Consumed on `craft-libs#662`.** That branch's `RuntimeContext` wrapper now forwards `request_read`, `poll_reads`, `free_buffer` and `device_status` to its inner context. It forwards `read_buffer` too, letting the inner backend's completion-preserving override apply. No logic in `craft-worker-host` or the runtime facade changed shape beyond that: `HostMessage::GpuJobs` still dispatches a whole batch synchronously today, answered per job. ## Named consumers (RFC-0022's "what this RFC decides") @@ -56,6 +56,6 @@ No backend here supports continuing to dispatch jobs against a context that alre The question that decides whether a render-path app can adopt `WgpuContext` as-is: who owns the `Device`/`Queue` when egui (via `eframe`/`egui-wgpu`) is also drawing? -**FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created — one device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. +**FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created. One device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. -`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor — it does not change `GpuContext`'s trait shape — but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. +`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor that does not change `GpuContext`'s trait shape, but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md index 0705b9124f..a1282b8a1e 100644 --- a/docs/gpu-providers.md +++ b/docs/gpu-providers.md @@ -2,17 +2,17 @@ Provider ids: -- `craft.*` — shared ops in **craft-gpu-providers** (no app crate deps) -- `craft.noop`, `craft.test.echo`, `craft.mask`, `craft.composite.premul`, `craft.readback` — registered by [`register_all()`](../crates/gpu-providers/src/lib.rs) for worker/runtime init - - `craft.mask` — CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu - - `craft.composite.premul` — CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu - - `craft.readback` — CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** -- `{app}.*` — registered by application wasm at init +- `craft.*`: shared ops in **craft-gpu-providers** (no app crate deps) +- `craft.noop`, `craft.test.echo`, `craft.mask`, `craft.composite.premul`, `craft.readback`: registered by [`register_all()`](../crates/gpu-providers/src/lib.rs) for worker/runtime init + - `craft.mask`: CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu + - `craft.composite.premul`: CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu + - `craft.readback`: CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** +- `{app}.*`: registered by application wasm at init -Generic worker code must only call `ProviderRegistry::dispatch` — never import app gpu crates. +Generic worker code must only call `ProviderRegistry::dispatch`: never import app gpu crates. Dependency lint: **craft-gpu-providers** must not depend on `effectcraft-*`, `filmcraft-*`, or `*-engine`. ## Readback is async underneath; these providers don't see it -`GpuContext::read_buffer`, the method every provider above calls, is a blocking convenience over the trait's real primitives, `request_read` + `poll_reads` (see [gpu-backends.md](./gpu-backends.md)). Nothing in this crate changed for that: `craft-gpu-null` still resolves `read_buffer` immediately, and `craft-gpu-wgpu`'s native path now does too, by blocking on the device between polls instead of staging in a plain `Vec>`. `crates/gpu-wgpu/src/tests.rs` runs these same providers (`craft.test.echo`, `craft.composite.premul`, `craft.readback`) against a real `WgpuContext`, not just the null one, when a real adapter is available (RFC-0022 requirement 2). A provider dispatching a real WGSL job will be the one that actually needs the non-blocking `request_read`/`poll_reads` shape directly, since on `wasm32` `read_buffer` itself returns a fault rather than blocking. +`GpuContext::read_buffer`, the method every provider above calls, is a blocking convenience over the trait's real primitives, `request_read` + `poll_reads` (see [gpu-backends.md](./gpu-backends.md)). Nothing in this crate changed for that. `craft-gpu-null` still resolves `read_buffer` immediately. `craft-gpu-wgpu`'s native path now does too, blocking on the device between polls. `crates/gpu-wgpu/src/tests.rs` runs these same providers (`craft.test.echo`, `craft.composite.premul`, `craft.readback`) against a real `WgpuContext` as well as the null one, when a real adapter is available (RFC-0022 requirement 2). A provider dispatching a real WGSL job will be the one that actually needs the non-blocking `request_read`/`poll_reads` shape directly. On `wasm32` today `read_buffer` serves the staging read, the only backing on that target. A read that did not resolve synchronously faults. A future real device backing there will refuse blocking outright, per `gpu-backends.md`. From ef6df591b4b88080a95d18cd61016fde4e8a1be6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:14:33 -0800 Subject: [PATCH 19/47] craft-gpu-yuv: RGBA to NV12, P010 and I420 on the GPU --- ATTRIBUTION.md | 4 + Cargo.lock | 8 + Cargo.toml | 1 + README.md | 4 + crates/gpu-yuv/Cargo.toml | 17 ++ crates/gpu-yuv/README.md | 61 ++++++ crates/gpu-yuv/src/cpu.rs | 129 +++++++++++++ crates/gpu-yuv/src/gpu.rs | 356 +++++++++++++++++++++++++++++++++++ crates/gpu-yuv/src/layout.rs | 101 ++++++++++ crates/gpu-yuv/src/lib.rs | 27 +++ crates/gpu-yuv/src/spec.rs | 180 ++++++++++++++++++ crates/gpu-yuv/src/tests.rs | 344 +++++++++++++++++++++++++++++++++ 12 files changed, 1232 insertions(+) create mode 100644 crates/gpu-yuv/Cargo.toml create mode 100644 crates/gpu-yuv/README.md create mode 100644 crates/gpu-yuv/src/cpu.rs create mode 100644 crates/gpu-yuv/src/gpu.rs create mode 100644 crates/gpu-yuv/src/layout.rs create mode 100644 crates/gpu-yuv/src/lib.rs create mode 100644 crates/gpu-yuv/src/spec.rs create mode 100644 crates/gpu-yuv/src/tests.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ae72ae8515..edff4ec38f 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -157,3 +157,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## HTTP Archive reader `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. + +## GPU color conversion + +`crates/gpu-yuv` comes from StudioCraft `crates/craft-gpu-yuv` at `8d8b6929e37217e0a3095cfc015b79c0e1e8e510` (MIT OR Apache-2.0). diff --git a/Cargo.lock b/Cargo.lock index cc0965d177..1e6c02533e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2137,6 +2137,14 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu-yuv" +version = "0.1.0" +dependencies = [ + "pollster 0.4.0", + "wgpu", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index fd9ccf7a62..ab4bd99df3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } craft-wasm = { path = "crates/wasm" } +craft-gpu-yuv = { path = "crates/gpu-yuv" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } diff --git a/README.md b/README.md index e21de2e1a3..602deac549 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. +- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): RGBA to NV12, P010 and I420 on the GPU, scaled to + the output size, in BT.601, BT.709 and BT.2020 at limited or full range; each output texel + averages the part of the source it covers; read-back layouts and unpacking to a packed frame; + and the same conversion on the CPU. Encoders and scopes stay in each app. - [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept unread and written back into a list. The workbook model and what follows a read stay in GridCraft. diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml new file mode 100644 index 0000000000..4d37856c86 --- /dev/null +++ b/crates/gpu-yuv/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-gpu-yuv" +description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, with a CPU reference of the same conversion" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +wgpu = "30" + +[dev-dependencies] +pollster = "0.4" diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md new file mode 100644 index 0000000000..76cc76881d --- /dev/null +++ b/crates/gpu-yuv/README.md @@ -0,0 +1,61 @@ +# craft-gpu-yuv + +RGBA to 4:2:0 Y'CbCr on the GPU for the Craft apps' encoders and scopes: NV12, P010 and I420, +scaled to the output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. +`cpu::convert` is the same conversion on the CPU. The crate depends only on `wgpu` 30. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `Format` | `Nv12` (8-bit luma, then interleaved Cb and Cr), `P010` (10-bit values in the high bits of little-endian 16-bit words, same planes as NV12) and `I420` (8-bit luma, Cb, then Cr) | +| `Matrix`, `Range` | BT.601, BT.709 and BT.2020 non-constant luminance; limited range (luma 16 to 235, chroma 16 to 240, times 4 at 10 bits) or full range (every code, chroma centered on 128 or 512) | +| `Conversion` | one format, matrix and range | +| `Converter::new(device, conversion)` | the two render pipelines of one conversion; no per-frame state | +| `Converter::bind(device, view)` | a source texture view bound once, as a `Source` | +| `Converter::planes(device, width, height)` | the plane textures of one output size, as `Planes` | +| `Converter::draw(encoder, source, planes)` | records a luma pass and a chroma pass | +| `Planes::copy_to_buffer(encoder, buffer, offset)` | records the copies of every plane into a read-back buffer | +| `FrameLayout` | each plane's size, its offset and row pitch in a read-back buffer (`buffer_size`), and the size of a packed frame (`frame_bytes`); `unpack` copies a mapped buffer into a packed frame | +| `cpu::convert(rgba, src_width, src_height, conversion, width, height)` | the conversion of an RGBA8 picture on the CPU, as one packed frame | + +## Sampling + +The source is scaled to the output size; the caller keeps the aspect ratio. Each output texel +(luma at the output size, chroma at half the output size in both directions) takes the average +of up to 4 × 4 bilinear taps spread over the part of the source it covers: 1 tap per axis while +the source is at most twice the plane's size, and one more for each further 2:1 of reduction. +At the same size, each chroma sample is the average of the 2 × 2 pixels it covers, and its +position is the center of those pixels. A reduction of more than 8:1 along an axis skips part of +the source between taps. + +The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`). The shader rounds +each value half to even. P010 does not need wgpu's 16-bit norm feature. + +## Limits + +- The matrix applies to the stored values: the source must already be in the output's primaries + and transfer function. An sRGB view of the source gives linear values, which the matrix does + not expect; bind a non-sRGB view. Alpha is ignored, so premultiplied pixels convert as if they + were over black. +- Output sides must be even and not zero (`Error::OutputSize`), and no larger than the device's + largest 2D texture (`Error::TooLarge`). A layout whose byte sizes do not fit in `u32` rows, `u64` + offsets or a `usize` frame is `Error::Overflow`. `Converter::planes` refuses a read-back layout + larger than the device's largest buffer (`Error::BufferLimit`), and `cpu::convert` refuses an + output side over `cpu::MAX_SIDE` (16384). +- The source view must be a 2D view of a filterable float format, such as `Rgba8Unorm`, + `Bgra8Unorm` or `Rgba16Float`. +- `copy_to_buffer` needs an offset that is a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` + (`Error::Offset`) and a buffer of at least `buffer_size` bytes from it (`Error::BufferSize`). + `draw` refuses planes made for another format (`Error::Mismatch`). + +## Tests + +The CPU tests check standard code values (BT.709 limited-range red is 63, 102, 240), each +format's plane order, the area average of a reduction and the read-back layout. The GPU tests +convert pictures with hard edges at the same size, and smooth pictures at five scales, in every +format, and compare each sample with `cpu::convert`. The tolerance is 2 code values at 8 bits and +6 at 10 bits. A machine without a graphics +adapter skips the GPU tests and prints that it did so. diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs new file mode 100644 index 0000000000..c268677091 --- /dev/null +++ b/crates/gpu-yuv/src/cpu.rs @@ -0,0 +1,129 @@ +//! The conversion on the CPU, sample for sample the rule the GPU passes follow. Tests compare the +//! two, and a caller without a GPU can use it directly. +//! +//! Each output texel (luma at the output size, chroma at half of it) takes the area of the source +//! under it: up to 4 × 4 bilinear taps spread over the texel's footprint, 1 per axis while the +//! source is at most twice the plane's size, one more for each further 2:1 of reduction. The +//! average of the taps goes through the matrix. At the same size the chroma tap lands between +//! four source pixels, so each chroma sample is the average of the 2 × 2 pixels it covers. + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error}; + +/// The largest output side [`convert`] takes. +pub const MAX_SIDE: u32 = 16384; + +/// The taps along one axis for a reduction of `r` (source size over plane size). +pub(crate) fn taps(r: f32) -> u32 { + ((r * 0.5 - 0.001).ceil() as i32).clamp(1, 4) as u32 +} + +struct Image<'a> { + rgba: &'a [u8], + width: usize, + height: usize, +} + +impl Image<'_> { + fn pixel(&self, x: i64, y: i64) -> [f32; 3] { + let x = x.clamp(0, self.width as i64 - 1) as usize; + let y = y.clamp(0, self.height as i64 - 1) as usize; + let i = (y * self.width + x) * 4; + match self.rgba.get(i..i + 3) { + Some(p) => [f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0], + None => [0.0; 3], + } + } + + /// The linear filter at `(x, y)` in pixels (pixel centers at .5), clamped to the edges. + fn bilinear(&self, x: f32, y: f32) -> [f32; 3] { + let (x, y) = (x - 0.5, y - 0.5); + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let (xi, yi) = (x0 as i64, y0 as i64); + let [a, b, c, d] = [self.pixel(xi, yi), self.pixel(xi + 1, yi), self.pixel(xi, yi + 1), self.pixel(xi + 1, yi + 1)]; + let mut out = [0.0; 3]; + for k in 0..3 { + let top = a[k] + (b[k] - a[k]) * fx; + let bottom = c[k] + (d[k] - c[k]) * fx; + out[k] = top + (bottom - top) * fy; + } + out + } + + /// The average color under the texel centered at `pos` of a plane of `size` texels. + fn area(&self, pos: [f32; 2], size: [f32; 2]) -> [f32; 3] { + let s = [self.width as f32, self.height as f32]; + let r = [s[0] / size[0], s[1] / size[1]]; + let n = [taps(r[0]), taps(r[1])]; + let nf = [n[0] as f32, n[1] as f32]; + let step = [r[0] / nf[0], r[1] / nf[1]]; + let center = [pos[0] / size[0] * s[0], pos[1] / size[1] * s[1]]; + let mut sum = [0.0f32; 3]; + for j in 0..n[1] { + for i in 0..n[0] { + let px = center[0] + (i as f32 + 0.5 - nf[0] * 0.5) * step[0]; + let py = center[1] + (j as f32 + 0.5 - nf[1] * 0.5) * step[1]; + let c = self.bilinear(px, py); + for k in 0..3 { + sum[k] += c[k]; + } + } + } + let count = nf[0] * nf[1]; + [sum[0] / count, sum[1] / count, sum[2] / count] + } +} + +/// `rgba` (`src_width × src_height`, 4 bytes per pixel; alpha is ignored, so premultiplied +/// pixels convert as if over black) scaled to `width × height` and converted, as one tightly +/// packed frame in [`FrameLayout`] order. +pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Conversion, width: u32, height: u32) -> Result, Error> { + let bytes = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || bytes != Some(rgba.len()) { + return Err(Error::Source { width: src_width, height: src_height, bytes: rgba.len() }); + } + if width > MAX_SIDE || height > MAX_SIDE { + return Err(Error::TooLarge { width, height, limit: MAX_SIDE }); + } + let layout = FrameLayout::new(conversion.format, width, height)?; + let image = Image { rgba, width: src_width as usize, height: src_height as usize }; + let c = Coefficients::of(conversion); + let (shift, wide) = (conversion.format.shift(), conversion.format.sample_bytes() == 2); + let mut out = Vec::with_capacity(layout.frame_bytes()); + let mut put = |v: u16| { + let v = v << shift; + if wide { + out.extend_from_slice(&v.to_le_bytes()); + } else { + out.push(v as u8); + } + }; + let plane = |pw: u32, ph: u32, pick: &mut dyn FnMut([u16; 3])| { + let size = [pw as f32, ph as f32]; + for j in 0..ph { + for i in 0..pw { + pick(c.codes(image.area([i as f32 + 0.5, j as f32 + 0.5], size))); + } + } + }; + let (cw, ch) = (width / 2, height / 2); + plane(width, height, &mut |v| put(v[0])); + match conversion.format { + crate::Format::Nv12 | crate::Format::P010 => plane(cw, ch, &mut |v| { + put(v[1]); + put(v[2]); + }), + crate::Format::I420 => { + let mut cr = Vec::with_capacity(cw as usize * ch as usize); + plane(cw, ch, &mut |v| { + put(v[1]); + cr.push(v[2]); + }); + for v in cr { + put(v); + } + } + } + Ok(out) +} diff --git a/crates/gpu-yuv/src/gpu.rs b/crates/gpu-yuv/src/gpu.rs new file mode 100644 index 0000000000..eb413e3c25 --- /dev/null +++ b/crates/gpu-yuv/src/gpu.rs @@ -0,0 +1,356 @@ +//! The conversion as render passes: one pass draws the luma plane, one draws the chroma plane or +//! planes, each into unsigned-integer textures that hold the exact stored words. + +use wgpu::util::DeviceExt; + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error, Format}; + +/// The render pipelines of one [`Conversion`]. Make it once per device and conversion; it holds +/// no per-frame state. +pub struct Converter { + conversion: Conversion, + plane_layout: wgpu::BindGroupLayout, + source_layout: wgpu::BindGroupLayout, + luma: wgpu::RenderPipeline, + chroma: wgpu::RenderPipeline, + sampler: wgpu::Sampler, +} + +/// A source texture view bound for a [`Converter`]. Keep one per texture that is converted more +/// than once. +pub struct Source { + bind: wgpu::BindGroup, +} + +/// The plane textures of one output size, and their read-back layout. +pub struct Planes { + layout: FrameLayout, + textures: Vec, + views: Vec, + luma_bind: wgpu::BindGroup, + chroma_bind: wgpu::BindGroup, +} + +fn plane_formats(format: Format) -> &'static [wgpu::TextureFormat] { + use wgpu::TextureFormat as T; + match format { + Format::Nv12 => &[T::R8Uint, T::Rg8Uint], + Format::P010 => &[T::R16Uint, T::Rg16Uint], + Format::I420 => &[T::R8Uint, T::R8Uint, T::R8Uint], + } +} + +fn attachment(view: &wgpu::TextureView) -> Option> { + Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + }) +} + +fn vec3(w: [f32; 3]) -> String { + format!("vec3({:?}, {:?}, {:?})", w[0], w[1], w[2]) +} + +/// The WGSL of `conversion`, with its weights and scale written in as constants. +pub(crate) fn shader(conversion: Conversion) -> String { + let k = Coefficients::of(conversion); + let chroma = match conversion.format { + Format::Nv12 | Format::P010 => { + "@fragment fn fs_chroma(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = area(pos.xy); + return vec4(code(dot(c, CB) * CS + CO), code(dot(c, CR) * CS + CO), 0u, 0u); +}" + } + Format::I420 => { + "struct Chroma { @location(0) cb: vec4, @location(1) cr: vec4 } +@fragment fn fs_chroma(@builtin(position) pos: vec4) -> Chroma { + let c = area(pos.xy); + var o: Chroma; + o.cb = vec4(code(dot(c, CB) * CS + CO), 0u, 0u, 0u); + o.cr = vec4(code(dot(c, CR) * CS + CO), 0u, 0u, 0u); + return o; +}" + } + }; + format!( + "const KY = {ky}; +const CB = {cb}; +const CR = {cr}; +const YS = {ys:?}; +const YO = {yo:?}; +const CS = {cs:?}; +const CO = {co:?}; +const MAX = {max:?}; +const SHIFT = {shift}u; + +struct Plane {{ size: vec2, pad: vec2 }} +@group(0) @binding(0) var plane: Plane; +@group(1) @binding(0) var tex: texture_2d; +@group(1) @binding(1) var samp: sampler; + +@vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 {{ + let x = f32((vi << 1u) & 2u); + let y = f32(vi & 2u); + return vec4(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0); +}} + +fn taps(r: f32) -> i32 {{ + return clamp(i32(ceil(r * 0.5 - 0.001)), 1, 4); +}} + +// The average color under the texel centered at `pos`: up to 4 x 4 bilinear taps over its +// footprint in the source. +fn area(pos: vec2) -> vec3 {{ + let src = vec2(textureDimensions(tex)); + let r = src / plane.size; + let n = vec2(taps(r.x), taps(r.y)); + let nf = vec2(n); + let step = r / nf; + let center = pos / plane.size * src; + var sum = vec3(0.0); + for (var j = 0; j < n.y; j++) {{ + for (var i = 0; i < n.x; i++) {{ + let p = center + (vec2(f32(i), f32(j)) + 0.5 - nf * 0.5) * step; + sum += textureSampleLevel(tex, samp, p / src, 0.0).rgb; + }} + }} + return sum / (nf.x * nf.y); +}} + +fn code(v: f32) -> u32 {{ + return u32(clamp(round(v), 0.0, MAX)) << SHIFT; +}} + +@fragment fn fs_luma(@builtin(position) pos: vec4) -> @location(0) vec4 {{ + return vec4(code(dot(area(pos.xy), KY) * YS + YO), 0u, 0u, 0u); +}} + +{chroma} +", + ky = vec3(k.y), + cb = vec3(k.cb), + cr = vec3(k.cr), + ys = k.y_scale, + yo = k.y_offset, + cs = k.c_scale, + co = k.c_offset, + max = k.max, + shift = conversion.format.shift(), + ) +} + +impl Converter { + /// The pipelines of `conversion` on `device`. + pub fn new(device: &wgpu::Device, conversion: Conversion) -> Converter { + let plane_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv plane"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(16), + }, + count: None, + }], + }); + let source_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv source"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("yuv"), + bind_group_layouts: &[Some(&plane_layout), Some(&source_layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(conversion.format.name()), + source: wgpu::ShaderSource::Wgsl(shader(conversion).into()), + }); + let target = |format| Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL }); + let formats = plane_formats(conversion.format); + let pipeline = |label: &str, fs: &str, targets: &[Option]| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(fs), targets, compilation_options: Default::default() }), + multiview_mask: None, + cache: None, + }) + }; + let luma = pipeline("yuv luma", "fs_luma", &[target(formats[0])]); + let chroma_targets: Vec<_> = formats[1..].iter().map(|f| target(*f)).collect(); + let chroma = pipeline("yuv chroma", "fs_chroma", &chroma_targets); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("yuv linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + Converter { conversion, plane_layout, source_layout, luma, chroma, sampler } + } + + pub fn conversion(&self) -> Conversion { + self.conversion + } + + /// Bind `view` as a source. The view must be a 2D view of a filterable float format, such as + /// `Rgba8Unorm` or `Bgra8Unorm`; an sRGB view gives linear values, which the matrix does not + /// expect. + pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> Source { + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv source"), + layout: &self.source_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + Source { bind } + } + + /// Plane textures for frames of `width × height`. Both sides must be even, not zero, and no + /// larger than the device's largest 2D texture. + pub fn planes(&self, device: &wgpu::Device, width: u32, height: u32) -> Result { + let limit = device.limits().max_texture_dimension_2d; + if width > limit || height > limit { + return Err(Error::TooLarge { width, height, limit }); + } + let layout = FrameLayout::new(self.conversion.format, width, height)?; + let max = device.limits().max_buffer_size; + if layout.buffer_size > max { + return Err(Error::BufferLimit { needed: layout.buffer_size, limit: max }); + } + let formats = plane_formats(self.conversion.format); + let textures: Vec = layout + .planes + .iter() + .zip(formats) + .map(|(p, format)| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("yuv plane"), + size: wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: *format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }) + }) + .collect(); + let views = textures.iter().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default())).collect(); + let uniform = |w: u32, h: u32| { + let mut bytes = [0u8; 16]; + bytes[..4].copy_from_slice(&(w as f32).to_le_bytes()); + bytes[4..8].copy_from_slice(&(h as f32).to_le_bytes()); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("yuv plane size"), + contents: &bytes, + usage: wgpu::BufferUsages::UNIFORM, + }); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv plane"), + layout: &self.plane_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }], + }) + }; + let luma_bind = uniform(width, height); + let chroma_bind = uniform(width / 2, height / 2); + Ok(Planes { layout, textures, views, luma_bind, chroma_bind }) + } + + /// Record the passes that convert `source` into `planes`. + pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, source: &Source, planes: &Planes) -> Result<(), Error> { + if planes.layout.format != self.conversion.format { + return Err(Error::Mismatch { converter: self.conversion.format, planes: planes.layout.format }); + } + // No allocation per frame: one luma view, then one or two chroma views. + let chroma_count = planes.views.len().saturating_sub(1).min(2); + let luma = [planes.views.first().and_then(attachment)]; + let chroma = [planes.views.get(1).and_then(attachment), planes.views.get(2).and_then(attachment)]; + let passes: [(&wgpu::RenderPipeline, &wgpu::BindGroup, &[Option>]); 2] = + [(&self.luma, &planes.luma_bind, &luma), (&self.chroma, &planes.chroma_bind, &chroma[..chroma_count])]; + for (pipeline, plane, attachments) in passes { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("yuv"), + color_attachments: attachments, + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, plane, &[]); + pass.set_bind_group(1, &source.bind, &[]); + pass.draw(0..3, 0..1); + } + Ok(()) + } +} + +impl Planes { + pub fn layout(&self) -> &FrameLayout { + &self.layout + } + + /// The plane textures, luma first. + pub fn textures(&self) -> &[wgpu::Texture] { + &self.textures + } + + /// Record copies of every plane into `buffer` from `offset`, in the [`FrameLayout`]'s + /// places. `offset` must be a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`, and the + /// buffer must hold `layout().buffer_size` bytes from it. + pub fn copy_to_buffer(&self, encoder: &mut wgpu::CommandEncoder, buffer: &wgpu::Buffer, offset: u64) -> Result<(), Error> { + if !offset.is_multiple_of(u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)) { + return Err(Error::Offset(offset)); + } + let needed = offset.saturating_add(self.layout.buffer_size); + if buffer.size() < needed { + return Err(Error::BufferSize { needed, actual: buffer.size() }); + } + for (texture, p) in self.textures.iter().zip(&self.layout.planes) { + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: offset + p.offset, + bytes_per_row: Some(p.bytes_per_row), + rows_per_image: Some(p.height), + }, + }, + wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + ); + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs new file mode 100644 index 0000000000..b5d4bbf170 --- /dev/null +++ b/crates/gpu-yuv/src/layout.rs @@ -0,0 +1,101 @@ +//! Where each plane sits in a read-back buffer and in a tightly packed frame. + +use crate::spec::{Error, Format}; + +/// One plane: its size in texels, the bytes of one texel, and where its rows start in a +/// read-back buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlaneLayout { + pub width: u32, + pub height: u32, + /// Bytes per texel: 1 or 2 for one sample, 2 or 4 for an interleaved Cb and Cr pair. + pub texel_bytes: u32, + /// The plane's first byte in the read-back buffer. + pub offset: u64, + /// Bytes from one row to the next in the read-back buffer, a multiple of + /// `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + pub bytes_per_row: u32, +} + +impl PlaneLayout { + /// Bytes of one row in a packed frame. + pub fn row_bytes(&self) -> u32 { + self.width * self.texel_bytes + } +} + +/// The planes of one frame of `format` at `width × height`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FrameLayout { + pub format: Format, + pub width: u32, + pub height: u32, + pub planes: Vec, + /// Bytes a read-back buffer needs from its offset. + pub buffer_size: u64, +} + +fn aligned(n: u32) -> Option { + let a = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + n.div_ceil(a).checked_mul(a) +} + +impl FrameLayout { + /// The layout of `format` at `width × height`; both sides must be even and not zero. + pub fn new(format: Format, width: u32, height: u32) -> Result { + if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { + return Err(Error::OutputSize { width, height }); + } + let s = format.sample_bytes(); + let (cw, ch) = (width / 2, height / 2); + let sizes: Vec<(u32, u32, u32)> = match format { + Format::Nv12 | Format::P010 => vec![(width, height, s), (cw, ch, 2 * s)], + Format::I420 => vec![(width, height, s), (cw, ch, s), (cw, ch, s)], + }; + let overflow = Error::Overflow { width, height }; + let mut offset = 0u64; + let mut tight = 0u64; + let mut planes = Vec::with_capacity(sizes.len()); + for (w, h, texel_bytes) in sizes { + let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; + let bytes_per_row = aligned(row).ok_or(overflow.clone())?; + planes.push(PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }); + offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; + tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; + } + // A packed frame must also fit in memory on this target. + usize::try_from(tight).map_err(|_| overflow)?; + Ok(FrameLayout { format, width, height, planes, buffer_size: offset }) + } + + /// Bytes of one tightly packed frame: the planes one after another, each row without padding. + pub fn frame_bytes(&self) -> usize { + self.planes.iter().map(|p| p.row_bytes() as usize * p.height as usize).sum() + } + + /// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to) + /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. + pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { + if (padded.len() as u64) < self.buffer_size { + return Err(Error::BufferSize { needed: self.buffer_size, actual: padded.len() as u64 }); + } + let tight = self.frame_bytes(); + if frame.len() != tight { + return Err(Error::BufferSize { needed: tight as u64, actual: frame.len() as u64 }); + } + let mut out = frame; + for p in &self.planes { + let (row, padded_row) = (p.row_bytes() as usize, p.bytes_per_row as usize); + let (dst, rest) = out.split_at_mut(row * p.height as usize); + let src = padded.get(p.offset as usize..).unwrap_or_default(); + for (d, s) in dst.chunks_exact_mut(row).zip(src.chunks(padded_row)) { + // The size check above leaves every row whole. + if let Some(s) = s.get(..row) { + d.copy_from_slice(s); + } + } + out = rest; + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/lib.rs b/crates/gpu-yuv/src/lib.rs new file mode 100644 index 0000000000..220fa5b3d0 --- /dev/null +++ b/crates/gpu-yuv/src/lib.rs @@ -0,0 +1,27 @@ +//! RGBA to 4:2:0 Y'CbCr on the GPU, for encoders and scopes. +//! +//! - [`Converter`] holds the render pipelines of one [`Conversion`]: a [`Format`] (NV12, P010 or +//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full). +//! - [`Converter::bind`] binds a source texture view once; [`Converter::planes`] makes the plane +//! textures of one output size; [`Converter::draw`] records the two passes. The source is scaled +//! to the output size. +//! - [`Planes::copy_to_buffer`] records the copies into a read-back buffer, and +//! [`FrameLayout::unpack`] turns the mapped buffer into one tightly packed frame. +//! - [`cpu::convert`] is the same conversion on the CPU. +//! +//! The matrix applies to the stored values as they are: the input must already be in the +//! output's primaries and transfer, and alpha is ignored. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod cpu; +mod gpu; +mod layout; +mod spec; + +pub use gpu::{Converter, Planes, Source}; +pub use layout::{FrameLayout, PlaneLayout}; +pub use spec::{Conversion, Error, Format, Matrix, Range}; + +#[cfg(test)] +mod tests; diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs new file mode 100644 index 0000000000..e11be59098 --- /dev/null +++ b/crates/gpu-yuv/src/spec.rs @@ -0,0 +1,180 @@ +//! What a conversion produces: the plane format, the matrix and the range, and the code values +//! they give. + +use std::fmt; + +/// The 4:2:0 layout a conversion writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Format { + /// 8 bits: the luma plane, then one plane of interleaved Cb and Cr samples. + Nv12, + /// 10 bits in the high bits of little-endian 16-bit words: the luma plane, then one plane of + /// interleaved Cb and Cr samples. + P010, + /// 8 bits: the luma plane, then the Cb plane, then the Cr plane. + I420, +} + +impl Format { + /// Bits per sample value. + pub fn bits(self) -> u32 { + match self { + Format::P010 => 10, + Format::Nv12 | Format::I420 => 8, + } + } + + /// Bytes each sample takes in memory. + pub fn sample_bytes(self) -> u32 { + match self { + Format::P010 => 2, + Format::Nv12 | Format::I420 => 1, + } + } + + /// The left shift from a sample value to the stored word: 6 for P010, else 0. + pub fn shift(self) -> u32 { + match self { + Format::P010 => 6, + Format::Nv12 | Format::I420 => 0, + } + } + + /// The format's usual name: `NV12`, `P010` or `I420`. + pub fn name(self) -> &'static str { + match self { + Format::Nv12 => "NV12", + Format::P010 => "P010", + Format::I420 => "I420", + } + } +} + +impl fmt::Display for Format { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// The RGB to Y'CbCr matrix (ITU-R BT.601, BT.709 and BT.2020 non-constant luminance). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Matrix { + Bt601, + Bt709, + Bt2020, +} + +impl Matrix { + /// The red and blue luma weights, Kr and Kb. + pub fn kr_kb(self) -> (f32, f32) { + match self { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } + } +} + +/// The code values the signal spans. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Range { + /// Luma from 16 to 235 and chroma from 16 to 240, scaled by 4 at 10 bits. + Limited, + /// Every code value, from 0 to 255 (1023 at 10 bits); chroma is centered on 128 (512). + Full, +} + +/// One conversion: the plane format, the matrix and the range. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Conversion { + pub format: Format, + pub matrix: Matrix, + pub range: Range, +} + +impl Conversion { + pub fn new(format: Format, matrix: Matrix, range: Range) -> Conversion { + Conversion { format, matrix, range } + } +} + +/// The weights and the scale of one conversion. The code value of luma is +/// `dot(y, rgb) * y_scale + y_offset`, of Cb `dot(cb, rgb) * c_scale + c_offset`, and of Cr +/// `dot(cr, rgb) * c_scale + c_offset`, rounded half to even and clamped to `0..=max`, for `rgb` +/// from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Coefficients { + pub y: [f32; 3], + pub cb: [f32; 3], + pub cr: [f32; 3], + pub y_scale: f32, + pub y_offset: f32, + pub c_scale: f32, + pub c_offset: f32, + pub max: f32, +} + +impl Coefficients { + pub fn of(c: Conversion) -> Coefficients { + let (kr, kb) = c.matrix.kr_kb(); + let kg = 1.0 - kr - kb; + let (db, dr) = (2.0 * (1.0 - kb), 2.0 * (1.0 - kr)); + let bits = c.format.bits(); + let max = ((1u32 << bits) - 1) as f32; + let step = (1u32 << (bits - 8)) as f32; + let (y_scale, y_offset, c_scale, c_offset) = match c.range { + Range::Limited => (219.0 * step, 16.0 * step, 224.0 * step, 128.0 * step), + Range::Full => (max, 0.0, max, (1u32 << (bits - 1)) as f32), + }; + Coefficients { y: [kr, kg, kb], cb: [-kr / db, -kg / db, 0.5], cr: [0.5, -kg / dr, -kb / dr], y_scale, y_offset, c_scale, c_offset, max } + } + + /// The code values of luma, Cb and Cr for `rgb`. + pub fn codes(&self, rgb: [f32; 3]) -> [u16; 3] { + let dot = |w: [f32; 3]| w[0] * rgb[0] + w[1] * rgb[1] + w[2] * rgb[2]; + let code = |v: f32| v.round_ties_even().clamp(0.0, self.max) as u16; + [ + code(dot(self.y) * self.y_scale + self.y_offset), + code(dot(self.cb) * self.c_scale + self.c_offset), + code(dot(self.cr) * self.c_scale + self.c_offset), + ] + } +} + +/// What a conversion cannot do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// An output side is zero or odd; 4:2:0 needs both sides even. + OutputSize { width: u32, height: u32 }, + /// A side is larger than the device's largest 2D texture. + TooLarge { width: u32, height: u32, limit: u32 }, + /// The frame's byte sizes do not fit in the integer types that hold them. + Overflow { width: u32, height: u32 }, + /// A read-back buffer for the frame would be larger than the device's largest buffer. + BufferLimit { needed: u64, limit: u64 }, + /// A source side is zero, or the pixels are not `width × height × 4` bytes. + Source { width: u32, height: u32, bytes: usize }, + /// A buffer or a frame does not have the size the layout needs. + BufferSize { needed: u64, actual: u64 }, + /// A buffer offset is not a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + Offset(u64), + /// The planes were made for another format than the converter's. + Mismatch { converter: Format, planes: Format }, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::OutputSize { width, height } => write!(f, "a 4:2:0 picture of {width}×{height} needs both sides even and not zero"), + Error::TooLarge { width, height, limit } => write!(f, "{width}×{height} is larger than the largest texture side, {limit}"), + Error::Overflow { width, height } => write!(f, "a frame of {width}×{height} is too large to hold"), + Error::BufferLimit { needed, limit } => write!(f, "a read-back buffer of {needed} bytes is larger than the largest buffer, {limit}"), + Error::Source { width, height, bytes } => write!(f, "{bytes} bytes are not an RGBA picture of {width}×{height}"), + Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"), + Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), + Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), + } + } +} + +impl std::error::Error for Error {} diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs new file mode 100644 index 0000000000..ad0476effd --- /dev/null +++ b/crates/gpu-yuv/src/tests.rs @@ -0,0 +1,344 @@ +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +fn solid(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect() +} + +/// The first luma sample and the first Cb and Cr samples of a converted frame, as values. +fn first(frame: &[u8], format: Format, w: u32, h: u32) -> [u16; 3] { + let s = samples(frame, format); + let luma = (w * h) as usize; + let quarter = luma / 4; + match format { + Format::Nv12 | Format::P010 => [s[0], s[luma], s[luma + 1]], + Format::I420 => [s[0], s[luma], s[luma + quarter]], + } +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +fn cpu(rgb: [u8; 3], c: Conversion) -> [u16; 3] { + let frame = cpu::convert(&solid(2, 2, rgb), 2, 2, c, 2, 2).unwrap(); + first(&frame, c.format, 2, 2) +} + +#[test] +fn bt709_limited_colors_have_their_standard_codes() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + assert_eq!(cpu([255, 255, 255], c), [235, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [16, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [63, 102, 240]); + assert_eq!(cpu([0, 0, 255], c), [32, 240, 118]); +} + +#[test] +fn each_matrix_weights_red_by_its_kr() { + let red = |m| cpu([255, 0, 0], Conversion::new(Format::Nv12, m, Range::Limited)); + assert_eq!(red(Matrix::Bt601), [81, 90, 240]); + assert_eq!(red(Matrix::Bt2020), [74, 97, 240]); +} + +#[test] +fn full_range_spans_every_code() { + let c = Conversion::new(Format::I420, Matrix::Bt709, Range::Full); + assert_eq!(cpu([255, 255, 255], c), [255, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [0, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [54, 99, 255]); +} + +#[test] +fn p010_holds_ten_bit_codes_in_the_high_bits() { + let limited = Conversion::new(Format::P010, Matrix::Bt2020, Range::Limited); + assert_eq!(cpu([255, 255, 255], limited), [940, 512, 512]); + assert_eq!(cpu([0, 0, 0], limited), [64, 512, 512]); + let full = Conversion::new(Format::P010, Matrix::Bt2020, Range::Full); + assert_eq!(cpu([255, 255, 255], full), [1023, 512, 512]); + let frame = cpu::convert(&solid(2, 2, [255, 255, 255]), 2, 2, limited, 2, 2).unwrap(); + assert_eq!(&frame[..2], &(940u16 << 6).to_le_bytes()); + assert_eq!(frame.len(), 12); +} + +#[test] +fn planes_follow_each_format_s_order() { + let red = solid(4, 2, [255, 0, 0]); + let nv12 = cpu::convert(&red, 4, 2, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(nv12, [63, 63, 63, 63, 63, 63, 63, 63, 102, 240, 102, 240]); + let i420 = cpu::convert(&red, 4, 2, Conversion::new(Format::I420, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(i420, [63, 63, 63, 63, 63, 63, 63, 63, 102, 102, 240, 240]); +} + +#[test] +fn chroma_at_the_same_size_averages_the_four_pixels_it_covers() { + // Red over blue: chroma is the code of their average, magenta at half strength. + let mut px = solid(2, 1, [255, 0, 0]); + px.extend(solid(2, 1, [0, 0, 255])); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 2, 2, c, 2, 2).unwrap(); + let half = cpu([128, 0, 128], c); + assert!(frame[4].abs_diff(half[1] as u8) <= 1 && frame[5].abs_diff(half[2] as u8) <= 1, "{frame:?} {half:?}"); +} + +#[test] +fn a_reduction_averages_the_area_under_each_texel() { + // One white column in four: a 4:1 reduction gives a quarter of white, where one bilinear tap + // at the texel's center would land between two black columns. + let px: Vec = (0..16).flat_map(|i| if i % 4 == 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect(); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 8, 2, c, 2, 2).unwrap(); + assert_eq!(&frame[..4], &[64, 64, 64, 64]); +} + +#[test] +fn the_tap_count_grows_with_the_reduction_up_to_four() { + assert_eq!([0.5, 1.0, 2.0, 2.01, 4.0, 4.5, 8.0, 100.0].map(cpu::taps), [1, 1, 1, 2, 2, 3, 4, 4]); +} + +#[test] +fn bad_sizes_are_errors() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let px = solid(2, 2, [0, 0, 0]); + assert_eq!(cpu::convert(&px, 2, 2, c, 3, 2).unwrap_err(), Error::OutputSize { width: 3, height: 2 }); + assert_eq!(cpu::convert(&px, 2, 2, c, 0, 0).unwrap_err(), Error::OutputSize { width: 0, height: 0 }); + assert_eq!(cpu::convert(&px, 2, 3, c, 2, 2).unwrap_err(), Error::Source { width: 2, height: 3, bytes: 16 }); + assert_eq!(cpu::convert(&[], 0, 0, c, 2, 2).unwrap_err(), Error::Source { width: 0, height: 0, bytes: 0 }); + assert_eq!(FrameLayout::new(Format::P010, 4, 5).unwrap_err(), Error::OutputSize { width: 4, height: 5 }); + let big = cpu::MAX_SIDE + 2; + assert_eq!(cpu::convert(&px, 2, 2, c, big, 2).unwrap_err(), Error::TooLarge { width: big, height: 2, limit: cpu::MAX_SIDE }); + // Byte sizes past the integer types are an error, not an overflow. + let huge = u32::MAX - 1; + assert_eq!(FrameLayout::new(Format::P010, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(FrameLayout::new(Format::Nv12, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(Error::OutputSize { width: 3, height: 2 }.to_string(), "a 4:2:0 picture of 3×2 needs both sides even and not zero"); +} + +#[test] +fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() { + let l = FrameLayout::new(Format::Nv12, 1920, 1080).unwrap(); + assert_eq!( + l.planes.iter().map(|p| (p.width, p.height, p.offset, p.bytes_per_row)).collect::>(), + [(1920, 1080, 0, 2048), (960, 540, 2048 * 1080, 2048)] + ); + assert_eq!((l.buffer_size, l.frame_bytes()), (2048 * 1620, 1920 * 1620)); + let p = FrameLayout::new(Format::P010, 640, 360).unwrap(); + assert_eq!((p.planes[0].bytes_per_row, p.planes[1].texel_bytes, p.frame_bytes()), (1280, 4, 640 * 360 * 3)); + let i = FrameLayout::new(Format::I420, 4, 2).unwrap(); + assert_eq!(i.planes.iter().map(|p| p.offset).collect::>(), [0, 512, 768]); + let mut padded = vec![0u8; i.buffer_size as usize]; + padded[..4].copy_from_slice(&[1, 2, 3, 4]); + padded[256..260].copy_from_slice(&[5, 6, 7, 8]); + padded[512..514].copy_from_slice(&[9, 10]); + padded[768..770].copy_from_slice(&[11, 12]); + let mut frame = vec![0u8; i.frame_bytes()]; + i.unpack(&padded, &mut frame).unwrap(); + assert_eq!(frame, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + assert_eq!(i.unpack(&padded[..100], &mut frame).unwrap_err(), Error::BufferSize { needed: 1024, actual: 100 }); + assert_eq!(i.unpack(&padded, &mut [0; 3]).unwrap_err(), Error::BufferSize { needed: 12, actual: 3 }); +} + +#[test] +fn an_enlarged_solid_color_keeps_its_codes() { + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&solid(3, 1, [10, 200, 90]), 3, 1, c, 8, 6).unwrap(); + let expect = cpu([10, 200, 90], c); + let s = samples(&frame, format); + assert_eq!(s.len(), 8 * 6 * 3 / 2); + assert!(s[..48].iter().all(|&v| v == expect[0]), "{format}"); + } +} + +#[test] +fn shaders_write_no_value_wgsl_cannot_read() { + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let s = gpu::shader(Conversion::new(format, matrix, range)); + assert!(!s.contains("NaN") && !s.contains("inf"), "{s}"); + assert!(s.contains("fn fs_chroma") && s.contains("fn fs_luma")); + } + } + } +} + +// The GPU half: the passes against the CPU reference. A machine without a graphics adapter skips +// these comparisons and says so on stderr. + +fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + device_with(|l| l) +} + +/// A device with the adapter's limits as `limits` changes them. +fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + eprintln!("no graphics adapter: the GPU half of this test is skipped"); + return None; + }; + let desc = wgpu::DeviceDescriptor { required_limits: limits(adapter.limits()), ..Default::default() }; + match pollster::block_on(adapter.request_device(&desc)) { + Ok(d) => Some(d), + Err(e) => { + eprintln!("the graphics adapter did not open ({e}): the GPU half of this test is skipped"); + None + } + } +} + +/// `src` (its pixels, width and height) converted on the GPU to `out` (width and height). +fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { + let ((rgba, sw, sh), (w, h)) = (src, out); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + texture.as_image_copy(), + rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }, + wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + ); + let converter = Converter::new(device, c); + let source = converter.bind(device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let planes = converter.planes(device, w, h).unwrap(); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256 + planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + converter.draw(&mut enc, &source, &planes).unwrap(); + planes.copy_to_buffer(&mut enc, &buffer, 256).unwrap(); + queue.submit([enc.finish()]); + buffer.map_async(wgpu::MapMode::Read, 256.., |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let view = buffer.get_mapped_range(256..).unwrap(); + let mut frame = vec![0; planes.layout().frame_bytes()]; + planes.layout().unpack(&view, &mut frame).unwrap(); + frame +} + +/// The tolerance in code values: 2 at 8 bits and 6 at 10 bits. GPUs filter with fewer bits of +/// weight than `f32` and may round a half the other way. +fn tolerance(format: Format) -> u16 { + if format.bits() == 10 { 6 } else { 2 } +} + +fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { + assert_eq!(gpu.len(), cpu.len(), "{what}"); + let (g, k) = (samples(gpu, c.format), samples(cpu, c.format)); + let worst = g.iter().zip(&k).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b)); + if let Some((i, (a, b))) = worst { + assert!(a.abs_diff(*b) <= tolerance(c.format), "{what} {c:?}: sample {i} is {a} on the GPU and {b} on the CPU"); + } +} + +/// A picture with hard edges: each pixel's channels from a fixed pseudo-random sequence. +fn noise(w: u32, h: u32) -> Vec { + let mut x = 0x2545_f491_u32; + (0..w * h * 4) + .map(|i| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + if i % 4 == 3 { 255 } else { (x >> 24) as u8 } + }) + .collect() +} + +/// A smooth picture: three ramps at different angles. +fn ramps(w: u32, h: u32) -> Vec { + (0..h) + .flat_map(|y| { + (0..w).flat_map(move |x| { + let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); + [(u * 255.0) as u8, (v * 255.0) as u8, ((1.0 - (u + v) * 0.5) * 255.0) as u8, 255] + }) + }) + .collect() +} + +#[test] +fn the_gpu_matches_the_cpu_at_the_same_size() { + let Some((device, queue)) = device() else { return }; + let px = noise(64, 36); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let g = gpu_convert(&device, &queue, (&px, 64, 36), c, (64, 36)); + assert_close(&g, &cpu::convert(&px, 64, 36, c, 64, 36).unwrap(), c, "64×36 at the same size"); + } + } + } +} + +#[test] +fn the_gpu_matches_the_cpu_when_scaling() { + let Some((device, queue)) = device() else { return }; + let px = ramps(160, 90); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (32, 18), (16, 10), (240, 136)] { + let g = gpu_convert(&device, &queue, (&px, 160, 90), c, (w, h)); + assert_close(&g, &cpu::convert(&px, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h}")); + } + let odd = ramps(37, 23); + let g = gpu_convert(&device, &queue, (&odd, 37, 23), c, (20, 12)); + assert_close(&g, &cpu::convert(&odd, 37, 23, c, 20, 12).unwrap(), c, "37×23 to 20×12"); + } +} + +#[test] +fn planes_larger_than_the_device_allows_are_errors() { + // The queue stays alive: a device whose queue was dropped cannot make an encoder. + let Some((device, _queue)) = device() else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + let limit = device.limits().max_texture_dimension_2d; + let too_big = (limit + 2) & !1; + assert_eq!(converter.planes(&device, too_big, 2).err(), Some(Error::TooLarge { width: too_big, height: 2, limit })); + let planes = converter.planes(&device, 4, 2).unwrap(); + let other = Converter::new(&device, Conversion::new(Format::P010, Matrix::Bt709, Range::Limited)); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 4, height: 2, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let source = other.bind(&device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + assert_eq!(other.draw(&mut enc, &source, &planes).unwrap_err(), Error::Mismatch { converter: Format::P010, planes: Format::Nv12 }); + let small = + device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 256, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 0).unwrap_err(), Error::BufferSize { needed: 768, actual: 256 }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 4).unwrap_err(), Error::Offset(4)); +} + +#[test] +fn planes_whose_read_back_is_larger_than_the_largest_buffer_are_errors() { + let Some((device, _queue)) = device_with(|l| wgpu::Limits { max_buffer_size: 1 << 20, ..l }) else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + // 1024 × 1024 NV12 reads back 1.5 MiB. + assert_eq!(converter.planes(&device, 1024, 1024).err(), Some(Error::BufferLimit { needed: 1024 * 1536, limit: 1 << 20 })); + assert!(converter.planes(&device, 512, 512).is_ok()); +} From 228e53c90422e40fccb15142796dded4b2afa272 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:25:36 -0800 Subject: [PATCH 20/47] craft-gpu-yuv: drop the source line from ATTRIBUTION.md --- ATTRIBUTION.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index edff4ec38f..ae72ae8515 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -157,7 +157,3 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## HTTP Archive reader `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. - -## GPU color conversion - -`crates/gpu-yuv` comes from StudioCraft `crates/craft-gpu-yuv` at `8d8b6929e37217e0a3095cfc015b79c0e1e8e510` (MIT OR Apache-2.0). From e66c13b9bf139d44cd4e3c76c9e836aabe135dd6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:23:21 -0800 Subject: [PATCH 21/47] craft-gpu-yuv: unpack refuses a layout whose fields were changed FrameLayout's fields are public, so a caller can change a layout after FrameLayout::new made it. unpack now compares the layout with the one FrameLayout::new gives for its format and size and returns Error::Layout when they differ, instead of panicking on a zero row length or returning Ok with rows left out. --- crates/gpu-yuv/src/layout.rs | 6 +++++- crates/gpu-yuv/src/spec.rs | 4 ++++ crates/gpu-yuv/src/tests.rs | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs index b5d4bbf170..4d3db5321e 100644 --- a/crates/gpu-yuv/src/layout.rs +++ b/crates/gpu-yuv/src/layout.rs @@ -75,7 +75,11 @@ impl FrameLayout { /// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to) /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. + /// A layout whose fields differ from what [`FrameLayout::new`] gives is [`Error::Layout`]. pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { + if FrameLayout::new(self.format, self.width, self.height).as_ref() != Ok(self) { + return Err(Error::Layout); + } if (padded.len() as u64) < self.buffer_size { return Err(Error::BufferSize { needed: self.buffer_size, actual: padded.len() as u64 }); } @@ -89,7 +93,7 @@ impl FrameLayout { let (dst, rest) = out.split_at_mut(row * p.height as usize); let src = padded.get(p.offset as usize..).unwrap_or_default(); for (d, s) in dst.chunks_exact_mut(row).zip(src.chunks(padded_row)) { - // The size check above leaves every row whole. + // The layout and size checks above leave every row whole. if let Some(s) = s.get(..row) { d.copy_from_slice(s); } diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs index e11be59098..cb852b8761 100644 --- a/crates/gpu-yuv/src/spec.rs +++ b/crates/gpu-yuv/src/spec.rs @@ -160,6 +160,9 @@ pub enum Error { Offset(u64), /// The planes were made for another format than the converter's. Mismatch { converter: Format, planes: Format }, + /// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and + /// size. + Layout, } impl fmt::Display for Error { @@ -173,6 +176,7 @@ impl fmt::Display for Error { Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"), Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), + Error::Layout => f.write_str("the frame layout does not match its format and size"), } } } diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index ad0476effd..1db1ef20d8 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -145,6 +145,27 @@ fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() { assert_eq!(i.unpack(&padded, &mut [0; 3]).unwrap_err(), Error::BufferSize { needed: 12, actual: 3 }); } +#[test] +fn unpack_refuses_a_layout_that_was_changed_after_it_was_made() { + let l = FrameLayout::new(Format::I420, 4, 2).unwrap(); + let padded = vec![0u8; l.buffer_size as usize]; + let changes: [fn(&mut FrameLayout); 6] = [ + |l| l.planes[0].bytes_per_row = 0, + |l| l.planes[0].width = 0, + |l| l.planes[0].texel_bytes = 0, + |l| l.planes[0].offset = 768, + |l| l.planes[0].bytes_per_row = 2, + |l| l.planes.truncate(1), + ]; + for (n, change) in changes.iter().enumerate() { + let mut bad = l.clone(); + change(&mut bad); + let mut frame = vec![0u8; bad.frame_bytes()]; + assert_eq!(bad.unpack(&padded, &mut frame), Err(Error::Layout), "change {n}"); + } + assert_eq!(Error::Layout.to_string(), "the frame layout does not match its format and size"); +} + #[test] fn an_enlarged_solid_color_keeps_its_codes() { for format in ALL { From ffd6453e34bc6485d2c7f8f3d9f17aa0b2d21a9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:26:32 -0800 Subject: [PATCH 22/47] craft-gpu-yuv: the layout check in unpack does not allocate unpack runs once per frame. The check now builds the expected planes in a stack array instead of a FrameLayout with its own Vec. --- crates/gpu-yuv/src/layout.rs | 62 ++++++++++++++++++++++-------------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs index 4d3db5321e..7898aa76d9 100644 --- a/crates/gpu-yuv/src/layout.rs +++ b/crates/gpu-yuv/src/layout.rs @@ -40,32 +40,46 @@ fn aligned(n: u32) -> Option { n.div_ceil(a).checked_mul(a) } +/// The planes of `format` at `width × height` (the first `count` of the array) and the read-back +/// buffer size. +fn planes_of(format: Format, width: u32, height: u32) -> Result<([PlaneLayout; 3], usize, u64), Error> { + if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { + return Err(Error::OutputSize { width, height }); + } + let s = format.sample_bytes(); + let (cw, ch) = (width / 2, height / 2); + let (sizes, count) = match format { + Format::Nv12 | Format::P010 => ([(width, height, s), (cw, ch, 2 * s), (0, 0, 0)], 2), + Format::I420 => ([(width, height, s), (cw, ch, s), (cw, ch, s)], 3), + }; + let overflow = Error::Overflow { width, height }; + let mut offset = 0u64; + let mut tight = 0u64; + let mut planes = [PlaneLayout { width: 0, height: 0, texel_bytes: 0, offset: 0, bytes_per_row: 0 }; 3]; + for (plane, (w, h, texel_bytes)) in planes.iter_mut().zip(sizes).take(count) { + let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; + let bytes_per_row = aligned(row).ok_or(overflow.clone())?; + *plane = PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }; + offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; + tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; + } + // A packed frame must also fit in memory on this target. + usize::try_from(tight).map_err(|_| overflow)?; + Ok((planes, count, offset)) +} + impl FrameLayout { /// The layout of `format` at `width × height`; both sides must be even and not zero. pub fn new(format: Format, width: u32, height: u32) -> Result { - if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { - return Err(Error::OutputSize { width, height }); - } - let s = format.sample_bytes(); - let (cw, ch) = (width / 2, height / 2); - let sizes: Vec<(u32, u32, u32)> = match format { - Format::Nv12 | Format::P010 => vec![(width, height, s), (cw, ch, 2 * s)], - Format::I420 => vec![(width, height, s), (cw, ch, s), (cw, ch, s)], - }; - let overflow = Error::Overflow { width, height }; - let mut offset = 0u64; - let mut tight = 0u64; - let mut planes = Vec::with_capacity(sizes.len()); - for (w, h, texel_bytes) in sizes { - let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; - let bytes_per_row = aligned(row).ok_or(overflow.clone())?; - planes.push(PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }); - offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; - tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; - } - // A packed frame must also fit in memory on this target. - usize::try_from(tight).map_err(|_| overflow)?; - Ok(FrameLayout { format, width, height, planes, buffer_size: offset }) + let (planes, count, buffer_size) = planes_of(format, width, height)?; + Ok(FrameLayout { format, width, height, planes: planes[..count].to_vec(), buffer_size }) + } + + /// Whether the fields are what [`FrameLayout::new`] gives for the format and size. It does not + /// allocate, so a frame loop can call it. + fn is_valid(&self) -> bool { + matches!(planes_of(self.format, self.width, self.height), + Ok((planes, count, size)) if planes[..count] == self.planes[..] && size == self.buffer_size) } /// Bytes of one tightly packed frame: the planes one after another, each row without padding. @@ -77,7 +91,7 @@ impl FrameLayout { /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. /// A layout whose fields differ from what [`FrameLayout::new`] gives is [`Error::Layout`]. pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { - if FrameLayout::new(self.format, self.width, self.height).as_ref() != Ok(self) { + if !self.is_valid() { return Err(Error::Layout); } if (padded.len() as u64) < self.buffer_size { From d9473fcefb265b8f0f9843f19579e62fc2e81edb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:08:53 -0800 Subject: [PATCH 23/47] craft-gpu-yuv: run as the craft.yuv provider on craft-gpu YuvProvider implements craft-gpu's GpuProvider under the id craft.yuv. YuvJob writes and strictly parses the job's key:value parameters. The provider checks the source and output sides and the padded read-back size against the context's DeviceCaps and the input's length before reading it, so a job is refused the same way on craft-gpu-null and on a device. YuvProvider::new() converts on the CPU on any context; with_device runs the render passes on a device the host holds, inside validation and out-of-memory error scopes. Code values now round halves away from zero on the CPU and in WGSL, as INT in BT.709 and BT.2020 and Round in BT.2100 do. Round-half-even gave full-range cyan a Cr of 0 instead of 1. oracle_tests.rs checks the conversion against sources outside the crate: code values computed in f64 from each recommendation's Kr, Kb and quantization, the nominal levels the recommendations state, the yuv crate's conversion (a dev-dependency) for every format, matrix and range, and a 4x4 frame against the byte offsets of the WebCodecs and Linux media API format definitions. The README documents the job parameters, the plane layout with its sources, the rounding rule, and why the CPU scaler takes the shader's taps. docs/gpu-providers.md lists craft.yuv. --- Cargo.lock | 12 + README.md | 10 +- crates/gpu-yuv/Cargo.toml | 11 +- crates/gpu-yuv/README.md | 108 ++++++++- crates/gpu-yuv/src/cpu.rs | 5 + crates/gpu-yuv/src/gpu.rs | 4 +- crates/gpu-yuv/src/job.rs | 351 +++++++++++++++++++++++++++++ crates/gpu-yuv/src/job_tests.rs | 233 +++++++++++++++++++ crates/gpu-yuv/src/lib.rs | 11 +- crates/gpu-yuv/src/oracle_tests.rs | 335 +++++++++++++++++++++++++++ crates/gpu-yuv/src/spec.rs | 11 +- crates/gpu-yuv/src/tests.rs | 12 +- docs/gpu-providers.md | 1 + 13 files changed, 1076 insertions(+), 28 deletions(-) create mode 100644 crates/gpu-yuv/src/job.rs create mode 100644 crates/gpu-yuv/src/job_tests.rs create mode 100644 crates/gpu-yuv/src/oracle_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 4a7c14296c..dea6be59cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2175,8 +2175,11 @@ dependencies = [ name = "craft-gpu-yuv" version = "0.1.0" dependencies = [ + "craft-gpu", + "craft-gpu-null", "pollster 0.4.0", "wgpu", + "yuv", ] [[package]] @@ -13078,6 +13081,15 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "yuv" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607" +dependencies = [ + "num-traits", +] + [[package]] name = "zbus" version = "5.19.0" diff --git a/README.md b/README.md index 602deac549..9f915aeddd 100644 --- a/README.md +++ b/README.md @@ -184,10 +184,12 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. -- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): RGBA to NV12, P010 and I420 on the GPU, scaled to - the output size, in BT.601, BT.709 and BT.2020 at limited or full range; each output texel - averages the part of the source it covers; read-back layouts and unpacking to a packed frame; - and the same conversion on the CPU. Encoders and scopes stay in each app. +- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to + NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full + range, through the `craft-gpu` job registry on the null context or on a device. Each output texel + averages the part of the source it covers. The crate also has the render passes for a caller's + own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the + CPU. Encoders and scopes stay in each app. - [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept unread and written back into a list. The workbook model and what follows a read stay in GridCraft. diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml index 4d37856c86..ddf2fa6cc2 100644 --- a/crates/gpu-yuv/Cargo.toml +++ b/crates/gpu-yuv/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-gpu-yuv" -description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, with a CPU reference of the same conversion" +description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, as a craft-gpu provider, with a CPU reference of the same conversion" version.workspace = true edition.workspace = true license.workspace = true @@ -11,7 +11,14 @@ repository.workspace = true workspace = true [dependencies] +craft-gpu = { workspace = true } wgpu = "30" +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true } + [dev-dependencies] -pollster = "0.4" +craft-gpu-null = { workspace = true } +pollster = { workspace = true } +# The independent reference the oracle tests compare with (BSD-3-Clause OR Apache-2.0). +yuv = { version = "0.8.20", default-features = false, features = ["professional_mode"] } diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md index 76cc76881d..4869219866 100644 --- a/crates/gpu-yuv/README.md +++ b/crates/gpu-yuv/README.md @@ -1,8 +1,9 @@ # craft-gpu-yuv -RGBA to 4:2:0 Y'CbCr on the GPU for the Craft apps' encoders and scopes: NV12, P010 and I420, -scaled to the output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. -`cpu::convert` is the same conversion on the CPU. The crate depends only on `wgpu` 30. +RGBA to 4:2:0 Y'CbCr for the Craft apps' encoders and scopes: NV12, P010 and I420, scaled to the +output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. `YuvProvider` is +the `craft.yuv` provider of the `craft-gpu` job layer. `Converter` records the same conversion as +render passes into a caller's own encoder, and `cpu::convert` is the same conversion on the CPU. Licensed under MIT OR Apache-2.0. @@ -10,6 +11,9 @@ Licensed under MIT OR Apache-2.0. | Item | What | |---|---| +| `YuvProvider` | the `craft.yuv` `GpuProvider`; `new()` converts on the CPU on any `GpuContext`, `with_device(device, queue)` converts with the render passes on that device (not on `wasm32`) | +| `YuvJob` | one job's conversion, source size and output size; `params()` writes them, `parse` reads them, `job(input)` makes the `GpuJob` | +| `PROVIDER_ID` | `"craft.yuv"` | | `Format` | `Nv12` (8-bit luma, then interleaved Cb and Cr), `P010` (10-bit values in the high bits of little-endian 16-bit words, same planes as NV12) and `I420` (8-bit luma, Cb, then Cr) | | `Matrix`, `Range` | BT.601, BT.709 and BT.2020 non-constant luminance; limited range (luma 16 to 235, chroma 16 to 240, times 4 at 10 bits) or full range (every code, chroma centered on 128 or 512) | | `Conversion` | one format, matrix and range | @@ -21,6 +25,72 @@ Licensed under MIT OR Apache-2.0. | `FrameLayout` | each plane's size, its offset and row pitch in a read-back buffer (`buffer_size`), and the size of a packed frame (`frame_bytes`); `unpack` copies a mapped buffer into a packed frame | | `cpu::convert(rgba, src_width, src_height, conversion, width, height)` | the conversion of an RGBA8 picture on the CPU, as one packed frame | +## Jobs + +A host registers `YuvProvider` in a `ProviderRegistry` and dispatches jobs made by `YuvJob::job`: + +```rust +let mut registry = craft_gpu::ProviderRegistry::new(); +registry.register(Box::new(craft_gpu_yuv::YuvProvider::new())); +let input = ctx.upload_buffer("rgba", &rgba)?; +let job = craft_gpu_yuv::YuvJob::new(conversion, 1920, 1080, 1280, 720).job(input); +let outcome = registry.dispatch(&mut ctx, &job)?; +let frame = ctx.read_buffer(outcome.outputs[0])?; +``` + +A job has one input, an RGBA8 buffer of exactly `src_width × src_height × 4` bytes, and no +outputs; its outcome has one output, a new buffer that holds the packed frame. The parameters are +ASCII `key:value` fields separated by `;`: +`fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +`i420`, `matrix` is `bt601`, `bt709` or `bt2020`, `range` is `limited` or `full`, and the four sides +are decimal digits. + +The provider checks the job against the context's `DeviceCaps` on every context, the null one +included: each source and output side must be at most `max_texture_dimension_2d`, and the +read-back layout with its padded rows (`FrameLayout::buffer_size`) at most `max_buffer_size` +bytes. It checks the input's length before reading it. A +malformed, missing, repeated or unknown parameter, a wrong input count or length, and a size the +caps or the conversion do not allow are `GpuFault::InvalidJob`. With a device, the provider also +checks the device's own limits, and an error the device reports during the job is +`GpuFault::Operation`. Each conversion's pipelines are made once per provider. + +`YuvProvider::new()` runs `cpu::convert`, so a consumer's tests and CI run on `craft-gpu-null` +without a graphics adapter. `YuvProvider::with_device` runs the render passes on the given device +and waits for each job to finish; the input and the output still move through the context's +buffers. + +## Plane layout + +A packed frame of `w × h` (both even) holds its planes one after another, each row without +padding: + +| Format | Plane | Offset | Row bytes | Rows | +|---|---|---|---|---| +| NV12 | Y' | 0 | `w` | `h` | +| NV12 | Cb, Cr interleaved | `w·h` | `w` | `h/2` | +| P010 | Y' | 0 | `2w` | `h` | +| P010 | Cb, Cr interleaved | `2w·h` | `2w` | `h/2` | +| I420 | Y' | 0 | `w` | `h` | +| I420 | Cb | `w·h` | `w/2` | `h/2` | +| I420 | Cr | `w·h + w·h/4` | `w/2` | `h/2` | + +A frame is `1.5·w·h` bytes in NV12 and I420 and `3·w·h` bytes in P010. Each P010 word holds the +10-bit value in its high bits, with the 6 low bits zero. NV12 and I420 follow the W3C WebCodecs +definitions (), and NV12 and P010 follow +the Linux media API's sample images +(). + +In a read-back buffer, `FrameLayout` pads each row to a multiple of +`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` (256) bytes, as a texture-to-buffer copy needs, and puts each +plane right after the previous plane's padded rows. `FrameLayout::unpack` removes the padding. + +## Code values + +Luma and chroma follow BT.601-7 section 2.5, BT.709-6 items 3.2 to 3.5 and BT.2020-2 tables 4 and +5 at limited range, and BT.2100-3 table 9 at full range. A half rounds away from zero, as `INT` in +BT.709 and BT.2020 and `Round` in BT.2100 do, so a full-range Cb or Cr that computes to 0.5 is +code 1. + ## Sampling The source is scaled to the output size; the caller keeps the aspect ratio. Each output texel @@ -31,8 +101,13 @@ At the same size, each chroma sample is the average of the 2 × 2 pixels it cove position is the center of those pixels. A reduction of more than 8:1 along an axis skips part of the source between taps. -The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`). The shader rounds -each value half to even. P010 does not need wgpu's 16-bit norm feature. +`cpu::convert` scales with these same taps rather than with a resampling crate such as +`fast_image_resize`, because it is the reference the shader is tested against, and a different +kernel would differ from the shader at every edge. A caller that wants another filter on the CPU +can resize first with such a crate and convert at the same size. + +The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`), so P010 +does not need wgpu's 16-bit norm feature. ## Limits @@ -53,9 +128,20 @@ each value half to even. P010 does not need wgpu's 16-bit norm feature. ## Tests -The CPU tests check standard code values (BT.709 limited-range red is 63, 102, 240), each -format's plane order, the area average of a reduction and the read-back layout. The GPU tests -convert pictures with hard edges at the same size, and smooth pictures at five scales, in every -format, and compare each sample with `cpu::convert`. The tolerance is 2 code values at 8 bits and -6 at 10 bits. A machine without a graphics -adapter skips the GPU tests and prints that it did so. +- `oracle_tests.rs` checks the conversion against sources outside the crate. It computes the + code values of 729 colors in `f64` from each recommendation's Kr, Kb and quantization, and + checks the nominal levels the recommendations state (white, black, neutral chroma and the + chroma extremes). It compares every format, matrix and range with the `yuv` crate's conversion + of the same pictures (`yuv` 0.8, a dev-dependency), within 1 code value at 8 bits and 2 at + 10 bits. It checks the packed plane sizes against the planes `yuv` allocates, and a 4 × 4 frame + against the byte offsets of the public format definitions. The GPU passes are checked against + the same equations, within 1 code value. +- `job_tests.rs` runs `craft.yuv` through a `ProviderRegistry` on `craft-gpu-null`, and with a + device. It checks the parameters, the inputs and outputs, the caps limits, and a device whose + limits are smaller than the context's. +- `tests.rs` checks standard code values, each format's plane order, the area average of a + reduction and the read-back layout. It also compares the GPU passes with `cpu::convert` on + pictures with hard edges at the same size and on smooth pictures at five scales, within 2 code + values at 8 bits and 6 at 10 bits. + +A machine without a graphics adapter skips the GPU tests and prints that it did so. diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs index c268677091..c7afe643f2 100644 --- a/crates/gpu-yuv/src/cpu.rs +++ b/crates/gpu-yuv/src/cpu.rs @@ -6,6 +6,11 @@ //! source is at most twice the plane's size, one more for each further 2:1 of reduction. The //! average of the taps goes through the matrix. At the same size the chroma tap lands between //! four source pixels, so each chroma sample is the average of the 2 × 2 pixels it covers. +//! +//! The scaler here takes the shader's taps at the shader's positions instead of using a +//! resampling crate such as `fast_image_resize`: this function is the reference the shader is +//! tested against, and another kernel would differ from the shader at every edge. For another +//! filter, resize with such a crate first and convert at the same size. use crate::layout::FrameLayout; use crate::spec::{Coefficients, Conversion, Error}; diff --git a/crates/gpu-yuv/src/gpu.rs b/crates/gpu-yuv/src/gpu.rs index eb413e3c25..350c6adb66 100644 --- a/crates/gpu-yuv/src/gpu.rs +++ b/crates/gpu-yuv/src/gpu.rs @@ -120,8 +120,10 @@ fn area(pos: vec2) -> vec3 {{ return sum / (nf.x * nf.y); }} +// A half rounds up, as INT and Round do in the recommendations; WGSL's round() takes it to the +// even neighbor. Values below 0 clamp to 0 either way. fn code(v: f32) -> u32 {{ - return u32(clamp(round(v), 0.0, MAX)) << SHIFT; + return u32(clamp(floor(v + 0.5), 0.0, MAX)) << SHIFT; }} @fragment fn fs_luma(@builtin(position) pos: vec4) -> @location(0) vec4 {{ diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs new file mode 100644 index 0000000000..3534816000 --- /dev/null +++ b/crates/gpu-yuv/src/job.rs @@ -0,0 +1,351 @@ +//! The conversion as a `craft-gpu` job: [`YuvProvider`] answers [`GpuJob`]s whose provider id is +//! [`PROVIDER_ID`], dispatched through a [`craft_gpu::ProviderRegistry`]. +//! +//! A job has one input, an RGBA8 buffer of `src_width × src_height × 4` bytes in the context, and +//! [`YuvJob::params`] as its parameters. Its outcome has one output: a new buffer that holds the +//! packed frame in [`FrameLayout`] order. Every side must be no larger than the context's +//! [`DeviceCaps::max_texture_dimension_2d`](craft_gpu::DeviceCaps), and the frame no larger than its +//! `max_buffer_size`, on every context, so that a job that runs on the null context also runs on a +//! device with the same caps. + +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuJobParams, GpuProvider, HandleId}; + +use crate::cpu; +use crate::layout::FrameLayout; +use crate::spec::{Conversion, Error, Format, Matrix, Range}; + +/// The provider id of [`YuvProvider`]. +pub const PROVIDER_ID: &str = "craft.yuv"; + +/// The parameter keys, in the order [`YuvJob::params`] writes them. +const KEYS: [&str; 7] = ["fmt", "matrix", "range", "sw", "sh", "w", "h"]; + +/// The parameters of one `craft.yuv` job: the conversion, the source size and the output size. +/// +/// They are written as ASCII `key:value` fields separated by `;`, for example +/// `fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +/// `i420`; `matrix` is `bt601`, `bt709` or `bt2020`; `range` is `limited` or `full`; the sides are +/// decimal digits. A missing, repeated or unknown key, or a value outside these, is +/// [`GpuFault::InvalidJob`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct YuvJob { + pub conversion: Conversion, + pub src_width: u32, + pub src_height: u32, + pub width: u32, + pub height: u32, +} + +fn invalid(message: impl std::fmt::Display) -> GpuFault { + GpuFault::InvalidJob(format!("{PROVIDER_ID}: {message}")) +} + +/// A conversion error as a fault: device errors are [`GpuFault::Operation`], the rest describe a +/// job that cannot run and are [`GpuFault::InvalidJob`]. +fn fault(e: Error) -> GpuFault { + match e { + Error::Device(_) => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")), + _ => invalid(e), + } +} + +fn format_token(f: Format) -> &'static str { + match f { + Format::Nv12 => "nv12", + Format::P010 => "p010", + Format::I420 => "i420", + } +} + +fn matrix_token(m: Matrix) -> &'static str { + match m { + Matrix::Bt601 => "bt601", + Matrix::Bt709 => "bt709", + Matrix::Bt2020 => "bt2020", + } +} + +fn range_token(r: Range) -> &'static str { + match r { + Range::Limited => "limited", + Range::Full => "full", + } +} + +impl YuvJob { + pub fn new(conversion: Conversion, src_width: u32, src_height: u32, width: u32, height: u32) -> YuvJob { + YuvJob { conversion, src_width, src_height, width, height } + } + + /// The job's parameters. + pub fn params(&self) -> GpuJobParams { + let c = self.conversion; + let text = format!( + "fmt:{};matrix:{};range:{};sw:{};sh:{};w:{};h:{}", + format_token(c.format), + matrix_token(c.matrix), + range_token(c.range), + self.src_width, + self.src_height, + self.width, + self.height + ); + GpuJobParams(text.into_bytes()) + } + + /// A `craft.yuv` job that converts the RGBA8 buffer `input`. + pub fn job(&self, input: HandleId) -> GpuJob { + GpuJob { provider_id: PROVIDER_ID.into(), params: self.params(), inputs: vec![input], outputs: Vec::new() } + } + + /// Read parameters written by [`YuvJob::params`]. + pub fn parse(params: &GpuJobParams) -> Result { + let text = std::str::from_utf8(¶ms.0).map_err(|_| invalid("the parameters are not UTF-8"))?; + let mut values: [Option<&str>; KEYS.len()] = [None; KEYS.len()]; + for field in text.split(';') { + let (key, value) = field.split_once(':').ok_or_else(|| invalid(format!("`{field}` is not a key:value field")))?; + let i = KEYS.iter().position(|k| *k == key).ok_or_else(|| invalid(format!("unknown key `{key}`")))?; + if values[i].replace(value).is_some() { + return Err(invalid(format!("`{key}` is given twice"))); + } + } + let get = |i: usize| values[i].ok_or_else(|| invalid(format!("`{}` is missing", KEYS[i]))); + let token = |i: usize, value: &str| invalid(format!("`{value}` is not a value of `{}`", KEYS[i])); + let format = match get(0)? { + "nv12" => Format::Nv12, + "p010" => Format::P010, + "i420" => Format::I420, + v => return Err(token(0, v)), + }; + let matrix = match get(1)? { + "bt601" => Matrix::Bt601, + "bt709" => Matrix::Bt709, + "bt2020" => Matrix::Bt2020, + v => return Err(token(1, v)), + }; + let range = match get(2)? { + "limited" => Range::Limited, + "full" => Range::Full, + v => return Err(token(2, v)), + }; + let side = |i: usize| -> Result { + let v = get(i)?; + if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) { + return Err(token(i, v)); + } + v.parse().map_err(|_| token(i, v)) + }; + Ok(YuvJob { + conversion: Conversion::new(format, matrix, range), + src_width: side(3)?, + src_height: side(4)?, + width: side(5)?, + height: side(6)?, + }) + } +} + +/// The `craft.yuv` provider. +/// +/// [`YuvProvider::new`] converts with [`cpu::convert`], on any context: the null context in tests +/// and CI, or a context whose device a provider cannot reach. [`YuvProvider::with_device`] +/// converts with the render passes on a device the caller holds, such as the one it already draws +/// with; the RGBA8 input and the output frame still move through the context's buffers. Both give +/// the same frame within the tolerance the crate's tests state. +pub struct YuvProvider { + device: Option, +} + +impl Default for YuvProvider { + fn default() -> Self { + Self::new() + } +} + +impl YuvProvider { + /// A provider that converts on the CPU. + pub fn new() -> YuvProvider { + YuvProvider { device: None } + } + + /// A provider that converts with the render passes on `device`. Each job waits for the device + /// to finish, so this is not available on `wasm32`, where a buffer map completes only from the + /// browser's event loop. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_device(device: wgpu::Device, queue: wgpu::Queue) -> YuvProvider { + YuvProvider { device: Some(device::DeviceRunner::new(device, queue)) } + } + + /// Whether jobs run on a device. + pub fn has_device(&self) -> bool { + self.device.is_some() + } + + fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + match &self.device { + Some(d) => d.convert(rgba, job), + None => cpu::convert(rgba, job.src_width, job.src_height, job.conversion, job.width, job.height), + } + } +} + +impl GpuProvider for YuvProvider { + fn id(&self) -> &'static str { + PROVIDER_ID + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let spec = YuvJob::parse(&job.params)?; + let [input] = job.inputs.as_slice() else { + return Err(invalid(format!("expects one RGBA8 input, not {}", job.inputs.len()))); + }; + if !job.outputs.is_empty() { + return Err(invalid("makes its own output buffer, so the job names no outputs")); + } + let YuvJob { conversion, src_width, src_height, width, height } = spec; + let layout = FrameLayout::new(conversion.format, width, height).map_err(fault)?; + let caps = ctx.caps(); + let limit = caps.max_texture_dimension_2d; + for (w, h) in [(src_width, src_height), (width, height)] { + if w > limit || h > limit { + return Err(fault(Error::TooLarge { width: w, height: h, limit })); + } + } + // The read-back buffer with its padded rows is the largest buffer a device run makes, so + // the null context refuses the same jobs a device with these caps does. + let needed = layout.buffer_size.max(layout.frame_bytes() as u64); + if needed > caps.max_buffer_size { + return Err(fault(Error::BufferLimit { needed, limit: caps.max_buffer_size })); + } + // The input's size is checked before its bytes are read. + let bytes = ctx.buffer_len(*input)?; + let expected = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || expected != Some(bytes) { + return Err(fault(Error::Source { width: src_width, height: src_height, bytes })); + } + let rgba = ctx.read_buffer(*input)?; + let frame = self.convert(&rgba, &spec).map_err(fault)?; + let output = ctx.upload_buffer("craft.yuv.frame", &frame)?; + Ok(GpuJobOutcome { outputs: vec![output], data: None }) + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod device { + use std::sync::Mutex; + + use crate::gpu::{Converter, Planes}; + use crate::spec::{Conversion, Error}; + + use super::YuvJob; + + /// A device, its queue, and the converters made on it so far, one per conversion. + pub(super) struct DeviceRunner { + device: wgpu::Device, + queue: wgpu::Queue, + converters: Mutex>, + } + + fn device_error(e: impl std::fmt::Display) -> Error { + Error::Device(e.to_string()) + } + + impl DeviceRunner { + pub(super) fn new(device: wgpu::Device, queue: wgpu::Queue) -> DeviceRunner { + DeviceRunner { device, queue, converters: Mutex::new(Vec::new()) } + } + + /// `rgba` converted on the device, as one packed frame. Errors the device reports go to + /// error scopes and come back as [`Error::Device`]. + pub(super) fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + let (sw, sh) = (job.src_width, job.src_height); + let limit = self.device.limits().max_texture_dimension_2d; + if sw > limit || sh > limit { + return Err(Error::TooLarge { width: sw, height: sh, limit }); + } + // A converter leaves the cache while a job uses it, and goes back only when the device + // reported no error, so a converter whose pipelines failed is not used again. + let mut converters = self.converters.lock().map_err(|_| device_error("the converter cache lock is poisoned"))?; + let cached = take(&mut converters, job.conversion); + drop(converters); + let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); + let converter = cached.unwrap_or_else(|| Converter::new(&self.device, job.conversion)); + let recorded = self.record(&converter, rgba, job); + // Both scopes are popped on every path, so that none stays open on the device. + let errors = [pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; + if let Some(e) = errors.into_iter().flatten().next() { + return Err(device_error(e)); + } + if let Ok(mut converters) = self.converters.lock() { + converters.push(converter); + } + let (planes, buffer) = recorded?; + let (tx, rx) = std::sync::mpsc::channel(); + buffer.map_async(wgpu::MapMode::Read, .., move |result| { + let _ = tx.send(result); + }); + self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(device_error)?; + rx.try_recv().map_err(|_| device_error("the read-back map did not complete"))?.map_err(device_error)?; + let mapped = buffer.get_mapped_range(..).map_err(device_error)?; + let mut frame = vec![0u8; planes.layout().frame_bytes()]; + let unpacked = planes.layout().unpack(&mapped, &mut frame); + drop(mapped); + buffer.unmap(); + unpacked.map(|()| frame) + } + + /// Upload `rgba` and record and submit the passes and the copy into a read-back buffer. + fn record(&self, converter: &Converter, rgba: &[u8], job: &YuvJob) -> Result<(Planes, wgpu::Buffer), Error> { + let (sw, sh) = (job.src_width, job.src_height); + let size = wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }; + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("craft.yuv source"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }; + self.queue.write_texture(texture.as_image_copy(), rgba, layout, size); + let source = converter.bind(&self.device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let planes = converter.planes(&self.device, job.width, job.height)?; + let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("craft.yuv read-back"), + size: planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft.yuv") }); + converter.draw(&mut encoder, &source, &planes)?; + planes.copy_to_buffer(&mut encoder, &buffer, 0)?; + self.queue.submit([encoder.finish()]); + Ok((planes, buffer)) + } + } + + /// Remove and return the converter of `conversion` from `converters`, if there is one. + fn take(converters: &mut Vec, conversion: Conversion) -> Option { + let i = converters.iter().position(|c| c.conversion() == conversion)?; + Some(converters.swap_remove(i)) + } +} + +#[cfg(target_arch = "wasm32")] +mod device { + use crate::spec::Error; + + use super::YuvJob; + + /// No device runs jobs on `wasm32`: [`super::YuvProvider::with_device`] is native only. + pub(super) enum DeviceRunner {} + + impl DeviceRunner { + pub(super) fn convert(&self, _rgba: &[u8], _job: &YuvJob) -> Result, Error> { + match *self {} + } + } +} diff --git a/crates/gpu-yuv/src/job_tests.rs b/crates/gpu-yuv/src/job_tests.rs new file mode 100644 index 0000000000..eb77b63e53 --- /dev/null +++ b/crates/gpu-yuv/src/job_tests.rs @@ -0,0 +1,233 @@ +//! `craft.yuv` through the job contract: on `craft-gpu-null`, which needs no hardware, and with a +//! device when the machine has a graphics adapter. + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind}; +use craft_gpu_null::NullContext; + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// A null context with caps of the test's choosing, which counts the buffers read. +struct Capped { + inner: NullContext, + caps: DeviceCaps, + reads: usize, +} + +impl Capped { + fn new(caps: DeviceCaps) -> Capped { + Capped { inner: NullContext::new(WorkerKind::Main), caps, reads: 0 } + } +} + +impl GpuContext for Capped { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + fn worker_kind(&self) -> WorkerKind { + self.inner.worker_kind() + } + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { + self.inner.upload_buffer(label, bytes) + } + fn buffer_len(&self, handle: HandleId) -> Result { + self.inner.buffer_len(handle) + } + fn request_read(&mut self, handle: HandleId) -> Result { + self.reads += 1; + self.inner.request_read(handle) + } + fn poll_reads(&mut self) -> Vec { + self.inner.poll_reads() + } + fn free_buffer(&mut self, handle: HandleId) { + self.inner.free_buffer(handle); + } + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + self.reads += 1; + self.inner.read_buffer(handle) + } +} + +fn registry(provider: YuvProvider) -> ProviderRegistry { + let mut r = ProviderRegistry::new(); + r.register(Box::new(provider)); + r +} + +/// Run `job` on `ctx` and read its one output back. +fn dispatch(r: &ProviderRegistry, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result, GpuFault> { + let outcome = r.dispatch(ctx, job)?; + assert_eq!(outcome.outputs.len(), 1); + assert_eq!(outcome.data, None); + ctx.read_buffer(outcome.outputs[0]) +} + +fn invalid(result: Result) -> String { + match result { + Err(GpuFault::InvalidJob(message)) => message, + other => panic!("expected an invalid job, got {other:?}"), + } +} + +#[test] +fn the_registry_runs_craft_yuv_on_the_null_context() { + let r = registry(YuvProvider::new()); + let mut ctx = NullContext::new(WorkerKind::Main); + let px = tests::noise(64, 36); + let input = ctx.upload_buffer("rgba", &px).unwrap(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + for (w, h) in [(64, 36), (32, 18), (100, 50)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, w, h).job(input)).unwrap(); + assert_eq!(frame, cpu::convert(&px, 64, 36, c, w, h).unwrap(), "{c:?} {w}×{h}"); + assert_eq!(frame.len(), FrameLayout::new(format, w, h).unwrap().frame_bytes()); + } + } + } + } +} + +#[test] +fn parameters_read_back_as_written() { + let job = YuvJob::new(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 1920, 1080, 1280, 720); + assert_eq!(job.params().0, b"fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720"); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let job = YuvJob::new(Conversion::new(format, matrix, range), 7, u32::MAX, 0, 4); + assert_eq!(YuvJob::parse(&job.params()), Ok(job)); + } + } + } + let job = YuvJob::new(Conversion::new(Format::P010, Matrix::Bt2020, Range::Full), 3, 5, 8, 6).job(HandleId(9)); + assert_eq!((job.provider_id.as_str(), job.inputs.as_slice(), job.outputs.len()), (PROVIDER_ID, [HandleId(9)].as_slice(), 0)); +} + +#[test] +fn bad_parameters_are_invalid_jobs() { + let good = "fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4"; + let cases: [(&[u8], &str); 14] = [ + (b"", "is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4", "`h` is missing"), + (b"fmt:nv12;fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`fmt` is given twice"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;alpha:1", "unknown key `alpha`"), + (b"fmt:NV12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`NV12` is not a value of `fmt`"), + (b"fmt:nv12;matrix:bt2100;range:limited;sw:4;sh:4;w:4;h:4", "`bt2100` is not a value of `matrix`"), + (b"fmt:nv12;matrix:bt709;range:studio;sw:4;sh:4;w:4;h:4", "`studio` is not a value of `range`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:+4;sh:4;w:4;h:4", "`+4` is not a value of `sw`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:-4;w:4;h:4", "`-4` is not a value of `sh`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:;h:4", "`` is not a value of `w`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4294967296", "`4294967296` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;", "`` is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4.0", "`4.0` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:\xff", "not UTF-8"), + ]; + assert!(YuvJob::parse(&GpuJobParams(good.as_bytes().to_vec())).is_ok()); + for (params, want) in cases { + let message = invalid(YuvJob::parse(&GpuJobParams(params.to_vec()))); + assert!(message.starts_with("craft.yuv: ") && message.contains(want), "{message:?} for {:?}", String::from_utf8_lossy(params)); + } +} + +#[test] +fn inputs_outputs_and_sizes_are_checked_before_any_read() { + let r = registry(YuvProvider::new()); + let mut ctx = Capped::new(DeviceCaps::default()); + let c = Conversion::new(Format::I420, Matrix::Bt601, Range::Limited); + let input = ctx.upload_buffer("rgba", &tests::noise(8, 4)).unwrap(); + let mut job = YuvJob::new(c, 8, 4, 8, 4).job(input); + job.inputs.clear(); + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("expects one RGBA8 input, not 0")); + job.inputs = vec![input, input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("not 2")); + job.inputs = vec![input]; + job.outputs = vec![input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("names no outputs")); + // A buffer whose size is not the source's, an odd or zero side, and a missing buffer. + let wrong = [ + YuvJob::new(c, 8, 8, 8, 4).job(input), + YuvJob::new(c, 0, 4, 8, 4).job(input), + YuvJob::new(c, 8, 4, 7, 4).job(input), + YuvJob::new(c, 8, 4, 8, 0).job(input), + YuvJob::new(c, u32::MAX, u32::MAX, 8, 4).job(input), + ]; + for job in &wrong { + invalid(r.dispatch(&mut ctx, job)); + } + assert!(matches!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(HandleId(99))), Err(GpuFault::InvalidJob(_)))); + assert_eq!(ctx.reads, 0, "no job above reads its input"); + assert!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(input)).is_ok()); + assert_eq!(ctx.reads, 1); +} + +#[test] +fn jobs_past_the_context_caps_are_refused() { + let r = registry(YuvProvider::new()); + let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let small = ctx.upload_buffer("small", &tests::noise(64, 4)).unwrap(); + let wide = ctx.upload_buffer("wide", &tests::noise(66, 2)).unwrap(); + // The source and the output sides against the largest texture side. + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 66, 2, 64, 2).job(wide))).contains("66×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 66, 4).job(small))).contains("66×4")); + // NV12 read-back rows at width 64 are padded to 256 bytes: 64 × 44 packs into 4224 bytes + // but reads back through 256 × (44 + 22) = 16896, more than the 16128-byte limit; 64 × 42 + // reads back through exactly 16128. + assert_eq!(FrameLayout::new(Format::Nv12, 64, 44).unwrap().frame_bytes(), 4224); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 64, 44).job(small))); + assert!(refused.contains("16896 bytes is larger than the largest buffer, 16128"), "{refused}"); + assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 4, 64, 42).job(small)).is_ok()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_provider_with_a_device_matches_the_cpu_through_the_registry() { + let Some((device, queue)) = tests::device() else { return }; + let provider = YuvProvider::with_device(device, queue); + assert!(provider.has_device() && !YuvProvider::new().has_device()); + let r = registry(provider); + let mut ctx = NullContext::new(WorkerKind::Main); + let (noise, ramps) = (tests::noise(64, 36), tests::ramps(160, 90)); + let (n, s) = (ctx.upload_buffer("noise", &noise).unwrap(), ctx.upload_buffer("ramps", &ramps).unwrap()); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, 64, 36).job(n)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&noise, 64, 36, c, 64, 36).unwrap(), c, "64×36 through the registry"); + } + } + // Each conversion's converter is made once and used again: the second run of a + // conversion gives the same frame. + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (240, 136)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&ramps, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h} through the registry")); + assert_eq!(frame, dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap()); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_device_smaller_than_the_context_caps_refuses_the_job_without_a_device_error() { + let Some((device, queue)) = tests::device_with(|l| wgpu::Limits { max_texture_dimension_2d: 64, ..l }) else { return }; + let r = registry(YuvProvider::with_device(device, queue)); + // The null context's caps allow 8192, so only the device's own limit stops these. + let mut ctx = NullContext::new(WorkerKind::Main); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let big = ctx.upload_buffer("big", &tests::noise(128, 2)).unwrap(); + let small = ctx.upload_buffer("small", &tests::noise(8, 2)).unwrap(); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 128, 2, 8, 2).job(big))).contains("128×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 2, 128, 2).job(small))).contains("128×2")); + // The device still runs a job that fits after refusing two. + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 8, 2, 8, 2).job(small)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&tests::noise(8, 2), 8, 2, c, 8, 2).unwrap(), c, "8×2 after two refusals"); +} diff --git a/crates/gpu-yuv/src/lib.rs b/crates/gpu-yuv/src/lib.rs index 220fa5b3d0..24afb1a4aa 100644 --- a/crates/gpu-yuv/src/lib.rs +++ b/crates/gpu-yuv/src/lib.rs @@ -1,7 +1,10 @@ //! RGBA to 4:2:0 Y'CbCr on the GPU, for encoders and scopes. //! +//! - [`YuvProvider`] is the `craft.yuv` [`craft_gpu::GpuProvider`]: a host registers it in a +//! [`craft_gpu::ProviderRegistry`] and dispatches [`YuvJob`]s, on the null context or on a device. //! - [`Converter`] holds the render pipelines of one [`Conversion`]: a [`Format`] (NV12, P010 or -//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full). +//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full), for a +//! caller that records the passes into its own command encoder. //! - [`Converter::bind`] binds a source texture view once; [`Converter::planes`] makes the plane //! textures of one output size; [`Converter::draw`] records the two passes. The source is scaled //! to the output size. @@ -16,12 +19,18 @@ pub mod cpu; mod gpu; +mod job; mod layout; mod spec; pub use gpu::{Converter, Planes, Source}; +pub use job::{PROVIDER_ID, YuvJob, YuvProvider}; pub use layout::{FrameLayout, PlaneLayout}; pub use spec::{Conversion, Error, Format, Matrix, Range}; +#[cfg(test)] +mod job_tests; +#[cfg(test)] +mod oracle_tests; #[cfg(test)] mod tests; diff --git a/crates/gpu-yuv/src/oracle_tests.rs b/crates/gpu-yuv/src/oracle_tests.rs new file mode 100644 index 0000000000..2b277805f4 --- /dev/null +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -0,0 +1,335 @@ +//! Checks against sources outside this crate: code values computed here in `f64` from the Kr and +//! Kb values and the quantization each ITU-R recommendation states, the `yuv` crate's conversion +//! of the same pictures, and the plane layouts the formats' public definitions give. None of these +//! checks reads `spec::Coefficients`. +//! +//! - BT.601-7 section 2.5, : Kr 0.299, Kb 0.114. +//! - BT.709-6 items 3.2 to 3.5, : Kr 0.2126, Kb 0.0722; +//! limited range `INT[(219 E'Y + 16) 2^(n-8)]` and `INT[(224 E'C + 128) 2^(n-8)]`, where INT +//! rounds a fraction of 0.5 up. +//! - BT.2020-2 tables 4 and 5, : Kr 0.2627, Kb 0.0593, +//! quantized as in BT.709. +//! - BT.2100-3 table 9, : full range +//! `Round[(2^n - 1) E'Y]` and `Round[(2^n - 1) E'C + 2^(n-1)]`, with +//! `Round(x) = Sign(x) Floor(|x| + 0.5)`. +//! - NV12 and I420: the W3C WebCodecs `VideoPixelFormat` definitions, +//! . +//! - NV12 and P010: the Linux media API's semi-planar YUV formats and their sample 4×4 images, +//! . + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// Kr and Kb as each recommendation states them. +fn kr_kb(m: Matrix) -> (f64, f64) { + match m { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } +} + +/// The unrounded luma, Cb and Cr code values of an 8-bit RGB color. +fn exact(rgb: [f64; 3], c: Conversion) -> [f64; 3] { + let (kr, kb) = kr_kb(c.matrix); + let [r, g, b] = rgb.map(|v| v / 255.0); + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + let pb = (b - y) / (2.0 * (1.0 - kb)); + let pr = (r - y) / (2.0 * (1.0 - kr)); + let n = c.format.bits() as i32; + match c.range { + Range::Limited => { + let s = 2f64.powi(n - 8); + [(219.0 * y + 16.0) * s, (224.0 * pb + 128.0) * s, (224.0 * pr + 128.0) * s] + } + Range::Full => { + let m = 2f64.powi(n) - 1.0; + let half = 2f64.powi(n - 1); + [m * y, m * pb + half, m * pr + half] + } + } +} + +/// `Round(x) = Sign(x) Floor(|x| + 0.5)`, clamped to the codes of `bits`. +fn round(x: f64, bits: u32) -> u16 { + (x.signum() * (x.abs() + 0.5).floor()).clamp(0.0, f64::from((1u32 << bits) - 1)) as u16 +} + +/// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either +/// way in `f32`, so either neighbor passes there. +fn rounds_to(got: u16, exact: f64, bits: u32) -> bool { + let want = round(exact, bits); + let near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3; + got == want || near_half && got.abs_diff(want) <= 1 +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +/// The luma sample of pixel `(x, y)` and the Cb and Cr samples of the chroma texel over it, in +/// a packed frame of `w × h`. +fn at(s: &[u16], format: Format, w: usize, h: usize, x: usize, y: usize) -> [u16; 3] { + let luma = w * h; + let (cw, ch) = (w / 2, h / 2); + let c = (y / 2) * cw + x / 2; + match format { + Format::Nv12 | Format::P010 => [s[y * w + x], s[luma + 2 * c], s[luma + 2 * c + 1]], + Format::I420 => [s[y * w + x], s[luma + c], s[luma + cw * ch + c]], + } +} + +/// Channel values that include black, white, the 75% level (191), the limited-range nominal +/// levels and values one step from the ends. +const LEVELS: [u8; 9] = [0, 1, 16, 64, 128, 191, 235, 254, 255]; + +/// A picture of every color whose channels are in [`LEVELS`], each as a 2 × 2 block, so that no +/// sample depends on how chroma is subsampled. Returns the pixels, the side and the colors. +fn blocks() -> (Vec, u32, Vec<[u8; 3]>) { + let colors: Vec<[u8; 3]> = LEVELS.iter().flat_map(|&r| LEVELS.iter().flat_map(move |&g| LEVELS.iter().map(move |&b| [r, g, b]))).collect(); + let per_row = 27usize; + let side = per_row * 2; + let mut px = vec![0u8; side * side * 4]; + for (k, rgb) in colors.iter().enumerate() { + let (bx, by) = (k % per_row, k / per_row); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let i = ((by * 2 + dy) * side + bx * 2 + dx) * 4; + px[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]); + } + } + (px, side as u32, colors) +} + +/// Every block of `frame` against the equations. `slack` is 0 for the CPU and 1 for the GPU. +fn check_blocks(frame: &[u8], c: Conversion, side: u32, colors: &[[u8; 3]], slack: u16, what: &str) { + let s = samples(frame, c.format); + let side = side as usize; + for (k, rgb) in colors.iter().enumerate() { + let (x, y) = ((k % 27) * 2, (k / 27) * 2); + let got = at(&s, c.format, side, side, x, y); + let want = exact(rgb.map(f64::from), c); + for i in 0..3 { + let ok = rounds_to(got[i], want[i], c.format.bits()) || got[i].abs_diff(round(want[i], c.format.bits())) <= slack; + assert!(ok, "{what} {c:?} {rgb:?}: component {i} is {} where the equations give {:.4}", got[i], want[i]); + } + } +} + +#[test] +fn the_cpu_gives_the_codes_of_the_published_equations() { + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = cpu::convert(&px, side, side, c, side, side).unwrap(); + check_blocks(&frame, c, side, &colors, 0, "CPU"); + } + } + } +} + +#[test] +fn nominal_levels_have_the_codes_the_recommendations_state() { + // White, black and neutral chroma are 235, 16 and 128 at limited range, 255, 0 and 128 at + // full range, times 4 (and 1023 for full white) at 10 bits. Chroma reaches 240 (960) for blue's + // Cb and red's Cr, and 16 (64) for yellow's Cb and cyan's Cr. At full range those are + // Round(255.5) and Round(0.5), clamped to 255 (1023) and 1. + for format in ALL { + let ten = format.bits() == 10; + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let (white, black, mid, high, low) = match (range, ten) { + (Range::Limited, false) => (235, 16, 128, 240, 16), + (Range::Limited, true) => (940, 64, 512, 960, 64), + (Range::Full, false) => (255, 0, 128, 255, 1), + (Range::Full, true) => (1023, 0, 512, 1023, 1), + }; + let code = |rgb: [u8; 3]| { + let frame = cpu::convert(&(0..4).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect::>(), 2, 2, c, 2, 2).unwrap(); + at(&samples(&frame, format), format, 2, 2, 0, 0) + }; + assert_eq!(code([255, 255, 255]), [white, mid, mid], "{c:?} white"); + assert_eq!(code([0, 0, 0]), [black, mid, mid], "{c:?} black"); + assert_eq!(code([0, 0, 255])[1], high, "{c:?} blue Cb"); + assert_eq!(code([255, 0, 0])[2], high, "{c:?} red Cr"); + assert_eq!(code([255, 255, 0])[1], low, "{c:?} yellow Cb"); + assert_eq!(code([0, 255, 255])[2], low, "{c:?} cyan Cr"); + } + } + } +} + +fn yuv_range(r: Range) -> yuv::YuvRange { + match r { + Range::Limited => yuv::YuvRange::Limited, + Range::Full => yuv::YuvRange::Full, + } +} + +fn yuv_matrix(m: Matrix) -> yuv::YuvStandardMatrix { + match m { + Matrix::Bt601 => yuv::YuvStandardMatrix::Bt601, + Matrix::Bt709 => yuv::YuvStandardMatrix::Bt709, + Matrix::Bt2020 => yuv::YuvStandardMatrix::Bt2020, + } +} + +/// The `yuv` crate's conversion of `px` (`w × h`) as one packed frame in this crate's order. +/// P010 takes 10-bit RGB there, so each channel is scaled to 0..=1023 and rounded first. +fn yuv_convert(px: &[u8], w: u32, h: u32, c: Conversion) -> Vec { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvConversionMode, YuvPlanarImageMut}; + let (range, matrix, mode) = (yuv_range(c.range), yuv_matrix(c.matrix), YuvConversionMode::Professional); + match c.format { + Format::Nv12 => { + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv_nv12(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat() + } + Format::I420 => { + let mut img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv420(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.u_plane.borrow(), img.v_plane.borrow()].concat() + } + Format::P010 => { + let wide: Vec = px.iter().map(|&v| (f64::from(v) * 1023.0 / 255.0).round() as u16).collect(); + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba10_to_p010(&mut img, &wide, w * 4, range, matrix).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat().iter().flat_map(|v| v.to_le_bytes()).collect() + } + } +} + +/// The largest difference allowed from the `yuv` crate: 1 code value at 8 bits, and 2 at 10 bits, +/// where its input was rounded to 10 bits first. +fn yuv_tolerance(format: Format) -> u16 { + if format.bits() == 10 { 2 } else { 1 } +} + +#[test] +fn the_cpu_matches_the_yuv_crate() { + let (px, side, _) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let ours = samples(&cpu::convert(&px, side, side, c, side, side).unwrap(), format); + let theirs = samples(&yuv_convert(&px, side, side, c), format); + assert_eq!(ours.len(), theirs.len(), "{c:?}"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + assert!(a.abs_diff(*b) <= yuv_tolerance(format), "{c:?}: sample {i} is {a} here and {b} in the yuv crate"); + } + } + } + } +} + +#[test] +fn packed_planes_have_the_sizes_the_yuv_crate_allocates() { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvPlanarImageMut}; + for (w, h) in [(2, 2), (4, 4), (16, 10), (1920, 1080), (3840, 2160)] { + for format in ALL { + let l = FrameLayout::new(format, w, h).unwrap(); + let s = format.sample_bytes() as usize; + let packed: Vec<(usize, usize)> = l.planes.iter().map(|p| (p.row_bytes() as usize, p.row_bytes() as usize * p.height as usize)).collect(); + let theirs: Vec<(usize, usize)> = match format { + Format::Nv12 | Format::P010 => { + let img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![(img.y_stride as usize * s, img.y_plane.borrow().len() * s), (img.uv_stride as usize * s, img.uv_plane.borrow().len() * s)] + } + Format::I420 => { + let img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![ + (img.y_stride as usize, img.y_plane.borrow().len()), + (img.u_stride as usize, img.u_plane.borrow().len()), + (img.v_stride as usize, img.v_plane.borrow().len()), + ] + } + }; + assert_eq!(packed, theirs, "{format} {w}×{h}: row bytes and plane bytes"); + assert_eq!(l.frame_bytes(), theirs.iter().map(|p| p.1).sum::(), "{format} {w}×{h}"); + } + } +} + +/// Sixteen different colors for a 4 × 4 picture. +fn sixteen() -> Vec<[u8; 3]> { + (0..16u32).map(|k| [(k * 17) as u8, ((k * 53 + 30) % 256) as u8, ((k * 91 + 60) % 256) as u8]).collect() +} + +/// The byte offset of luma sample `(x, y)`. +type LumaAt = fn(usize, usize) -> usize; +/// The byte offsets of the Cb and Cr samples of chroma texel `(x, y)`. +type ChromaAt = fn(usize, usize) -> (usize, usize); + +/// Where the public definitions put each sample of a 4 × 4 frame. +fn documented_offsets(format: Format) -> (LumaAt, ChromaAt) { + match format { + // "start + 0: Y'00 Y'01 Y'02 Y'03 ... start + 16: Cb00 Cr00 Cb01 Cr01, start + 20: Cb10 Cr10 Cb11 Cr11" + Format::Nv12 => (|x, y| y * 4 + x, |x, y| (16 + y * 4 + x * 2, 17 + y * 4 + x * 2)), + // Rows of 8 bytes: "start + 8: Y'10 ... start + 32: Cb00 Cr00 Cb01 Cr01, start + 40: Cb10 ..." + Format::P010 => (|x, y| y * 8 + x * 2, |x, y| (32 + y * 8 + x * 4, 34 + y * 8 + x * 4)), + // Y, then U, then V; each chroma plane has 2 rows of 2 samples. + Format::I420 => (|x, y| y * 4 + x, |x, y| (16 + y * 2 + x, 20 + y * 2 + x)), + } +} + +#[test] +fn a_4x4_frame_puts_each_sample_where_the_format_definitions_do() { + let colors = sixteen(); + let px: Vec = colors.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect(); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&px, 4, 4, c, 4, 4).unwrap(); + assert_eq!(frame.len(), 4 * 4 * 3 / 2 * format.sample_bytes() as usize, "{format}"); + let read = |offset: usize| match format { + Format::P010 => { + let word = u16::from_le_bytes([frame[offset], frame[offset + 1]]); + assert_eq!(word & 0x3f, 0, "{format}: the 6 low bits are zero"); + word >> 6 + } + Format::Nv12 | Format::I420 => u16::from(frame[offset]), + }; + let (luma, chroma) = documented_offsets(format); + for y in 0..4 { + for x in 0..4 { + let want = exact(colors[y * 4 + x].map(f64::from), c)[0]; + assert!(rounds_to(read(luma(x, y)), want, format.bits()), "{format}: luma {x},{y}"); + } + } + for y in 0..2 { + for x in 0..2 { + // Each chroma sample is the code of the average of the 2 × 2 pixels under it. + let quad = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| colors[(y * 2 + dy) * 4 + x * 2 + dx]); + let mean = [0, 1, 2].map(|i| quad.iter().map(|p| f64::from(p[i])).sum::() / 4.0); + let want = exact(mean, c); + let (cb, cr) = chroma(x, y); + assert!(rounds_to(read(cb), want[1], format.bits()), "{format}: Cb {x},{y}"); + assert!(rounds_to(read(cr), want[2], format.bits()), "{format}: Cr {x},{y}"); + } + } + } +} + +#[test] +fn the_gpu_gives_the_codes_of_the_published_equations() { + let Some((device, queue)) = tests::device() else { return }; + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = tests::gpu_convert(&device, &queue, (&px, side, side), c, (side, side)); + check_blocks(&frame, c, side, &colors, 1, "GPU"); + } + } + } +} diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs index cb852b8761..0ee3f5ba6b 100644 --- a/crates/gpu-yuv/src/spec.rs +++ b/crates/gpu-yuv/src/spec.rs @@ -100,8 +100,9 @@ impl Conversion { /// The weights and the scale of one conversion. The code value of luma is /// `dot(y, rgb) * y_scale + y_offset`, of Cb `dot(cb, rgb) * c_scale + c_offset`, and of Cr -/// `dot(cr, rgb) * c_scale + c_offset`, rounded half to even and clamped to `0..=max`, for `rgb` -/// from 0 to 1. +/// `dot(cr, rgb) * c_scale + c_offset`, rounded with halves away from zero and clamped to +/// `0..=max`, for `rgb` from 0 to 1. That rounding is `INT` in BT.709 and BT.2020 and `Round` in +/// BT.2100. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Coefficients { pub y: [f32; 3], @@ -132,7 +133,7 @@ impl Coefficients { /// The code values of luma, Cb and Cr for `rgb`. pub fn codes(&self, rgb: [f32; 3]) -> [u16; 3] { let dot = |w: [f32; 3]| w[0] * rgb[0] + w[1] * rgb[1] + w[2] * rgb[2]; - let code = |v: f32| v.round_ties_even().clamp(0.0, self.max) as u16; + let code = |v: f32| v.round().clamp(0.0, self.max) as u16; [ code(dot(self.y) * self.y_scale + self.y_offset), code(dot(self.cb) * self.c_scale + self.c_offset), @@ -163,6 +164,9 @@ pub enum Error { /// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and /// size. Layout, + /// The device reported an error (validation, out of memory, a failed map or poll) while + /// [`crate::YuvProvider`] ran a job on it. + Device(String), } impl fmt::Display for Error { @@ -177,6 +181,7 @@ impl fmt::Display for Error { Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), Error::Layout => f.write_str("the frame layout does not match its format and size"), + Error::Device(message) => write!(f, "the device reported an error: {message}"), } } } diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index 1db1ef20d8..68e3a84a8f 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -194,12 +194,12 @@ fn shaders_write_no_value_wgsl_cannot_read() { // The GPU half: the passes against the CPU reference. A machine without a graphics adapter skips // these comparisons and says so on stderr. -fn device() -> Option<(wgpu::Device, wgpu::Queue)> { +pub(crate) fn device() -> Option<(wgpu::Device, wgpu::Queue)> { device_with(|l| l) } /// A device with the adapter's limits as `limits` changes them. -fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { +pub(crate) fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { eprintln!("no graphics adapter: the GPU half of this test is skipped"); @@ -216,7 +216,7 @@ fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgp } /// `src` (its pixels, width and height) converted on the GPU to `out` (width and height). -fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { +pub(crate) fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { let ((rgba, sw, sh), (w, h)) = (src, out); let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, @@ -261,7 +261,7 @@ fn tolerance(format: Format) -> u16 { if format.bits() == 10 { 6 } else { 2 } } -fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { +pub(crate) fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { assert_eq!(gpu.len(), cpu.len(), "{what}"); let (g, k) = (samples(gpu, c.format), samples(cpu, c.format)); let worst = g.iter().zip(&k).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b)); @@ -271,7 +271,7 @@ fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { } /// A picture with hard edges: each pixel's channels from a fixed pseudo-random sequence. -fn noise(w: u32, h: u32) -> Vec { +pub(crate) fn noise(w: u32, h: u32) -> Vec { let mut x = 0x2545_f491_u32; (0..w * h * 4) .map(|i| { @@ -284,7 +284,7 @@ fn noise(w: u32, h: u32) -> Vec { } /// A smooth picture: three ramps at different angles. -fn ramps(w: u32, h: u32) -> Vec { +pub(crate) fn ramps(w: u32, h: u32) -> Vec { (0..h) .flat_map(|y| { (0..w).flat_map(move |x| { diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md index a1282b8a1e..a4d0c27d5f 100644 --- a/docs/gpu-providers.md +++ b/docs/gpu-providers.md @@ -7,6 +7,7 @@ Provider ids: - `craft.mask`: CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu - `craft.composite.premul`: CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu - `craft.readback`: CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** +- `craft.yuv`: RGBA8 to NV12, P010 or I420 with scaling, registered from **craft-gpu-yuv** (`YuvProvider`, see [its README](../crates/gpu-yuv/README.md)). It is not in `register_all()`, since it depends on wgpu. `YuvProvider::new()` converts on the CPU on any context; `YuvProvider::with_device` runs its WGSL render passes on a device the host passes in. - `{app}.*`: registered by application wasm at init Generic worker code must only call `ProviderRegistry::dispatch`: never import app gpu crates. From 2f1b129d07e94cf94ab2ec7202270e7ea420bbbd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:56:58 -0800 Subject: [PATCH 24/47] craft-gpu-yuv: allocation failures, internal device errors and the rounding check - `cpu::convert` and the device read-back reserve the frame (and the I420 Cr plane) with `try_reserve_exact`; a failed reservation is the new `Error::Memory`, which a job reports as `GpuFault::Operation`. - A device job also pushes an `Internal` error scope, and the three scopes are popped in the reverse of the order they were pushed. - `record` makes the output planes before it uploads the source, so a job the device's limits reject queues no upload. - The equation tests accept only the floor or the ceiling of a value near a half, instead of anything within one code of the rounded value. --- crates/gpu-yuv/src/cpu.rs | 14 +++++++++++--- crates/gpu-yuv/src/job.rs | 24 ++++++++++++++++-------- crates/gpu-yuv/src/oracle_tests.rs | 18 +++++++++++++++--- crates/gpu-yuv/src/spec.rs | 3 +++ crates/gpu-yuv/src/tests.rs | 11 +++++++++++ 5 files changed, 56 insertions(+), 14 deletions(-) diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs index c7afe643f2..b96bc90ed3 100644 --- a/crates/gpu-yuv/src/cpu.rs +++ b/crates/gpu-yuv/src/cpu.rs @@ -80,6 +80,14 @@ impl Image<'_> { } } +/// An empty vector with room for `len` values, or [`Error::Memory`] when the room cannot be +/// allocated. +pub(crate) fn reserve(len: usize) -> Result, Error> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| Error::Memory { bytes: len.saturating_mul(size_of::()) })?; + Ok(v) +} + /// `rgba` (`src_width × src_height`, 4 bytes per pixel; alpha is ignored, so premultiplied /// pixels convert as if over black) scaled to `width × height` and converted, as one tightly /// packed frame in [`FrameLayout`] order. @@ -95,7 +103,9 @@ pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Convers let image = Image { rgba, width: src_width as usize, height: src_height as usize }; let c = Coefficients::of(conversion); let (shift, wide) = (conversion.format.shift(), conversion.format.sample_bytes() == 2); - let mut out = Vec::with_capacity(layout.frame_bytes()); + let (cw, ch) = (width / 2, height / 2); + let mut out = reserve(layout.frame_bytes())?; + let mut cr: Vec = if conversion.format == crate::Format::I420 { reserve(cw as usize * ch as usize)? } else { Vec::new() }; let mut put = |v: u16| { let v = v << shift; if wide { @@ -112,7 +122,6 @@ pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Convers } } }; - let (cw, ch) = (width / 2, height / 2); plane(width, height, &mut |v| put(v[0])); match conversion.format { crate::Format::Nv12 | crate::Format::P010 => plane(cw, ch, &mut |v| { @@ -120,7 +129,6 @@ pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Convers put(v[2]); }), crate::Format::I420 => { - let mut cr = Vec::with_capacity(cw as usize * ch as usize); plane(cw, ch, &mut |v| { put(v[1]); cr.push(v[2]); diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs index 3534816000..b37e346f92 100644 --- a/crates/gpu-yuv/src/job.rs +++ b/crates/gpu-yuv/src/job.rs @@ -40,11 +40,12 @@ fn invalid(message: impl std::fmt::Display) -> GpuFault { GpuFault::InvalidJob(format!("{PROVIDER_ID}: {message}")) } -/// A conversion error as a fault: device errors are [`GpuFault::Operation`], the rest describe a -/// job that cannot run and are [`GpuFault::InvalidJob`]. +/// A conversion error as a fault: device errors and allocation failures are +/// [`GpuFault::Operation`], the rest describe a job that cannot run and are +/// [`GpuFault::InvalidJob`]. fn fault(e: Error) -> GpuFault { match e { - Error::Device(_) => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")), + Error::Device(_) | Error::Memory { .. } => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")), _ => invalid(e), } } @@ -256,7 +257,8 @@ mod device { } /// `rgba` converted on the device, as one packed frame. Errors the device reports go to - /// error scopes and come back as [`Error::Device`]. + /// error scopes and come back as [`Error::Device`]; a frame that cannot be allocated is + /// [`Error::Memory`]. pub(super) fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { let (sw, sh) = (job.src_width, job.src_height); let limit = self.device.limits().max_texture_dimension_2d; @@ -270,10 +272,12 @@ mod device { drop(converters); let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = self.device.push_error_scope(wgpu::ErrorFilter::Internal); let converter = cached.unwrap_or_else(|| Converter::new(&self.device, job.conversion)); let recorded = self.record(&converter, rgba, job); - // Both scopes are popped on every path, so that none stays open on the device. - let errors = [pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; + // The scopes are popped on every path, in the reverse of the order they were pushed, + // so that none stays open on the device. + let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; if let Some(e) = errors.into_iter().flatten().next() { return Err(device_error(e)); } @@ -288,7 +292,9 @@ mod device { self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(device_error)?; rx.try_recv().map_err(|_| device_error("the read-back map did not complete"))?.map_err(device_error)?; let mapped = buffer.get_mapped_range(..).map_err(device_error)?; - let mut frame = vec![0u8; planes.layout().frame_bytes()]; + let bytes = planes.layout().frame_bytes(); + let mut frame = crate::cpu::reserve(bytes)?; + frame.resize(bytes, 0u8); let unpacked = planes.layout().unpack(&mapped, &mut frame); drop(mapped); buffer.unmap(); @@ -297,6 +303,9 @@ mod device { /// Upload `rgba` and record and submit the passes and the copy into a read-back buffer. fn record(&self, converter: &Converter, rgba: &[u8], job: &YuvJob) -> Result<(Planes, wgpu::Buffer), Error> { + // The output size is checked against the device before the source is uploaded, so a + // rejected job queues no upload. + let planes = converter.planes(&self.device, job.width, job.height)?; let (sw, sh) = (job.src_width, job.src_height); let size = wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }; let texture = self.device.create_texture(&wgpu::TextureDescriptor { @@ -312,7 +321,6 @@ mod device { let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }; self.queue.write_texture(texture.as_image_copy(), rgba, layout, size); let source = converter.bind(&self.device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); - let planes = converter.planes(&self.device, job.width, job.height)?; let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft.yuv read-back"), size: planes.layout().buffer_size, diff --git a/crates/gpu-yuv/src/oracle_tests.rs b/crates/gpu-yuv/src/oracle_tests.rs index 2b277805f4..354426a4e0 100644 --- a/crates/gpu-yuv/src/oracle_tests.rs +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -59,11 +59,23 @@ fn round(x: f64, bits: u32) -> u16 { } /// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either -/// way in `f32`, so either neighbor passes there. +/// way in `f32`, so there the floor and the ceiling of `exact`, clamped to the codes, both pass. fn rounds_to(got: u16, exact: f64, bits: u32) -> bool { - let want = round(exact, bits); let near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3; - got == want || near_half && got.abs_diff(want) <= 1 + let code = |v: f64| v.clamp(0.0, f64::from((1u32 << bits) - 1)) as u16; + got == round(exact, bits) || near_half && (got == code(exact.floor()) || got == code(exact.ceil())) +} + +#[test] +fn a_value_near_a_half_passes_only_as_its_floor_or_ceiling() { + assert!(rounds_to(128, 128.5, 8)); + assert!(rounds_to(129, 128.5, 8)); + assert!(!rounds_to(130, 128.5, 8)); + assert!(!rounds_to(127, 128.5, 8)); + assert!(rounds_to(255, 254.9995, 8)); + assert!(!rounds_to(254, 254.9, 8)); + assert!(rounds_to(0, -0.5, 8)); + assert!(!rounds_to(1, -0.5, 8)); } /// Every sample of a frame as its value (P010 words shifted down by 6). diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs index 0ee3f5ba6b..cff46fe1a8 100644 --- a/crates/gpu-yuv/src/spec.rs +++ b/crates/gpu-yuv/src/spec.rs @@ -164,6 +164,8 @@ pub enum Error { /// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and /// size. Layout, + /// A buffer of `bytes` bytes for the frame could not be allocated. + Memory { bytes: usize }, /// The device reported an error (validation, out of memory, a failed map or poll) while /// [`crate::YuvProvider`] ran a job on it. Device(String), @@ -181,6 +183,7 @@ impl fmt::Display for Error { Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), Error::Layout => f.write_str("the frame layout does not match its format and size"), + Error::Memory { bytes } => write!(f, "a buffer of {bytes} bytes could not be allocated"), Error::Device(message) => write!(f, "the device reported an error: {message}"), } } diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index 68e3a84a8f..157398ce26 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -121,6 +121,17 @@ fn bad_sizes_are_errors() { assert_eq!(Error::OutputSize { width: 3, height: 2 }.to_string(), "a 4:2:0 picture of 3×2 needs both sides even and not zero"); } +#[test] +fn a_frame_buffer_that_cannot_be_allocated_is_an_error() { + // A request past `isize::MAX` bytes fails on every allocator, so the failure path runs + // without exhausting memory. + assert_eq!(cpu::reserve::(usize::MAX).unwrap_err(), Error::Memory { bytes: usize::MAX }); + assert_eq!(cpu::reserve::(usize::MAX / 2).unwrap_err(), Error::Memory { bytes: usize::MAX - 1 }); + let room = cpu::reserve::(4096).unwrap(); + assert!(room.is_empty() && room.capacity() >= 4096); + assert_eq!(Error::Memory { bytes: 16 }.to_string(), "a buffer of 16 bytes could not be allocated"); +} + #[test] fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() { let l = FrameLayout::new(Format::Nv12, 1920, 1080).unwrap(); From 29452e1957593c21d05deb399631be4b791764e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 19:02:00 -0800 Subject: [PATCH 25/47] craft-gpu-yuv: layout sizes saturate instead of overflowing `PlaneLayout::row_bytes` and `FrameLayout::frame_bytes` saturate when a caller changes a layout's public fields to sizes past their integer types, instead of overflowing. Layouts from `FrameLayout::new` keep their sizes. --- crates/gpu-yuv/src/layout.rs | 10 +++++++--- crates/gpu-yuv/src/tests.rs | 13 +++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs index 7898aa76d9..93b3f77269 100644 --- a/crates/gpu-yuv/src/layout.rs +++ b/crates/gpu-yuv/src/layout.rs @@ -18,9 +18,9 @@ pub struct PlaneLayout { } impl PlaneLayout { - /// Bytes of one row in a packed frame. + /// Bytes of one row in a packed frame, or `u32::MAX` when the fields give more. pub fn row_bytes(&self) -> u32 { - self.width * self.texel_bytes + self.width.saturating_mul(self.texel_bytes) } } @@ -83,8 +83,12 @@ impl FrameLayout { } /// Bytes of one tightly packed frame: the planes one after another, each row without padding. + /// Fields changed after [`FrameLayout::new`] that give more than `usize::MAX` give + /// `usize::MAX`. pub fn frame_bytes(&self) -> usize { - self.planes.iter().map(|p| p.row_bytes() as usize * p.height as usize).sum() + self.planes + .iter() + .fold(0usize, |n, p| n.saturating_add((p.width as usize).saturating_mul(p.texel_bytes as usize).saturating_mul(p.height as usize))) } /// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to) diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index 157398ce26..e2e6977836 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -177,6 +177,19 @@ fn unpack_refuses_a_layout_that_was_changed_after_it_was_made() { assert_eq!(Error::Layout.to_string(), "the frame layout does not match its format and size"); } +#[test] +fn sizes_of_a_changed_layout_saturate_instead_of_overflowing() { + let mut l = FrameLayout::new(Format::I420, 4, 2).unwrap(); + let huge = PlaneLayout { width: u32::MAX, height: u32::MAX, texel_bytes: 4, offset: 0, bytes_per_row: 0 }; + assert_eq!(huge.row_bytes(), u32::MAX); + l.planes = vec![PlaneLayout { height: 1, ..huge }]; + let full = usize::try_from(u64::from(u32::MAX) * 4).unwrap_or(usize::MAX); + assert_eq!(l.frame_bytes(), full, "a row past u32::MAX bytes counts in full"); + l.planes = vec![huge; 3]; + assert_eq!(l.frame_bytes(), usize::MAX); + assert_eq!(l.unpack(&[], &mut []), Err(Error::Layout)); +} + #[test] fn an_enlarged_solid_color_keeps_its_codes() { for format in ALL { From f3e24c3846e5bf89629c693c3d9c44f90dc28ef8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:27:26 -0800 Subject: [PATCH 26/47] craft-gpu-yuv: the shader rounds a value just below a half down The shader's code() rounded with floor(v + 0.5). In f32, v + 0.5 for v = 0.49999997 rounds to 1.0, so that value became code 1 instead of 0. code() now takes the fraction v - floor(v), which is exact, and adds 1 when it is 0.5 or more. The CPU path already used f32::round. The f64 oracle in oracle_tests.rs had the same form and now uses f64::round, which is BT.2100's Round(x) for every input. --- crates/gpu-yuv/src/gpu.rs | 6 ++- crates/gpu-yuv/src/oracle_tests.rs | 7 ++- crates/gpu-yuv/src/tests.rs | 79 ++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 4 deletions(-) diff --git a/crates/gpu-yuv/src/gpu.rs b/crates/gpu-yuv/src/gpu.rs index 350c6adb66..a77e3316c5 100644 --- a/crates/gpu-yuv/src/gpu.rs +++ b/crates/gpu-yuv/src/gpu.rs @@ -121,9 +121,11 @@ fn area(pos: vec2) -> vec3 {{ }} // A half rounds up, as INT and Round do in the recommendations; WGSL's round() takes it to the -// even neighbor. Values below 0 clamp to 0 either way. +// even neighbor. The fraction v - floor(v) is exact in f32, while floor(v + 0.5) takes a value +// just below a half up, because v + 0.5 rounds to the next integer. Values below 0 clamp to 0. fn code(v: f32) -> u32 {{ - return u32(clamp(floor(v + 0.5), 0.0, MAX)) << SHIFT; + let f = floor(v); + return u32(clamp(select(f, f + 1.0, v - f >= 0.5), 0.0, MAX)) << SHIFT; }} @fragment fn fs_luma(@builtin(position) pos: vec4) -> @location(0) vec4 {{ diff --git a/crates/gpu-yuv/src/oracle_tests.rs b/crates/gpu-yuv/src/oracle_tests.rs index 354426a4e0..303abad3c7 100644 --- a/crates/gpu-yuv/src/oracle_tests.rs +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -53,9 +53,10 @@ fn exact(rgb: [f64; 3], c: Conversion) -> [f64; 3] { } } -/// `Round(x) = Sign(x) Floor(|x| + 0.5)`, clamped to the codes of `bits`. +/// `Round(x) = Sign(x) Floor(|x| + 0.5)`, clamped to the codes of `bits`. `f64::round` is that +/// function; adding 0.5 in `f64` would take the largest value below a half up to 1. fn round(x: f64, bits: u32) -> u16 { - (x.signum() * (x.abs() + 0.5).floor()).clamp(0.0, f64::from((1u32 << bits) - 1)) as u16 + x.round().clamp(0.0, f64::from((1u32 << bits) - 1)) as u16 } /// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either @@ -76,6 +77,8 @@ fn a_value_near_a_half_passes_only_as_its_floor_or_ceiling() { assert!(!rounds_to(254, 254.9, 8)); assert!(rounds_to(0, -0.5, 8)); assert!(!rounds_to(1, -0.5, 8)); + assert_eq!(round(0.5 - f64::EPSILON / 4.0, 8), 0); + assert_eq!(round(2.5, 8), 3); } /// Every sample of a frame as its value (P010 words shifted down by 6). diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index e2e6977836..b0c601e773 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -350,6 +350,85 @@ fn the_gpu_matches_the_cpu_when_scaling() { } } +#[test] +fn the_gpu_rounds_a_value_just_below_a_half_down() { + let Some((device, queue)) = device() else { return }; + // The shader's own code(), driven by one extra entry point. The values are built from the + // texel position so that no compiler folds them: k is 0 at the only texel's center. + // 0x3effffff is 0.49999997, the largest f32 below 0.5, and 0x3f7fffff is 0.99999994. + let probe = "@fragment fn fs_probe(@builtin(position) pos: vec4) -> @location(0) vec4 { + let k = u32(pos.x); + let z = f32(k); + return vec4(code(bitcast(0x3effffffu + k)), code(0.5 + z), code(2.5 + z), code(bitcast(0x3f7fffffu + k))); +}"; + let wgsl = gpu::shader(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full)) + probe; + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(wgsl.into()) }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + layout: None, + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_probe"), + targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Uint, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Uint, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + { + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&pipeline); + pass.draw(0..3, 0..1); + } + enc.copy_texture_to_buffer( + texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(1) }, + }, + wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + ); + queue.submit([enc.finish()]); + buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let got = buffer.get_mapped_range(..4).unwrap().to_vec(); + assert_eq!(got, [0, 1, 3, 1], "code() of 0.49999997, 0.5, 2.5 and 0.99999994"); +} + #[test] fn planes_larger_than_the_device_allows_are_errors() { // The queue stays alive: a device whose queue was dropped cannot make an encoder. From dfeb20ddcf283d04623ec8916ec9a01951a19e24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 23:54:49 -0800 Subject: [PATCH 27/47] craft-gpu-yuv: an input larger than the largest buffer is refused before it is read The provider checked the read-back frame against max_buffer_size but not the RGBA8 input. A job whose input exceeds the limit is now GpuFault::InvalidJob before the context reads it, on every context. The BufferLimit message now names any buffer, not only the read-back one. --- crates/gpu-yuv/README.md | 4 ++-- crates/gpu-yuv/src/job.rs | 10 +++++++--- crates/gpu-yuv/src/job_tests.rs | 15 +++++++++++++++ crates/gpu-yuv/src/spec.rs | 5 +++-- 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md index 4869219866..cae588d0e6 100644 --- a/crates/gpu-yuv/README.md +++ b/crates/gpu-yuv/README.md @@ -47,8 +47,8 @@ are decimal digits. The provider checks the job against the context's `DeviceCaps` on every context, the null one included: each source and output side must be at most `max_texture_dimension_2d`, and the -read-back layout with its padded rows (`FrameLayout::buffer_size`) at most `max_buffer_size` -bytes. It checks the input's length before reading it. A +read-back layout with its padded rows (`FrameLayout::buffer_size`) and the RGBA8 input at most +`max_buffer_size` bytes. It checks the input's length before reading it. A malformed, missing, repeated or unknown parameter, a wrong input count or length, and a size the caps or the conversion do not allow are `GpuFault::InvalidJob`. With a device, the provider also checks the device's own limits, and an error the device reports during the job is diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs index b37e346f92..cbbff522b6 100644 --- a/crates/gpu-yuv/src/job.rs +++ b/crates/gpu-yuv/src/job.rs @@ -4,9 +4,9 @@ //! A job has one input, an RGBA8 buffer of `src_width × src_height × 4` bytes in the context, and //! [`YuvJob::params`] as its parameters. Its outcome has one output: a new buffer that holds the //! packed frame in [`FrameLayout`] order. Every side must be no larger than the context's -//! [`DeviceCaps::max_texture_dimension_2d`](craft_gpu::DeviceCaps), and the frame no larger than its -//! `max_buffer_size`, on every context, so that a job that runs on the null context also runs on a -//! device with the same caps. +//! [`DeviceCaps::max_texture_dimension_2d`](craft_gpu::DeviceCaps), and the input and the frame no +//! larger than its `max_buffer_size`, on every context, so that a job that runs on the null context +//! also runs on a device with the same caps. use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuJobParams, GpuProvider, HandleId}; @@ -224,6 +224,10 @@ impl GpuProvider for YuvProvider { if src_width == 0 || src_height == 0 || expected != Some(bytes) { return Err(fault(Error::Source { width: src_width, height: src_height, bytes })); } + let input_bytes = bytes as u64; + if input_bytes > caps.max_buffer_size { + return Err(fault(Error::BufferLimit { needed: input_bytes, limit: caps.max_buffer_size })); + } let rgba = ctx.read_buffer(*input)?; let frame = self.convert(&rgba, &spec).map_err(fault)?; let output = ctx.upload_buffer("craft.yuv.frame", &frame)?; diff --git a/crates/gpu-yuv/src/job_tests.rs b/crates/gpu-yuv/src/job_tests.rs index eb77b63e53..32fa92b47b 100644 --- a/crates/gpu-yuv/src/job_tests.rs +++ b/crates/gpu-yuv/src/job_tests.rs @@ -186,6 +186,21 @@ fn jobs_past_the_context_caps_are_refused() { assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 4, 64, 42).job(small)).is_ok()); } +#[test] +fn an_input_past_the_buffer_limit_is_refused_before_it_is_read() { + let r = registry(YuvProvider::new()); + let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + // 64 × 64 × 4 = 16384 bytes, more than the 16128-byte limit; 64 × 63 × 4 is exactly 16128. + let large = ctx.upload_buffer("large", &tests::noise(64, 64)).unwrap(); + let at_limit = ctx.upload_buffer("at limit", &tests::noise(64, 63)).unwrap(); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 64, 64, 4).job(large))); + assert!(refused.contains("16384 bytes is larger than the largest buffer, 16128"), "{refused}"); + assert_eq!(ctx.reads, 0, "the refused input is not read"); + assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 63, 64, 4).job(at_limit)).is_ok()); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_provider_with_a_device_matches_the_cpu_through_the_registry() { diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs index cff46fe1a8..2e311a9401 100644 --- a/crates/gpu-yuv/src/spec.rs +++ b/crates/gpu-yuv/src/spec.rs @@ -151,7 +151,8 @@ pub enum Error { TooLarge { width: u32, height: u32, limit: u32 }, /// The frame's byte sizes do not fit in the integer types that hold them. Overflow { width: u32, height: u32 }, - /// A read-back buffer for the frame would be larger than the device's largest buffer. + /// A buffer the job uses (the RGBA8 input, or the read-back buffer for the frame) would be + /// larger than the device's largest buffer. BufferLimit { needed: u64, limit: u64 }, /// A source side is zero, or the pixels are not `width × height × 4` bytes. Source { width: u32, height: u32, bytes: usize }, @@ -177,7 +178,7 @@ impl fmt::Display for Error { Error::OutputSize { width, height } => write!(f, "a 4:2:0 picture of {width}×{height} needs both sides even and not zero"), Error::TooLarge { width, height, limit } => write!(f, "{width}×{height} is larger than the largest texture side, {limit}"), Error::Overflow { width, height } => write!(f, "a frame of {width}×{height} is too large to hold"), - Error::BufferLimit { needed, limit } => write!(f, "a read-back buffer of {needed} bytes is larger than the largest buffer, {limit}"), + Error::BufferLimit { needed, limit } => write!(f, "a buffer of {needed} bytes is larger than the largest buffer, {limit}"), Error::Source { width, height, bytes } => write!(f, "{bytes} bytes are not an RGBA picture of {width}×{height}"), Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"), Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), From b67fab9d1b7b027d957e7f91ebdfebd039556596 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 23:58:44 -0800 Subject: [PATCH 28/47] craft-gpu-yuv: both provider modes take the same output sizes YuvProvider::run now holds each output side to cpu::MAX_SIDE (16384) with or without a device. Before, a context whose largest texture side was above 16384 let a device run a job that the CPU mode refused with TooLarge after reading the input. --- crates/gpu-yuv/README.md | 3 ++- crates/gpu-yuv/src/job.rs | 4 +++- crates/gpu-yuv/src/job_tests.rs | 13 +++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md index cae588d0e6..9a39ce0ff3 100644 --- a/crates/gpu-yuv/README.md +++ b/crates/gpu-yuv/README.md @@ -48,7 +48,8 @@ are decimal digits. The provider checks the job against the context's `DeviceCaps` on every context, the null one included: each source and output side must be at most `max_texture_dimension_2d`, and the read-back layout with its padded rows (`FrameLayout::buffer_size`) and the RGBA8 input at most -`max_buffer_size` bytes. It checks the input's length before reading it. A +`max_buffer_size` bytes. Each output side must also be at most `cpu::MAX_SIDE` (16384), with or +without a device. It checks the input's length before reading it. A malformed, missing, repeated or unknown parameter, a wrong input count or length, and a size the caps or the conversion do not allow are `GpuFault::InvalidJob`. With a device, the provider also checks the device's own limits, and an error the device reports during the job is diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs index cbbff522b6..4f98dccca8 100644 --- a/crates/gpu-yuv/src/job.rs +++ b/crates/gpu-yuv/src/job.rs @@ -206,8 +206,10 @@ impl GpuProvider for YuvProvider { let YuvJob { conversion, src_width, src_height, width, height } = spec; let layout = FrameLayout::new(conversion.format, width, height).map_err(fault)?; let caps = ctx.caps(); + // An output side is also held to `cpu::MAX_SIDE`, so that both provider modes take the + // same jobs. let limit = caps.max_texture_dimension_2d; - for (w, h) in [(src_width, src_height), (width, height)] { + for (w, h, limit) in [(src_width, src_height, limit), (width, height, limit.min(cpu::MAX_SIDE))] { if w > limit || h > limit { return Err(fault(Error::TooLarge { width: w, height: h, limit })); } diff --git a/crates/gpu-yuv/src/job_tests.rs b/crates/gpu-yuv/src/job_tests.rs index 32fa92b47b..c1a723da4b 100644 --- a/crates/gpu-yuv/src/job_tests.rs +++ b/crates/gpu-yuv/src/job_tests.rs @@ -186,6 +186,19 @@ fn jobs_past_the_context_caps_are_refused() { assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 4, 64, 42).job(small)).is_ok()); } +#[test] +fn an_output_side_past_the_cpu_limit_is_refused_before_the_input_is_read() { + let r = registry(YuvProvider::new()); + let side = cpu::MAX_SIDE + 2; + let caps = DeviceCaps { max_texture_dimension_2d: side, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let input = ctx.upload_buffer("input", &tests::noise(2, 2)).unwrap(); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 2, 2, side, 2).job(input))); + assert!(refused.contains(&format!("{side}×2 is larger than the largest texture side, {}", cpu::MAX_SIDE)), "{refused}"); + assert_eq!(ctx.reads, 0, "the refused input is not read"); +} + #[test] fn an_input_past_the_buffer_limit_is_refused_before_it_is_read() { let r = registry(YuvProvider::new()); From 3096cf1b80523ca3fb2b82d4f57a7c5f316fb8bc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 23:59:09 -0800 Subject: [PATCH 29/47] craft-xtask: fix the name scanner's review findings - A banned word that overlaps itself is found at every candidate, not only the first (`A-A` in `XA-A-A`). - A link to a folder is not followed when it is an input either. - The scan's remaining byte budget is checked before a file is read. - A shebang line is skipped before the lexer reads tokens. - Under `#[cfg(test)]`, const parameters, const arguments in a return type and struct patterns in `if let` no longer end an item early. - Under `#[cfg(test)]`, an item keyword counts only after an item's qualifiers, so the `fn` in `helper::(..)` or in a field's type does not start an item that hides the code after it, and the braces of a macro in an item's header (`-> ty! { u8 }`) are not its body. - The allow marker counts in a comment inside a `cfg(test)` attribute, and attribute strings are read as tokens when outer attributes are skipped. - A manifest's dotted `package.description` before the first header is read, as documented. - A relative and an absolute input for one file are read once, also under a relative base folder. --- crates/xtask/README.md | 29 +- crates/xtask/src/names.rs | 550 ++++++++++++++++++++++++++++++++------ 2 files changed, 483 insertions(+), 96 deletions(-) diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 80659f8597..c6a74f1488 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -87,24 +87,29 @@ fn production_display_names_stay_neutral() { - `Input::rust` takes a Rust file or a folder, which is read recursively for `.rs` files that `Policy::skip` keeps, given their path below the folder (`test_path` by default: `tests.rs`, - `*_tests.rs` and files under a `tests` folder). Links to folders are not followed. A file input - is read whatever its name. + `*_tests.rs` and files under a `tests` folder). Links to folders are not followed, also when the + link is an input. A file input is read whatever its name. - `Input::manifest` reads the values at the key paths `package.description` and `workspace.package.description` of a `Cargo.toml`: the table header (`[package]`, `[workspace.package]`) joined with the key, which may be bare, quoted or dotted. Headers and keys - inside strings and arrays do not count, and a key inside an inline table is not read. A - `description` under any other table, or before the first header, is not read. A TOML string, + inside strings and arrays do not count, and a key inside an inline table is not read. Before the + first header, the dotted keys `package.description` and `workspace.package.description` are read, + and a bare `description` is not. A `description` under any other table is not read. A TOML string, single-line or multi-line, is decoded, and a comment after it is not read; any other value is read as the rest of its line. `Input::text` reads every line of a text file, and `Input::text_mark_above` also lets a `#` line with the marker exempt the line below it. Inputs must not include binary files. - In Rust, the scanner reads `"…"` and `r"…"` literals with any number of `#`, decodes every escape (`\n`, `\x7A`, `\u{…}`, a backslash before a line break) and reads CRLF as LF. `b"…"`, `br"…"`, - `c"…"` and `cr"…"` are read when `Policy::literals` asks for them. Comments, character, byte and - lifetime tokens, and the rest of a module after `#![cfg(test)]` are skipped. So is the code under - `#[cfg(test)]`, comments in the attribute included: a `const`, `static` or `let` up to its `;`, - another item up to the `}` that closes it or the `;` that ends it, and a field, argument, arm or - statement up to its `,` or `;`. A block expression (a block, a macro's braces, a labeled block, or + `c"…"` and `cr"…"` are read when `Policy::literals` asks for them; their `\x` escapes are decoded + together as UTF-8, and bytes that are not UTF-8 become U+FFFD. A shebang line, comments, + character, byte and lifetime tokens, and the rest of a module after `#![cfg(test)]` are skipped. + So is the code under `#[cfg(test)]`, comments in the attribute included: a `const`, `static` or + `let` up to its `;`, another item up to the `}` that closes it or the `;` that ends it, and a + field, argument, arm or statement up to its `,` or `;`. An item keyword counts only when nothing + but qualifiers (`pub`, `unsafe`, `extern "C"` and the like) comes before it, so the `fn` in + `f::(…)` or in a field's type does not start an item, and the braces of a macro in an + item's header (`-> ty! { u8 }`) are not its body. A block expression (a block, a macro's braces, a labeled block, or `if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as an arm's expression after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` branches. When a method call, field or `?` follows that `}`, it runs up to its `,` or `;` @@ -116,6 +121,9 @@ fn production_display_names_stay_neutral() { description or trimmed text line, never part of one. - In Rust, the marker counts only inside a comment on a line the literal spans. In a manifest it counts anywhere on a line the description spans, and in a text file anywhere on the line. +- `scan` identifies a file by its input path joined to the base folder, and joins a relative base + folder to the current folder first, so a relative and an absolute input for one file are read + once; `..` and links are not resolved. - `scan` reads each file once, in path order, and returns the findings in path order, then source order, then the order of `banned`. A `Finding` has the path, the first line of the literal or description, the word, the decoded text or text line and the kind; its `Display` text is @@ -124,7 +132,8 @@ fn production_display_names_stay_neutral() { - `names::Error` is `Policy` (no banned words, an empty word or an empty marker), `Io` (with the path), `InvalidUtf8`, `FileTooLarge`, `TotalTooLarge`, `TooDeep`, `Conflict` (a file given as two kinds of input) or `Syntax` (with the path and line). `DEFAULT_LIMITS` is 8 MiB per file, 512 MiB - per scan and folders 64 deep; a file over the limit is rejected before it is read. + per scan and folders 64 deep; a file larger than the per-file limit, or than what is left of the + scan's limit, is rejected before it is read. The source copies differ in a few rules. An app that switches lists the results that change: diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 57d4f89de8..0cbb1a0b20 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -292,10 +292,14 @@ impl From for String { /// Every finding in `inputs`, read from `base`. Files are read once each, in path order, and the /// findings come in path order, then in source order, then in the order of [`Policy::banned`]. /// +/// A file is identified by its path joined to `base`, and a relative `base` is joined to the +/// current folder first, so a relative and an absolute path to it are one file, read once and +/// reported by the input path that sorts first; `..` and links are not resolved. +/// /// A [`Kind::Rust`] folder is read recursively for `.rs` files that [`Policy::skip`] keeps; links to -/// folders are not followed. A file input is read whatever its name. Every error stops the scan: a -/// missing input, a file that cannot be read, is not UTF-8 or is over a limit, and a Rust source the -/// lexer cannot read. Inputs must not include binary files. +/// folders are not followed, also when the link is an input. A file input is read whatever its +/// name. Every error stops the scan: a missing input, a file that cannot be read, is not UTF-8 or +/// is over a limit, and a Rust source the lexer cannot read. Inputs must not include binary files. pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result, Error> { policy.validate()?; let mut files = Vec::new(); @@ -306,15 +310,24 @@ pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result = files.into_iter().map(|(path, kind)| (root.join(&path), kind, path)).collect(); files.sort(); - files.dedup(); + files.dedup_by(|later, first| later.0 == first.0 && later.1 == first.1); if let Some(pair) = files.windows(2).find(|pair| pair[0].0 == pair[1].0) { - return Err(Error::Conflict { path: pair[0].0.clone() }); + return Err(Error::Conflict { path: pair[0].2.clone() }); } + files.sort_by(|a, b| a.2.cmp(&b.2)); let mut total = 0; let mut findings = Vec::new(); - for (path, kind) in &files { - let source = read_limited(&base.join(path), path, &policy.limits, &mut total)?; + for (full, kind, path) in &files { + let source = read_limited(full, path, &policy.limits, &mut total)?; findings.extend(scan_source(path, &source, *kind, policy)?); } Ok(findings) @@ -565,22 +578,33 @@ pub struct Literal { /// `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as an arm's expression /// after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` branches. When a method /// call, field or `?` follows that `}`, it runs up to its `,` or `;` instead. Character, byte and -/// lifetime tokens are read, so a quote in them does not start a string. +/// lifetime tokens are read, so a quote in them does not start a string. A shebang first line is +/// skipped. pub fn literals(source: &str, kinds: Literals) -> Result, SyntaxError> { lex(source, kinds, None).map(|lexed| lexed.literals) } fn contains_word(text: &str, word: &str, case: MatchCase) -> bool { match case { - MatchCase::Exact => text.match_indices(word).any(|(at, _)| whole_word(text, at, word.len())), - MatchCase::AsciiInsensitive => { - let lower = text.to_ascii_lowercase(); - let word = word.to_ascii_lowercase(); - lower.match_indices(&word).any(|(at, _)| whole_word(text, at, word.len())) - } + MatchCase::Exact => any_whole_word(text, text, word), + MatchCase::AsciiInsensitive => any_whole_word(&text.to_ascii_lowercase(), text, &word.to_ascii_lowercase()), } } +/// Whether `word` occurs in `haystack` at an index where it is a whole word of `text`, which has the +/// same byte offsets. Every occurrence is checked, overlapping ones included. +fn any_whole_word(haystack: &str, text: &str, word: &str) -> bool { + let mut from = 0; + while let Some(found) = haystack.get(from..).and_then(|rest| rest.find(word)) { + let at = from + found; + if whole_word(text, at, word.len()) { + return true; + } + from = at + haystack.get(at..).and_then(|rest| rest.chars().next()).map_or(1, char::len_utf8); + } + false +} + fn is_word(c: char) -> bool { c.is_alphanumeric() || c == '_' } @@ -591,14 +615,21 @@ fn whole_word(text: &str, at: usize, len: usize) -> bool { !before.is_some_and(is_word) && !after.is_some_and(is_word) } +fn push_char(text: &mut Vec, c: char) { + text.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()); +} + fn io_error(path: &Path) -> impl FnOnce(io::Error) -> Error + '_ { move |source| Error::Io { path: path.to_path_buf(), source } } fn collect_rust(base: &Path, path: &Path, policy: &Policy<'_>, out: &mut Vec<(PathBuf, Kind)>) -> Result<(), Error> { - let meta = fs::metadata(base.join(path)).map_err(io_error(path))?; + let full = base.join(path); + let link = fs::symlink_metadata(&full).map_err(io_error(path))?.file_type().is_symlink(); + let meta = fs::metadata(&full).map_err(io_error(path))?; if meta.is_dir() { - walk(base, path, path, policy, 0, out) + // A link to a folder is not followed, also when it is an input. + if link { Ok(()) } else { walk(base, path, path, policy, 0, out) } } else { out.push((path.to_path_buf(), Kind::Rust)); Ok(()) @@ -636,16 +667,23 @@ fn read_limited(full: &Path, path: &Path, limits: &Limits, total: &mut u64) -> R if len > limits.max_file_bytes { return Err(Error::FileTooLarge { path: path.to_path_buf(), limit: limits.max_file_bytes }); } + let remaining = limits.max_total_bytes.saturating_sub(*total); + let over_total = || Error::TotalTooLarge { path: path.to_path_buf(), limit: limits.max_total_bytes }; + if len > remaining { + return Err(over_total()); + } let mut bytes = Vec::with_capacity(usize::try_from(len).unwrap_or(0)); - file.take(limits.max_file_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(io_error(path))?; + // One byte past the smaller limit shows a file that grew after its length was read. + let cap = limits.max_file_bytes.min(remaining); + file.take(cap.saturating_add(1)).read_to_end(&mut bytes).map_err(io_error(path))?; let read = u64::try_from(bytes.len()).unwrap_or(u64::MAX); if read > limits.max_file_bytes { return Err(Error::FileTooLarge { path: path.to_path_buf(), limit: limits.max_file_bytes }); } - *total = total.saturating_add(read); - if *total > limits.max_total_bytes { - return Err(Error::TotalTooLarge { path: path.to_path_buf(), limit: limits.max_total_bytes }); + if read > remaining { + return Err(over_total()); } + *total = total.saturating_add(read); let mut text = String::from_utf8(bytes).map_err(|_| Error::InvalidUtf8 { path: path.to_path_buf() })?; if text.starts_with('\u{feff}') { text.remove(0); @@ -682,17 +720,30 @@ const BLOCK_KEYWORDS: &[&str] = &["async", "const", "for", "if", "loop", "match" enum TestRegion { /// An item, field, argument, arm or statement under `#[cfg(test)]`, at this delimiter depth. /// `start` is the index where its code (or an arm's expression, after `=>`) starts; `opened` is - /// set once its first `{` is read, `item` once an item keyword (`fn`, `impl`, `mod`…) is read, - /// and `semi` while the last such keyword is `const`, `let` or `static`, whose items end at their - /// `;`. Without an item keyword, `block` is set when that first `{` starts a block expression (a - /// block, a macro's braces, or `if`, `match`, `loop` and the like), which ends at its `}` unless - /// an `else` follows. A `.` or `?` after that `}` clears `block`, so the expression ends at its - /// `;` or `,`. - Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool }, + /// set once its first `{` is read, `item` once its first item keyword (`fn`, `impl`, `mod`…) is + /// read where only qualifiers (`pub`, `unsafe`, `extern "C"`…) come before it, and `semi` when that keyword is `const` (not `const fn`), `let` or `static`, whose items + /// end at their `;`. Without an item keyword, `block` is set when that first `{` starts a block + /// expression (a block, a macro's braces, or `if`, `match`, `loop` and the like), which ends at + /// its `}` unless an `else` follows. A `.` or `?` after that `}` clears `block`, so the expression + /// ends at its `;` or `,`. A `{` does not count as the first while `pattern` is set (between the + /// `let` of an `if` or `while` condition and its `=`, or a `for` and its `in`) or while `angle` + /// generic brackets of an item's header are open. + Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool, pattern: bool, angle: usize }, /// The rest of the module that `#![cfg(test)]` starts, at this delimiter depth. Inner { level: usize }, } +impl TestRegion { + /// Test-only code at `level` whose code starts at `start`. + fn item(level: usize, start: usize) -> Self { + TestRegion::Item { level, start, opened: false, item: false, semi: false, block: false, pattern: false, angle: 0 } + } +} + +/// The keywords that start a block expression whose header can hold item keywords that do not start +/// an item (`if let`, `for … in`). +const HEADER_KEYWORDS: &[&str] = &["for", "if", "loop", "match", "while"]; + struct Lexer<'s> { chars: Vec, at: usize, @@ -702,6 +753,11 @@ struct Lexer<'s> { /// Open delimiters and the line of each. delims: Vec<(char, usize)>, test: Option, + /// Whether the last token read, past whitespace and comments, is a word. + after_word: bool, + /// Whether the last token read, past whitespace and comments, is a macro's `!`: a `!` after a + /// word, not the `!` of a never type (`-> !`). + after_bang: bool, out: Lexed, } @@ -714,6 +770,8 @@ fn lex(source: &str, kinds: Literals, marker: Option<&str>) -> Result { } fn run(&mut self) -> Result<(), SyntaxError> { + // A first line that starts with `#!` is a shebang, unless a `[` follows (an inner attribute). + let start = usize::from(self.peek(0) == Some('\u{feff}')); + if self.chars.get(start..start + 2) == Some(&['#', '!'][..]) && self.chars.get(self.skip_space(start + 2)) != Some(&'[') { + while self.peek(0).is_some_and(|c| c != '\n') { + self.at += 1; + } + } while let Some(c) = self.peek(0) { + let token = !c.is_whitespace() && !(c == '/' && matches!(self.peek(1), Some('/' | '*'))); match c { '\n' => { self.line += 1; @@ -749,16 +815,22 @@ impl Lexer<'_> { self.string(Form::Str)?; } '\'' => self.quote(Form::Char)?, - '#' => self.hash(), + '#' => self.hash()?, '{' | '(' | '[' => self.open(c), '}' | ')' | ']' => self.close(c)?, ';' => self.item_end(false), ',' => self.item_end(true), '=' if self.peek(1) == Some('>') => self.arrow(), + '=' => self.equals(), + '<' | '>' => self.angle(c), c if c.is_ascii_digit() => self.number(), c if is_word(c) => self.word()?, _ => self.at += 1, } + if token { + self.after_bang = c == '!' && self.after_word; + self.after_word = is_word(c); + } } match self.delims.last() { Some(&(_, line)) => Err(Self::error(line, "unclosed delimiter")), @@ -820,10 +892,12 @@ impl Lexer<'_> { } } - /// A `"…"` body after its opening quote. + /// A `"…"` body after its opening quote. The text is collected as bytes, so that the `\x` + /// escapes of a byte or C string decode as UTF-8 together; bytes that are not UTF-8 become + /// U+FFFD. fn string(&mut self, form: Form) -> Result<(), SyntaxError> { let first = self.line; - let mut text = String::new(); + let mut text = Vec::new(); loop { match self.next() { None => return Err(Self::error(first, "unterminated string literal")), @@ -832,17 +906,17 @@ impl Lexer<'_> { Some('\r') if self.peek(0) == Some('\n') => {} Some('\n') => { self.line += 1; - text.push('\n'); + text.push(b'\n'); } - Some(c) => text.push(c), + Some(c) => push_char(&mut text, c), } } - self.push(first, text, form); + self.push(first, String::from_utf8_lossy(&text).into_owned(), form); Ok(()) } /// The escape after a backslash, decoded into `text`. - fn escape(&mut self, form: Form, text: &mut String, first: usize) -> Result<(), SyntaxError> { + fn escape(&mut self, form: Form, text: &mut Vec, first: usize) -> Result<(), SyntaxError> { let decoded = match self.next() { None => return Err(Self::error(first, "unterminated escape")), Some('n') => '\n', @@ -850,7 +924,10 @@ impl Lexer<'_> { Some('t') => '\t', Some('0') => '\0', Some(c @ ('\\' | '\'' | '"')) => c, - Some('x') => self.hex_escape(form)?, + Some('x') => { + text.push(self.hex_escape(form)?); + return Ok(()); + } Some('u') if form != Form::Byte => self.unicode_escape()?, Some('\n') if form != Form::Char => { self.continuation(); @@ -863,7 +940,7 @@ impl Lexer<'_> { } Some(_) => return Err(Self::error(self.line, "unknown character escape")), }; - text.push(decoded); + push_char(text, decoded); Ok(()) } @@ -876,16 +953,16 @@ impl Lexer<'_> { } } - fn hex_escape(&mut self, form: Form) -> Result { + /// The byte of a `\x` escape after its `x`. + fn hex_escape(&mut self, form: Form) -> Result { let digits = (self.peek(0).and_then(|c| c.to_digit(16)), self.peek(1).and_then(|c| c.to_digit(16))); let (Some(high), Some(low)) = digits else { return Err(Self::error(self.line, "a \\x escape needs two hex digits")); }; self.at += 2; - let value = high * 16 + low; + let value = u8::try_from(high * 16 + low).unwrap_or(u8::MAX); match (value, form) { - (0..=0x7f, _) => Ok(char::from_u32(value).unwrap_or(char::REPLACEMENT_CHARACTER)), - (_, Form::Byte | Form::C) => Ok(char::REPLACEMENT_CHARACTER), + (0..=0x7f, _) | (_, Form::Byte | Form::C) => Ok(value), _ => Err(Self::error(self.line, "a \\x escape above 0x7F")), } } @@ -919,7 +996,7 @@ impl Lexer<'_> { (Some('\\'), _) => { let first = self.line; self.at += 2; - self.escape(form, &mut String::new(), first)?; + self.escape(form, &mut Vec::new(), first)?; if self.next() != Some('\'') { return Err(Self::error(first, "unterminated character literal")); } @@ -941,16 +1018,7 @@ impl Lexer<'_> { let start = self.at; self.number(); let word: String = self.chars.get(start..self.at).unwrap_or_default().iter().collect(); - // `const { .. }` is a block expression, not an item. - let const_block = word == "const" && self.chars.get(self.skip_space(self.at)) == Some(&'{'); - if let Some(TestRegion::Item { level, opened: false, item, semi, .. }) = &mut self.test - && *level == self.delims.len() - && ITEM_KEYWORDS.contains(&word.as_str()) - && !const_block - { - *item = true; - *semi = SEMICOLON_KEYWORDS.contains(&word.as_str()); - } + self.header_word(start, &word); match (word.as_str(), self.peek(0)) { ("b", Some('\'')) => self.quote(Form::Byte), ("b", Some('"')) => { @@ -968,6 +1036,63 @@ impl Lexer<'_> { } } + /// Reads a word at `at` in the header of test-only code: its first item keyword decides how the + /// item ends, and `let`, `for` and `in` mark where a pattern's braces are. + fn header_word(&mut self, at: usize, word: &str) { + let Some(TestRegion::Item { level, start, opened: false, item, .. }) = self.test else { return }; + if level != self.delims.len() { + return; + } + let code = self.code_start(start); + let lead = self.word_at(code); + let next = self.word_at(self.skip_space(self.at)); + let header = HEADER_KEYWORDS.contains(&lead.as_str()); + let (keyword, pattern) = match word { + "let" if matches!(lead.as_str(), "if" | "while") => (false, Some(true)), + "for" if lead == "for" && at == code => (false, Some(true)), + "in" if lead == "for" => (false, Some(false)), + // `const { .. }` is a block expression, not an item. + "const" if self.chars.get(self.skip_space(self.at)) == Some(&'{') => (false, None), + // An item keyword counts only after the item's qualifiers, so `fn` in `f::(..)` does not. + _ => (!item && !header && ITEM_KEYWORDS.contains(&word) && self.item_qualifiers(code, at), None), + }; + if let Some(TestRegion::Item { item, semi, pattern: reading, .. }) = &mut self.test { + if keyword { + *item = true; + *semi = SEMICOLON_KEYWORDS.contains(&word) && !(word == "const" && matches!(next.as_str(), "async" | "extern" | "fn" | "unsafe")); + } + if let Some(pattern) = pattern { + *reading = pattern; + } + } + } + + /// A `=` that is not part of `==`, `!=`, `<=`, `>=` or `..=` ends a `let` pattern. + fn equals(&mut self) { + let before = self.at.checked_sub(1).and_then(|i| self.chars.get(i)).copied(); + let compares = matches!(before, Some('=' | '!' | '<' | '>' | '.')) || self.peek(1) == Some('='); + if let Some(TestRegion::Item { level, pattern, .. }) = &mut self.test + && *level == self.delims.len() + && !compares + { + *pattern = false; + } + self.at += 1; + } + + /// A `<` or `>` (not the `>` of `->`) in an item's header before its body opens or closes a + /// generic bracket. + fn angle(&mut self, c: char) { + let arrow = c == '>' && self.at.checked_sub(1).and_then(|i| self.chars.get(i)) == Some(&'-'); + if let Some(TestRegion::Item { level, opened: false, item: true, angle, .. }) = &mut self.test + && *level == self.delims.len() + && !arrow + { + *angle = if c == '<' { *angle + 1 } else { angle.saturating_sub(1) }; + } + self.at += 1; + } + /// A raw literal after its `r`, or a raw identifier (`r#name`), which is left to the caller. fn raw(&mut self, form: Form) -> Result<(), SyntaxError> { let hashes = self.chars.get(self.at..).unwrap_or_default().iter().take_while(|&&c| c == '#').count(); @@ -1048,22 +1173,29 @@ impl Lexer<'_> { Some((at, inner)) } - fn hash(&mut self) { + fn hash(&mut self) -> Result<(), SyntaxError> { let Some((end, inner)) = self.cfg_test_end() else { self.at += 1; - return; + return Ok(()); }; - let skipped = self.chars.get(self.at..end).unwrap_or_default(); - self.line += skipped.iter().filter(|&&c| c == '\n').count(); - self.at = end; + // The attribute holds only its tokens, whitespace and comments; the comments can hold the + // marker. + while self.at < end { + match (self.peek(0), self.peek(1)) { + (Some('/'), Some('/')) => self.line_comment(), + (Some('/'), Some('*')) => self.block_comment()?, + (Some('\n'), _) => { + self.line += 1; + self.at += 1; + } + _ => self.at += 1, + } + } if self.test.is_none() { let level = self.delims.len(); - self.test = Some(if inner { - TestRegion::Inner { level } - } else { - TestRegion::Item { level, start: end, opened: false, item: false, semi: false, block: false } - }); + self.test = Some(if inner { TestRegion::Inner { level } } else { TestRegion::item(level, end) }); } + Ok(()) } /// A `=>` at the level of a test-only arm: its expression starts after it. @@ -1072,7 +1204,7 @@ impl Lexer<'_> { if let Some(TestRegion::Item { level, item: false, .. }) = self.test && level == self.delims.len() { - self.test = Some(TestRegion::Item { level, start: self.at, opened: false, item: false, semi: false, block: false }); + self.test = Some(TestRegion::item(level, self.at)); } } @@ -1080,30 +1212,78 @@ impl Lexer<'_> { /// the block itself, a macro's braces, a labeled block or loop, or a block keyword's expression. /// Outer attributes before it are passed over. fn starts_block(&self, start: usize) -> bool { + let at = self.code_start(start); + at == self.at || self.chars.get(at) == Some(&'\'') || BLOCK_KEYWORDS.contains(&self.word_at(at).as_str()) || self.macro_braces(at) + } + + /// The index of the code at `start`, past whitespace, comments and outer attributes. + fn code_start(&self, start: usize) -> usize { let mut at = self.skip_space(start); while self.chars.get(at) == Some(&'#') { - at = self.skip_space(at + 1); - if self.chars.get(at) != Some(&'[') { - return false; - } - let mut depth = 0_usize; - loop { - match self.chars.get(at) { - None => return false, - Some('[') => depth += 1, - Some(']') => { - depth -= 1; - if depth == 0 { - break; - } + let open = self.skip_space(at + 1); + let Some(end) = self.chars.get(open).filter(|&&c| c == '[').and_then(|_| self.group_end(open)) else { + break; + }; + at = self.skip_space(end); + } + at + } + + /// The index after the delimiter group that opens at `at`, read as tokens: delimiters inside + /// strings, character literals and comments do not count. `None` when it does not close. + fn group_end(&self, mut at: usize) -> Option { + let mut depth = 0_usize; + loop { + let c = *self.chars.get(at)?; + match c { + '[' | '(' | '{' => depth += 1, + ']' | ')' | '}' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + return Some(at + 1); + } + } + '/' if matches!(self.chars.get(at + 1), Some('/' | '*')) => { + at = self.skip_space(at); + continue; + } + '"' => { + at = self.quoted_end(at + 1, false, 0)?; + continue; + } + '\'' => { + at += match (self.chars.get(at + 1), self.chars.get(at + 2)) { + (Some('\\'), _) => self.chars.get(at + 3..)?.iter().position(|&q| q == '\'')? + 4, + (Some(_), Some('\'')) => 3, + _ => 1, + }; + continue; + } + c if is_word(c) => { + let word = self.word_at(at); + at += word.chars().count(); + let hashes = self.chars.get(at..).unwrap_or_default().iter().take_while(|&&h| h == '#').count(); + if matches!(word.as_str(), "r" | "br" | "cr") && self.chars.get(at + hashes) == Some(&'"') { + at = self.quoted_end(at + hashes + 1, true, hashes)?; } - _ => {} + continue; } - at += 1; + _ => {} + } + at += 1; + } + } + + /// The index after the closing quote of a string whose text starts at `at`: a raw string closed + /// by a quote and `hashes` hashes, or a string whose backslashes escape the next character. + fn quoted_end(&self, mut at: usize, raw: bool, hashes: usize) -> Option { + loop { + match *self.chars.get(at)? { + '\\' if !raw => at += 2, + '"' if (1..=hashes).all(|n| self.chars.get(at + n) == Some(&'#')) => return Some(at + 1 + hashes), + _ => at += 1, } - at = self.skip_space(at + 1); } - at == self.at || self.chars.get(at) == Some(&'\'') || BLOCK_KEYWORDS.contains(&self.word_at(at).as_str()) || self.macro_braces(at) } /// Whether the code at `at` is a macro path, `!` and the `{` at the current index. @@ -1125,17 +1305,52 @@ impl Lexer<'_> { self.chars.get(at) == Some(&'!') && self.skip_space(at + 1) == self.at } + /// Whether the code from `at` to `end` holds only an item's qualifiers: `pub` with its optional + /// `(..)`, `async`, `const`, `default`, `extern` with its optional ABI string, `safe` and + /// `unsafe`. + fn item_qualifiers(&self, mut at: usize, end: usize) -> bool { + loop { + at = self.skip_space(at); + if at >= end { + return at == end; + } + let word = self.word_at(at); + match word.as_str() { + "pub" => { + at += 3; + let open = self.skip_space(at); + if open < end && self.chars.get(open) == Some(&'(') { + let Some(close) = self.group_end(open) else { return false }; + at = close; + } + } + "async" | "const" | "default" | "extern" | "safe" | "unsafe" => at += word.chars().count(), + "" if self.chars.get(at) == Some(&'"') => { + let Some(close) = self.quoted_end(at + 1, false, 0) else { return false }; + at = close; + } + _ => return false, + } + } + } + fn word_at(&self, at: usize) -> String { self.chars.get(at..).unwrap_or_default().iter().take_while(|&&c| is_word(c)).collect() } fn open(&mut self, c: char) { - if let Some(TestRegion::Item { level, start, opened: false, item, semi, .. }) = self.test + if let Some(TestRegion::Item { level, start, opened: false, item, pattern: false, angle: 0, .. }) = self.test && level == self.delims.len() && c == '{' { - let block = !item && self.starts_block(start); - self.test = Some(TestRegion::Item { level, start, opened: true, item, semi, block }); + let starts = !item && self.starts_block(start); + // In an item's header, the braces of a macro (`fn f() -> ty! { u8 } { .. }`) are not its body. + if !(item && self.after_bang) + && let Some(TestRegion::Item { opened, block, .. }) = &mut self.test + { + *opened = true; + *block = starts; + } } self.delims.push((c, self.line)); self.at += 1; @@ -1154,14 +1369,23 @@ impl Lexer<'_> { self.at += 1; let depth = self.delims.len(); let ends = match self.test { - Some(TestRegion::Item { level, start, opened, item, semi, block }) => { + Some(TestRegion::Item { level, opened, item, semi, block, .. }) => { let block_end = opened && depth == level && c == '}'; + let branch = block_end && !item && block && self.word_at(self.skip_space(self.at)) == "else"; if block_end && !item && block && self.postfix_follows() { // A method call, field or `?` continues the expression to its `;` or `,`. - self.test = Some(TestRegion::Item { level, start, opened, item, semi, block: false }); + if let Some(TestRegion::Item { block, .. }) = &mut self.test { + *block = false; + } + false + } else if branch { + // The `else` branch's header (`else if let P { .. } = p`) is read like the first. + if let Some(TestRegion::Item { opened, .. }) = &mut self.test { + *opened = false; + } false } else { - depth < level || (block_end && if item { !semi } else { block && self.word_at(self.skip_space(self.at)) != "else" }) + depth < level || (block_end && if item { !semi } else { block }) } } Some(TestRegion::Inner { level }) => depth < level, @@ -1754,6 +1978,9 @@ fn after() { let _ = "seven"; } std::os::unix::fs::symlink(root.join("gone"), root.join("src/tests.rs")).unwrap(); let found = scan(root, &[Input::rust(Path::new("src"))], &POLICY).unwrap(); assert_eq!(hits(&found), [("src/file_link.rs".to_string(), 1, "AzureKit"), ("src/lib.rs".to_string(), 1, "BlueCore")]); + let explicit = [Input::rust(Path::new("src/linked")), Input::rust(Path::new("src/file_link.rs"))]; + let found = scan(root, &explicit, &POLICY).unwrap(); + assert_eq!(hits(&found), [("src/file_link.rs".to_string(), 1, "AzureKit")]); } #[test] @@ -1779,6 +2006,157 @@ fn after() { let _ = "seven"; } assert!(matches!(&err, Error::Conflict { path } if path.ends_with("a.rs")), "{err}"); } + #[test] + fn overlapping_candidates_are_each_checked() { + for case in [MatchCase::Exact, MatchCase::AsciiInsensitive] { + let policy = Policy { case, ..Policy::new(&["A-A"]) }; + assert_eq!(policy.words_in("XA-A-A"), ["A-A"]); + assert!(policy.words_in("XA-A-AX").is_empty()); + } + } + + #[test] + fn a_shebang_line_is_not_read_as_code() { + let source = "#!/opt/tool(v1/bin/rust-script\nconst S: &str = \"AzureKit\";\n"; + let found = scan_source(Path::new("main.rs"), source, Kind::Rust, &POLICY).unwrap(); + assert_eq!(found.iter().map(|f| (f.line, f.word.as_str())).collect::>(), [(2, "AzureKit")]); + assert_eq!(literals("#!/usr/bin/env run-cargo-script\n\"live\""), ["live"]); + assert_eq!(literals("#![cfg(test)]\nfn a() { \"AzureKit\"; }\n"), Vec::::new()); + assert_eq!(literals("#! /* note */ [cfg(test)]\nfn a() { \"AzureKit\"; }\n"), Vec::::new()); + assert_eq!(literals("\"one\" #!x"), ["one"]); + } + + #[test] + fn test_only_item_headers_do_not_end_items_early() { + let source = r#"#[cfg(test)] fn generic() {} +fn one() { let _ = "one"; } +#[cfg(test)] impl Probe {} +fn two() { let _ = "two"; } +#[cfg(test)] fn fixture() -> Tag<{ 1 }> { let _ = "AzureKit"; Tag } +fn three() { let _ = "three"; } +#[cfg(test)] fn nested() -> Tag> where Tag<{ 3 }>: Clone { let _ = "AzureKit"; Tag } +#[cfg(test)] const fn k() -> u8 { 1 } +fn four() { let _ = "four"; } +#[cfg(test)] const unsafe fn u() -> u8 { 1 } +fn five() { let _ = "five"; } +#[cfg(test)] const C: fn() -> u8 = k; +fn six() { let _ = "six"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six"]); + } + + #[test] + fn item_keywords_inside_test_only_expressions_do_not_start_items() { + let source = r#"fn arms(x: u8) { + match x { + #[cfg(test)] + 0 => helper::("AzureKit"), + _ => helper::("one"), + } + call(#[cfg(test)] cast::("AzureKit"), "two"); +} +struct S { + #[cfg(test)] + hook: fn() -> u8, + name: Tag<"three">, +} +#[cfg(test)] pub(crate) unsafe extern "C" fn ffi() { let _ = "AzureKit"; } +fn four() { let _ = "four"; } +#[cfg(test)] fn typed() -> ty! { u8 } { let _ = "AzureKit"; 0 } +fn five() { let _ = "five"; } +#[cfg(test)] fn noted() -> ty! /* a { */ { u8 } { let _ = "AzureKit"; 0 } +fn six() { let _ = "six"; } +#[cfg(test)] fn halt() -> ! { let _ = "AzureKit"; loop {} } +fn seven() { let _ = "seven"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six", "seven"]); + } + + #[test] + fn test_only_let_conditions_end_at_their_body() { + let source = r#"fn statements(p: P, o: Option) { + #[cfg(test)] if let P { x: 0 } = p { let _ = "AzureKit"; } + let _ = "one"; + #[cfg(test)] if let Some(x) = o { "AzureKit"; } + let _ = "two"; + #[cfg(test)] while let P { x: 1 } = p { "AzureKit"; } + let _ = "three"; + #[cfg(test)] for P { x } in [p] { "AzureKit"; } + let _ = "four"; + #[cfg(test)] if true && let P { x: 0..=2 } = p { "AzureKit"; } else { "AzureKit"; } + let _ = "five"; + #[cfg(test)] if o == Some(1) { "AzureKit"; } + let _ = "six"; + #[cfg(test)] if o.is_none() { "AzureKit"; } else if let P { x: 0 } = p { "AzureKit"; } else { "AzureKit"; } + let _ = "seven"; +} +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six", "seven"]); + } + + #[test] + fn attribute_strings_and_comments_are_read_as_tokens() { + let source = r#"fn statements() { + #[cfg(test)] #[allow(unused, reason = "]")] { "AzureKit"; } + let _ = "one"; + #[cfg(test)] #[doc = r"]"] #[allow(unused, /* ] */)] { "AzureKit"; } + let _ = "two"; +} +"#; + assert_eq!(literals(source), ["one", "two"]); + let policy = Policy { allow_marker: Some("name-ok"), ..POLICY }; + let rust = |src: &str| scan_source(Path::new("lib.rs"), src, Kind::Rust, &policy).unwrap().len(); + assert_eq!(rust("const LIVE: &str = \"AzureKit\"; #[cfg(/* name-ok */ test)] const TEST: &str = \"\";"), 0); + assert_eq!(rust("const LIVE: &str = \"AzureKit\"; #[cfg( // name-ok\n test)] const TEST: &str = \"\";"), 0); + assert_eq!(rust("const LIVE: &str = \"AzureKit\"; #[cfg(test)] const TEST: &str = \"\"; // other"), 1); + } + + #[test] + fn escaped_bytes_are_decoded_as_utf8() { + let both = Literals { byte_strings: true, c_strings: true }; + let texts = |source: &str| super::literals(source, both).unwrap().into_iter().map(|lit| lit.text).collect::>(); + let source = r#"c"Caf\xC3\xA9" b"Caf\xc3\xa9" c"Caf\u{e9}" b"Caf\xC3" b"\xFFok""#; + assert_eq!(texts(source), ["Café", "Café", "Café", "Caf\u{FFFD}", "\u{FFFD}ok"]); + } + + #[test] + fn aliases_of_one_file_are_read_once() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "src/a.rs", "\"AzureKit\""); + let absolute = root.join("src/a.rs"); + let fits = Policy { limits: Limits { max_total_bytes: 10, ..DEFAULT_LIMITS }, ..POLICY }; + let same = [Input::rust(Path::new("src/a.rs")), Input::rust(&absolute), Input::rust(Path::new("./src/a.rs"))]; + let found = scan(root, &same, &fits).unwrap(); + assert_eq!(found.len(), 1, "{found:#?}"); + let mixed = [Input::text(Path::new("src/a.rs")), Input::rust(&absolute)]; + let err = scan(root, &mixed, &POLICY).unwrap_err(); + assert!(matches!(&err, Error::Conflict { path } if path.ends_with("a.rs")), "{err}"); + } + + #[test] + fn aliases_under_a_relative_base_are_read_once() { + let absolute = std::env::current_dir().unwrap().join("Cargo.toml"); + let size = std::fs::metadata(&absolute).unwrap().len(); + let fits = Policy { limits: Limits { max_total_bytes: size, ..DEFAULT_LIMITS }, ..POLICY }; + let same = [Input::manifest(Path::new("Cargo.toml")), Input::manifest(&absolute)]; + scan(Path::new("."), &same, &fits).unwrap(); + } + + #[test] + fn the_total_budget_is_checked_before_reading() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "a.rs", "\"one\""); + write(root, "b.rs", "\"two\""); + let inputs = [Input::rust(Path::new("a.rs")), Input::rust(Path::new("b.rs"))]; + let exact = Policy { limits: Limits { max_total_bytes: 10, ..DEFAULT_LIMITS }, ..POLICY }; + assert!(scan(root, &inputs, &exact).unwrap().is_empty()); + let short = Policy { limits: Limits { max_total_bytes: 9, ..DEFAULT_LIMITS }, ..POLICY }; + let err = scan(root, &inputs, &short).unwrap_err(); + assert!(matches!(&err, Error::TotalTooLarge { path, limit: 9 } if path.ends_with("b.rs")), "{err}"); + } + #[test] fn policies_that_match_nothing_are_errors() { let empty: &[&str] = &[]; From 59500168a8971cad8fbad0b7e699e421bbe5ee85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 05:19:42 -0800 Subject: [PATCH 30/47] craft-xtask: fix more of the name scanner's review findings - The base folder is made absolute once, before any input is listed, so listing and reading use the same folder. On Windows, a drive-relative base such as `C:src` is joined to the current folder of its drive, so its keys match the absolute paths of the same files. - A doc comment between `#!` and `[` on the first line makes the line a shebang, as in rustc; other comments still leave an inner attribute. - Under `#[cfg(test)]`, a `,` in an expression's generic arguments (`pair::(..)`) or in the parameters of a closure that starts the expression no longer ends the test-only arm or argument. - Braces in the condition of a test-only `if`, `while`, `match` or `for` (`if ready! { } { .. }`, `if { ready } { .. }`) are not read as its body. - A raw identifier (`r#try! { }`) is read as one word, so its macro braces end the test-only statement. --- crates/xtask/README.md | 13 +- crates/xtask/src/names.rs | 314 +++++++++++++++++++++++++++++++------- 2 files changed, 264 insertions(+), 63 deletions(-) diff --git a/crates/xtask/README.md b/crates/xtask/README.md index c6a74f1488..95394832a7 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -106,13 +106,17 @@ fn production_display_names_stay_neutral() { character, byte and lifetime tokens, and the rest of a module after `#![cfg(test)]` are skipped. So is the code under `#[cfg(test)]`, comments in the attribute included: a `const`, `static` or `let` up to its `;`, another item up to the `}` that closes it or the `;` that ends it, and a - field, argument, arm or statement up to its `,` or `;`. An item keyword counts only when nothing + field, argument, arm or statement up to its `,` or `;`. A `,` in an expression's generic + arguments (`f::`) or in the parameters of a closure that starts the expression does not + end it. An item keyword counts only when nothing but qualifiers (`pub`, `unsafe`, `extern "C"` and the like) comes before it, so the `fn` in `f::(…)` or in a field's type does not start an item, and the braces of a macro in an item's header (`-> ty! { u8 }`) are not its body. A block expression (a block, a macro's braces, a labeled block, or `if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as an arm's expression after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` - branches. When a method call, field or `?` follows that `}`, it runs up to its `,` or `;` + branches. Braces in the condition of an `if`, `while`, `match` or `for` (a macro's, or a block + operand such as `if { ready } { … }`) are not its block. When a method call, field or `?` follows + that `}`, it runs up to its `,` or `;` instead. Other `cfg` expressions and macros are not evaluated. A source the lexer cannot read (an unterminated literal or comment, an unknown escape, unbalanced delimiters) is an error. - A word matches as a whole word: the characters next to it are not letters, digits or `_`, in any @@ -122,8 +126,9 @@ fn production_display_names_stay_neutral() { - In Rust, the marker counts only inside a comment on a line the literal spans. In a manifest it counts anywhere on a line the description spans, and in a text file anywhere on the line. - `scan` identifies a file by its input path joined to the base folder, and joins a relative base - folder to the current folder first, so a relative and an absolute input for one file are read - once; `..` and links are not resolved. + folder to the current folder before it lists any input (on Windows, a drive-relative base such as + `C:src` to the current folder of its drive), so a relative and an absolute input for one file are + read once; `..` and links are not resolved. - `scan` reads each file once, in path order, and returns the findings in path order, then source order, then the order of `banned`. A `Finding` has the path, the first line of the literal or description, the word, the decoded text or text line and the kind; its `Display` text is diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 0cbb1a0b20..2969b83a3a 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -16,7 +16,7 @@ use std::collections::HashSet; use std::fmt; use std::fs::{self, File}; use std::io::{self, Read}; -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; /// The limits [`Policy::new`] sets: 8 MiB per file, 512 MiB in all, folders 64 deep. pub const DEFAULT_LIMITS: Limits = Limits { max_file_bytes: 8 << 20, max_total_bytes: 512 << 20, max_depth: 64 }; @@ -293,8 +293,9 @@ impl From for String { /// findings come in path order, then in source order, then in the order of [`Policy::banned`]. /// /// A file is identified by its path joined to `base`, and a relative `base` is joined to the -/// current folder first, so a relative and an absolute path to it are one file, read once and -/// reported by the input path that sorts first; `..` and links are not resolved. +/// current folder (on Windows, a drive-relative `base` such as `C:src` to the current folder of +/// its drive) before any input is listed, so a relative and an absolute path to it are one file, +/// read once and reported by the input path that sorts first; `..` and links are not resolved. /// /// A [`Kind::Rust`] folder is read recursively for `.rs` files that [`Policy::skip`] keeps; links to /// folders are not followed, also when the link is an input. A file input is read whatever its @@ -302,21 +303,17 @@ impl From for String { /// is over a limit, and a Rust source the lexer cannot read. Inputs must not include binary files. pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result, Error> { policy.validate()?; + // The base is made absolute once, so that every input is listed and read under one folder. + let root = absolute_base(base)?; let mut files = Vec::new(); for input in inputs { if input.kind == Kind::Rust { - collect_rust(base, input.path, policy, &mut files)?; + collect_rust(&root, input.path, policy, &mut files)?; } else { files.push((input.path.to_path_buf(), input.kind)); } } // A file is known by the path that is opened, so a relative and an absolute input for it are one. - // A relative base is joined to the current folder first, so the keys of both inputs are absolute. - let root = if base.is_absolute() { - base.to_path_buf() - } else { - std::env::current_dir().map_err(|source| Error::Io { path: base.to_path_buf(), source })?.join(base) - }; let mut files: Vec<(PathBuf, Kind, PathBuf)> = files.into_iter().map(|(path, kind)| (root.join(&path), kind, path)).collect(); files.sort(); files.dedup_by(|later, first| later.0 == first.0 && later.1 == first.1); @@ -333,6 +330,20 @@ pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result Result { + if base.is_absolute() { + return Ok(base.to_path_buf()); + } + let error = |source: io::Error| Error::Io { path: base.to_path_buf(), source }; + let mut parts = base.components(); + match parts.next() { + Some(Component::Prefix(drive)) => Ok(std::path::absolute(drive.as_os_str()).map_err(error)?.join(parts.as_path())), + _ => Ok(std::env::current_dir().map_err(error)?.join(base)), + } +} + /// The findings in one source that is already in memory. `path` is only reported. A /// [`Kind::Rust`] source is a single file here. pub fn scan_source(path: &Path, source: &str, kind: Kind, policy: &Policy<'_>) -> Result, Error> { @@ -574,9 +585,12 @@ pub struct Literal { /// Test-only code is the code under `#[cfg(test)]` and the rest of a module that starts with /// `#![cfg(test)]`. Under `#[cfg(test)]`, a `const`, `static` or `let` runs up to its `;`, another /// item up to its closing `}` or its `;`, and a field, argument, arm or statement up to its `,` or -/// `;`. A block expression (a block, a macro's braces, a labeled block, or `if`, `match`, `loop`, -/// `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as an arm's expression -/// after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` branches. When a method +/// `;`; a `,` in an expression's generic arguments (`f::`) or in the parameters of a closure +/// that starts the expression does not end it. A block expression (a block, a macro's braces, a +/// labeled block, or `if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the +/// whole statement or as an arm's expression after `=>`, ends at its `}`, or at the last `}` of an +/// `if` with `else` branches; braces in the condition of an `if`, `while`, `match` or `for` (a +/// macro's, or a block operand such as `if { ready } { .. }`) are not its block. When a method /// call, field or `?` follows that `}`, it runs up to its `,` or `;` instead. Character, byte and /// lifetime tokens are read, so a quote in them does not start a string. A shebang first line is /// skipped. @@ -726,9 +740,11 @@ enum TestRegion { /// expression (a block, a macro's braces, or `if`, `match`, `loop` and the like), which ends at /// its `}` unless an `else` follows. A `.` or `?` after that `}` clears `block`, so the expression /// ends at its `;` or `,`. A `{` does not count as the first while `pattern` is set (between the - /// `let` of an `if` or `while` condition and its `=`, or a `for` and its `in`) or while `angle` - /// generic brackets of an item's header are open. - Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool, pattern: bool, angle: usize }, + /// `let` of an `if` or `while` condition and its `=`, or a `for` and its `in`), while `angle` + /// generic brackets are open (of an item's header, or after a `::` in an expression), or while + /// `params` is set (between the `|`s of a closure that starts the expression). A `,` does not + /// end it while `angle` or `params` is set either. + Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool, pattern: bool, angle: usize, params: bool }, /// The rest of the module that `#![cfg(test)]` starts, at this delimiter depth. Inner { level: usize }, } @@ -736,7 +752,7 @@ enum TestRegion { impl TestRegion { /// Test-only code at `level` whose code starts at `start`. fn item(level: usize, start: usize) -> Self { - TestRegion::Item { level, start, opened: false, item: false, semi: false, block: false, pattern: false, angle: 0 } + TestRegion::Item { level, start, opened: false, item: false, semi: false, block: false, pattern: false, angle: 0, params: false } } } @@ -758,6 +774,12 @@ struct Lexer<'s> { /// Whether the last token read, past whitespace and comments, is a macro's `!`: a `!` after a /// word, not the `!` of a never type (`-> !`). after_bang: bool, + /// The first character of the last token read, past whitespace and comments. + prev: Option, + /// The first character of the token before that one. + prev_prev: Option, + /// The index where the last word or number read starts. + last_word: usize, out: Lexed, } @@ -772,6 +794,9 @@ fn lex(source: &str, kinds: Literals, marker: Option<&str>) -> Result { } fn run(&mut self) -> Result<(), SyntaxError> { - // A first line that starts with `#!` is a shebang, unless a `[` follows (an inner attribute). + // A first line that starts with `#!` is a shebang, unless a `[` follows past whitespace and + // comments that are not doc comments (an inner attribute). let start = usize::from(self.peek(0) == Some('\u{feff}')); - if self.chars.get(start..start + 2) == Some(&['#', '!'][..]) && self.chars.get(self.skip_space(start + 2)) != Some(&'[') { + if self.chars.get(start..start + 2) == Some(&['#', '!'][..]) && self.chars.get(self.skip_plain_space(start + 2)) != Some(&'[') { while self.peek(0).is_some_and(|c| c != '\n') { self.at += 1; } } while let Some(c) = self.peek(0) { + let begin = self.at; let token = !c.is_whitespace() && !(c == '/' && matches!(self.peek(1), Some('/' | '*'))); match c { '\n' => { @@ -823,6 +850,7 @@ impl Lexer<'_> { '=' if self.peek(1) == Some('>') => self.arrow(), '=' => self.equals(), '<' | '>' => self.angle(c), + '|' => self.pipe(), c if c.is_ascii_digit() => self.number(), c if is_word(c) => self.word()?, _ => self.at += 1, @@ -830,6 +858,11 @@ impl Lexer<'_> { if token { self.after_bang = c == '!' && self.after_word; self.after_word = is_word(c); + self.prev_prev = self.prev; + self.prev = Some(c); + if is_word(c) { + self.last_word = begin; + } } } match self.delims.last() { @@ -1080,19 +1113,40 @@ impl Lexer<'_> { self.at += 1; } - /// A `<` or `>` (not the `>` of `->`) in an item's header before its body opens or closes a - /// generic bracket. + /// A `<` or `>` (not the `>` of `->`) opens or closes a generic bracket in an item's header + /// before its body, and in an expression from a `::<` until its brackets close + /// (`pair::`), so that a comparison does not. fn angle(&mut self, c: char) { let arrow = c == '>' && self.at.checked_sub(1).and_then(|i| self.chars.get(i)) == Some(&'-'); - if let Some(TestRegion::Item { level, opened: false, item: true, angle, .. }) = &mut self.test + let turbofish = c == '<' && self.prev == Some(':') && self.prev_prev == Some(':'); + if let Some(TestRegion::Item { level, opened, item, angle, .. }) = &mut self.test && *level == self.delims.len() && !arrow + && if *item { !*opened } else { turbofish || *angle > 0 } { *angle = if c == '<' { *angle + 1 } else { angle.saturating_sub(1) }; } self.at += 1; } + /// A `|` at the start of a test-only expression, after any `async` and `move`, opens the + /// parameters of a closure (`|a, b| ..`), and the next `|` at its level closes them. + fn pipe(&mut self) { + if let Some(TestRegion::Item { level, start, item: false, params, .. }) = self.test + && level == self.delims.len() + { + let mut code = self.code_start(start); + while matches!(self.word_at(code).as_str(), "async" | "move") { + code = self.skip_space(code + self.word_at(code).chars().count()); + } + let opens = !params && code == self.at; + if let Some(TestRegion::Item { params, .. }) = &mut self.test { + *params = opens; + } + } + self.at += 1; + } + /// A raw literal after its `r`, or a raw identifier (`r#name`), which is left to the caller. fn raw(&mut self, form: Form) -> Result<(), SyntaxError> { let hashes = self.chars.get(self.at..).unwrap_or_default().iter().take_while(|&&c| c == '#').count(); @@ -1121,38 +1175,74 @@ impl Lexer<'_> { /// The index after the whitespace and comments at `at`. fn skip_space(&self, mut at: usize) -> usize { loop { - match (self.chars.get(at), self.chars.get(at + 1)) { - (Some(c), _) if c.is_whitespace() => at += 1, - (Some('/'), Some('/')) => { - while self.chars.get(at).is_some_and(|&c| c != '\n') { - at += 1; - } - } - (Some('/'), Some('*')) => { - let mut depth = 0_usize; - loop { - match (self.chars.get(at), self.chars.get(at + 1)) { - (None, _) => return at, - (Some('/'), Some('*')) => { - depth += 1; - at += 2; - } - (Some('*'), Some('/')) => { - depth -= 1; - at += 2; - if depth == 0 { - break; - } - } - _ => at += 1, - } - } - } - _ => return at, + if self.chars.get(at).is_some_and(|c| c.is_whitespace()) { + at += 1; + } else if let Some(end) = self.comment_end(at) { + at = end; + } else { + return at; } } } + /// The index after the whitespace and the comments that are not doc comments at `at`. + fn skip_plain_space(&self, mut at: usize) -> usize { + loop { + if self.chars.get(at).is_some_and(|c| c.is_whitespace()) { + at += 1; + } else if let Some(end) = self.comment_end(at).filter(|_| !self.doc_comment(at)) { + at = end; + } else { + return at; + } + } + } + + /// The index after the comment that starts at `at`, or `None` when none starts there. + fn comment_end(&self, mut at: usize) -> Option { + match (self.chars.get(at), self.chars.get(at + 1)) { + (Some('/'), Some('/')) => { + while self.chars.get(at).is_some_and(|&c| c != '\n') { + at += 1; + } + } + (Some('/'), Some('*')) => { + let mut depth = 0_usize; + loop { + match (self.chars.get(at), self.chars.get(at + 1)) { + (None, _) => break, + (Some('/'), Some('*')) => { + depth += 1; + at += 2; + } + (Some('*'), Some('/')) => { + depth -= 1; + at += 2; + if depth == 0 { + break; + } + } + _ => at += 1, + } + } + } + _ => return None, + } + Some(at) + } + + /// Whether the comment at `at` is a doc comment: `//!`, `/*!`, `///` but not `////`, or `/**` + /// but not `/***` or `/**/`. + fn doc_comment(&self, at: usize) -> bool { + let c = |n: usize| self.chars.get(at + n).copied(); + match (c(0), c(1), c(2)) { + (Some('/'), Some('/' | '*'), Some('!')) => true, + (Some('/'), Some('/'), Some('/')) => c(3) != Some('/'), + (Some('/'), Some('*'), Some('*')) => !matches!(c(3), Some('*' | '/')), + _ => false, + } + } + /// The end of a `#[cfg(test)]` or `#![cfg(test)]` attribute at the current `#`, and whether it /// is the inner form. fn cfg_test_end(&self) -> Option<(usize, bool)> { @@ -1334,20 +1424,24 @@ impl Lexer<'_> { } } + /// The word at `at`, with the `r#` of a raw identifier (`r#try`), which is never a keyword. fn word_at(&self, at: usize) -> String { - self.chars.get(at..).unwrap_or_default().iter().take_while(|&&c| is_word(c)).collect() + let raw = self.chars.get(at..at + 2) == Some(&['r', '#'][..]) && self.chars.get(at + 2).is_some_and(|&c| is_word(c) && !c.is_ascii_digit()); + let from = if raw { at + 2 } else { at }; + let word: String = self.chars.get(from..).unwrap_or_default().iter().take_while(|&&c| is_word(c)).collect(); + if raw { format!("r#{word}") } else { word } } fn open(&mut self, c: char) { - if let Some(TestRegion::Item { level, start, opened: false, item, pattern: false, angle: 0, .. }) = self.test + if let Some(TestRegion::Item { level, start, opened: false, item, pattern: false, angle: 0, params: false, .. }) = self.test && level == self.delims.len() && c == '{' { let starts = !item && self.starts_block(start); - // In an item's header, the braces of a macro (`fn f() -> ty! { u8 } { .. }`) are not its body. - if !(item && self.after_bang) - && let Some(TestRegion::Item { opened, block, .. }) = &mut self.test - { + // In an item's header, the braces of a macro (`fn f() -> ty! { u8 } { .. }`) are not its + // body, and neither are braces in the condition of an `if` and the like. + let header = if item { self.after_bang } else { self.in_condition(start) }; + if !header && let Some(TestRegion::Item { opened, block, .. }) = &mut self.test { *opened = true; *block = starts; } @@ -1356,6 +1450,26 @@ impl Lexer<'_> { self.at += 1; } + /// Whether the `{` at the current index is in the condition of the test-only `if`, `while`, + /// `match` or `for` whose code starts at `start`, not its body: the braces of a macro + /// (`if ready! { } { .. }`), or a block where an operand starts, after the keyword, an `in`, an + /// operator or a block keyword (`if { ready } { .. }`, `while !{ done } { .. }`, + /// `if const { true } { .. }`). + fn in_condition(&self, start: usize) -> bool { + if !matches!(self.word_at(self.code_start(start)).as_str(), "if" | "while" | "match" | "for") { + return false; + } + if self.after_bang { + return true; + } + if self.after_word { + let raw = self.last_word.checked_sub(1).and_then(|i| self.chars.get(i)) == Some(&'#'); + let word = self.word_at(self.last_word); + return !raw && matches!(word.as_str(), "if" | "while" | "match" | "in" | "const" | "unsafe" | "loop" | "async" | "move"); + } + matches!(self.prev, Some('!' | '&' | '|' | '=' | '<' | '+' | '-' | '*' | '/' | '%' | '^')) + } + fn close(&mut self, c: char) -> Result<(), SyntaxError> { let expected = match self.delims.pop() { Some(('{', _)) => '}', @@ -1409,11 +1523,12 @@ impl Lexer<'_> { /// A `;` ends a test-only statement, or an item that has no body or ends at its `;`, and a `,` /// inside a delimiter ends a test-only field, argument or arm. A `,` in an item's header - /// (`impl`, a `where` clause) does not. + /// (`impl`, a `where` clause) does not, and neither does one in an expression's generic + /// arguments (`f::`) or in the parameters of a closure that starts it. fn item_end(&mut self, comma: bool) { - if let Some(TestRegion::Item { level, opened, item, semi, .. }) = self.test + if let Some(TestRegion::Item { level, opened, item, semi, angle, params, .. }) = self.test && level == self.delims.len() - && if comma { level > 0 && !item } else { !item || !opened || semi } + && if comma { level > 0 && !item && angle == 0 && !params } else { !item || !opened || semi } { self.test = None; } @@ -2026,6 +2141,75 @@ fn after() { let _ = "seven"; } assert_eq!(literals("\"one\" #!x"), ["one"]); } + #[test] + fn a_doc_comment_after_a_shebang_does_not_make_it_an_attribute() { + assert_eq!(literals("#! /*! doc */ [allow(unused)] \"AzureKit\"\n\"live\""), ["live"]); + assert_eq!(literals("#! /** doc */ [allow(unused)] \"AzureKit\"\n\"live\""), ["live"]); + assert_eq!(literals("#! /**/ /*** note */ [cfg(test)]\nfn a() { \"AzureKit\"; }\n"), Vec::::new()); + } + + #[test] + fn test_only_generic_arguments_and_closure_parameters_keep_their_commas() { + let source = r#"fn arms(x: u8) { + match x { + #[cfg(test)] + 0 => pair::("AzureKit"), + #[cfg(test)] + 1 => pair::, u16>("AzureKit"), + #[cfg(test)] + 2 => |_: u8, _: u8| "AzureKit", + #[cfg(test)] + 3 => move |P { a, b }: P, _: u8| "AzureKit", + #[cfg(test)] + 4 => pair:: /* spaced */ ("AzureKit"), + _ => pair::("one"), + } + call(#[cfg(test)] pair::("AzureKit"), "two"); + call(#[cfg(test)] |a, b| a | b, "three"); + call(#[cfg(test)] a < b, "four"); +} +"#; + assert_eq!(literals(source), ["one", "two", "three", "four"]); + } + + #[test] + fn braces_in_a_test_only_condition_are_not_its_body() { + let source = r#"fn statements(ready: bool) { + #[cfg(test)] if ready! { } { let _ = "AzureKit"; } + let _ = "one"; + #[cfg(test)] if { ready } { "AzureKit"; } + let _ = "two"; + #[cfg(test)] while !{ ready } { "AzureKit"; } + let _ = "three"; + #[cfg(test)] if ready { "AzureKit"; } else if { ready } { "AzureKit"; } else { "AzureKit"; } + let _ = "four"; + #[cfg(test)] match { 1 } { _ => "AzureKit" } + let _ = "five"; + #[cfg(test)] if ready() { "AzureKit"; } + let _ = "six"; + #[cfg(test)] for x in { [1] } { "AzureKit"; } + let _ = "seven"; + #[cfg(test)] if const { true } { "AzureKit"; } + let _ = "eight"; + #[cfg(test)] while unsafe { ready } { "AzureKit"; } + let _ = "nine"; +} +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]); + } + + #[test] + fn a_raw_identifier_macro_is_read_as_one_word() { + let source = r#"fn statements() { + #[cfg(test)] r#try! {} + let _ = "one"; + #[cfg(test)] r#try! { "AzureKit" } + let _ = "two"; +} +"#; + assert_eq!(literals(source), ["one", "two"]); + } + #[test] fn test_only_item_headers_do_not_end_items_early() { let source = r#"#[cfg(test)] fn generic() {} @@ -2143,6 +2327,18 @@ fn seven() { let _ = "seven"; } scan(Path::new("."), &same, &fits).unwrap(); } + #[cfg(windows)] + #[test] + fn aliases_under_a_drive_relative_base_are_read_once() { + let current = std::env::current_dir().unwrap(); + let Some(Component::Prefix(drive)) = current.components().next() else { panic!("no drive in {}", current.display()) }; + let absolute = current.join("Cargo.toml"); + let size = std::fs::metadata(&absolute).unwrap().len(); + let fits = Policy { limits: Limits { max_total_bytes: size, ..DEFAULT_LIMITS }, ..POLICY }; + let same = [Input::manifest(Path::new("Cargo.toml")), Input::manifest(&absolute)]; + scan(Path::new(drive.as_os_str()), &same, &fits).unwrap(); + } + #[test] fn the_total_budget_is_checked_before_reading() { let dir = tempfile::tempdir().unwrap(); From 73b9c0b9238061ade65a0a4e248f1b413a2069b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:28:59 -0800 Subject: [PATCH 31/47] audio-dsp: bitcrusher gives a live voice a lo-fi sound with no latency bitcrusher is a new Special effect. It takes one input sample every Rate Divide samples (1 to 50), holds it until the next one, and rounds it to the nearest multiple of 2^(1 - Bits) (1 to 16 bits), so silence stays silence. A fractional Rate Divide alternates the two nearest whole hold lengths, and fractional Bits give steps between the whole-bit ones. Bits and Rate Divide take effect from the next sample, and a shorter hold cuts the one in progress short. Mix moves to a new value over 20 ms. The tail covers one hold. A channel a block leaves out is fed silence, non-finite samples are taken as silence, and the rounding and mix run in f64, so samples at the f32 limit stay finite. Nothing allocates while processing. The effect joins the channel-cap test and the no-allocation tests. --- crates/audio-dsp/README.md | 3 +- crates/audio-dsp/src/effects.rs | 3 +- .../audio-dsp/src/effects/behavior_tests.rs | 1 + crates/audio-dsp/src/effects/character.rs | 227 ++++++++++++++++++ crates/audio-dsp/tests/it/no_alloc.rs | 44 ++++ 5 files changed, 276 insertions(+), 2 deletions(-) diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index aeff6e58e6..b08b39cfac 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -19,7 +19,8 @@ and contains no `unsafe` code. them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency, and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic voices (ring, frequency modulation, and positive or negative comb resonators, with the - frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency. + frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and + neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index a2b3edacde..255857b783 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -22,7 +22,7 @@ pub(crate) mod util; pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; -pub use character::RingMod; +pub use character::{Bitcrusher, RingMod}; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -158,6 +158,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover), entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer), entry!("distortion", "Distortion", Special, Distortion), + entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher), entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite), entry!("mastering", "Mastering", Special, Mastering), entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index ac10bae923..5e628f28ea 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -991,6 +991,7 @@ fn direct_constructors_cap_the_channel_count() { voice::VoiceFormant, suppress::NoiseSuppression, character::RingMod, + character::Bitcrusher, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index c61293ba6e..ec9b82d258 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -14,6 +14,9 @@ //! An LFO, an envelope follower (5 ms attack, 100 ms release) or a sample-and-hold source moves the //! frequency by up to two octaves either way at 100 % depth. The envelope follower moves it up //! only. +//! +//! The bitcrusher (`bitcrusher`) takes one input sample every `rate_divide` samples, holds it until +//! the next one, and rounds it to a word length of 1 to 16 bits. use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail}; use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; @@ -214,6 +217,97 @@ impl AudioEffect for RingMod { } } +/// Bit-depth and sample-rate reduction. The input is sampled once every `rate_divide` samples and +/// held in between; a fractional value alternates between the two nearest whole hold lengths, so +/// the holds average it. Each held sample is rounded to the nearest multiple of the step +/// `2^(1 - bits)`, so silence stays silence and the range -1 ..= 1 takes `2^bits + 1` levels; +/// fractional bits give steps between the whole-bit ones. Bits and Rate Divide take effect from +/// the next sample, and a shorter hold cuts the one in progress short. Mix moves to a new value +/// over 20 ms. +pub struct Bitcrusher { + pv: ParamValues, + held: Vec, + /// Samples since the last capture, counted so that a capture happens when it reaches the hold + /// length. Infinite after a reset, so the next sample is captured. + since: f64, + mix: Smoothed, +} + +impl Bitcrusher { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::new("bits", "Bits", 1.0, 16.0, 8.0, Unit::None), + ParamSpec::new("rate_divide", "Rate Divide", 1.0, 50.0, 4.0, Unit::None), + ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + let mut s = Bitcrusher { + pv: ParamValues::new(Self::PARAMS), + held: vec![0.0; ch], + since: f64::INFINITY, + mix: Smoothed::with_ms(1.0, sample_rate, SM), + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, snap: bool) { + self.mix.set(self.pv.v("mix") / 100.0); + if snap { + self.mix.snap(); + } + } +} + +impl AudioEffect for Bitcrusher { + param_plumbing!("bitcrusher"); + /// A held sample lasts at most the hold length rounded up, so it sounds for up to that many + /// samples less one after the input ends. + fn tail_samples(&self) -> usize { + (self.pv.v("rate_divide").ceil() as usize).saturating_sub(1) + } + fn reset(&mut self) { + self.held.fill(0.0); + self.since = f64::INFINITY; + self.mix.snap(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + let nch = channels.len().min(self.held.len()); + let hold = f64::from(self.pv.v("rate_divide")); + // The rounding and the mix run in f64, so a finite input near the f32 limit stays finite. + let step = (1.0 - f64::from(self.pv.v("bits"))).exp2(); + let limit = f64::from(f32::MAX); + for i in 0..n { + let capture = self.since >= hold; + if capture { + // On schedule, less than one sample is left over. More is left after a reset or + // after the hold got shorter; the new holds then count from this capture. + let left = self.since - hold; + self.since = if left < 1.0 { left } else { 0.0 }; + } + self.since += 1.0; + let mix = f64::from(self.mix.tick()); + for (ch, held) in self.held.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out is fed + // silence, so it holds none of its earlier audio when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => f64::from(c[i]), + _ => 0.0, + }; + if capture { + *held = ((dry / step).round() * step).clamp(-limit, limit) as f32; + } + if ch < nch { + channels[ch][i] = (dry + mix * (f64::from(*held) - dry)) as f32; + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -387,4 +481,137 @@ mod tests { assert!(x.iter().all(|v| v.is_finite()), "effect {effect}"); } } + + fn crush(params: &[(&str, f32)], channels: usize) -> Bitcrusher { + let mut c = Bitcrusher::new(SR, channels); + for (id, v) in params { + assert!(c.set_param(id, *v), "{id}"); + } + c.reset(); + c + } + + /// Indices of the samples where the output changes, with the first sample counted. + fn changes(x: &[f32]) -> Vec { + (0..x.len()).filter(|&i| i == 0 || x[i] != x[i - 1]).collect() + } + + /// Every output sample is the multiple of `2^(1 - bits)` nearest the input, and silence stays + /// silence. + #[test] + fn bitcrusher_rounds_to_the_word_length() { + for (bits, step) in [(1.0, 1.0f32), (3.0, 0.25), (5.5, 2f32.powf(-4.5))] { + let mut c = crush(&[("bits", bits), ("rate_divide", 1.0)], 1); + let x: Vec = (0..2000).map(|i| -1.0 + i as f32 / 1000.0).collect(); + let mut y = x.clone(); + c.process(&mut [&mut y]); + for (a, b) in x.iter().zip(&y) { + let k = b / step; + assert!((k - k.round()).abs() < 1e-3, "bits {bits}: {b} is not a multiple of {step}"); + assert!((a - b).abs() <= step / 2.0 + 1e-6, "bits {bits}: {a} became {b}"); + } + let mut z = vec![0.0f32; 480]; + c.process(&mut [&mut z]); + assert!(z.iter().all(|v| *v == 0.0), "bits {bits}"); + } + } + + /// The input is taken once every `rate_divide` samples and held: a whole value holds each + /// sample for exactly that many samples, and 2.5 alternates holds of 3 and 2. + #[test] + fn bitcrusher_holds_each_sample_for_the_rate_divide() { + let x: Vec = (0..200).map(|i| (i + 1) as f32 / 1024.0).collect(); + for (divide, want) in [(1.0, vec![1usize]), (5.0, vec![5]), (2.5, vec![3, 2])] { + let mut c = crush(&[("bits", 16.0), ("rate_divide", divide)], 1); + let mut y = x.clone(); + c.process(&mut [&mut y]); + let at = changes(&y); + for (k, w) in at.windows(2).enumerate() { + assert_eq!(w[1] - w[0], want[k % want.len()], "divide {divide}: hold {k}"); + } + assert!(at.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input"); + } + } + + /// A shorter rate divide cuts the hold in progress short, and the holds after it have the new + /// length from the first one on. + #[test] + fn bitcrusher_follows_a_shorter_hold_at_once() { + let mut c = crush(&[("bits", 16.0), ("rate_divide", 50.0)], 1); + let mut a: Vec = (0..10).map(|i| (i + 1) as f32 / 1024.0).collect(); + c.process(&mut [&mut a]); + assert!(c.set_param("rate_divide", 2.0)); + let mut b: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + c.process(&mut [&mut b]); + let at = changes(&b); + assert_eq!(at[0], 0); + assert!(at.windows(2).all(|w| w[1] - w[0] == 2), "holds after the change: {at:?}"); + } + + /// A held sample sounds for no longer than the tail reports after the input ends. + #[test] + fn bitcrusher_tail_covers_the_hold() { + for divide in [1.0, 4.0, 7.5, 50.0] { + let mut c = crush(&[("bits", 4.0), ("rate_divide", divide)], 1); + let tail = c.tail_samples(); + let mut x = vec![0.0f32; 200]; + x[0] = 0.5; + c.process(&mut [&mut x]); + let last = x.iter().rposition(|v| *v != 0.0).unwrap_or(0); + assert_eq!(last, tail, "divide {divide}"); + } + } + + /// A block that leaves a channel out feeds it silence, so the channel holds none of its earlier + /// audio when it comes back. + #[test] + fn bitcrusher_feeds_channels_a_block_leaves_out_silence() { + let p = [("bits", 6.0), ("rate_divide", 7.0)]; + let (mut left_out, mut silent) = (crush(&p, 2), crush(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 4801, 0.0); + for c in [&mut left_out, &mut silent] { + let (mut l, mut r) = (x.clone(), x.clone()); + c.process(&mut [&mut l, &mut r]); + } + let mut l = x[..10].to_vec(); + left_out.process(&mut [&mut l]); + let (mut l, mut r) = (x[..10].to_vec(), vec![0.0f32; 10]); + silent.process(&mut [&mut l, &mut r]); + let (mut la, mut ra) = (vec![0.0f32; 480], vec![0.0f32; 480]); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (vec![0.0f32; 480], vec![0.0f32; 480]); + silent.process(&mut [&mut lb, &mut rb]); + assert_eq!(ra, rb); + assert_eq!(la, lb); + } + + /// At a mix of 0 the input passes through unchanged, and a non-finite sample comes out finite. + #[test] + fn bitcrusher_mix_zero_and_non_finite_input() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut c = crush(&[("mix", 0.0), ("bits", 2.0), ("rate_divide", 9.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + c.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut c = crush(&[("bits", 2.0), ("rate_divide", 3.0)], 1); + let mut y = x.clone(); + y[99] = f32::NAN; + y[200] = f32::INFINITY; + c.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite())); + } + + /// Finite samples at the f32 limit, held while the input swings to the other limit, come out + /// finite at every mix. + #[test] + fn bitcrusher_keeps_samples_at_the_f32_limit_finite() { + for mix in [0.0, 50.0, 100.0] { + for bits in [1.0, 7.3, 16.0] { + let mut c = crush(&[("mix", mix), ("bits", bits), ("rate_divide", 3.0)], 1); + let mut y: Vec = (0..30).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + c.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite()), "mix {mix}, bits {bits}: {y:?}"); + } + } + } } diff --git a/crates/audio-dsp/tests/it/no_alloc.rs b/crates/audio-dsp/tests/it/no_alloc.rs index e12a386e0f..5189e3177e 100644 --- a/crates/audio-dsp/tests/it/no_alloc.rs +++ b/crates/audio-dsp/tests/it/no_alloc.rs @@ -136,6 +136,50 @@ fn noise_suppression_does_not_allocate_while_processing() { assert!(l.iter().chain(&r).all(|v| v.is_finite())); } +/// The bitcrusher runs a voiced tone through 10,000 blocks of 480 frames, with its bits, rate +/// divide and mix changed between blocks, blocks that leave the second channel out, a NaN sample +/// and a reset, without one heap allocation. +#[test] +fn bitcrusher_does_not_allocate_while_processing() { + let Some(mut fx) = create_effect("bitcrusher", 48_000.0, 2) else { panic!("bitcrusher is not registered") }; + let tone: Vec = (0..480).map(|i| (0.4 * (std::f64::consts::TAU * 150.0 * i as f64 / 48_000.0).sin()) as f32).collect(); + let (mut l, mut r) = (tone.clone(), tone.clone()); + let info = allocation_counter::measure(|| { + for block in 0..10_000u32 { + match block % 500 { + 0 => { + fx.set_param("bits", 1.0 + (block / 500 % 16) as f32); + } + 100 => { + fx.set_param("rate_divide", 1.0 + (block / 500 % 7) as f32 * 7.5); + } + 250 => { + fx.set_param("mix", 40.0); + } + 499 => { + fx.set_param("mix", 100.0); + } + _ => {} + } + if block == 7_777 { + fx.reset(); + } + l.copy_from_slice(&tone); + r.copy_from_slice(&tone); + if block == 5_000 { + l[100] = f32::NAN; + } + if (6_000..6_020).contains(&block) { + fx.process(&mut [&mut l]); + } else { + fx.process(&mut [&mut l, &mut r]); + } + } + }); + assert_eq!(info.count_total, 0, "{info:?}"); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); +} + /// The ring modulator runs a voiced tone through 10,000 blocks of 480 frames, with its effect, /// modulation source, frequency and depth changed between blocks, blocks that leave the second /// channel out, a NaN sample and a reset, without one heap allocation. From 2e30cc9522fe966318439bca3137ea66b51a9550 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:37:33 -0800 Subject: [PATCH 32/47] craft-xtask: keep generic commas, borrowed closures and raw identifiers in test-only code - A Windows drive-relative input (`C:a.rs`) is keyed by the file it opens under the current folder of its drive, so it deduplicates with the absolute path and takes part in the mixed-kind conflict check. - A `<` opens generic brackets where an operand starts (` as Fixture>::LABEL`, also after `return` and the like), in the type of a declared field or parameter (`field: Pair`), and in a tuple field, so their commas do not end the test-only region. Fields and parameters count as declared only in the braces or parentheses of a struct, union, enum variant or function, so a comparison in a struct expression (`probe: a < b`) stays one. - A closure after a borrow (`&|_, _|`, `&mut move |..|`) keeps its parameter commas. - A raw identifier (`r#let`) is read as one word and is never taken for a keyword. --- crates/xtask/src/names.rs | 356 +++++++++++++++++++++++++++++++++++--- 1 file changed, 333 insertions(+), 23 deletions(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 2969b83a3a..2d4518d2ff 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -294,7 +294,8 @@ impl From for String { /// /// A file is identified by its path joined to `base`, and a relative `base` is joined to the /// current folder (on Windows, a drive-relative `base` such as `C:src` to the current folder of -/// its drive) before any input is listed, so a relative and an absolute path to it are one file, +/// its drive) before any input is listed. A drive-relative input (`C:a.rs`) is joined to the +/// current folder of its drive instead. A relative and an absolute path to a file are one file, /// read once and reported by the input path that sorts first; `..` and links are not resolved. /// /// A [`Kind::Rust`] folder is read recursively for `.rs` files that [`Policy::skip`] keeps; links to @@ -314,7 +315,7 @@ pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result = files.into_iter().map(|(path, kind)| (root.join(&path), kind, path)).collect(); + let mut files = files.into_iter().map(|(path, kind)| Ok((input_path(&root, &path)?, kind, path))).collect::, Error>>()?; files.sort(); files.dedup_by(|later, first| later.0 == first.0 && later.1 == first.1); if let Some(pair) = files.windows(2).find(|pair| pair[0].0 == pair[1].0) { @@ -344,6 +345,15 @@ fn absolute_base(base: &Path) -> Result { } } +/// The absolute path that `path` opens under the absolute `root`: `path` joined to `root`, or for a +/// Windows drive-relative path (`C:a.rs`), joined to the current folder of its drive. +fn input_path(root: &Path, path: &Path) -> Result { + match path.components().next() { + Some(Component::Prefix(_)) if !path.has_root() => absolute_base(path), + _ => Ok(root.join(path)), + } +} + /// The findings in one source that is already in memory. `path` is only reported. A /// [`Kind::Rust`] source is a single file here. pub fn scan_source(path: &Path, source: &str, kind: Kind, policy: &Policy<'_>) -> Result, Error> { @@ -585,8 +595,9 @@ pub struct Literal { /// Test-only code is the code under `#[cfg(test)]` and the rest of a module that starts with /// `#![cfg(test)]`. Under `#[cfg(test)]`, a `const`, `static` or `let` runs up to its `;`, another /// item up to its closing `}` or its `;`, and a field, argument, arm or statement up to its `,` or -/// `;`; a `,` in an expression's generic arguments (`f::`) or in the parameters of a closure -/// that starts the expression does not end it. A block expression (a block, a macro's braces, a +/// `;`; a `,` in generic arguments (`f::`, ` as Fixture>::LABEL`, or a field's +/// `field: Pair`) or in the parameters of a closure that starts the expression (after any +/// `move` or `&`) does not end it. A raw identifier (`r#let`) is never a keyword. A block expression (a block, a macro's braces, a /// labeled block, or `if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the /// whole statement or as an arm's expression after `=>`, ends at its `}`, or at the last `}` of an /// `if` with `else` branches; braces in the condition of an `if`, `while`, `match` or `for` (a @@ -741,10 +752,11 @@ enum TestRegion { /// its `}` unless an `else` follows. A `.` or `?` after that `}` clears `block`, so the expression /// ends at its `;` or `,`. A `{` does not count as the first while `pattern` is set (between the /// `let` of an `if` or `while` condition and its `=`, or a `for` and its `in`), while `angle` - /// generic brackets are open (of an item's header, or after a `::` in an expression), or while - /// `params` is set (between the `|`s of a closure that starts the expression). A `,` does not - /// end it while `angle` or `params` is set either. - Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool, pattern: bool, angle: usize, params: bool }, + /// generic brackets are open (of an item's header, after a `::` or where an operand starts in an + /// expression, or in the type after `typed` is set), or while `params` is set (between the `|`s + /// of a closure that starts the expression). A `,` does not end it while `angle` or `params` is + /// set either. `typed` is set at the `:` after the name of a field or parameter (`name: Type`). + Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool, pattern: bool, angle: usize, params: bool, typed: bool }, /// The rest of the module that `#![cfg(test)]` starts, at this delimiter depth. Inner { level: usize }, } @@ -752,7 +764,18 @@ enum TestRegion { impl TestRegion { /// Test-only code at `level` whose code starts at `start`. fn item(level: usize, start: usize) -> Self { - TestRegion::Item { level, start, opened: false, item: false, semi: false, block: false, pattern: false, angle: 0, params: false } + TestRegion::Item { + level, + start, + opened: false, + item: false, + semi: false, + block: false, + pattern: false, + angle: 0, + params: false, + typed: false, + } } } @@ -760,14 +783,44 @@ impl TestRegion { /// an item (`if let`, `for … in`). const HEADER_KEYWORDS: &[&str] = &["for", "if", "loop", "match", "while"]; +/// What the fields or parameters in a delimiter are. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Fields { + /// None are declared there: the delimiter is an expression's, a pattern's or a block's. + Untyped, + /// They are declared with their types: a struct's, union's or variant's named fields, or a + /// function's parameters. + Typed, + /// The types of a tuple struct's or tuple variant's fields. + Tuple, + /// An enum's variants, whose `{ .. }` and `( .. )` hold typed fields. + Variants, +} + +/// A declaration whose fields or parameters have not opened yet. +#[derive(Debug, Clone, Copy)] +struct Declares { + /// The delimiter depth of its keyword. + level: usize, + /// Its keyword: `struct`, `union`, `enum` or `fn`. + keyword: &'static str, + /// The generic brackets of its header that are open (`fn f`). + angle: usize, + /// Whether its `where` clause has started, after which only a `{` opens its fields. + after_where: bool, +} + struct Lexer<'s> { chars: Vec, at: usize, line: usize, kinds: Literals, marker: Option<&'s str>, - /// Open delimiters and the line of each. - delims: Vec<(char, usize)>, + /// Open delimiters, the line of each, and what the fields or parameters in each are. + delims: Vec<(char, usize, Fields)>, + /// The next `{` or `(` that declares fields or parameters, after a `struct`, `union`, `enum` or + /// `fn`. + declares: Option, test: Option, /// Whether the last token read, past whitespace and comments, is a word. after_word: bool, @@ -791,6 +844,7 @@ fn lex(source: &str, kinds: Literals, marker: Option<&str>) -> Result { '=' => self.equals(), '<' | '>' => self.angle(c), '|' => self.pipe(), + ':' => self.colon(), c if c.is_ascii_digit() => self.number(), c if is_word(c) => self.word()?, _ => self.at += 1, @@ -866,7 +921,7 @@ impl Lexer<'_> { } } match self.delims.last() { - Some(&(_, line)) => Err(Self::error(line, "unclosed delimiter")), + Some(&(_, line, _)) => Err(Self::error(line, "unclosed delimiter")), None => Ok(()), } } @@ -1046,12 +1101,31 @@ impl Lexer<'_> { } } - /// An identifier, or the prefix of a byte, C or raw literal. + /// An identifier, or the prefix of a byte, C or raw literal. A raw identifier (`r#let`) is read + /// whole, so its name is not taken for a keyword. fn word(&mut self) -> Result<(), SyntaxError> { let start = self.at; self.number(); + let raw_name = self.peek(1).is_some_and(|c| is_word(c) && !c.is_ascii_digit()); + if self.at == start + 1 && self.chars.get(start) == Some(&'r') && self.peek(0) == Some('#') && raw_name { + self.at += 1; + self.number(); + } let word: String = self.chars.get(start..self.at).unwrap_or_default().iter().collect(); self.header_word(start, &word); + // `union` is a keyword only before the union's name. + let named = word != "union" || !self.word_at(self.skip_space(self.at)).is_empty(); + let keyword = ["struct", "union", "enum", "fn"].into_iter().find(|&k| k == word); + // A `fn` type in a declaration's header (`struct S`) does not replace it. + let in_header = self.declares.is_some_and(|d| d.level == self.delims.len() && (d.angle > 0 || d.after_where)); + if let Some(keyword) = keyword.filter(|_| named && !in_header) { + self.declares = Some(Declares { level: self.delims.len(), keyword, angle: 0, after_where: false }); + } else if word == "where" + && let Some(declares) = &mut self.declares + && declares.level == self.delims.len() + { + declares.after_where = true; + } match (word.as_str(), self.peek(0)) { ("b", Some('\'')) => self.quote(Form::Byte), ("b", Some('"')) => { @@ -1114,30 +1188,140 @@ impl Lexer<'_> { } /// A `<` or `>` (not the `>` of `->`) opens or closes a generic bracket in an item's header - /// before its body, and in an expression from a `::<` until its brackets close - /// (`pair::`), so that a comparison does not. + /// before its body. In an expression, a `<` opens one after a `::` (`pair::`), where an + /// operand starts (` as Fixture>::LABEL`), and after a word in the type of a field + /// or parameter when its `>` follows (`field: Pair`), and the brackets stay open until + /// they close, so that a comparison (`a < b`) does not. fn angle(&mut self, c: char) { let arrow = c == '>' && self.at.checked_sub(1).and_then(|i| self.chars.get(i)) == Some(&'-'); let turbofish = c == '<' && self.prev == Some(':') && self.prev_prev == Some(':'); + let level_now = self.delims.len(); + if let Some(declares) = &mut self.declares + && declares.level == level_now + && !arrow + { + declares.angle = if c == '<' { declares.angle + 1 } else { declares.angle.saturating_sub(1) }; + } + // A tuple field is a type from its start. + let tuple = self.delims.last().is_some_and(|&(_, _, fields)| fields == Fields::Tuple); + let generic = c == '<' + && match self.test { + Some(TestRegion::Item { level, start, item: false, angle: 0, typed, .. }) if level == level_now => { + self.operand_starts(start) || ((typed || tuple) && self.after_word && self.angle_closes()) + } + _ => false, + }; if let Some(TestRegion::Item { level, opened, item, angle, .. }) = &mut self.test && *level == self.delims.len() && !arrow - && if *item { !*opened } else { turbofish || *angle > 0 } + && if *item { !*opened } else { turbofish || generic || *angle > 0 } { *angle = if c == '<' { *angle + 1 } else { angle.saturating_sub(1) }; } self.at += 1; } - /// A `|` at the start of a test-only expression, after any `async` and `move`, opens the - /// parameters of a closure (`|a, b| ..`), and the next `|` at its level closes them. + /// Whether an operand starts at the current index in the test-only expression whose code starts + /// at `start`: at that code, or after an operator or a keyword that takes one. + fn operand_starts(&self, start: usize) -> bool { + if self.after_word { + return matches!(self.word_at(self.last_word).as_str(), "as" | "break" | "if" | "in" | "match" | "return" | "while"); + } + self.code_start(start) == self.at || matches!(self.prev, Some('=' | '!' | '&' | '|' | '+' | '-' | '*' | '/' | '%' | '^' | ':')) + } + + /// Whether the `<` at the current index has its `>` before a `;`, a `=>`, a closing delimiter of + /// its level, or a string or `.` that a type does not hold. Whitespace, comments, groups in + /// delimiters and character literals are passed over whole. + fn angle_closes(&self) -> bool { + let mut depth = 0_usize; + let mut at = self.at + 1; + loop { + at = self.skip_space(at); + let Some(&c) = self.chars.get(at) else { return false }; + match c { + '(' | '[' | '{' => { + let Some(end) = self.group_end(at) else { return false }; + at = end; + continue; + } + ')' | ']' | '}' | ';' | '"' | '.' => return false, + '=' if self.chars.get(at + 1) == Some(&'>') => return false, + '-' if self.chars.get(at + 1) == Some(&'>') => at += 1, + '<' => depth += 1, + '>' if depth == 0 => return true, + '>' => depth -= 1, + '\'' => { + at += match (self.chars.get(at + 1), self.chars.get(at + 2)) { + (Some('\\'), _) => self.chars.get(at + 3..).and_then(|rest| rest.iter().position(|&q| q == '\'')).map_or(1, |end| end + 4), + (Some(_), Some('\'')) => 3, + _ => 1, + }; + continue; + } + c if is_word(c) => { + at += self.word_at(at).chars().count(); + continue; + } + _ => {} + } + at += 1; + } + } + + /// A `:` (not part of a `::`) right after the name that starts a test-only field or parameter, + /// after any `pub`, starts its type (`name: Type`) in the fields of a struct, union or variant + /// and in a function's parameters, not in a struct expression. + fn colon(&mut self) { + let single = self.peek(1) != Some(':') && self.at.checked_sub(1).and_then(|i| self.chars.get(i)) != Some(&':'); + let declared = self.delims.last().is_some_and(|&(_, _, fields)| fields == Fields::Typed); + if single + && declared + && let Some(TestRegion::Item { level, start, item: false, typed: false, .. }) = self.test + && level == self.delims.len() + && self.name_before(start) + && let Some(TestRegion::Item { typed, .. }) = &mut self.test + { + *typed = true; + } + self.at += 1; + } + + /// Whether the code at `start` is one name, after any `pub` and its `(..)`, that ends at the + /// current index. + fn name_before(&self, start: usize) -> bool { + let mut at = self.code_start(start); + if self.word_at(at) == "pub" { + at = self.skip_space(at + 3); + if self.chars.get(at) == Some(&'(') { + let Some(end) = self.group_end(at) else { return false }; + at = self.skip_space(end); + } + } + let len = self.word_at(at).chars().count(); + len > 0 && self.skip_space(at + len) == self.at + } + + /// A `|` at the start of a test-only expression, after any `async`, `move` and borrow (`&`, + /// `&mut`), opens the parameters of a closure (`|a, b| ..`), and the next `|` at its level + /// closes them. fn pipe(&mut self) { if let Some(TestRegion::Item { level, start, item: false, params, .. }) = self.test && level == self.delims.len() { let mut code = self.code_start(start); - while matches!(self.word_at(code).as_str(), "async" | "move") { - code = self.skip_space(code + self.word_at(code).chars().count()); + loop { + let word = self.word_at(code); + if matches!(word.as_str(), "async" | "move") { + code = self.skip_space(code + word.chars().count()); + } else if self.chars.get(code) == Some(&'&') { + code = self.skip_space(code + 1); + if self.word_at(code) == "mut" { + code = self.skip_space(code + 3); + } + } else { + break; + } } let opens = !params && code == self.at; if let Some(TestRegion::Item { params, .. }) = &mut self.test { @@ -1446,7 +1630,25 @@ impl Lexer<'_> { *block = starts; } } - self.delims.push((c, self.line)); + let level = self.delims.len(); + let fields = match self.declares { + Some(Declares { level: at, keyword, angle: 0, after_where }) if at == level && (c == '{' || (c == '(' && !after_where)) => { + self.declares = None; + match (keyword, c) { + ("enum", '{') => Fields::Variants, + ("fn", _) | (_, '{') => Fields::Typed, + _ => Fields::Tuple, + } + } + // A variant's `{ .. }` or `( .. )` after its name. + _ if self.after_word && self.delims.last().is_some_and(|&(_, _, fields)| fields == Fields::Variants) => match c { + '{' => Fields::Typed, + '(' => Fields::Tuple, + _ => Fields::Untyped, + }, + _ => Fields::Untyped, + }; + self.delims.push((c, self.line, fields)); self.at += 1; } @@ -1472,8 +1674,8 @@ impl Lexer<'_> { fn close(&mut self, c: char) -> Result<(), SyntaxError> { let expected = match self.delims.pop() { - Some(('{', _)) => '}', - Some(('(', _)) => ')', + Some(('{', _, _)) => '}', + Some(('(', _, _)) => ')', Some(_) => ']', None => return Err(Self::error(self.line, "unmatched closing delimiter")), }; @@ -1482,6 +1684,9 @@ impl Lexer<'_> { } self.at += 1; let depth = self.delims.len(); + if self.declares.is_some_and(|declares| declares.level > depth) { + self.declares = None; + } let ends = match self.test { Some(TestRegion::Item { level, opened, item, semi, block, .. }) => { let block_end = opened && depth == level && c == '}'; @@ -1526,6 +1731,10 @@ impl Lexer<'_> { /// (`impl`, a `where` clause) does not, and neither does one in an expression's generic /// arguments (`f::`) or in the parameters of a closure that starts it. fn item_end(&mut self, comma: bool) { + // A unit struct (`struct S;`) declares no fields. + if !comma && self.declares.is_some_and(|declares| declares.level == self.delims.len()) { + self.declares = None; + } if let Some(TestRegion::Item { level, opened, item, semi, angle, params, .. }) = self.test && level == self.delims.len() && if comma { level > 0 && !item && angle == 0 && !params } else { !item || !opened || semi } @@ -2172,6 +2381,96 @@ fn after() { let _ = "seven"; } assert_eq!(literals(source), ["one", "two", "three", "four"]); } + #[test] + fn test_only_types_and_qualified_paths_keep_their_generic_commas() { + let source = r#"struct S { + #[cfg(test)] + field: Pair>, + live: Tag<{ "one".len() }>, +} +fn arms(x: u8, a: u8, b: u8) { + match x { + #[cfg(test)] + 0 => > as Fixture>::LABEL, + #[cfg(test)] + 1 => a < b, + _ => "two", + } + call(#[cfg(test)] a < b, "three"); + let _ = S { #[cfg(test)] probe: a < b, label: "four" }; + let _ = S { #[cfg(test)] probe: a < b, live: "six".len() > 0 }; + let _ = S { #[cfg(test)] probe: a < b, live: x("seven") > d }; + let _ = S { #[cfg(test)] probe: a < /* > */ b, live: "eight" }; +} +fn typed(#[cfg(test)] p: Pair>, q: Tag<{ "five".len() }>) {} +struct Bounds<'a> { + #[cfg(test)] + field: &'a dyn Foo>, + live: Tag<{ "nine".len() }>, +} +enum E { + V { + #[cfg(test)] + field: Pair>, + live: Tag<{ "ten".len() }>, + }, + W(#[cfg(test)] Pair>, Tag<{ "eleven".len() }>), +} +fn bounded(#[cfg(test)] p: Pair>, f: F) -> Tag<{ "twelve".len() }> {} +struct Tuple(#[cfg(test)] pub Pair>, Tag<{ "thirteen".len() }>); +struct Where where F: Fn(u8, u16) { + #[cfg(test)] + field: Pair>, + live: Tag<{ "fourteen".len() }>, +} +struct Defaulted { + #[cfg(test)] + field: Pair>, + live: Tag<{ "fifteen".len() }>, +} +fn returns(x: u8) -> &'static str { + match x { + #[cfg(test)] + 0 => return > as Fixture>::LABEL, + _ => "sixteen", + } +} +"#; + let expected = [ + "one", "two", "three", "four", "six", "seven", "eight", "five", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", + "sixteen", + ]; + assert_eq!(literals(source), expected); + } + + #[test] + fn test_only_borrowed_closures_keep_their_parameter_commas() { + let source = r#"fn arms(x: u8) { + match x { + #[cfg(test)] + 0 => &|_, _| "AzureKit", + #[cfg(test)] + 1 => &mut move |_, _| "AzureKit", + 2 => &|_, _| "one", + _ => &|_, _| "two", + } +} +"#; + assert_eq!(literals(source), ["one", "two"]); + } + + #[test] + fn a_raw_identifier_is_not_read_as_a_keyword() { + let source = r##"fn f(r#let: bool) { + #[cfg(test)] if r#let {} + let _ = "one"; + #[cfg(test)] if r#let { "AzureKit"; } + let _ = r#"two"#; +} +"##; + assert_eq!(literals(source), ["one", "two"]); + } + #[test] fn braces_in_a_test_only_condition_are_not_its_body() { let source = r#"fn statements(ready: bool) { @@ -2337,6 +2636,17 @@ fn seven() { let _ = "seven"; } let fits = Policy { limits: Limits { max_total_bytes: size, ..DEFAULT_LIMITS }, ..POLICY }; let same = [Input::manifest(Path::new("Cargo.toml")), Input::manifest(&absolute)]; scan(Path::new(drive.as_os_str()), &same, &fits).unwrap(); + // A drive-relative input names the file under the current folder of its drive. + let mut spelled = drive.as_os_str().to_os_string(); + spelled.push("Cargo.toml"); + let relative = PathBuf::from(spelled); + for base in [Path::new(drive.as_os_str()), current.as_path()] { + let same = [Input::manifest(&relative), Input::manifest(&absolute)]; + scan(base, &same, &fits).unwrap(); + let mixed = [Input::text(&relative), Input::manifest(&absolute)]; + let err = scan(base, &mixed, &POLICY).unwrap_err(); + assert!(matches!(&err, Error::Conflict { path } if path.ends_with("Cargo.toml")), "{err}"); + } } #[test] From 03d26a82c9f31b8d453980c1506dd3e910707f62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:58:32 -0800 Subject: [PATCH 33/47] audio-dsp: bitcrusher rounds the hold in progress at new bits and clears left-out channels - The bitcrusher holds each channel's input before rounding and rounds it at the current step on every sample, so a change of Bits applies to the hold in progress, and a higher Bits recovers the precision of the held input. - A channel the block leaves out holds silence from its first left-out sample on, so it comes back silent even when no capture fell in the gap. The capture clock is unchanged. - The hold tests compare the whole sequence of hold starts, and the shortened-hold test checks the first sample after the change. - Noise suppression keeps frames that hold a sample of a mute shorter than a frame (down to one hop of zeros) out of the noise estimate. - The allocation tests assert each set_param result. - The voice effects' comments and test state that a left-out channel comes back silent after a gap of at least the latency and the tail. - AudioEffect::tail_samples states the 60 s cap of the feedback delays and resonators. --- crates/audio-dsp/src/effects/character.rs | 77 +++++++++++--- crates/audio-dsp/src/effects/suppress.rs | 116 ++++++++++++++++++++-- crates/audio-dsp/src/effects/voice.rs | 16 +-- crates/audio-dsp/src/lib.rs | 2 + crates/audio-dsp/tests/it/no_alloc.rs | 38 +++---- 5 files changed, 198 insertions(+), 51 deletions(-) diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index f415ae49cf..3b1b0597b9 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -225,10 +225,11 @@ impl AudioEffect for RingMod { /// the holds average it. Each held sample is rounded to the nearest multiple of the step /// `2^(1 - bits)`, so silence stays silence and the range -1 ..= 1 takes `2^bits + 1` levels; /// fractional bits give steps between the whole-bit ones. Bits and Rate Divide take effect from -/// the next sample, and a shorter hold cuts the one in progress short. Mix moves to a new value -/// over 20 ms. +/// the next sample: a new Bits rounds the sample being held again, and a shorter hold cuts the +/// one in progress short. Mix moves to a new value over 20 ms. pub struct Bitcrusher { pv: ParamValues, + /// The input sample each channel holds, before rounding. held: Vec, /// Samples since the last capture, counted so that a capture happens when it reaches the hold /// length. Infinite after a reset, so the next sample is captured. @@ -294,17 +295,21 @@ impl AudioEffect for Bitcrusher { self.since += 1.0; let mix = f64::from(self.mix.tick()); for (ch, held) in self.held.iter_mut().enumerate() { - // A non-finite sample is taken as silence. A channel the block leaves out is fed - // silence, so it holds none of its earlier audio when it comes back. + // A non-finite sample is taken as silence. A channel the block leaves out holds + // silence from its first left-out sample on, so it holds none of its earlier audio + // when it comes back. let dry = match channels.get(ch).filter(|_| ch < nch) { Some(c) if c[i].is_finite() => f64::from(c[i]), _ => 0.0, }; - if capture { - *held = ((dry / step).round() * step).clamp(-limit, limit) as f32; + if capture || ch >= nch { + *held = dry as f32; } if ch < nch { - channels[ch][i] = (dry + mix * (f64::from(*held) - dry)) as f32; + // The held input is rounded at the current step, so a change of Bits also + // applies to the hold in progress. + let crushed = ((f64::from(*held) / step).round() * step).clamp(-limit, limit); + channels[ch][i] = (dry + mix * (crushed - dry)) as f32; } } } @@ -588,11 +593,16 @@ mod tests { let mut c = crush(&[("bits", 16.0), ("rate_divide", divide)], 1); let mut y = x.clone(); c.process(&mut [&mut y]); - let at = changes(&y); - for (k, w) in at.windows(2).enumerate() { - assert_eq!(w[1] - w[0], want[k % want.len()], "divide {divide}: hold {k}"); + let mut expected = vec![0usize]; + while let Some(&last) = expected.last() { + let next = last + want[(expected.len() - 1) % want.len()]; + if next >= x.len() { + break; + } + expected.push(next); } - assert!(at.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input"); + assert_eq!(changes(&y), expected, "divide {divide}"); + assert!(expected.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input"); } } @@ -604,11 +614,48 @@ mod tests { let mut a: Vec = (0..10).map(|i| (i + 1) as f32 / 1024.0).collect(); c.process(&mut [&mut a]); assert!(c.set_param("rate_divide", 2.0)); - let mut b: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let input: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let mut b = input.clone(); c.process(&mut [&mut b]); - let at = changes(&b); - assert_eq!(at[0], 0); - assert!(at.windows(2).all(|w| w[1] - w[0] == 2), "holds after the change: {at:?}"); + // `changes` counts the first sample whatever it holds, so the capture is checked apart. + assert_eq!(b[0], input[0], "the hold in progress was not cut short"); + assert_eq!(changes(&b), (0..30).step_by(2).collect::>()); + assert!((0..30).step_by(2).all(|i| b[i] == input[i])); + } + + /// A new Bits rounds the sample being held again from the next sample on, from the input it + /// took rather than from its rounded value, and the hold keeps its length. + #[test] + fn bitcrusher_rounds_the_hold_in_progress_at_new_bits() { + let mut c = crush(&[("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut a = [0.3f32]; + c.process(&mut [&mut a]); + assert!((a[0] - 0.3).abs() < 1e-4); + assert!(c.set_param("bits", 1.0)); + let mut b = [0.9f32]; + c.process(&mut [&mut b]); + assert_eq!(b[0], 0.0, "1 bit did not round the held 0.3 to 0"); + assert!(c.set_param("bits", 16.0)); + let mut d = [0.9f32, 0.9, 0.7]; + c.process(&mut [&mut d]); + assert!((d[0] - 0.3).abs() < 1e-4 && d[0] == d[1], "the held input was lost: {d:?}"); + assert_eq!(changes(&[a[0], b[0], d[0], d[1], d[2]]), vec![0, 1, 2, 4], "the hold did not keep its length"); + } + + /// A channel left out of one block of a single sample, between two captures, holds silence + /// when it comes back instead of the sample it held before. + #[test] + fn bitcrusher_clears_a_channel_left_out_for_one_sample() { + let mut c = crush(&[("bits", 8.0), ("rate_divide", 4.0)], 2); + let (mut l, mut r) = ([1.0f32], [1.0f32]); + c.process(&mut [&mut l, &mut r]); + assert_eq!(r[0], 1.0); + let mut l = [0.0f32]; + c.process(&mut [&mut l]); + let (mut l, mut r) = ([0.0f32; 2], [0.0f32; 2]); + c.process(&mut [&mut l, &mut r]); + assert_eq!(r, [0.0, 0.0], "the channel came back with its earlier hold"); + assert_eq!(l, [1.0, 1.0], "the channel kept in the block lost its hold"); } /// A held sample sounds for no longer than the tail reports after the input ends. diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index fe9236291d..c8566025b2 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -13,6 +13,8 @@ //! digital silence (a mute or a gate) drops the frames still waiting, and the four frames after //! it do not enter either, so no frame that shares a sample with the silence lowers the estimate //! and lets the noise pass when the sound resumes, wherever between two hops the silence ends. +//! A mute too short to fill a frame keeps every frame that holds a sample of it out too, down to +//! a run of zeros one hop long (64 samples at 48 kHz); a shorter run of zeros counts as sound. //! Nor does a frame more than 15 dB below the estimate, until such frames have lasted a whole //! search window without digital silence between them (the floor has really fallen). //! The noise power the gains are computed from falls at once and rises by at most 10 dB a @@ -27,7 +29,7 @@ //! spectrum is uneven takes up to 3 s more in the bins well above the median. use super::stft::{Pairing, Plan, Spectral, StftChannel, stream}; -use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; +use crate::{AudioEffect, MAX_CHANNELS, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; /// Length of the minimum-statistics search, and the number of sub-windows it rotates through. const SEARCH_S: f32 = 1.5; @@ -118,6 +120,13 @@ struct Bins { seeded: bool, /// Room to find the median bin of the first estimate. scratch: Vec, + /// Zero samples in a row up to the last sample, up to a hop. + zero_run: usize, + /// Samples since the last sample of a mute (a run of at least a hop of zeros), or `usize::MAX` + /// when there has been none since the last reset. + since_mute: usize, + /// Samples since the last frame. + since_frame: usize, } impl Bins { @@ -143,6 +152,9 @@ impl Bins { quiet_run: 0, seeded: false, scratch: vec![0.0; bins], + zero_run: 0, + since_mute: usize::MAX, + since_frame: 0, } } @@ -163,6 +175,30 @@ impl Bins { self.since_zero = 1; self.quiet_run = 0; self.seeded = false; + self.zero_run = 0; + self.since_mute = usize::MAX; + self.since_frame = 0; + } + + /// Takes one input sample before the STFT does, to find mutes too short to give a frame of + /// digital silence. Once `hop` zeros run in a row, the frame still waiting that holds the first + /// of them leaves the queue, and so does every later frame that holds a sample of the run. + fn sample(&mut self, x: f32, hop: usize) { + self.since_frame += 1; + self.zero_run = if x == 0.0 { (self.zero_run + 1).min(hop) } else { 0 }; + if self.zero_run < hop { + self.since_mute = self.since_mute.saturating_add(1); + return; + } + if self.since_mute != 0 { + // The run has just reached a hop. It started `hop - 1` samples ago, so of the frames + // waiting only the newest can hold it: when it ended less than a hop ago. + if self.queued > 0 && self.since_frame < hop { + self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; + } + self.quiet_run = 0; + } + self.since_mute = 0; } /// Noise power of bin `k` for the frame last processed: the smallest smoothed power of the @@ -212,6 +248,7 @@ impl Bins { /// state as it is and repeats the last gains. fn frame(&mut self, re: &[f32], im: &[f32], c: &Coefs, out: &mut [f32]) { let bins = self.power.len(); + self.since_frame = 0; let finite = re.iter().zip(im).fold(true, |ok, (a, b)| ok & (a * a + b * b).is_finite()); if finite { for k in 0..bins { @@ -235,7 +272,8 @@ impl Bins { self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; } self.queue_total[at] = total; - self.queue_ok[at] = self.since_zero > OVERLAP; + // A frame holds the last STFT size of samples, `2 * (bins - 1)`. + self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); self.queued += 1; } if self.started && !self.seeded { @@ -287,6 +325,8 @@ pub struct NoiseSuppression { smoothed: Vec, coefs: Coefs, sample_rate: f32, + /// Samples since the last frame, the same in every channel. + pos: usize, } impl NoiseSuppression { @@ -307,6 +347,7 @@ impl NoiseSuppression { smoothed: vec![1.0; bins], coefs: Coefs { floor: 1.0, smooth: 0.0, priori: 0.0, sub_frames: 1, window: SUBWINDOWS, rise: 1.0 }, sample_rate, + pos: 0, }; s.apply_params(true); s @@ -338,6 +379,7 @@ impl AudioEffect for NoiseSuppression { fn reset(&mut self) { self.stft.iter_mut().for_each(StftChannel::reset); self.bins.iter_mut().for_each(Bins::reset); + self.pos = 0; } fn process(&mut self, channels: &mut [&mut [f32]]) { let len = block_len(channels); @@ -347,22 +389,38 @@ impl AudioEffect for NoiseSuppression { c[..len].iter_mut().for_each(|v| *v = flush32(*v)); } let (n, hop, coefs) = (self.n, self.hop, self.coefs); - let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); let scale = 1.0 / (n as f32 * 2.0); let plan = Plan { hop, scale, pairing: Pairing::SynthesisOnly }; - stream(&mut self.stft, &mut self.spec, channels, len, plan, &mut |ch, _, re, im| { - bins[ch].frame(re, im, &coefs, smoothed); - for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { - *r *= g; - *i *= g; + // The block runs in pieces that end at the next frame, so each channel's noise estimate + // takes every sample of a frame before the STFT frames it. + let mut start = 0; + while start < len { + let end = len.min(start + hop - self.pos); + for (b, c) in self.bins.iter_mut().zip(channels.iter()).take(nch) { + c[start..end].iter().for_each(|&x| b.sample(x, hop)); } - }); + let mut piece: [&mut [f32]; MAX_CHANNELS] = std::array::from_fn(|_| <&mut [f32]>::default()); + for (p, c) in piece.iter_mut().zip(channels.iter_mut()).take(nch) { + *p = &mut c[start..end]; + } + let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); + stream(&mut self.stft, &mut self.spec, &mut piece[..nch], end - start, plan, &mut |ch, _, re, im| { + bins[ch].frame(re, im, &coefs, smoothed); + for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { + *r *= g; + *i *= g; + } + }); + self.pos = (self.pos + end - start) % hop; + start = end; + } // A channel the block leaves out is fed silence, so it holds none of its earlier audio // when it comes back. let half = n / 2 + 1; - let spec = &mut self.spec; - for (st, b) in self.stft.iter_mut().zip(bins.iter_mut()).skip(nch) { + let (spec, smoothed) = (&mut self.spec, &mut self.smoothed); + for (st, b) in self.stft.iter_mut().zip(self.bins.iter_mut()).skip(nch) { for _ in 0..len { + b.sample(0.0, hop); st.tick(0.0, hop, &mut |input, out| { spec.analyze(input); b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); @@ -641,6 +699,42 @@ mod tests { } } + /// A mute too short to fill a frame, from one hop long up, keeps the frames that hold a sample + /// of it out of the estimate too, wherever it starts and ends between two hops. + #[test] + fn frames_that_touch_a_short_mute_stay_out_of_the_estimate() { + for offset in [0usize, 17, 40, 63] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut x = white(31, SR as usize / 2, 0.05); + let mutes = [(192 + offset, 256 + offset), (6000 + offset, 6100 + offset), (12_000 + offset, 12_200 + offset)]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + // One hop per block, so each block ends with a frame. A frame enters the estimate when + // the frame `OVERLAP` after it arrives, which is when `heard` grows. + let mut entered = Vec::new(); + for (k, chunk) in x.chunks(hop).enumerate() { + let heard = s.bins[0].heard; + let mut y = chunk.to_vec(); + s.process(&mut [&mut y]); + if s.bins[0].heard > heard { + entered.push(k + 1 - OVERLAP); + } + } + let frames = x.len() / hop; + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < s.coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), s.bins[0].heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(s.bins[0].heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", s.bins[0].heard); + } + } + /// Quiet stretches that a mute separates do not add up to a search window: the estimate stays /// at the noise before them, and falls only after a whole search window of quiet in a row. #[test] diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index 311fdf362a..466520b9b7 100644 --- a/crates/audio-dsp/src/effects/voice.rs +++ b/crates/audio-dsp/src/effects/voice.rs @@ -459,8 +459,9 @@ impl AudioEffect for VoicePitch { let mut sum = 0.0f32; for (c, line) in self.lines.iter_mut().enumerate() { // A non-finite sample is stored as silence, so it never reaches the output. A - // channel the block leaves out is stored as silence too, so its line holds none - // of its earlier audio when it comes back. + // channel the block leaves out is stored as silence too while its line advances, + // so after a gap of at least `latency() + tail_samples()` samples it holds none of + // its earlier audio; after a shorter gap, audio still in the line can sound. let x = channels.get(c).map_or(0.0, |io| flush32(io[i])); line[self.pos] = x; sum += x; @@ -757,8 +758,9 @@ impl AudioEffect for VoiceFormant { for i in 0..len { for c in 0..self.stage.stft.len() { // A non-finite sample is taken as silence, so it never reaches the output. A - // channel the block leaves out is fed silence, so it holds none of its earlier - // audio when it comes back. + // channel the block leaves out is fed silence while its state advances, so after + // a gap of at least `latency() + tail_samples()` samples it holds none of its + // earlier audio; after a shorter gap, audio still pending can sound. match channels.get_mut(c) { Some(io) => io[i] = self.stage.tick(c, flush32(io[i]), self.ratio), None => { @@ -1191,8 +1193,9 @@ mod tests { } /// A block that leaves channels out feeds them silence, so when they come back without a - /// reset none of their earlier audio sounds. Checked for the formant shifter and for the - /// pitch shifter with and without Keep Formants. + /// reset, after a gap at least as long as the latency and the tail, none of their earlier + /// audio sounds. Checked for the formant shifter and for the pitch shifter with and without + /// Keep Formants. #[test] fn channels_left_out_of_a_block_come_back_silent() { let mut rng = Rng::new(19); @@ -1207,6 +1210,7 @@ mod tests { keep.reset(); let fxs: [&mut dyn AudioEffect; 3] = [&mut f, &mut plain, &mut keep]; for fx in fxs { + assert!(fx.latency() + fx.tail_samples() <= noise.len(), "{}: the gap is shorter than the latency and the tail", fx.id()); let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); fx.process(&mut [&mut a, &mut b, &mut c]); let mut a = noise.clone(); diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index a20bc1d9a2..e81bd7e386 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -206,6 +206,8 @@ pub trait AudioEffect: Send { /// the end of its input. An effect whose output decays without reaching zero (a feedback /// delay, a resonator) reports where the decay falls below a cutoff, 60 dB under its start /// for the feedback delays and resonators, so quieter output can still follow that point. + /// Those effects also cap the tail they report at 60 s, which is what a feedback of 1 or more + /// reports. fn tail_samples(&self) -> usize { 0 } diff --git a/crates/audio-dsp/tests/it/no_alloc.rs b/crates/audio-dsp/tests/it/no_alloc.rs index 5189e3177e..81e0e5ced7 100644 --- a/crates/audio-dsp/tests/it/no_alloc.rs +++ b/crates/audio-dsp/tests/it/no_alloc.rs @@ -14,20 +14,20 @@ fn voice_pitch_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0); + assert!(fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0)); } 100 => { - fx.set_param("formant_follow", 1.0); + assert!(fx.set_param("formant_follow", 1.0)); } 250 => { - fx.set_param("cents", -35.0); + assert!(fx.set_param("cents", -35.0)); } 400 => { - fx.set_param("formant_follow", 0.0); + assert!(fx.set_param("formant_follow", 0.0)); } 499 => { - fx.set_param("semitones", 0.0); - fx.set_param("cents", 0.0); + assert!(fx.set_param("semitones", 0.0)); + assert!(fx.set_param("cents", 0.0)); } _ => {} } @@ -60,10 +60,10 @@ fn voice_formant_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0); + assert!(fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0)); } 499 => { - fx.set_param("semitones", 0.0); + assert!(fx.set_param("semitones", 0.0)); } _ => {} } @@ -105,10 +105,10 @@ fn noise_suppression_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("reduction", (block / 500 % 5) as f32 * 10.0); + assert!(fx.set_param("reduction", (block / 500 % 5) as f32 * 10.0)); } 499 => { - fx.set_param("reduction", 0.0); + assert!(fx.set_param("reduction", 0.0)); } _ => {} } @@ -148,16 +148,16 @@ fn bitcrusher_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("bits", 1.0 + (block / 500 % 16) as f32); + assert!(fx.set_param("bits", 1.0 + (block / 500 % 16) as f32)); } 100 => { - fx.set_param("rate_divide", 1.0 + (block / 500 % 7) as f32 * 7.5); + assert!(fx.set_param("rate_divide", 1.0 + (block / 500 % 7) as f32 * 7.5)); } 250 => { - fx.set_param("mix", 40.0); + assert!(fx.set_param("mix", 40.0)); } 499 => { - fx.set_param("mix", 100.0); + assert!(fx.set_param("mix", 100.0)); } _ => {} } @@ -192,17 +192,17 @@ fn ring_mod_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("effect", (block / 500 % 4) as f32); + assert!(fx.set_param("effect", (block / 500 % 4) as f32)); } 100 => { - fx.set_param("mod_source", (block / 500 % 3) as f32); + assert!(fx.set_param("mod_source", (block / 500 % 3) as f32)); } 250 => { - fx.set_param("frequency", 30.0 + (block / 500 % 5) as f32 * 400.0); - fx.set_param("mod_depth", 60.0); + assert!(fx.set_param("frequency", 30.0 + (block / 500 % 5) as f32 * 400.0)); + assert!(fx.set_param("mod_depth", 60.0)); } 499 => { - fx.set_param("mod_depth", 0.0); + assert!(fx.set_param("mod_depth", 0.0)); } _ => {} } From acb2b98ee1cbcc5ed5212a4e7719c92534b3d37a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:03:20 -0800 Subject: [PATCH 34/47] audio-dsp: noise_suppression test covers a mute one STFT size long The short-mute test adds a 256-sample mute (one STFT size at 48 kHz) that starts 0, 17, 40 and 63 samples into a hop, so only the aligned one holds a whole frame of silence. --- crates/audio-dsp/src/effects/suppress.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index c8566025b2..c4bd01534d 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -707,7 +707,13 @@ mod tests { let mut s = suppressor(24.0); let (n, hop) = (s.n, s.hop); let mut x = white(31, SR as usize / 2, 0.05); - let mutes = [(192 + offset, 256 + offset), (6000 + offset, 6100 + offset), (12_000 + offset, 12_200 + offset)]; + // The last mute is one STFT size long and holds no whole frame unless it starts on a hop. + let mutes = [ + (192 + offset, 256 + offset), + (6000 + offset, 6100 + offset), + (12_000 + offset, 12_200 + offset), + (17_984 + offset, 17_984 + offset + n), + ]; for &(a, b) in &mutes { x[a..b].fill(0.0); } From a2854ae0fbd3fbc27b597d957fa8e26e5b33405a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:09:47 -0800 Subject: [PATCH 35/47] craft-xtask: read the type after a test-only parameter pattern A `:` at the level of a test-only parameter now starts its type after any pattern (`mut p`, `ref mut p`, `(a, b)`, `&(a, b)`, `P { x, .. }`, `m::P(x)`), not only after a bare name, so a generic comma in that type no longer ends the test-only code. --- crates/xtask/src/names.rs | 41 +++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 2d4518d2ff..a40ea73a5c 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -755,7 +755,8 @@ enum TestRegion { /// generic brackets are open (of an item's header, after a `::` or where an operand starts in an /// expression, or in the type after `typed` is set), or while `params` is set (between the `|`s /// of a closure that starts the expression). A `,` does not end it while `angle` or `params` is - /// set either. `typed` is set at the `:` after the name of a field or parameter (`name: Type`). + /// set either. `typed` is set at the `:` after the name of a field or the pattern of a parameter + /// (`name: Type`, `mut p: Type`). Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool, pattern: bool, angle: usize, params: bool, typed: bool }, /// The rest of the module that `#![cfg(test)]` starts, at this delimiter depth. Inner { level: usize }, @@ -1269,17 +1270,18 @@ impl Lexer<'_> { } } - /// A `:` (not part of a `::`) right after the name that starts a test-only field or parameter, - /// after any `pub`, starts its type (`name: Type`) in the fields of a struct, union or variant - /// and in a function's parameters, not in a struct expression. + /// A `:` (not part of a `::`) at the level of a test-only field or parameter, after its name + /// (and any `pub`) or its pattern (`mut p`, `(a, b)`, `P { x, .. }`), starts its type + /// (`name: Type`) in the fields of a struct, union or variant and in a function's parameters, + /// not in a struct expression. A `:` inside the pattern's own delimiters is at a deeper level. fn colon(&mut self) { let single = self.peek(1) != Some(':') && self.at.checked_sub(1).and_then(|i| self.chars.get(i)) != Some(&':'); let declared = self.delims.last().is_some_and(|&(_, _, fields)| fields == Fields::Typed); if single && declared - && let Some(TestRegion::Item { level, start, item: false, typed: false, .. }) = self.test + && let Some(TestRegion::Item { level, start, item: false, typed: false, angle: 0, .. }) = self.test && level == self.delims.len() - && self.name_before(start) + && self.code_start(start) < self.at && let Some(TestRegion::Item { typed, .. }) = &mut self.test { *typed = true; @@ -1287,21 +1289,6 @@ impl Lexer<'_> { self.at += 1; } - /// Whether the code at `start` is one name, after any `pub` and its `(..)`, that ends at the - /// current index. - fn name_before(&self, start: usize) -> bool { - let mut at = self.code_start(start); - if self.word_at(at) == "pub" { - at = self.skip_space(at + 3); - if self.chars.get(at) == Some(&'(') { - let Some(end) = self.group_end(at) else { return false }; - at = self.skip_space(end); - } - } - let len = self.word_at(at).chars().count(); - len > 0 && self.skip_space(at + len) == self.at - } - /// A `|` at the start of a test-only expression, after any `async`, `move` and borrow (`&`, /// `&mut`), opens the parameters of a closure (`|a, b| ..`), and the next `|` at its level /// closes them. @@ -2443,6 +2430,18 @@ fn returns(x: u8) -> &'static str { assert_eq!(literals(source), expected); } + #[test] + fn test_only_parameter_patterns_keep_their_generic_commas() { + let source = r#"fn mutable(#[cfg(test)] mut p: Pair>, q: Tag<{ "one".len() }>) {} +fn tuple(#[cfg(test)] (a, b): Pair>, q: Tag<{ "two".len() }>) {} +fn borrowed(#[cfg(test)] &(a, b): &Pair>, q: Tag<{ "three".len() }>) {} +fn fields(#[cfg(test)] P { x, .. }: Pair>, q: Tag<{ "four".len() }>) {} +fn by_ref(#[cfg(test)] ref mut p: Pair>, q: Tag<{ "five".len() }>) {} +fn paths(#[cfg(test)] m::P(x): Pair>, q: Tag<{ "six".len() }>) {} +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six"]); + } + #[test] fn test_only_borrowed_closures_keep_their_parameter_commas() { let source = r#"fn arms(x: u8) { From 3e48c109c578e9d485cb6b0813231bd331425ce6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:13:46 -0800 Subject: [PATCH 36/47] craft-xtask: keep a declaration pending across nested declarations in its header The pending declarations are now a stack, innermost last. A `fn` pointer type or a local item inside a declaration's header (`struct S`, `Box<[fn(u8, u16); 2]>`, a const generic default block that declares a struct) is consumed by its own delimiter and leaves the outer declaration pending, so the outer body still opens as typed fields. --- crates/xtask/src/names.rs | 63 ++++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 17 deletions(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index a40ea73a5c..0d86fb887e 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -819,9 +819,10 @@ struct Lexer<'s> { marker: Option<&'s str>, /// Open delimiters, the line of each, and what the fields or parameters in each are. delims: Vec<(char, usize, Fields)>, - /// The next `{` or `(` that declares fields or parameters, after a `struct`, `union`, `enum` or - /// `fn`. - declares: Option, + /// The declarations after a `struct`, `union`, `enum` or `fn` whose `{` or `(` of fields or + /// parameters has not opened yet, innermost last: a declaration in another's header + /// (`struct S`) is pending until its own delimiter opens, and the outer one after. + declares: Vec, test: Option, /// Whether the last token read, past whitespace and comments, is a word. after_word: bool, @@ -845,7 +846,7 @@ fn lex(source: &str, kinds: Literals, marker: Option<&str>) -> Result { // `union` is a keyword only before the union's name. let named = word != "union" || !self.word_at(self.skip_space(self.at)).is_empty(); let keyword = ["struct", "union", "enum", "fn"].into_iter().find(|&k| k == word); - // A `fn` type in a declaration's header (`struct S`) does not replace it. - let in_header = self.declares.is_some_and(|d| d.level == self.delims.len() && (d.angle > 0 || d.after_where)); - if let Some(keyword) = keyword.filter(|_| named && !in_header) { - self.declares = Some(Declares { level: self.delims.len(), keyword, angle: 0, after_where: false }); + // A `fn` type in a declaration's header (`struct S`, `struct S`) + // is pending on top of it, and its `(` opens before the declaration's fields. + if let Some(keyword) = keyword.filter(|_| named) { + self.declares.push(Declares { level: self.delims.len(), keyword, angle: 0, after_where: false }); } else if word == "where" - && let Some(declares) = &mut self.declares + && let Some(declares) = self.declares.last_mut() && declares.level == self.delims.len() { declares.after_where = true; @@ -1197,7 +1198,7 @@ impl Lexer<'_> { let arrow = c == '>' && self.at.checked_sub(1).and_then(|i| self.chars.get(i)) == Some(&'-'); let turbofish = c == '<' && self.prev == Some(':') && self.prev_prev == Some(':'); let level_now = self.delims.len(); - if let Some(declares) = &mut self.declares + if let Some(declares) = self.declares.last_mut() && declares.level == level_now && !arrow { @@ -1618,9 +1619,9 @@ impl Lexer<'_> { } } let level = self.delims.len(); - let fields = match self.declares { + let fields = match self.declares.last().copied() { Some(Declares { level: at, keyword, angle: 0, after_where }) if at == level && (c == '{' || (c == '(' && !after_where)) => { - self.declares = None; + self.declares.pop(); match (keyword, c) { ("enum", '{') => Fields::Variants, ("fn", _) | (_, '{') => Fields::Typed, @@ -1671,9 +1672,7 @@ impl Lexer<'_> { } self.at += 1; let depth = self.delims.len(); - if self.declares.is_some_and(|declares| declares.level > depth) { - self.declares = None; - } + self.declares.retain(|declares| declares.level <= depth); let ends = match self.test { Some(TestRegion::Item { level, opened, item, semi, block, .. }) => { let block_end = opened && depth == level && c == '}'; @@ -1719,8 +1718,9 @@ impl Lexer<'_> { /// arguments (`f::`) or in the parameters of a closure that starts it. fn item_end(&mut self, comma: bool) { // A unit struct (`struct S;`) declares no fields. - if !comma && self.declares.is_some_and(|declares| declares.level == self.delims.len()) { - self.declares = None; + if !comma { + let level = self.delims.len(); + self.declares.retain(|declares| declares.level < level); } if let Some(TestRegion::Item { level, opened, item, semi, angle, params, .. }) = self.test && level == self.delims.len() @@ -2442,6 +2442,35 @@ fn paths(#[cfg(test)] m::P(x): Pair>, q: Tag<{ "si assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six"]); } + #[test] + fn nested_function_pointer_types_keep_the_declaration() { + let source = r#"struct Nested { + #[cfg(test)] + field: Pair>, + live: Tag<{ "one".len() }>, +} +struct Boxed>(#[cfg(test)] Pair>, Tag<{ "two".len() }>); +enum Listed { + V { + #[cfg(test)] + field: Pair>, + live: Tag<{ "three".len() }>, + }, +} +struct Bounded where F: Into<(fn(u8),)> { + #[cfg(test)] + field: Pair>, + live: Tag<{ "four".len() }>, +} +struct Outer>, live: Tag<{ "five".len() }> } 0 }> { + #[cfg(test)] + field: Pair>, + live: Tag<{ "six".len() }>, +} +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six"]); + } + #[test] fn test_only_borrowed_closures_keep_their_parameter_commas() { let source = r#"fn arms(x: u8) { From a83685686a6c953799e3bc50c1e2e743a0709f9e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:23:22 -0800 Subject: [PATCH 37/47] craft-xtask: keep generic commas in test-only cast types An `as` in test-only code now starts a cast type that runs until a token a type does not hold. A `<` after a word in that type opens generic brackets, so a comma in `ptr as *const Pair`, in a qualified or generic path (`::Assoc`, `Pair::Assoc`) or in a function pointer's return type (`f as fn() -> Pair`) no longer ends the test-only code. A comparison after the cast's parentheses (`(a as u8) < b`) or after an operator (`a as u8 + a < b`) is still read as a comparison. --- crates/xtask/src/names.rs | 102 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 98 insertions(+), 4 deletions(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 0d86fb887e..f4c9c1c281 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -756,8 +756,21 @@ enum TestRegion { /// expression, or in the type after `typed` is set), or while `params` is set (between the `|`s /// of a closure that starts the expression). A `,` does not end it while `angle` or `params` is /// set either. `typed` is set at the `:` after the name of a field or the pattern of a parameter - /// (`name: Type`, `mut p: Type`). - Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool, pattern: bool, angle: usize, params: bool, typed: bool }, + /// (`name: Type`, `mut p: Type`), and `cast` at an `as` until the token that ends its type + /// (`ptr as *const Pair`). + Item { + level: usize, + start: usize, + opened: bool, + item: bool, + semi: bool, + block: bool, + pattern: bool, + angle: usize, + params: bool, + typed: bool, + cast: bool, + }, /// The rest of the module that `#![cfg(test)]` starts, at this delimiter depth. Inner { level: usize }, } @@ -776,6 +789,7 @@ impl TestRegion { angle: 0, params: false, typed: false, + cast: false, } } } @@ -886,6 +900,9 @@ impl Lexer<'_> { while let Some(c) = self.peek(0) { let begin = self.at; let token = !c.is_whitespace() && !(c == '/' && matches!(self.peek(1), Some('/' | '*'))); + if token { + self.cast_token(c); + } match c { '\n' => { self.line += 1; @@ -1115,6 +1132,13 @@ impl Lexer<'_> { } let word: String = self.chars.get(start..self.at).unwrap_or_default().iter().collect(); self.header_word(start, &word); + let level = self.delims.len(); + if word == "as" + && let Some(TestRegion::Item { level: at, item: false, angle: 0, cast, .. }) = &mut self.test + && *at == level + { + *cast = true; + } // `union` is a keyword only before the union's name. let named = word != "union" || !self.word_at(self.skip_space(self.at)).is_empty(); let keyword = ["struct", "union", "enum", "fn"].into_iter().find(|&k| k == word); @@ -1208,8 +1232,8 @@ impl Lexer<'_> { let tuple = self.delims.last().is_some_and(|&(_, _, fields)| fields == Fields::Tuple); let generic = c == '<' && match self.test { - Some(TestRegion::Item { level, start, item: false, angle: 0, typed, .. }) if level == level_now => { - self.operand_starts(start) || ((typed || tuple) && self.after_word && self.angle_closes()) + Some(TestRegion::Item { level, start, item: false, angle: 0, typed, cast, .. }) if level == level_now => { + self.operand_starts(start) || ((typed || tuple || cast) && self.after_word && self.angle_closes()) } _ => false, }; @@ -1232,6 +1256,25 @@ impl Lexer<'_> { self.code_start(start) == self.at || matches!(self.prev, Some('=' | '!' | '&' | '|' | '+' | '-' | '*' | '/' | '%' | '^' | ':')) } + /// Reads the token that starts with `c` at the current index against the type of a cast in + /// test-only code: outside its generic brackets and other delimiters, the type holds words (with + /// `::` and lifetimes), `&`, `*`, `(` and `[` after `as`, `const`, `mut`, `dyn` or `fn` (or + /// another of them), the `->` of a function pointer's return type, and `<` and the `>` that close + /// them, and any other token ends it. + fn cast_token(&mut self, c: char) { + let level = self.delims.len(); + let Some(TestRegion::Item { level: at, angle: 0, cast: true, .. }) = self.test else { return }; + if at != level { + return; + } + let prefix = !self.after_word || matches!(self.word_at(self.last_word).as_str(), "as" | "const" | "mut" | "dyn" | "fn"); + let arrow = (c == '-' && self.peek(1) == Some('>')) || (c == '>' && self.at.checked_sub(1).and_then(|i| self.chars.get(i)) == Some(&'-')); + let keeps = is_word(c) || arrow || matches!(c, ':' | '\'' | '<') || (matches!(c, '&' | '*' | '(' | '[') && prefix); + if !keeps && let Some(TestRegion::Item { cast, .. }) = &mut self.test { + *cast = false; + } + } + /// Whether the `<` at the current index has its `>` before a `;`, a `=>`, a closing delimiter of /// its level, or a string or `.` that a type does not hold. Whitespace, comments, groups in /// delimiters and character literals are passed over whole. @@ -2471,6 +2514,57 @@ struct Outer ptr as *const Pair>, + #[cfg(test)] + 1 => ptr as Pair>, + #[cfg(test)] + 2 => ptr as &'static dyn Foo>, + #[cfg(test)] + 3 => ptr as ::std::ptr::NonNull>, + #[cfg(test)] + 4 => ptr as *mut m::Pair>, + #[cfg(test)] + 6 => ptr as *const ::Assoc>, + #[cfg(test)] + 7 => ptr as >::Assoc>, + #[cfg(test)] + 8 => ptr as m::Pair u8>::Assoc>, + #[cfg(test)] + 9 => ptr as Vec::::Assoc>, + #[cfg(test)] + 10 => ptr as Pair<{ 1 > 0 }>::Assoc>, + #[cfg(test)] + 11 => ptr as m::r#Pair::Assoc>, + #[cfg(test)] + 12 => ptr as /* type */ Pair>, + #[cfg(test)] + 13 => f as fn() -> Pair>, + #[cfg(test)] + 14 => f as unsafe fn(u8, &[u8]) -> &'static Pair>, + #[cfg(test)] + 15 => f as fn() -> (u8, Pair), + #[cfg(test)] + 16 => f as fn() -> m::Pair>, + #[cfg(test)] + 5 => a < b, + _ => "one", + } + call(#[cfg(test)] (a as u8) < b, "two"); + call(#[cfg(test)] a < b, "three"); + call(#[cfg(test)] a as u8 + a < b, "four"); + call(#[cfg(test)] a as u8 > b && a < b, "five"); + call(#[cfg(test)] a as u8 == b || a < b, "six"); + call(#[cfg(test)] a as u8 - b < b, "seven"); +} +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six", "seven"]); + } + #[test] fn test_only_borrowed_closures_keep_their_parameter_commas() { let source = r#"fn arms(x: u8) { From 3641b5c8bc09f52ebc699c21b63d2ffb0a312e79 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:24:46 -0800 Subject: [PATCH 38/47] craft-xtask: keep a declaration pending across a macro in its header A `{` or `(` right after a macro's `!` in a struct, union or enum header (`struct S where ty!{}: Copy { .. }`) is the macro's group, not the declaration's fields. The declaration stays pending until its own body brace, so the body still opens as typed fields. --- crates/xtask/src/names.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index f4c9c1c281..3eec539238 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -1662,8 +1662,12 @@ impl Lexer<'_> { } } let level = self.delims.len(); + // A macro's delimiters in the header (`struct S where ty!{}: Copy { .. }`) are not the + // fields; the declaration stays pending across them. let fields = match self.declares.last().copied() { - Some(Declares { level: at, keyword, angle: 0, after_where }) if at == level && (c == '{' || (c == '(' && !after_where)) => { + Some(Declares { level: at, keyword, angle: 0, after_where }) + if at == level && !self.after_bang && (c == '{' || (c == '(' && !after_where)) => + { self.declares.pop(); match (keyword, c) { ("enum", '{') => Fields::Variants, @@ -2514,6 +2518,30 @@ struct Outer>, + live: Tag<{ "one".len() }>, +} +enum E where m::ty! { u8 }: Copy, F: Fn(u8, u16) { + V { + #[cfg(test)] + field: Pair>, + live: Tag<{ "two".len() }>, + }, +} +union U where ty! {}: Copy { + #[cfg(test)] + field: Pair>, + live: Tag<{ "three".len() }>, +} +fn f() where ty!{}: Copy { let _ = S { #[cfg(test)] probe: a < b, live: "four" }; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four"]); + } + #[test] fn test_only_cast_types_keep_their_generic_commas() { let source = r#"fn arms(x: u8, a: u8, b: u8, ptr: *const u8) { From 6f34164a3704599fa1d40a5873408f01b77e8551 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:32:34 -0800 Subject: [PATCH 39/47] craft-xtask: read enum discriminants as expressions A `=` among an enum's variants starts a discriminant that runs to the next `,`, and its `( .. )` and `{ .. }` are an expression's, so a call such as `V = f(..)` is no longer read as a tuple variant's fields. A `(` after a path, a method or an operator is not a variant's either, which covers a discriminant whose generic arguments hold a comma (`V = m::f::::call(..)`). Variants named by a macro's `$name` or after repeated macro attributes keep their fields. --- crates/xtask/src/names.rs | 62 ++++++++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 7 deletions(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 3eec539238..caa2ac585a 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -810,6 +810,9 @@ enum Fields { Tuple, /// An enum's variants, whose `{ .. }` and `( .. )` hold typed fields. Variants, + /// An enum's variants, in the discriminant (`V = f(..)`) that runs from a variant's `=` to the + /// next `,`: its delimiters are an expression's. + Discriminant, } /// A declaration whose fields or parameters have not opened yet. @@ -1200,10 +1203,16 @@ impl Lexer<'_> { } } - /// A `=` that is not part of `==`, `!=`, `<=`, `>=` or `..=` ends a `let` pattern. + /// A `=` that is not part of `==`, `!=`, `<=`, `>=` or `..=` ends a `let` pattern, and among an + /// enum's variants starts a discriminant. fn equals(&mut self) { let before = self.at.checked_sub(1).and_then(|i| self.chars.get(i)).copied(); let compares = matches!(before, Some('=' | '!' | '<' | '>' | '.')) || self.peek(1) == Some('='); + if let Some((_, _, fields @ Fields::Variants)) = self.delims.last_mut() + && !compares + { + *fields = Fields::Discriminant; + } if let Some(TestRegion::Item { level, pattern, .. }) = &mut self.test && *level == self.delims.len() && !compares @@ -1675,12 +1684,19 @@ impl Lexer<'_> { _ => Fields::Tuple, } } - // A variant's `{ .. }` or `( .. )` after its name. - _ if self.after_word && self.delims.last().is_some_and(|&(_, _, fields)| fields == Fields::Variants) => match c { - '{' => Fields::Typed, - '(' => Fields::Tuple, - _ => Fields::Untyped, - }, + // A variant's `{ .. }` or `( .. )` after its name, not in its discriminant, and not after + // a path, a method or an operator (`m::f::::call(..)` after a comma in the + // discriminant's generic arguments). + _ if self.after_word + && !matches!(self.prev_prev, Some(':' | '.' | '=' | '+' | '-' | '/' | '%' | '&' | '|' | '^' | '<' | '>')) + && self.delims.last().is_some_and(|&(_, _, fields)| fields == Fields::Variants) => + { + match c { + '{' => Fields::Typed, + '(' => Fields::Tuple, + _ => Fields::Untyped, + } + } _ => Fields::Untyped, }; self.delims.push((c, self.line, fields)); @@ -1769,6 +1785,12 @@ impl Lexer<'_> { let level = self.delims.len(); self.declares.retain(|declares| declares.level < level); } + // A `,` among an enum's variants ends a discriminant. + if let Some((_, _, fields @ Fields::Discriminant)) = self.delims.last_mut() + && comma + { + *fields = Fields::Variants; + } if let Some(TestRegion::Item { level, opened, item, semi, angle, params, .. }) = self.test && level == self.delims.len() && if comma { level > 0 && !item && angle == 0 && !params } else { !item || !opened || semi } @@ -2542,6 +2564,32 @@ fn f() where ty!{}: Copy { let _ = S { #[cfg(test)] probe: a < b, live: "four" } assert_eq!(literals(source), ["one", "two", "three", "four"]); } + #[test] + fn enum_discriminants_are_expressions() { + let source = r#"enum E { + V = f(#[cfg(test)] if 1 < 2 { true } else { false }, live("one") > 0), + W = m::f(#[cfg(test)] a < b, live("two") > 0), + X = g(1)(#[cfg(test)] a < b, live("three") > 0), + T = m::f::::call(#[cfg(test)] a < b, live("ten") > 0), + S = >::call(#[cfg(test)] a < b, live("eleven") > 0), + #[doc = "four"] + Y(#[cfg(test)] Pair>, Tag<{ "five".len() }>), + Z { #[cfg(test)] field: Pair>, live: Tag<{ "six".len() }> }, +} +macro_rules! variants { + ($a:ident, $b:ident, $c:ident) => { + enum M { + $a = f(#[cfg(test)] a < b, live("seven") > 0), + $b(#[cfg(test)] Pair>, Tag<{ "eight".len() }>), + $c { #[cfg(test)] field: Pair>, live: Tag<{ "nine".len() }> }, + $(#[$meta])* V(#[cfg(test)] Pair>, Tag<{ "twelve".len() }>), + } + }; +} +"#; + assert_eq!(literals(source), ["one", "two", "three", "ten", "eleven", "four", "five", "six", "seven", "eight", "nine", "twelve"]); + } + #[test] fn test_only_cast_types_keep_their_generic_commas() { let source = r#"fn arms(x: u8, a: u8, b: u8, ptr: *const u8) { From f84b8eec3dccaca9c4e8cc873616535bfa4c4060 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:34:27 -0800 Subject: [PATCH 40/47] craft-xtask: resolve each input once before it is listed Each input is now joined to the base, or a Windows drive-relative input (`C:src`) to the current folder of its drive, before its folder is listed. The listing and the reads use that path, and findings keep the input's spelling, so a change of the drive's current folder during the walk does not change which files are read. --- crates/xtask/src/names.rs | 53 ++++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index caa2ac585a..9f507d1d1e 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -294,8 +294,9 @@ impl From for String { /// /// A file is identified by its path joined to `base`, and a relative `base` is joined to the /// current folder (on Windows, a drive-relative `base` such as `C:src` to the current folder of -/// its drive) before any input is listed. A drive-relative input (`C:a.rs`) is joined to the -/// current folder of its drive instead. A relative and an absolute path to a file are one file, +/// its drive) before any input is listed. A drive-relative input (`C:a.rs`, `C:src`) is joined to +/// the current folder of its drive instead, once, before it is listed, and the files of a folder +/// input are opened under that path. A relative and an absolute path to a file are one file, /// read once and reported by the input path that sorts first; `..` and links are not resolved. /// /// A [`Kind::Rust`] folder is read recursively for `.rs` files that [`Policy::skip`] keeps; links to @@ -306,16 +307,17 @@ pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result, Error>>()?; files.sort(); files.dedup_by(|later, first| later.0 == first.0 && later.1 == first.1); if let Some(pair) = files.windows(2).find(|pair| pair[0].0 == pair[1].0) { @@ -648,39 +650,43 @@ fn io_error(path: &Path) -> impl FnOnce(io::Error) -> Error + '_ { move |source| Error::Io { path: path.to_path_buf(), source } } -fn collect_rust(base: &Path, path: &Path, policy: &Policy<'_>, out: &mut Vec<(PathBuf, Kind)>) -> Result<(), Error> { - let full = base.join(path); +/// The Rust files of the input `path` under the absolute `root`: the path that is opened, the kind, +/// and the path that is reported. `path` is resolved once, so the folder that is listed is the +/// folder whose files are read. +fn collect_rust(root: &Path, path: &Path, policy: &Policy<'_>, out: &mut Vec<(PathBuf, Kind, PathBuf)>) -> Result<(), Error> { + let full = input_path(root, path)?; let link = fs::symlink_metadata(&full).map_err(io_error(path))?.file_type().is_symlink(); let meta = fs::metadata(&full).map_err(io_error(path))?; if meta.is_dir() { // A link to a folder is not followed, also when it is an input. - if link { Ok(()) } else { walk(base, path, path, policy, 0, out) } + if link { Ok(()) } else { walk(&full, path, path, policy, 0, out) } } else { - out.push((path.to_path_buf(), Kind::Rust)); + out.push((full, Kind::Rust, path.to_path_buf())); Ok(()) } } -fn walk(base: &Path, input: &Path, dir: &Path, policy: &Policy<'_>, depth: usize, out: &mut Vec<(PathBuf, Kind)>) -> Result<(), Error> { +/// The Rust files in the folder `full`, which is reported as `dir`, under the input `input`. +fn walk(full: &Path, input: &Path, dir: &Path, policy: &Policy<'_>, depth: usize, out: &mut Vec<(PathBuf, Kind, PathBuf)>) -> Result<(), Error> { if depth > policy.limits.max_depth { return Err(Error::TooDeep { path: dir.to_path_buf(), limit: policy.limits.max_depth }); } - let mut entries = fs::read_dir(base.join(dir)).and_then(|entries| entries.collect::>>()).map_err(io_error(dir))?; + let mut entries = fs::read_dir(full).and_then(|entries| entries.collect::>>()).map_err(io_error(dir))?; entries.sort_by_key(fs::DirEntry::file_name); for entry in entries { - let path = dir.join(entry.file_name()); + let (opened, path) = (full.join(entry.file_name()), dir.join(entry.file_name())); let file_type = entry.file_type().map_err(io_error(&path))?; if file_type.is_dir() { - walk(base, input, &path, policy, depth + 1, out)?; + walk(&opened, input, &path, policy, depth + 1, out)?; continue; } if !path.extension().is_some_and(|ext| ext == "rs") || (policy.skip)(path.strip_prefix(input).unwrap_or(&path)) { continue; } // A link to a folder is not followed; a link to a file is read like the file. - let is_file = if file_type.is_symlink() { fs::metadata(base.join(&path)).map_err(io_error(&path))?.is_file() } else { file_type.is_file() }; + let is_file = if file_type.is_symlink() { fs::metadata(&opened).map_err(io_error(&path))?.is_file() } else { file_type.is_file() }; if is_file { - out.push((path, Kind::Rust)); + out.push((opened, Kind::Rust, path)); } } Ok(()) @@ -2847,6 +2853,25 @@ fn seven() { let _ = "seven"; } } } + #[cfg(windows)] + #[test] + fn a_drive_relative_rust_folder_is_resolved_before_it_is_listed() { + let current = std::env::current_dir().unwrap(); + let Some(Component::Prefix(drive)) = current.components().next() else { panic!("no drive in {}", current.display()) }; + let mut spelled = drive.as_os_str().to_os_string(); + spelled.push("src"); + let input = PathBuf::from(spelled); + let mut files = Vec::new(); + collect_rust(¤t, &input, &POLICY, &mut files).unwrap(); + assert!(!files.is_empty()); + for (opened, kind, path) in &files { + assert_eq!(*kind, Kind::Rust); + // The file is opened by the path that was listed, and reported by the input's spelling. + let rest = path.strip_prefix(&input).unwrap(); + assert_eq!(opened, ¤t.join("src").join(rest), "{}", path.display()); + } + } + #[test] fn the_total_budget_is_checked_before_reading() { let dir = tempfile::tempdir().unwrap(); From 08c0d99732f291e8dc53d13d9e871e07fdf74442 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:35:40 -0800 Subject: [PATCH 41/47] craft-xtask: describe parameter, cast and drive-relative input rules The README and the `literals` docs now say that a comma in the type of a parameter after its pattern, or of a cast, does not end test-only code, and that a drive-relative input is resolved once before it is listed. --- crates/xtask/README.md | 8 +++++--- crates/xtask/src/names.rs | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 95394832a7..982ee0ec28 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -107,8 +107,9 @@ fn production_display_names_stay_neutral() { So is the code under `#[cfg(test)]`, comments in the attribute included: a `const`, `static` or `let` up to its `;`, another item up to the `}` that closes it or the `;` that ends it, and a field, argument, arm or statement up to its `,` or `;`. A `,` in an expression's generic - arguments (`f::`) or in the parameters of a closure that starts the expression does not - end it. An item keyword counts only when nothing + arguments (`f::`), in the type of a field, a parameter (after its name or pattern) or a + cast (`mut p: Pair`, `ptr as *const Pair`), or in the parameters of a closure that + starts the expression does not end it. An item keyword counts only when nothing but qualifiers (`pub`, `unsafe`, `extern "C"` and the like) comes before it, so the `fn` in `f::(…)` or in a field's type does not start an item, and the braces of a macro in an item's header (`-> ty! { u8 }`) are not its body. A block expression (a block, a macro's braces, a labeled block, or @@ -128,7 +129,8 @@ fn production_display_names_stay_neutral() { - `scan` identifies a file by its input path joined to the base folder, and joins a relative base folder to the current folder before it lists any input (on Windows, a drive-relative base such as `C:src` to the current folder of its drive), so a relative and an absolute input for one file are - read once; `..` and links are not resolved. + read once; `..` and links are not resolved. A drive-relative input is joined to the current + folder of its drive once, before it is listed, and its files are opened under that path. - `scan` reads each file once, in path order, and returns the findings in path order, then source order, then the order of `banned`. A `Finding` has the path, the first line of the literal or description, the word, the decoded text or text line and the kind; its `Display` text is diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 9f507d1d1e..0f05da1e85 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -597,8 +597,9 @@ pub struct Literal { /// Test-only code is the code under `#[cfg(test)]` and the rest of a module that starts with /// `#![cfg(test)]`. Under `#[cfg(test)]`, a `const`, `static` or `let` runs up to its `;`, another /// item up to its closing `}` or its `;`, and a field, argument, arm or statement up to its `,` or -/// `;`; a `,` in generic arguments (`f::`, ` as Fixture>::LABEL`, or a field's -/// `field: Pair`) or in the parameters of a closure that starts the expression (after any +/// `;`; a `,` in generic arguments (`f::`, ` as Fixture>::LABEL`, a field's +/// `field: Pair`, a parameter's `mut p: Pair`, or a cast's `ptr as *const Pair`) +/// or in the parameters of a closure that starts the expression (after any /// `move` or `&`) does not end it. A raw identifier (`r#let`) is never a keyword. A block expression (a block, a macro's braces, a /// labeled block, or `if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the /// whole statement or as an arm's expression after `=>`, ends at its `}`, or at the last `}` of an From 994d03d02f3396d88c5536f2665093f5790f59d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:17:10 -0800 Subject: [PATCH 42/47] craft-xtask: drop only the out-of-scope pending declarations Pending declarations are kept innermost last, so a closing delimiter or an item's end now pops the ones above the current depth from the end instead of scanning the whole list. A source with 200,000 pending `fn`s and 200,000 `[]` groups took 216 s in a debug test before and reads at once now. --- crates/xtask/src/names.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index 0f05da1e85..5cd3d65c77 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -1742,7 +1742,10 @@ impl Lexer<'_> { } self.at += 1; let depth = self.delims.len(); - self.declares.retain(|declares| declares.level <= depth); + // `declares` is in ascending order of level, so the ones out of scope are at its end. + while self.declares.last().is_some_and(|declares| declares.level > depth) { + self.declares.pop(); + } let ends = match self.test { Some(TestRegion::Item { level, opened, item, semi, block, .. }) => { let block_end = opened && depth == level && c == '}'; @@ -1790,7 +1793,9 @@ impl Lexer<'_> { // A unit struct (`struct S;`) declares no fields. if !comma { let level = self.delims.len(); - self.declares.retain(|declares| declares.level < level); + while self.declares.last().is_some_and(|declares| declares.level >= level) { + self.declares.pop(); + } } // A `,` among an enum's variants ends a discriminant. if let Some((_, _, fields @ Fields::Discriminant)) = self.delims.last_mut() @@ -2518,6 +2523,15 @@ fn paths(#[cfg(test)] m::P(x): Pair>, q: Tag<{ "si assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six"]); } + #[test] + fn closing_delimiters_keep_pending_declarations_in_linear_time() { + // 200,000 pending `fn`s and 200,000 `[]` groups: scanning every pending declaration at + // each `]` makes 4 * 10^10 comparisons, which takes minutes. + let count = 200_000; + let source = format!("m! {{ {}{}}} \"done\"", "fn ".repeat(count), "[] ".repeat(count)); + assert_eq!(literals(&source), ["done"]); + } + #[test] fn nested_function_pointer_types_keep_the_declaration() { let source = r#"struct Nested { From f825dd1b3f158a79485c7899710f75a46de34349 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:27:25 -0800 Subject: [PATCH 43/47] craft-testkit: font tests join the crate's one test binary tests/fonts.rs moves to tests/it/fonts.rs and tests/it/main.rs adds it as a module, so craft-testkit keeps a single integration test binary. --- crates/testkit/tests/{ => it}/fonts.rs | 0 crates/testkit/tests/it/main.rs | 1 + 2 files changed, 1 insertion(+) rename crates/testkit/tests/{ => it}/fonts.rs (100%) diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/it/fonts.rs similarity index 100% rename from crates/testkit/tests/fonts.rs rename to crates/testkit/tests/it/fonts.rs diff --git a/crates/testkit/tests/it/main.rs b/crates/testkit/tests/it/main.rs index f686c5c39d..6d0f5f8080 100644 --- a/crates/testkit/tests/it/main.rs +++ b/crates/testkit/tests/it/main.rs @@ -1,4 +1,5 @@ //! The crate's integration tests, linked into one test binary. +mod fonts; mod guards; mod source_limits; From 2e8fef56dd3a78a8b09229e04d057ccbafba522d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:37:14 -0800 Subject: [PATCH 44/47] craft-gpu-yuv: take wgpu from the workspace The crate depended on `wgpu = "30"`, which turned on all of wgpu's default backends in every crate that depends on it. It now uses the workspace wgpu (`std` and `wgsl`). The native backends are enabled in a non-wasm32 dev-dependency so the crate's device tests can still open an adapter. --- crates/gpu-yuv/Cargo.toml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml index ddf2fa6cc2..28053d83b1 100644 --- a/crates/gpu-yuv/Cargo.toml +++ b/crates/gpu-yuv/Cargo.toml @@ -12,11 +12,16 @@ workspace = true [dependencies] craft-gpu = { workspace = true } -wgpu = "30" +wgpu = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = { workspace = true } +# The device tests (src/tests.rs) open a native adapter. The backends are on for this crate's own +# tests only; crates that depend on craft-gpu-yuv get the workspace wgpu with `std` and `wgsl`. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +wgpu = { workspace = true, features = ["dx12", "metal", "vulkan", "gles"] } + [dev-dependencies] craft-gpu-null = { workspace = true } pollster = { workspace = true } From 0265dd5f52bd4a84ce3e74aad18d73d175b51e29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:15:05 -0800 Subject: [PATCH 45/47] Testkit: an empty table inside name or head no longer fails rename_family The overlap check treated a table of length 0 whose offset points inside the name or head table as sharing bytes, so rename_family returned MalformedFont for a valid face. An overlap now needs at least one shared byte. Nonempty overlapping tables are still refused. --- crates/testkit/src/fonts.rs | 5 +++-- crates/testkit/tests/it/fonts.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index cfc3096a0c..6c7ab56bca 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -201,10 +201,11 @@ fn table_count(face: &[u8]) -> Result { Ok(usize::from(u16_at(face, 4)?)) } -/// Whether `table` shares bytes with the table directory or with another table of the face. +/// Whether `table` shares bytes with the table directory or with another table of the face. Another +/// table of length 0 shares no bytes, wherever its offset points. fn shares_bytes(tables: &[Table], table: &Table) -> bool { let end = table.offset + table.length; - let overlaps = |start: usize, other_end: usize| start < end && table.offset < other_end; + let overlaps = |start: usize, other_end: usize| start < other_end && start < end && table.offset < other_end; overlaps(0, SFNT_HEADER + tables.len() * TABLE_RECORD) || tables.iter().any(|other| other.record != table.record && overlaps(other.offset, other.offset + other.length)) } diff --git a/crates/testkit/tests/it/fonts.rs b/crates/testkit/tests/it/fonts.rs index 56e20b79ac..b3eb2ff5bc 100644 --- a/crates/testkit/tests/it/fonts.rs +++ b/crates/testkit/tests/it/fonts.rs @@ -420,6 +420,20 @@ fn rename_rejects_name_table_sharing_bytes() { assert_eq!(rename_family(&under_head, FROM, TO), Err(FontError::MalformedFont), "checkSumAdjustment would land in zzzz"); } +#[test] +fn rename_accepts_an_empty_table_inside_name_or_head() { + let font = face(&[(b"head", head()), (b"name", names(&[win(1, FROM)])), (b"zzzz", vec![7; 8])]); + let (record, _, _) = table(&font, b"zzzz"); + let (_, name_at, _) = table(&font, b"name"); + let (_, head_at, _) = table(&font, b"head"); + for inside in [name_at + 18, head_at + 8] { + let mut empty = font.clone(); + set32(&mut empty, record + 8, inside as u32); + set32(&mut empty, record + 12, 0); + assert!(rename_family(&empty, FROM, TO).is_ok(), "an empty table at {inside} shares no bytes"); + } +} + #[test] fn rename_rejects_unknown_name_format() { let font = family_face(&[win(1, FROM)]); From 7aa08eb5d8cf849b002d76cec8d618d5e0e049c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:55:23 -0800 Subject: [PATCH 46/47] audio-dsp: preserve resonator state on empty blocks --- crates/audio-dsp/src/effects/character.rs | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index 3b1b0597b9..993fd2bf1a 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -153,6 +153,9 @@ impl AudioEffect for RingMod { } fn process(&mut self, channels: &mut [&mut [f32]]) { let n = block_len(channels); + if n == 0 { + return; + } let nch = channels.len().min(self.lines.len()); let effect = self.pv.idx("effect"); if effect != self.effect { @@ -365,6 +368,27 @@ mod tests { } } + #[test] + fn an_empty_block_keeps_the_resonator_ring() { + let p = [("effect", 2.0), ("frequency", 500.0), ("resonance", 80.0)]; + let (mut r, mut still) = (ring(&p, 1), ring(&p, 1)); + for f in [&mut r, &mut still] { + let mut x = vec![0.0f32; 50]; + x[10] = 1.0; + f.process(&mut [&mut x]); + } + assert!(r.set_param("effect", 0.0)); + let mut empty: [f32; 0] = []; + r.process(&mut [&mut empty[..]]); + r.process(&mut []); + assert!(r.set_param("effect", 2.0)); + let (mut a, mut b) = (vec![0.0f32; 500], vec![0.0f32; 500]); + r.process(&mut [&mut a]); + still.process(&mut [&mut b]); + assert!(rms(&b) > 1e-3, "the ring has already died out"); + assert_eq!(a, b); + } + /// Frequency Mod delays the input by 2 samples to 2 samples plus 2 ms, swinging across the /// whole range at the carrier's rate. #[test] From bd410233d39207d6e1dabce2f00a4b6ed8c0333c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:22:37 -0800 Subject: [PATCH 47/47] audio-dsp: preserve held samples and order mute resets --- crates/audio-dsp/src/effects/character.rs | 10 +++++- crates/audio-dsp/src/effects/suppress.rs | 38 ++++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index 431cc66811..6bc52eeb3e 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -315,7 +315,7 @@ impl AudioEffect for Bitcrusher { // The held input is rounded at the current step, so a change of Bits also // applies to the hold in progress. let crushed = ((f64::from(*held) / step).round() * step).clamp(-limit, limit); - channels[ch][i] = (dry + mix * (crushed - dry)) as f32; + channels[ch][i] = blend(dry, crushed, mix) as f32; } } } @@ -642,6 +642,14 @@ mod tests { } } + #[test] + fn full_mix_keeps_a_small_wet_sample_beside_a_huge_dry_one() { + let mut c = crush(&[("mix", 100.0), ("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut y = vec![0.5, f32::MAX, f32::MAX, f32::MAX, 0.25]; + c.process(&mut [&mut y]); + assert_eq!(y[1], 0.5, "the held sample was lost at full mix: {y:?}"); + } + /// A shorter rate divide cuts the hold in progress short, and the holds after it have the new /// length from the first one on. #[test] diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index 6476b74c4e..9c4a8ed1d6 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -105,6 +105,10 @@ struct Bins { /// Total power of each waiting frame, and whether it may enter the estimate. queue_total: [f32; OVERLAP], queue_ok: [bool; OVERLAP], + /// Whether a mute began between a waiting frame and the one before it. + queue_cut: [bool; OVERLAP], + /// Whether a mute began since the last frame was queued. + cut_pending: bool, head: usize, queued: usize, /// Whether a frame has entered the estimate since the last reset. @@ -144,6 +148,8 @@ impl Bins { queue: vec![0.0; bins * OVERLAP], queue_total: [0.0; OVERLAP], queue_ok: [false; OVERLAP], + queue_cut: [false; OVERLAP], + cut_pending: false, head: 0, queued: 0, started: false, @@ -170,6 +176,7 @@ impl Bins { self.frames = 0; self.head = 0; self.queued = 0; + self.cut_pending = false; self.started = false; self.heard = 0; self.since_zero = 1; @@ -196,7 +203,7 @@ impl Bins { if self.queued > 0 && self.since_frame < hop { self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; } - self.quiet_run = 0; + self.cut_pending = true; } self.since_mute = 0; } @@ -214,6 +221,9 @@ impl Bins { let at = self.head; self.head = (at + 1) % OVERLAP; self.queued -= 1; + if self.queue_cut[at] { + self.quiet_run = 0; + } if !self.queue_ok[at] { return; } @@ -260,6 +270,7 @@ impl Bins { // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between // two hops. A quiet run ends here too. self.queued = 0; + self.cut_pending = false; self.since_zero = 0; self.quiet_run = 0; } else { @@ -272,6 +283,7 @@ impl Bins { self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; } self.queue_total[at] = total; + self.queue_cut[at] = std::mem::take(&mut self.cut_pending); // A frame holds the last STFT size of samples, `2 * (bins - 1)`. self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); self.queued += 1; @@ -498,6 +510,7 @@ mod tests { let mut out = [vec![0.0f32; speech.len()], vec![0.0f32; speech.len()], vec![0.0f32; speech.len()]]; for i in 0..speech.len() { let x = [speech[i] + noise[i], speech[i], noise[i]]; + bins.sample(x[0], hop); for (lane, (st, o)) in lanes.iter_mut().zip(out.iter_mut()).enumerate() { o[i] = st.tick(x[lane], hop, &mut |input, frame_out| { spec.analyze(input); @@ -776,6 +789,29 @@ mod tests { assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); } + #[test] + fn a_short_mute_ends_the_queued_quiet_run() { + for offset in [0, 17] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut loud = white(47, SR as usize * 2, 0.05); + s.process(&mut [&mut loud]); + let mut quiet = white(51, 20 * hop + offset, 0.0005); + s.process(&mut [&mut quiet]); + assert!(s.bins[0].quiet_run > 0); + let mute_end = loud.len() + quiet.len() + hop; + let first_clean_frame = (mute_end + n).div_ceil(hop); + let commit_end = (first_clean_frame + OVERLAP) * hop; + let mut after = white(53, commit_end - loud.len() - quiet.len(), 0.0005); + after[..hop].fill(0.0); + let before_mute = s.bins[0].quiet_run; + s.process(&mut [&mut after[..hop]]); + assert_eq!(s.bins[0].quiet_run, before_mute + 1, "offset {offset}: queued pre-mute frames lost their quiet run"); + s.process(&mut [&mut after[hop..]]); + assert_eq!(s.bins[0].quiet_run, 1, "offset {offset}: pre-mute quiet frames contributed to the new run"); + } + } + /// A voice that starts with the stream keeps its level within 3 dB over its first 0.25 s and /// its first 1.5 s, while the suppressor has no noise estimate yet. One of the voices starts on /// its first sample with a vowel held for 0.25 s.