diff --git a/Cargo.lock b/Cargo.lock index c889f8256b..49cd102685 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1823,6 +1823,7 @@ dependencies = [ "craft-gpu-null", "craft-gpu-providers", "craft-gpu-wgpu", + "craft-gpu-yuv", "craft-gridcraft-format", "craft-gzip", "craft-har", @@ -2960,6 +2961,17 @@ dependencies = [ "wgpu", ] +[[package]] +name = "craft-gpu-yuv" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-null", + "pollster 0.4.0", + "wgpu", + "yuv", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" @@ -3595,6 +3607,9 @@ version = "0.1.0" name = "craft-pbr" version = "0.1.0" dependencies = [ + "craft-materialx", + "craft-mesh", + "craft-pbr", "craft-texture", "glam 0.30.10", "naga", @@ -4319,8 +4334,11 @@ version = "0.1.0" dependencies = [ "libc", "rustix 1.1.6", + "serde_json", "sha2 0.10.9", "skrifa 0.47.0", + "tempfile", + "toml", ] [[package]] @@ -4354,8 +4372,12 @@ name = "craft-texture" version = "0.1.0" dependencies = [ "bytemuck", + "craft-exr", + "craft-hdr", + "craft-image-codecs", "dds", "half", + "png 0.18.1", "rayon", "thiserror 2.0.21", ] @@ -4957,10 +4979,14 @@ name = "craft-xtask" version = "0.1.0" dependencies = [ "craft-atomic", + "flate2", "libc", "serde_json", + "sha2 0.10.9", + "tar", "tempfile", "toml_edit", + "unicode-normalization", ] [[package]] @@ -15061,6 +15087,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/Cargo.toml b/Cargo.toml index 399345661a..d8c95f5cbf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ log = "0.4" craft-plist = { path = "crates/plist" } craft-gpu-device = { path = "crates/gpu-device" } craft-wasm = { path = "crates/wasm" } +craft-gpu-yuv = { path = "crates/gpu-yuv" } craft-platform = { path = "crates/platform" } craft-png = { path = "crates/png" } craft-aep = { path = "crates/aep" } diff --git a/NOTICE b/NOTICE index d474937863..f84ffba17c 100644 --- a/NOTICE +++ b/NOTICE @@ -288,11 +288,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs, -src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its -manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman +as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local -patches and the files left out. +changes and the files left out. kurbo diff --git a/README.md b/README.md index af82eafac8..8bdff6f63e 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target). - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. -- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. +- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from @@ -211,6 +211,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): 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-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto, low power, a named adapter that survives a reordered list and a driver update, or software; corrections for drivers that crash; the next adapter and then a software one when a device fails @@ -417,15 +423,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit reference picking, selection statistics, error tags and filter buttons (`ui` feature). - [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals - out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test - whose body runs past a limit, or whose condition does not hold in time; a variable the caller names - replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged - copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng` - module holds two seeded generators for repeatable test input. Its `skip` module prints a `SKIPPED:` - line when a test lacks a program, a corpus or the craft-fonts faces, or fails the test when the - variable the caller names is `1`. Any other value of that variable except empty fails the test as a - configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder against a - pinned SHA-256 list. Not published. + out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts + from font bytes the caller supplies: a face with a renamed family and a TrueType collection. Its + `deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time; + a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation + and on seeded damaged copies of a valid input, and fails the test with the case that panicked or did + not finish. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module + prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the + test when the variable the caller names is `1`. Any other value of that variable except empty fails + the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder + against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures + under `target/fixtures` and publishes each one under a lock. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and @@ -433,8 +441,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit (ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find` (regex) are features. - [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with - nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are - bounded by `Limits`. From MaterialCraft. + nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and + (optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float + samples. Sizes are bounded by `Limits`. From MaterialCraft. - [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates, timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE, CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel, diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index 5aa1811309..48daa625b1 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -19,7 +19,12 @@ 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, + or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato + that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds + no latency either: the delay is 0 at the start of each cycle, except while it glides to new + settings. - `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 e8acfdb18e..0ea9055b1f 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, Tremolo, Vibrato}; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -151,6 +151,8 @@ static REGISTRY: &[EffectInfo] = &[ entry!("flanger", "Flanger", Modulation, Flanger), entry!("phaser", "Phaser", Modulation, Phaser), entry!("ring_mod", "Ring Modulator", Modulation, RingMod), + entry!("tremolo", "Tremolo", Modulation, Tremolo), + entry!("vibrato", "Vibrato", Modulation, Vibrato), entry!("analog_delay", "Analog Delay", Time, AnalogDelay), entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay), entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb), @@ -158,6 +160,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 fc83ffbeec..6433aa26c7 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -991,6 +991,9 @@ fn direct_constructors_cap_the_channel_count() { voice::VoiceFormant, suppress::NoiseSuppression, character::RingMod, + character::Bitcrusher, + character::Tremolo, + character::Vibrato, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index 5a67d4a354..eb623f0870 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -14,8 +14,18 @@ //! 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. +//! +//! The tremolo (`tremolo`) lowers the gain of every channel by up to `depth` once per cycle of a +//! sine, triangle or square LFO at `rate`. +//! +//! The vibrato (`vibrato`) reads the input through a delay that grows from 0 and shrinks back once +//! per cycle of a sine or triangle LFO at `rate`, so the pitch swings by up to `depth` cents. While +//! no glide to new settings is in progress, the delay is 0 at the start of each cycle. -use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail}; +use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail, uni_sine, uni_tri}; use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; use std::f64::consts::TAU; @@ -39,6 +49,16 @@ const FM_BASE: f32 = 2.0; const SEED: u64 = 0x5EED_1234; /// Highest frequency the modulation reaches, as a fraction of the sample rate. const MAX_FRACTION: f32 = 0.45; +const TREMOLO_SHAPES: &[&str] = &["Sine", "Triangle", "Square"]; +/// Length of each edge of the tremolo's square, in ms. +const EDGE_MS: f64 = 2.0; +const VIBRATO_SHAPES: &[&str] = &["Sine", "Triangle"]; +/// Lowest rate of the vibrato, in Hz. +const VIBRATO_MIN_RATE: f32 = 1.0; +/// Greatest depth of the vibrato, in cents. +const VIBRATO_MAX_CENTS: f32 = 100.0; +/// Most the vibrato's glide moves the delay per sample on top of the curve. +const VIBRATO_GLIDE_SLOPE: f32 = 1.0 / 32.0; /// Ring modulation, frequency modulation and positive or negative comb resonators, with the /// frequency moved by an LFO, an envelope follower or a sample-and-hold source. @@ -205,7 +225,12 @@ impl AudioEffect for RingMod { let wet = match effect { 1 => { line.push(dry); - line.read(FM_BASE + swing * (1.0 + carrier)) + // The read interpolates in f64, as Vibrato's does, so neighboring samples + // near the f32 limit with opposite signs do not overflow. + let d = (FM_BASE + swing * (1.0 + carrier)).clamp(0.0, line.max_delay()); + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + (a + (b - a) * frac) as f32 } 2 | 3 => { let y = flush32(dry + sign * fb * line.read(back)); @@ -223,6 +248,376 @@ 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: 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. + 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 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 || ch >= nch { + *held = dry as f32; + } + if ch < nch { + // 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] = blend(dry, crushed, mix) as f32; + } + } + } + } +} + +/// Amplitude modulation. The gain is `1 - depth * m`, where the LFO value `m` runs from 0 at the +/// start of each cycle to 1 at its middle and back, as a sine, a triangle or a square. The square +/// holds 0 and 1 for half a cycle each and moves between them along a raised-cosine edge 2 ms long, +/// centered on the quarter and three-quarter points, so it does not click. Rate takes effect from +/// the next sample with the phase kept. A change of Shape, or of Rate while the shape is the +/// square, glides from the last LFO value to the new curve over 20 ms, with the value kept within +/// 0 ..= 1. Depth moves to a new value over 20 ms. +pub struct Tremolo { + pv: ParamValues, + sr: f32, + channels: usize, + lfo: Lfo, + /// Shape the LFO value follows. + shape: usize, + /// Length of the square's edges, in cycles, for the rate of the last block. + edge: f64, + /// LFO value of the last sample. + last: f32, + /// Difference between the last LFO value and the new curve at a change of Shape, or of the + /// square's edges. It fades to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, + depth: Smoothed, +} + +impl Tremolo { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", 0.1, 20.0, 5.0, Unit::Hertz), + ParamSpec::new("depth", "Depth", 0.0, 100.0, 50.0, Unit::Percent), + ParamSpec::choice("shape", "Shape", TREMOLO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = Tremolo { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + channels: crate::sane_channels(channels), + lfo: Lfo::default(), + shape: 0, + edge: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: ((SM * 0.001 * sample_rate) as usize).max(1), + depth: Smoothed::with_ms(0.5, sample_rate, SM), + }; + s.apply_params(true); + s.shape = s.pv.idx("shape"); + s.edge = s.edge_len(); + s + } + + /// Length of the square's edges at the current rate, in cycles. + fn edge_len(&self) -> f64 { + (EDGE_MS * 0.001 * f64::from(self.pv.v("rate"))).clamp(1e-9, 0.25) + } + + fn apply_params(&mut self, snap: bool) { + self.depth.set(self.pv.v("depth") / 100.0); + if snap { + self.depth.snap(); + } + } + + /// LFO value of `shape` at phase `p` (cycles), with square edges `edge` cycles long. + fn shape_value(shape: usize, p: f64, edge: f64) -> f32 { + match shape { + 1 => uni_tri(p), + 2 => { + // The triangle crosses 1/2 at the edges' centers with a slope of 2 per cycle, so an + // edge `edge` cycles long spans `2 * edge` of it. + let tri = if p < 0.5 { 2.0 * p } else { 2.0 - 2.0 * p }; + let u = ((tri - 0.5) / (2.0 * edge) + 0.5).clamp(0.0, 1.0); + (0.5 - 0.5 * (std::f64::consts::PI * u).cos()) as f32 + } + _ => uni_sine(p), + } + } +} + +impl AudioEffect for Tremolo { + param_plumbing!("tremolo"); + fn reset(&mut self) { + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.edge = self.edge_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + self.depth.snap(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + // No sample used the current settings, so a glide in progress goes on unchanged. + return; + } + let nch = channels.len().min(self.channels); + let rate = self.pv.v("rate"); + let edge = self.edge_len(); + let shape = self.pv.idx("shape"); + if shape != self.shape || (shape == 2 && edge != self.edge) { + self.glide = self.last - Self::shape_value(shape, self.lfo.phase(0.0), edge); + self.glide_left = self.glide_len; + self.shape = shape; + } + self.edge = edge; + for i in 0..n { + let mut m = Self::shape_value(shape, self.lfo.phase(0.0), edge); + if self.glide_left > 0 { + m = (m + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, 1.0); + self.glide_left -= 1; + } + self.last = m; + self.lfo.advance(rate, self.sr); + let gain = 1.0 - self.depth.tick() * m; + for c in channels[..nch].iter_mut() { + // A non-finite sample is taken as silence. + c[i] = if c[i].is_finite() { c[i] * gain } else { 0.0 }; + } + } + } +} + +/// Pitch modulation. The input is read through a delay of `swing * m` samples, where the LFO value +/// `m` runs from 0 at the start of each cycle to 1 at its middle and back, as a sine or a triangle. +/// The swing is set so that the pitch falls by `depth` cents while the delay grows, and rises by a +/// little less while it shrinks: the read moves at `1 -/+ d` samples per sample, with +/// `d = 1 - 2^(-depth / 1200)`. A sine reaches `d` at its steepest point, and a triangle holds it +/// for each half of the cycle. While no glide is in progress, the delay is 0 at the start of each +/// cycle. Rate takes effect from the next sample with the phase kept. A change of Rate, Depth or +/// Shape glides the delay from its last value to the new curve, moving it by at most 1/32 sample +/// per sample on top of the curve, so the output neither clicks nor jumps in pitch. A glide can run +/// past the start of a cycle, and the delay there stays above 0 until the glide ends. +pub struct Vibrato { + pv: ParamValues, + sr: f32, + lines: Vec, + lfo: Lfo, + /// Shape the delay follows. + shape: usize, + /// Peak delay of the curve, in samples, for the settings of the last block. + swing: f32, + /// Delay of the last sample, in samples. + last: f32, + /// Difference between the last delay and the new curve at a change of the settings. It fades + /// to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, +} + +impl Vibrato { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", VIBRATO_MIN_RATE, 14.0, 6.0, Unit::Hertz), + ParamSpec::new("depth", "Depth (cents)", 0.0, VIBRATO_MAX_CENTS, 40.0, Unit::None), + ParamSpec::choice("shape", "Shape", VIBRATO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + // The widest swing is the triangle's at the lowest rate and the greatest depth. A glide + // can add up to one more swing on top of the curve. + let widest_ms = (1000.0 * Self::slope(VIBRATO_MAX_CENTS) / (2.0 * f64::from(VIBRATO_MIN_RATE))) as f32; + let len = delay_line_len(2.0 * widest_ms + 1.0, sample_rate, ch); + let mut s = Vibrato { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + lfo: Lfo::default(), + shape: 0, + swing: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: 1, + }; + s.shape = s.pv.idx("shape"); + s.swing = s.swing_len(); + s + } + + fn apply_params(&mut self, _snap: bool) {} + + /// Samples the read moves per sample, away from 1, at a depth of `cents`. + fn slope(cents: f32) -> f64 { + 1.0 - (-f64::from(cents) / 1200.0).exp2() + } + + /// Peak delay of the curve for the current settings, in samples. + fn swing_len(&self) -> f32 { + let (d, rate, sr) = (Self::slope(self.pv.v("depth")), f64::from(self.pv.v("rate")), f64::from(self.sr)); + // The sine's delay `swing * (1 - cos(2 pi p)) / 2` moves by at most `swing * pi * rate / sr` + // per sample, and the triangle's moves by `swing * 2 * rate / sr`. + let swing = if self.pv.idx("shape") == 1 { d * sr / (2.0 * rate) } else { d * sr / (std::f64::consts::PI * rate) }; + (swing as f32).min(self.max_delay()) + } + + fn max_delay(&self) -> f32 { + self.lines.first().map_or(0.0, DelayLine::max_delay) + } + + /// LFO value of `shape` at phase `p` (cycles). + fn shape_value(shape: usize, p: f64) -> f32 { + if shape == 1 { uni_tri(p) } else { uni_sine(p) } + } +} + +impl AudioEffect for Vibrato { + param_plumbing!("vibrato"); + /// The input sounds until the delay has passed it. The delay reaches at most the new curve's + /// swing plus the last delay, so the tail covers both. + fn tail_samples(&self) -> usize { + (self.swing_len() + self.last).min(self.max_delay()).ceil() as usize + 1 + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.swing = self.swing_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + // No sample uses the new settings, so no glide starts. + return; + } + let nch = channels.len().min(self.lines.len()); + let rate = self.pv.v("rate"); + let shape = self.pv.idx("shape"); + let swing = self.swing_len(); + if shape != self.shape || swing != self.swing { + self.glide = self.last - swing * Self::shape_value(shape, self.lfo.phase(0.0)); + self.glide_len = ((self.glide.abs() / VIBRATO_GLIDE_SLOPE).ceil() as usize).max(1); + self.glide_left = if self.glide == 0.0 { 0 } else { self.glide_len }; + self.shape = shape; + self.swing = swing; + } + let max = self.max_delay(); + for i in 0..n { + let mut d = swing * Self::shape_value(shape, self.lfo.phase(0.0)); + if self.glide_left > 0 { + d = (d + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, max); + self.glide_left -= 1; + } + self.last = d; + self.lfo.advance(rate, self.sr); + // The read interpolates in f64, so neighboring samples near the f32 limit with opposite + // signs do not overflow. + let d = if d.is_nan() { 0.0 } else { d.clamp(0.0, max) }; + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + for (ch, line) in self.lines.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() => c[i], + _ => 0.0, + }; + line.push(dry); + if ch < nch { + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + channels[ch][i] = (a + (b - a) * frac) as f32; + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -272,27 +667,6 @@ 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] @@ -420,6 +794,15 @@ mod tests { } } + /// At a mix of 100% the output is the wet sample even when the dry sample is far larger. + #[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:?}"); + } + /// Raising the sample-and-hold rate takes effect within one new hold, instead of after the /// value already held at the slow rate runs out. #[test] @@ -486,4 +869,619 @@ mod tests { assert!(x.iter().all(|v| v.is_finite()), "effect {effect}"); } } + + /// An empty block does not take up a change of effect, so a resonator switched away from and + /// back before the next sample keeps its ring. + #[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); + } + + /// Neighboring samples at the f32 limit with opposite signs come out finite from every effect + /// at every mix, through Frequency Mod's fractional and whole-sample reads, and a mix of 0 + /// passes them through unchanged. + #[test] + fn samples_at_the_f32_limit_stay_finite() { + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for effect in 0..4 { + for mix in [0.0, 50.0, 100.0] { + let mut r = ring(&[("effect", effect as f32), ("frequency", 5000.0), ("mix", mix)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite()), "effect {effect}, mix {mix}"); + if mix == 0.0 { + assert_eq!(y, edge, "effect {effect}"); + } + } + } + // At 48 kHz Frequency Mod's first read is 50 samples back, a whole number, and the next + // ones fall between samples. + let mut r = ring(&[("effect", 1.0)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y[60..].iter().any(|v| v.abs() > 1e30 && v.abs() < f32::MAX), "no fractional read near the limit"); + } + + 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 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_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"); + } + } + + /// 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 input: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let mut b = input.clone(); + c.process(&mut [&mut b]); + // `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. + #[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:?}"); + } + } + } + + fn tremolo(params: &[(&str, f32)], channels: usize) -> Tremolo { + let mut t = Tremolo::new(SR, channels); + for (id, v) in params { + assert!(t.set_param(id, *v), "{id}"); + } + t.reset(); + t + } + + /// The gain of a tremolo over `n` samples, read from a constant input of 1. + fn gains(t: &mut Tremolo, n: usize) -> Vec { + let mut x = vec![1.0f32; n]; + t.process(&mut [&mut x]); + x + } + + /// At full depth the gain is 1 at the start of each cycle and 0 at its middle. The sine and the + /// triangle follow their curves, the square holds each level for most of half a cycle, and + /// half depth swings the gain between 1 and 1/2. + #[test] + fn tremolo_gain_follows_the_shape() { + let period = 9600; + for shape in 0..3 { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, 2 * period); + for (i, v) in g.iter().enumerate() { + let p = (i % period) as f64 / period as f64; + let want = match shape { + 0 => 0.5 + 0.5 * (TAU * p).cos(), + 1 => 1.0 - 2.0 * p.min(1.0 - p), + _ if !(0.24..=0.26).contains(&p) && !(0.74..=0.76).contains(&p) => { + if (0.25..0.75).contains(&p) { + 0.0 + } else { + 1.0 + } + } + _ => continue, + }; + assert!((f64::from(*v) - want).abs() < 1e-4, "shape {shape} at {i}: {v}, want {want}"); + } + let mut t = tremolo(&[("rate", 5.0), ("depth", 50.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, period); + let (lo, hi) = g.iter().fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!((lo - 0.5).abs() < 1e-4 && (hi - 1.0).abs() < 1e-6, "shape {shape}: {lo} ..= {hi}"); + } + } + + /// The square's edges are 2 ms raised-cosine ramps at every rate, centered on the quarter and + /// three-quarter points of the cycle. + #[test] + fn tremolo_square_edges_do_not_click() { + let edge = (0.002 * SR) as usize; + for rate in [0.1f32, 1.0, 20.0] { + let mut t = tremolo(&[("rate", rate), ("depth", 100.0), ("shape", 2.0)], 1); + let g = gains(&mut t, (SR / rate) as usize); + let worst = g.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0f32, f32::max); + // A raised cosine over `edge` samples moves at most pi / 2 / edge per sample. + assert!(worst <= std::f32::consts::FRAC_PI_2 / edge as f32 * 1.01, "rate {rate}: step {worst}"); + let moving = g.windows(2).filter(|w| w[1] != w[0]).count(); + assert!(moving <= 2 * edge + 2, "rate {rate}: the gain moves on {moving} samples"); + let quarter = (SR / rate / 4.0) as usize; + assert!((g[quarter] - 0.5).abs() < 0.02, "rate {rate}: {} at the quarter point", g[quarter]); + } + } + + /// A new rate takes effect from the next sample, with the phase kept. + #[test] + fn tremolo_rate_change_keeps_the_phase() { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0)], 1); + let a = gains(&mut t, 2400); + assert!(t.set_param("rate", 10.0)); + let b = gains(&mut t, 2400); + // A quarter of a cycle at 5 Hz, then a quarter at 10 Hz ends at the middle of the cycle. + assert!((a[2399] - 0.5).abs() < 1e-3 && (b[0] - a[2399]).abs() < 1e-3, "{} then {}", a[2399], b[0]); + assert!(b[1199] < 1e-3 && b[1201] < 1e-3, "{} {}", b[1199], b[1201]); + } + + /// A change of shape glides from where the old shape was to the new one over 20 ms, so the + /// gain does not jump, and the new shape is followed exactly afterward. + #[test] + fn tremolo_shape_change_glides() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 2.0)], 1); + // 2,000 samples in, the sine has the gain at 0.63 and the square at 1. + let a = gains(&mut t, 2000); + gains(&mut s, 2000); + assert!(t.set_param("shape", 2.0)); + let b = gains(&mut t, 2 * glide); + let want = gains(&mut s, 2 * glide); + // The square's own edge moves the gain by up to pi / 2 / 96 (0.0164) per sample. + let step = (b[0] - a[1999]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + assert_eq!(b[glide..], want[glide..]); + assert!((b[0] - want[0]).abs() > 0.2, "{} {}", b[0], want[0]); + } + + /// A shape that only an empty block saw does not restart a glide in progress: the glide goes + /// on as if the shape had not changed. + #[test] + fn tremolo_empty_block_keeps_the_glide() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + for fx in [&mut t, &mut s] { + gains(fx, 2000); + assert!(fx.set_param("shape", 2.0)); + gains(fx, 100); + } + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + assert!(t.set_param("shape", 2.0)); + assert_eq!(gains(&mut t, 2 * glide), gains(&mut s, 2 * glide)); + } + + /// A new rate moves the square's edges to a new share of the cycle. Changed just before an + /// edge, from 0.1 Hz (where the edge is still ahead) to 20 Hz (where the phase is inside it), + /// the gain glides instead of jumping. + #[test] + fn tremolo_square_rate_change_glides() { + let mut t = tremolo(&[("rate", 0.1), ("depth", 100.0), ("shape", 2.0)], 1); + // Phase 0.249 at 0.1 Hz. + let a = gains(&mut t, 119_520); + assert_eq!(a[119_519], 1.0); + assert!(t.set_param("rate", 20.0)); + let b = gains(&mut t, 2000); + let step = (b[0] - a[119_519]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn tremolo_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut t = tremolo(&[("depth", 0.0), ("shape", 2.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + t.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut t = tremolo(&[("depth", 100.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + t.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|v| v.is_finite())); + assert_eq!(r, x); + } + + /// A glide keeps the LFO value within 0 ..= 1, so the gain stays between 1 - depth and 1 and + /// never inverts the input, even when the new curve moves away from the glide's offset. + #[test] + fn tremolo_glide_keeps_the_gain_in_range() { + for (from, to) in [(1.0, 2.0), (2.0, 1.0), (0.0, 2.0), (2.0, 0.0)] { + for start in [240, 480, 1680, 1900] { + let mut t = tremolo(&[("rate", 20.0), ("depth", 100.0), ("shape", from)], 1); + gains(&mut t, start); + assert!(t.set_param("shape", to)); + let g = gains(&mut t, 2400); + assert!(g.iter().all(|v| (0.0..=1.0).contains(v)), "{from} to {to} at {start}: {g:?}"); + } + } + } + + /// An empty block does not take up a change of shape, so a shape changed and restored before + /// the next sample starts no glide. + #[test] + fn tremolo_empty_block_starts_no_glide() { + let p = [("rate", 5.0), ("depth", 100.0), ("shape", 0.0)]; + let (mut t, mut still) = (tremolo(&p, 1), tremolo(&p, 1)); + gains(&mut t, 1000); + gains(&mut still, 1000); + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + t.process(&mut []); + assert!(t.set_param("shape", 0.0)); + assert_eq!(gains(&mut t, 2000), gains(&mut still, 2000)); + } + + fn vibrato(params: &[(&str, f32)], channels: usize) -> Vibrato { + let mut v = Vibrato::new(SR, channels); + for (id, x) in params { + assert!(v.set_param(id, *x), "{id}"); + } + v.reset(); + v + } + + /// Slope of the ramp the delay tests feed in, per sample. + const RAMP: f32 = 1e-3; + /// Most the delay moves per sample during a glide at a depth of 100 cents: the curve's + /// steepest slope plus the glide's, with room for the rounding of the ramp. + const GLIDE_STEP: f32 = 0.0562 + 1.0 / 32.0 + 0.002; + + /// The delay of a vibrato over `n` samples, read from a ramp that starts at `start` samples. + fn delays(v: &mut Vibrato, start: usize, n: usize) -> Vec { + let x: Vec = (start..start + n).map(|i| i as f32 * RAMP).collect(); + let mut y = x.clone(); + v.process(&mut [&mut y]); + x.iter().zip(&y).map(|(a, b)| (a - b) / RAMP).collect() + } + + /// Largest change of the delay between neighboring samples, averaged over 2 * `k` samples to + /// smooth out the rounding of the ramp. + fn steepest(d: &[f32], k: usize) -> f32 { + (k..d.len() - k).map(|i| (d[i + k] - d[i - k]).abs() / (2 * k) as f32).fold(0.0, f32::max) + } + + /// The delay is 0 at the start of each cycle and follows the sine or the triangle, and its + /// steepest slope lowers the pitch by the depth: 100 cents at a depth of 100 for both shapes. + #[test] + fn vibrato_delay_follows_the_shape_and_the_depth() { + let d_max = 1.0 - 2f32.powf(-100.0 / 1200.0); + for (shape, rate) in [(0, 6.0f32), (1, 6.0), (0, 1.0), (1, 14.0)] { + let mut v = vibrato(&[("rate", rate), ("depth", 100.0), ("shape", shape as f32)], 1); + let period = (SR / rate) as usize; + let swing = v.swing; + let d = delays(&mut v, 0, 2 * period); + for (i, got) in d.iter().enumerate() { + let p = (i as f64 * f64::from(rate) / f64::from(SR)).fract(); + let want = swing * if shape == 1 { uni_tri(p) } else { uni_sine(p) }; + assert!((got - want).abs() < 0.05, "shape {shape} at {rate} Hz, sample {i}: {got}, want {want}"); + } + assert!(d[0].abs() < 0.05 && d[period].abs() < 0.05, "shape {shape}: {} {}", d[0], d[period]); + let slope = steepest(&d, 40); + let cents = 1200.0 * (1.0 - slope).log2(); + assert!((cents + 100.0).abs() < 2.0, "shape {shape} at {rate} Hz: the pitch falls by {cents} cents"); + assert!((slope - d_max).abs() < 0.002, "shape {shape} at {rate} Hz: slope {slope}"); + } + } + + /// A lower depth set at the middle of the cycle, where the delay is longest, glides the delay + /// down to the new curve without jumping, and afterward the output matches a vibrato that had + /// the new depth from the start. + #[test] + fn vibrato_depth_change_glides_to_the_new_curve() { + let half = 4000; + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + let mut w = vibrato(&[("rate", 6.0), ("depth", 10.0)], 1); + let a = delays(&mut v, 0, half); + delays(&mut w, 0, half); + assert!(v.set_param("depth", 10.0)); + let b = delays(&mut v, half, 16_000); + let want = delays(&mut w, half, 16_000); + // The new curve moves by up to 0.0058 per sample, and the glide by 1/32 more. + let step = (b[0] - a[half - 1]).abs(); + assert!(step < 0.04, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < 0.04), "the glide moved too fast"); + assert!(b[100] > want[100] + 100.0, "{} {}", b[100], want[100]); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + assert_eq!(b[glide..], want[glide..]); + } + + /// A new rate takes effect from the next sample with the phase kept, the delay glides to the + /// new curve without jumping, and afterward follows it. + #[test] + fn vibrato_rate_change_keeps_the_phase_and_glides() { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + // A quarter of a cycle at 6 Hz. + let a = delays(&mut v, 0, 2000); + assert!(v.set_param("rate", 3.0)); + let swing = v.swing_len(); + let b = delays(&mut v, 2000, 12000); + let step = (b[0] - a[1999]).abs(); + assert!(step < GLIDE_STEP, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "the glide moved too fast"); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + for (k, got) in b.iter().enumerate().skip(glide) { + let p = (0.25 + k as f64 * 3.0 / f64::from(SR)).fract(); + let want = swing * uni_sine(p); + assert!((got - want).abs() < 0.05, "sample {k}: {got}, want {want}"); + } + } + + /// A change of shape glides from the last delay to the new curve without jumping. + #[test] + fn vibrato_shape_change_glides() { + for (from, to) in [(0.0, 1.0), (1.0, 0.0)] { + for start in [600, 2000, 4000, 7000] { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0), ("shape", from)], 1); + let a = delays(&mut v, 0, start); + assert!(v.set_param("shape", to)); + let b = delays(&mut v, start, 8000); + assert!((b[0] - a[start - 1]).abs() < GLIDE_STEP, "{from} to {to} at {start}: jumped"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "{from} to {to} at {start}: the glide moved too fast"); + assert!(b.iter().all(|d| *d > -0.05), "{from} to {to} at {start}: the delay went below 0"); + } + } + } + + /// An empty block does not take up a change of depth, so a depth changed and restored before + /// the next sample starts no glide. + #[test] + fn vibrato_empty_block_starts_no_glide() { + let p = [("rate", 6.0), ("depth", 100.0)]; + let (mut v, mut still) = (vibrato(&p, 1), vibrato(&p, 1)); + delays(&mut v, 0, 1000); + delays(&mut still, 0, 1000); + assert!(v.set_param("depth", 10.0)); + let mut empty: [f32; 0] = []; + v.process(&mut [&mut empty[..]]); + v.process(&mut []); + assert!(v.set_param("depth", 100.0)); + assert_eq!(delays(&mut v, 1000, 4000), delays(&mut still, 1000, 4000)); + } + + /// After the input ends, the output falls silent within the reported tail, for every shape and + /// for a depth lowered just before the end, while the delay is still gliding down. + #[test] + fn vibrato_tail_covers_the_delay() { + for (rate, depth, shape, lower) in + [(1.0f32, 100.0f32, 1.0f32, false), (14.0, 50.0, 0.0, false), (1.0, 100.0, 1.0, true), (2.0, 100.0, 0.0, true)] + { + for len in [5000usize, 12000, 24000] { + let mut v = vibrato(&[("rate", rate), ("depth", depth), ("shape", shape)], 1); + let mut x = vec![0.5f32; len]; + v.process(&mut [&mut x]); + if lower { + assert!(v.set_param("depth", 0.0)); + } + let tail = v.tail_samples(); + let mut z = vec![0.0f32; 96_000]; + v.process(&mut [&mut z]); + let last = z.iter().rposition(|s| *s != 0.0).map_or(0, |i| i + 1); + assert!(last <= tail, "{rate} Hz {depth} ct shape {shape} lower {lower} len {len}: sound until {last} after a tail of {tail}"); + } + } + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn vibrato_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut v = vibrato(&[("depth", 0.0), ("shape", 1.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut v = vibrato(&[("depth", 0.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + v.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|s| s.is_finite())); + assert_eq!(r, x); + let mut v = vibrato(&[("depth", 100.0)], 1); + let mut l = x.clone(); + l[99] = f32::NAN; + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite())); + // Neighboring samples at the f32 limit with opposite signs stay finite. + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for depth in [0.0, 100.0] { + let mut v = vibrato(&[("depth", depth)], 1); + let mut l = edge.clone(); + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite()), "depth {depth}"); + if depth == 0.0 { + assert_eq!(l, edge); + } + } + } + + /// 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 vibrato_feeds_channels_a_block_leaves_out_silence() { + let p = [("rate", 1.0), ("depth", 100.0), ("shape", 1.0)]; + let (mut left_out, mut silent) = (vibrato(&p, 2), vibrato(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 12_000, 0.0); + for v in [&mut left_out, &mut silent] { + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + } + let mut l = x[..2000].to_vec(); + left_out.process(&mut [&mut l]); + let (mut l, mut r) = (x[..2000].to_vec(), vec![0.0f32; 2000]); + silent.process(&mut [&mut l, &mut r]); + let (mut la, mut ra) = (x[..4800].to_vec(), x[..4800].to_vec()); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (x[..4800].to_vec(), x[..4800].to_vec()); + silent.process(&mut [&mut lb, &mut rb]); + assert_eq!(ra, rb); + assert_eq!(la, lb); + } } diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index acebd93e37..eff764db08 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -790,6 +790,44 @@ mod tests { assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); } + /// A mute of one hop, which leaves no frame of digital silence, ends the quiet run where it + /// falls in the stream: the quiet frames waiting before it still count, and only the frames + /// after the mute that may enter the estimate start the next run. + #[test] + fn a_short_mute_ends_the_quiet_run_in_queue_order() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let im = vec![0.0f32; half]; + let (loud, quiet) = (vec![1.0f32; half], vec![0.001f32; half]); + let mut step = |bins: &mut Bins, sample: f32, spectrum: &[f32]| { + for _ in 0..hop { + bins.sample(sample, hop); + } + bins.frame(spectrum, &im, &coefs, &mut gains); + }; + for _ in 0..40 { + step(&mut bins, 0.1, &loud); + } + for _ in 0..OVERLAP + 3 { + step(&mut bins, 0.001, &quiet); + } + assert!(bins.quiet_run > 0, "the quiet frames before the mute did not count"); + step(&mut bins, 0.0, &quiet); + let mut eligible = 0; + for _ in 0..2 * n / hop { + step(&mut bins, 0.001, &quiet); + let newest = (bins.head + bins.queued - 1) % OVERLAP; + eligible += usize::from(bins.queue_ok[newest]); + } + let waiting = (0..bins.queued).filter(|j| bins.queue_ok[(bins.head + j) % OVERLAP]).count(); + assert_eq!(waiting, bins.queued, "a frame waiting after the mute may not enter the estimate"); + assert!(eligible + 3 < coefs.window, "the test needs the run below its cap"); + assert_eq!(bins.quiet_run, eligible - waiting, "frames from before the mute counted in the new run"); + } + #[test] fn a_short_mute_ends_the_queued_quiet_run() { for offset in [0, 17] { diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index 9b8afd96e2..4b059b67b3 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; @@ -759,8 +760,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 => { @@ -1197,8 +1199,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); @@ -1213,6 +1216,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(); @@ -1246,6 +1250,33 @@ mod tests { } } + /// A block that leaves a channel out gives the same output, once the channel is back, as a + /// block that holds silence for it: with Keep Formants on, an impulse just before the block + /// still sounds afterward. + #[test] + fn a_channel_left_out_of_a_block_runs_as_silence() { + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + r[479] = 1.0; + p.process(&mut [&mut l, &mut r]); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + if omit { + p.process(&mut [&mut l]); + } else { + p.process(&mut [&mut l, &mut r]); + } + let (mut l, mut r) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + p.process(&mut [&mut l, &mut r]); + assert!(r.iter().any(|v| *v != 0.0), "omit {omit}: the impulse did not sound"); + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving the channel out changed the output"); + } + /// Leaving a silent third channel out of a block does not change the pitch the tracker finds, /// so a shifted voice comes out the same on the channels that remain. #[test] diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index 22270476da..42018ade17 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -208,6 +208,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/README.md b/crates/audio/README.md index 3b868392a8..69e9d247c0 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -31,7 +31,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `repair_wav` (size fields of a WAV left unfinished by a crash); `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` | diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 6cc18ab901..f7e69692d4 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,9 +19,9 @@ //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also -//! gives [`wav_float_header`] and [`wav_float_header_with_bwf`]), FLAC (feature `flac-encode`), -//! AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams -//! (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature +//! gives [`wav_float_header`], [`wav_float_header_with_bwf`] and [`repair_wav`]), FLAC (feature +//! `flac-encode`), AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 +//! streams (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. //! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`, //! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC, @@ -221,9 +221,9 @@ pub use write::FileEncoder; ))] pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] -pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; +pub use write::{WavRepair, repair_wav, wav_float_header, wav_float_header_with_bwf}; #[cfg(feature = "pcm-encode")] -pub use write::{wav_float_header, wav_float_header_with_bwf}; +pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; /// Errors from probing, decoding and encoding. #[non_exhaustive] diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index 2cc5202780..44b2e56423 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -3,12 +3,9 @@ use super::source::Src; use crate::pcm::{PcmKind, le_u16, le_u32, le_u64, tag}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioError, AudioInfo, BwfInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; -/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. -const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; - /// Parsed WAV layout (no sample data decoded yet). pub(crate) struct WavLayout { pub info: AudioInfo, @@ -359,7 +356,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); } } - b"ds64" => ds64_data = le_u64(&small(64), 8), + // The sizes come from the first `ds64` chunk that holds them. + b"ds64" if ds64_data.is_none() => ds64_data = le_u64(&small(64), 8), _ => {} } } diff --git a/crates/audio/src/wav.rs b/crates/audio/src/wav.rs index 61e32593a1..2a208d68bb 100644 --- a/crates/audio/src/wav.rs +++ b/crates/audio/src/wav.rs @@ -5,3 +5,5 @@ pub(crate) const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; pub(crate) const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; /// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag. pub(crate) const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; +/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. +pub(crate) const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 25267e9a05..6f24e3bd1e 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -478,3 +478,70 @@ fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, f } wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false) } + +/// What [`repair_wav`] wrote into a file. +#[cfg(feature = "pcm-encode")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct WavRepair { + /// The whole frames the data chunk holds. + pub frames: u64, + /// The length of the repaired file. Bytes past it are a partial last frame; truncate the + /// file to this length (`File::set_len`) to drop them. + pub len: u64, +} + +/// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such +/// as a recorder's file after a crash, for the whole frames the file holds. The file must end in +/// its data chunk: everything after the data chunk's header counts as samples, whatever its size +/// field says. +/// +/// It writes these fields and leaves every other byte before the samples as it is, `fmt `, `bext` +/// and unknown chunks included: +/// +/// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file); +/// - the frame count, the first field of the first `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames); +/// - in an RF64 file, the RIFF size, data size and frame count at the start of the first `ds64` chunk; +/// - the pad byte after an odd data length. +/// +/// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that +/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk +/// becomes a `ds64` chunk with an empty table. A RIFF file whose 28-byte chunk there already has the +/// `ds64` id, left by an earlier repair that stopped before writing `RF64`, becomes RF64 the same way. +/// +/// Errors: +/// +/// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within +/// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter +/// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size +/// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize +/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk or with a +/// first `ds64` chunk of 16 to 27 bytes (the WAV reader takes the data size from that chunk). +/// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format +/// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits, +/// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte +/// may be a sample or a pad byte). +/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or +/// `ds64` chunk. +/// - [`AudioError::Io`] when reading, writing or seeking `file` fails. +/// +/// ``` +/// use craft_audio::{repair_wav, wav_float_header}; +/// use std::io::Cursor; +/// +/// // A recorder wrote the header for 0 frames, then 2 frames and part of a third, then stopped. +/// let mut bytes = wav_float_header(48_000, 2, 0).unwrap(); +/// bytes.extend([0.25f32, -0.25, 0.5, -0.5, 0.75].iter().flat_map(|s| s.to_le_bytes())); +/// let mut file = Cursor::new(bytes); +/// let repaired = repair_wav(&mut file).unwrap(); +/// assert_eq!(repaired.frames, 2); +/// let mut bytes = file.into_inner(); +/// bytes.truncate(repaired.len as usize); +/// let header = wav_float_header(48_000, 2, 2).unwrap(); +/// assert_eq!(bytes[..header.len()], header[..]); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn repair_wav(file: &mut F) -> Result { + let (frames, len) = wav::repair(file)?; + Ok(WavRepair { frames, len }) +} diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 96ba532510..496bb95801 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -2,9 +2,9 @@ //! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306). use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result}; -use std::io::{Cursor, Seek, SeekFrom, Write}; +use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write}; const BEXT_MIN_LEN: usize = 602; @@ -239,3 +239,175 @@ pub(crate) fn header( head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes()); Ok(head) } + +/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`. +struct Layout { + rf64: bool, + /// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte + /// `JUNK` or `ds64` chunk right after `WAVE` that can become one. + ds64: Option, + junk: bool, + fact: Option, + block_align: u64, + data: u64, +} + +fn read_at(file: &mut F, pos: u64, buf: &mut [u8]) -> Result { + file.seek(SeekFrom::Start(pos))?; + match file.read_exact(buf) { + Ok(()) => Ok(true), + Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false), + Err(e) => Err(e.into()), + } +} + +fn write_at(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> { + file.seek(SeekFrom::Start(pos))?; + file.write_all(bytes)?; + Ok(()) +} + +/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes. +fn pcm_block_align(file: &mut F, pos: u64, size: u32) -> Result { + let mut fmt = [0u8; 40]; + let n = if size >= 40 { 40 } else { 16 }; + if size < 16 || !read_at(file, pos, &mut fmt[..n])? { + return Err(AudioError::Malformed("WAV fmt chunk is cut short".into())); + } + let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]); + let mut tag = field(0); + if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 { + // The extensible fields the reader checks. + if field(16) < 22 || field(18) > field(14) { + return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into())); + } + if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL { + tag = field(24); + } + } + if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}"))); + } + let (channels, align, bits) = (field(2), field(12), field(14)); + if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) { + return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits"))); + } + // The widths the WAV reader decodes. + if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample"))); + } + Ok(u64::from(align)) +} + +fn layout(file: &mut F, len: u64) -> Result { + let mut riff = [0u8; 12]; + if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" { + return Err(AudioError::Malformed("not a WAV file".into())); + } + let rf64 = riff.starts_with(b"RF64"); + let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None); + let mut pos = 12u64; + let mut chunk = [0u8; 8]; + // The same bound as the reader's, so a file of tiny chunks can't spin forever. + for _ in 0..100_000 { + if pos >= len || !read_at(file, pos, &mut chunk)? { + break; + } + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); + let body = pos + 8; + match &chunk[..4] { + b"data" => { + let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?; + return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body }); + } + // The first `ds64` and `fact` chunks take the sizes; later ones are left as they are. + // The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more. + b"ds64" if rf64 && size >= 16 && ds64.is_none() => { + if size < 28 { + return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into())); + } + ds64 = Some(body); + } + // A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id. + b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), + b"fact" if size >= 4 && fact.is_none() => fact = Some(body), + b"fmt " => block_align = Some(pcm_block_align(file, body, size)?), + _ => {} + } + pos = body + u64::from(size) + u64::from(size & 1); + } + Err(AudioError::Malformed("WAV has no data chunk".into())) +} + +/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's. +fn stored_data_len(file: &mut F, l: &Layout) -> Result> { + let mut size = [0u8; 8]; + Ok(match (l.rf64, l.ds64) { + (true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)), + (true, None) => None, + (false, _) => read_at(file, l.data - 4, &mut size[..4])? + .then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]])) + .filter(|&s| s != u32::MAX) + .map(u64::from), + }) +} + +/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds. +/// Returns the frame count and the length the file should have; bytes past it are a partial frame. +pub(crate) fn repair(file: &mut F) -> Result<(u64, u64)> { + let len = file.seek(SeekFrom::End(0))?; + let l = layout(file, len)?; + let held = len.saturating_sub(l.data); + // A finished file's own size, which also tells its pad byte from a frame of one byte. + let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held)); + if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 { + // The last byte may be a sample or the pad byte after an odd count of them. + return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into())); + } + let frames = stored.unwrap_or(held) / l.block_align; + let data_len = frames * l.block_align; + let pad = data_len & 1; + let new_len = l.data + data_len + pad; + let riff_len = new_len - 8; + let rf64 = l.rf64 || u32::try_from(riff_len).is_err(); + let ds64 = match (rf64, l.ds64) { + (false, _) => None, + (true, Some(at)) if l.rf64 || l.junk => Some(at), + (true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())), + (true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())), + }; + if let Some(at) = l.fact { + write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?; + } + match ds64 { + Some(at) => { + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&riff_len.to_le_bytes()); + body.extend_from_slice(&data_len.to_le_bytes()); + body.extend_from_slice(&frames.to_le_bytes()); + if !l.rf64 { + // The `JUNK` chunk's last 4 bytes become the table length: no table entries. + body.extend_from_slice(&0u32.to_le_bytes()); + } + write_at(file, at, &body)?; + if !l.rf64 { + write_at(file, at - 8, b"ds64")?; + write_at(file, 0, b"RF64")?; + } + write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?; + write_at(file, 4, &u32::MAX.to_le_bytes())?; + } + None => { + write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?; + write_at(file, 4, &(riff_len as u32).to_le_bytes())?; + } + } + // The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a + // repeated repair can count. + if pad == 1 { + write_at(file, l.data + data_len, &[0])?; + } + file.seek(SeekFrom::Start(new_len))?; + file.flush()?; + Ok((frames, new_len)) +} diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index dd7005fbfb..803d85f293 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -68,6 +68,315 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() { } } +/// A file that stopped growing before its header was rewritten: the header for 0 frames, the +/// samples of `buf`, then `extra` bytes of a frame that was never finished. +fn unfinished_wav(buf: &AudioBuffer, opts: &EncodeOptions, extra: usize) -> (Vec, Vec) { + let finished = encode(buf, opts).unwrap(); + let mut file = encode(&AudioBuffer::new(buf.sample_rate, buf.num_channels(), 0), opts).unwrap(); + let head = file.len(); + let sample_bytes = match opts.bit_depth { + BitDepth::Int16 => 2, + BitDepth::Int24 => 3, + _ => 4, + }; + let data_len = buf.frames() * usize::from(buf.num_channels()) * sample_bytes; + file.extend_from_slice(&finished[head..head + data_len]); + file.extend(std::iter::repeat_n(0x55, extra)); + (file, finished) +} + +#[test] +fn repair_wav_rewrites_the_sizes_of_an_unfinished_file() { + let bwf = BwfInfo::default().with_description("take 3").with_time_reference(48_000 * 3600); + let cases = [ + (sine(48_000, 2, 1_000), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()), 5), + // 3 bytes a frame and an odd frame count: the data needs a pad byte. + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf.clone()), 2), + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf), 0), + (sine(48_000, 6, 300), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true), 11), + (sine(48_000, 2, 0), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), 3), + ]; + for (buf, opts, extra) in cases { + let (file, finished) = unfinished_wav(&buf, &opts, extra); + assert_ne!(file, finished); + let mut file = std::io::Cursor::new(file); + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repaired.frames, buf.frames() as u64); + let mut file = file.into_inner(); + assert!(file.len() as u64 >= repaired.len); + file.truncate(repaired.len as usize); + assert_eq!(file, finished, "{opts:?}"); + // A finished file stays as it is. + let mut again = std::io::Cursor::new(file.clone()); + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired); + assert_eq!(again.into_inner(), file); + } +} + +/// A file whose data is all zeros past `head`, `len` bytes long, without holding them in memory. +struct SparseWav { + head: Vec, + len: u64, + pos: u64, +} + +impl std::io::Read for SparseWav { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = (self.len.saturating_sub(self.pos)).min(buf.len() as u64) as usize; + for (i, b) in buf[..n].iter_mut().enumerate() { + *b = self.head.get(self.pos as usize + i).copied().unwrap_or(0); + } + self.pos += n as u64; + Ok(n) + } +} + +impl std::io::Write for SparseWav { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let end = self.pos as usize + buf.len(); + if end <= self.head.len() { + self.head[self.pos as usize..end].copy_from_slice(buf); + } else { + assert!(buf.iter().all(|&b| b == 0), "only padding is written past the header"); + } + self.pos += buf.len() as u64; + self.len = self.len.max(self.pos); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for SparseWav { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.pos = match to { + std::io::SeekFrom::Start(p) => p, + std::io::SeekFrom::End(d) => self.len.checked_add_signed(d).unwrap(), + std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).unwrap(), + }; + Ok(self.pos) + } +} + +#[test] +fn repair_wav_turns_a_file_past_4_gib_into_rf64() { + let frames = 600_000_000u64; // 4.8 GB of stereo float + let head = wav_float_header(48_000, 2, 0).unwrap(); + let len = head.len() as u64 + frames * 8 + 3; + let mut file = SparseWav { head: head.clone(), len, pos: 0 }; + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((repaired.frames, repaired.len), (frames, len - 3)); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // A JUNK chunk holding other bytes becomes a ds64 chunk with an empty table. + let mut dirty = head.clone(); + assert_eq!(&dirty[12..16], b"JUNK"); + dirty[20..48].fill(0xAA); + let mut file = SparseWav { head: dirty, len, pos: 0 }; + craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // A repair that stopped after naming the ds64 chunk but before writing RF64 finishes next time. + let mut half = head.clone(); + half[12..16].copy_from_slice(b"ds64"); + let mut file = SparseWav { head: half, len, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap(), repaired); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // In a RIFF file only the chunk right after WAVE becomes ds64; a later ds64 chunk is left as it is. + let at = head.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"ds64"[..], &28u32.to_le_bytes(), &[0xBB; 28]].concat(); + let mut two = head.clone(); + two.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: two, len: len + 36, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, frames); + assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..])); + assert_eq!(file.head[at..at + 36], later[..]); + + // In an RF64 file the ds64 chunk right after WAVE takes the sizes; a later ds64 chunk is left as it is. + let finished = wav_float_header(48_000, 2, frames).unwrap(); + assert_eq!((&finished[..4], &finished[12..16]), (&b"RF64"[..], &b"ds64"[..])); + let mut stale = finished.clone(); + stale[20..44].fill(0); + stale.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: stale, len: len + 36, pos: 0 }; + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((r.frames, r.len), (frames, len + 33)); + let field = |at: usize| u64::from_le_bytes(file.head[at..at + 8].try_into().unwrap()); + assert_eq!((field(20), field(28), field(36)), (len + 25, frames * 8, frames)); + assert_eq!(file.head[at..at + 36], later[..]); + + // A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB. + let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16); + assert_eq!(&bare[12..16], b"fmt "); + let len = bare.len() as u64 + (1u64 << 32); + let mut file = SparseWav { head: bare, len, pos: 0 }; + assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_)))); +} + +#[test] +fn repair_wav_writes_the_frame_count_into_the_first_fact_chunk() { + let mut file = wav_float_header(48_000, 2, 0).unwrap(); + let fact = file.windows(4).position(|w| w == b"fact").unwrap() + 8; + let at = file.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"fact"[..], &4u32.to_le_bytes(), &[0xCC; 4]].concat(); + file.splice(at..at, later.iter().copied()); + file.extend(std::iter::repeat_n(0, 100 * 8)); + let mut file = std::io::Cursor::new(file); + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, 100); + let file = file.into_inner(); + assert_eq!(file[fact..fact + 4], 100u32.to_le_bytes()); + assert_eq!(file[at..at + 12], later[..]); +} + +#[test] +fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() { + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true); + let wav = encode(&sine(48_000, 2, 300), &opts).unwrap(); + assert_eq!(&wav[12..16], b"ds64"); + // A later ds64 chunk that gives the data 4 bytes, one frame. + let mut body = [0u8; 28]; + body[8..16].copy_from_slice(&4u64.to_le_bytes()); + let later = [&b"ds64"[..], &28u32.to_le_bytes(), &body].concat(); + let at = wav.windows(4).position(|w| w == b"data").unwrap(); + let mut two = wav.clone(); + two.splice(at..at, later); + let (info, buf) = decode(&two, Some("wav")).unwrap(); + assert_eq!((info.frames, buf.frames()), (300, 300)); + + // A 16-byte first ds64 chunk gives the reader the data size, so repair does not use the later one. + let mut short = two; + short[16..20].copy_from_slice(&16u32.to_le_bytes()); + short[28..36].copy_from_slice(&4u64.to_le_bytes()); + short[36..44].copy_from_slice(&[&b"JUNK"[..], &4u32.to_le_bytes()].concat()); + assert_eq!(decode(&short, Some("wav")).unwrap().1.frames(), 1); + let repaired = craft_audio::repair_wav(&mut std::io::Cursor::new(short)); + assert!(matches!(repaired, Err(craft_audio::AudioError::Malformed(_))), "{repaired:?}"); +} + +/// A file whose writes fail once `writes` of them have gone through. +struct FailingWrites { + file: std::io::Cursor>, + writes: usize, +} + +impl std::io::Read for FailingWrites { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + std::io::Read::read(&mut self.file, buf) + } +} + +impl std::io::Write for FailingWrites { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.writes -= 1; + std::io::Write::write(&mut self.file, buf) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for FailingWrites { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + std::io::Seek::seek(&mut self.file, to) + } +} + +#[test] +fn repair_wav_runs_again_after_a_write_error() { + let mut u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + u8_mono.extend([0x80; 3]); + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24); + let (int24, _) = unfinished_wav(&sine(44_100, 1, 999), &opts, 2); + for (file, frames) in [(u8_mono, 3), (int24, 999)] { + let mut whole = std::io::Cursor::new(file.clone()); + let repaired = craft_audio::repair_wav(&mut whole).unwrap(); + assert_eq!(repaired.frames, frames); + for writes in 0.. { + let mut failing = FailingWrites { file: std::io::Cursor::new(file.clone()), writes }; + if craft_audio::repair_wav(&mut failing).is_ok() { + break; + } + let mut again = failing.file; + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired, "stopped after {writes} writes"); + assert_eq!(again.into_inner(), *whole.get_ref(), "stopped after {writes} writes"); + } + } +} + +#[test] +fn repair_wav_refuses_what_it_cannot_repair() { + use craft_audio::AudioError; + let repair = |bytes: Vec| craft_audio::repair_wav(&mut std::io::Cursor::new(bytes)); + let wav = encode(&sine(48_000, 1, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16)).unwrap(); + assert!(matches!(repair(b"not a wave file at all".to_vec()), Err(AudioError::Malformed(_)))); + // Every cut inside the header is an error, not a panic. + let data = wav.windows(4).position(|w| w == b"data").unwrap(); + for cut in 0..data + 8 { + assert!(repair(wav[..cut].to_vec()).is_err(), "cut at {cut}"); + } + // A compressed format (format tag 2, Microsoft ADPCM) has no fixed frame size to count by. + let fmt = wav.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + let mut adpcm = wav.clone(); + adpcm[fmt..fmt + 2].copy_from_slice(&2u16.to_le_bytes()); + assert!(matches!(repair(adpcm), Err(AudioError::Unsupported(_)))); + // The chunk walk stops, as the reader's does, after 100,000 chunks. + let mut many = wav[..12].to_vec(); + many.extend(b"JUNK\0\0\0\0".repeat(100_001)); + many.extend_from_slice(&wav[12..]); + assert!(matches!(repair(many), Err(AudioError::Malformed(_)))); + // 8-bit mono: an even data length could end in a sample or in the pad after an odd count. + let u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + for (samples, ok) in [(3, true), (4, false)] { + let mut file = u8_mono.clone(); + file.extend(std::iter::repeat_n(0x80, samples)); + assert_eq!(repair(file.clone()).map(|r| r.frames).ok(), ok.then_some(3), "{samples} bytes"); + if ok { + // Once repaired, the size settles it. + let mut file = std::io::Cursor::new(file); + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repair(file.into_inner()).unwrap(), r); + } + } + // A block size that is not channels × sample bytes would count the wrong frames. + let mut odd_align = wav.clone(); + odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes()); + assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_)))); + // Widths the reader does not decode: 16-bit float and 40-bit PCM, each with a block size that fits. + let mut float16 = wav.clone(); + float16[fmt..fmt + 2].copy_from_slice(&3u16.to_le_bytes()); + let mut pcm40 = wav.clone(); + pcm40[fmt + 12..fmt + 16].copy_from_slice(&[5, 0, 40, 0]); + for bad in [float16, pcm40] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Unsupported(_)))); + } + // An extensible file whose subformat is PCM's tag under another GUID is not PCM. + let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); + let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + assert!(repair(ext.clone()).is_ok()); + let mut other_guid = ext.clone(); + other_guid[fmt + 39] ^= 0xFF; + assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_)))); + // Extensible fields the reader refuses: a cbSize below 22 and more valid bits than the sample holds. + let mut short_cb = ext.clone(); + short_cb[fmt + 16..fmt + 18].copy_from_slice(&21u16.to_le_bytes()); + let mut wide_valid = ext.clone(); + wide_valid[fmt + 18..fmt + 20].copy_from_slice(&25u16.to_le_bytes()); + for bad in [short_cb, wide_valid] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Malformed(_)))); + } + // The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM. + let mut ambisonic = ext; + ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]); + assert_eq!(repair(ambisonic).unwrap().frames, 100); +} + #[test] fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() { let take = sine(48_000, 2, 1_000); diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 46687dae3b..8a767ddd21 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -103,10 +103,8 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() { let mut client = ControlClient::connect(addr, TOKEN).unwrap(); assert!(client.is_usable(), "an idle connection with nothing pending is usable"); said.send(()).unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while client.is_usable() && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + // A blocking peek (under the client's read timeout) returns once the line has arrived. + assert!(client.stream.peek(&mut [0]).unwrap() > 0, "the unasked line arrived"); assert!(!client.is_usable(), "the unasked line makes the connection unusable"); assert_eq!(client.call("next", json!({})), Err("connection closed".to_string())); assert!(client.is_broken(), "the unusable connection is closed"); diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 8e75f07ecd..180a331752 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -487,20 +487,40 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> { stream.set_write_timeout(Some(IO_TIMEOUT)) } +/// The time an [`AuthDeadlineStream`] reads its deadline against: [`Instant::now`] in a server, or a time a test sets +/// by hand. +pub type DeadlineClock = std::sync::Arc Instant + Send + Sync>; + +/// The real clock, [`Instant::now`]. +pub fn real_clock() -> DeadlineClock { + std::sync::Arc::new(Instant::now) +} + /// A read wrapper that fails once [`AUTH_DEADLINE`] passes without [`Self::authenticated`] being /// called, whatever the client sends meanwhile; after that only [`IO_TIMEOUT`] applies. -#[derive(Debug)] pub struct AuthDeadlineStream { inner: std::net::TcpStream, deadline: Option, + clock: DeadlineClock, +} + +impl std::fmt::Debug for AuthDeadlineStream { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AuthDeadlineStream").field("inner", &self.inner).field("deadline", &self.deadline).finish_non_exhaustive() + } } impl AuthDeadlineStream { /// Wraps `inner`; reads fail once `auth_deadline` has passed unauthenticated. pub fn new(inner: std::net::TcpStream, auth_deadline: Duration) -> Self { + Self::with_clock(inner, auth_deadline, real_clock()) + } + + /// [`Self::new`] with the deadline read against `clock` instead of the real clock. + pub fn with_clock(inner: std::net::TcpStream, auth_deadline: Duration, clock: DeadlineClock) -> Self { // A limit too large to represent expires at once rather than never. - let now = Instant::now(); - Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)) } + let now = clock(); + Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)), clock } } /// The handshake succeeded: lift the deadline and restore the idle timeout. @@ -513,7 +533,7 @@ impl AuthDeadlineStream { impl std::io::Read for AuthDeadlineStream { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { if let Some(deadline) = self.deadline { - let left = deadline.saturating_duration_since(Instant::now()); + let left = deadline.saturating_duration_since((self.clock)()); if left.is_zero() { return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time")); } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index 2716fc24c2..2d3625c0a7 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -170,6 +170,37 @@ fn server_token_sources_and_validation() { ); } +// An unauthenticated connection's reads succeed while its deadline is ahead, however much it sends, and fail once the +// deadline has passed even with input waiting; after `authenticated` the deadline no longer applies. +#[trial] +fn the_authentication_deadline_holds_whatever_the_client_sends() { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (server, _) = listener.accept().unwrap(); + server.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let start = Instant::now(); + let at = std::sync::Arc::new(std::sync::Mutex::new(start)); + let read_at = std::sync::Arc::clone(&at); + let clock: DeadlineClock = std::sync::Arc::new(move || *read_at.lock().unwrap()); + let mut stream = AuthDeadlineStream::with_clock(server.try_clone().unwrap(), Duration::from_secs(10), clock); + let mut byte = [0]; + // Blank lines and partial frames, each read while the deadline is ahead. + for (step, sent) in [b"\n", b" ", b"{", b"\n"].into_iter().enumerate() { + *at.lock().unwrap() = start + Duration::from_secs(3 * step as u64); + client.write_all(sent).unwrap(); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "read {step} is before the deadline"); + } + *at.lock().unwrap() = start + Duration::from_secs(10); + client.write_all(b"\n").unwrap(); + let late = stream.read(&mut byte).unwrap_err(); + assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "the input sent did not move the deadline: {late}"); + + stream.authenticated().unwrap(); + *at.lock().unwrap() = start + Duration::from_secs(60); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "an authenticated connection reads past the deadline"); +} + // A token file create that runs out of time fails with its own error, even when it left a file at // the path: that file is not read as another process's. A create that another process beat to the // path reads that process's token. diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index c6808156d7..e913cf3b4c 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -16,8 +16,8 @@ use serde_json::{Value, json}; use crate::control::{ControlRequest, REPLY_DEADLINE}; use crate::protocol::write_reply; use crate::security::{ - AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream, - read_bounded_line, repeat_auth_reply, + AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, DeadlineClock, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, + configure_stream, read_bounded_line, real_clock, repeat_auth_reply, }; /// A running control server. Dropping it stops accepting connections and returns once the port is @@ -72,6 +72,36 @@ pub fn serve_with_deadline( host: WindowHost, auth_deadline: Duration, ) -> std::io::Result<(Receiver, Listening)> { + serve_with(listener, token, host, ServeOptions { auth_deadline, ..ServeOptions::default() }) +} + +/// What a test sets on a server [`serve_with`] starts. +#[doc(hidden)] +pub struct ServeOptions { + /// How long a connection has to authenticate ([`AUTH_DEADLINE`] in [`serve`]). + pub auth_deadline: Duration, + /// The clock the authentication deadline is read against. + pub clock: DeadlineClock, + /// Sent `()` each time a connection has ended: its request sender is dropped and its place under + /// [`MAX_CONNECTIONS`] is free again. + pub ended: Option>, +} + +impl Default for ServeOptions { + fn default() -> Self { + Self { auth_deadline: AUTH_DEADLINE, clock: real_clock(), ended: None } + } +} + +/// [`serve`] with the authentication deadline, its clock and a signal for each ended connection set by a test. +#[doc(hidden)] +pub fn serve_with( + listener: TcpListener, + token: String, + host: WindowHost, + options: ServeOptions, +) -> std::io::Result<(Receiver, Listening)> { + let ServeOptions { auth_deadline, clock, ended } = options; let (tx, rx) = channel::(); let addr = listener.local_addr()?; // `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept @@ -95,13 +125,19 @@ pub fn serve_with_deadline( let tx = tx.clone(); let host = host.clone(); let token = Arc::clone(&token); + let clock = Arc::clone(&clock); + let ended = ended.clone(); std::thread::spawn(move || { - serve_connection(stream, &token, &tx, &host, auth_deadline); + serve_connection(stream, &token, &tx, &host, auth_deadline, clock); + drop(tx); // What the last client held down would otherwise stay held with no one left to // release it; while another connection is live, its input is left alone. if permit.release() { host.end_injection(); } + if let Some(ended) = ended { + let _ = ended.send(()); + } }); } })?; @@ -110,12 +146,12 @@ pub fn serve_with_deadline( /// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of /// connecting, however much it sends meanwhile; after that only the idle timeout applies. -fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration) { +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration, clock: DeadlineClock) { if configure_stream(&stream).is_err() { return; } let Ok(read) = stream.try_clone() else { return }; - let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline)); + let mut reader = BufReader::new(AuthDeadlineStream::with_clock(read, auth_deadline, clock)); let mut out = stream; let mut line = String::new(); let mut handshake = ServerHandshake::new(); diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index 913d02d16a..6e1dc700fc 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -2,14 +2,15 @@ use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; -use std::sync::mpsc::{Receiver, channel}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use craft_automation::client::ControlClient; use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error}; use craft_automation::protocol::MAX_RESPONSE_BYTES; use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; -use craft_automation::server; +use craft_automation::server::{self, ServeOptions}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::trial; @@ -101,39 +102,90 @@ fn host() -> WindowHost { /// sent is dispatched. #[trial] fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { - // A short deadline, so the test does not wait out the real one. - let deadline = Duration::from_millis(400); - let listener = TcpListener::bind("127.0.0.1:0").expect("bound"); - let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started"); - // Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout. + let start = motion::now(); + let at = Arc::new(Mutex::new(start)); + let read_at = Arc::clone(&at); + let (ended, connection_ended) = channel(); + // Each read of the clock is announced, so the test moves it only after the connection has set its deadline. + let (read, clock_read) = channel(); + let clock = Arc::new(move || { + let now = *read_at.lock().expect("the clock"); + let _ = read.send(()); + now + }); + let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); let mut stream = TcpStream::connect(server.addr).expect("connected"); - let started = motion::now(); - let mut closed = false; - for i in 0..1000 { - let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " }; - if stream.write_all(byte).is_err() { - closed = true; - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - let served = started.elapsed(); - assert!(closed, "the trickle did not keep the connection open"); - assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline"); + // Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses. + stream.write_all(b"\n \n ").expect("written"); + *at.lock().expect("the clock") = start + Duration::from_secs(10); + // The server may already have closed when this is written; if not, it wakes the server's read. + let _ = stream.write_all(b" "); + assert!(is_closed(&mut reader), "the input sent did not keep the connection open past the deadline"); + assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched"); } -/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. +/// Whether the server closed the connection: the next read is the end of the stream, or an error other than a timeout. +/// A server that closes with input still unread makes the kernel send a reset, so the read fails with +/// `ConnectionReset` or `ConnectionAborted` instead of returning the end of the stream (mostly on Windows). fn is_closed(reader: &mut impl BufRead) -> bool { let mut line = String::new(); - matches!(reader.read_line(&mut line), Ok(0)) + match reader.read_line(&mut line) { + Ok(read) => read == 0, + Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), + } +} + +/// A reader whose every read fails with the given error kind. +struct Failing(std::io::ErrorKind); + +impl std::io::Read for Failing { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(self.0.into()) + } +} + +/// A reset or aborted connection counts as closed; a read timeout does not. +#[trial] +fn a_reset_connection_counts_as_closed() { + use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, TimedOut, WouldBlock}; + assert!(is_closed(&mut BufReader::new(Failing(ConnectionReset))), "a reset is a close"); + assert!(is_closed(&mut BufReader::new(Failing(ConnectionAborted))), "an abort is a close"); + assert!(!is_closed(&mut BufReader::new(Failing(TimedOut))), "a timeout is not a close"); + assert!(!is_closed(&mut BufReader::new(Failing(WouldBlock))), "a timeout is not a close"); +} + +/// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no +/// connection reaches the authentication deadline: only the client or a refusal ends one. The frozen clock does not +/// stop the socket's read timeout, which runs on real time and is the time left to the deadline capped at the idle +/// timeout. The deadline is a minute, so a waiting connection's read times out after the 30-second idle timeout +/// instead of after 10 seconds. +fn serve_counting_ends() -> (Receiver, server::Listening, Receiver<()>) { + let (ended, connection_ended) = channel(); + let start = motion::now(); + let options = ServeOptions { auth_deadline: Duration::from_secs(60), clock: Arc::new(move || start), ended: Some(ended) }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); + (rx, server, connection_ended) +} + +/// Stops `server` and waits for its `connections` connections to end, so the request receiver `rx` is disconnected +/// once every request that reached it has been taken: `rx` then answers whether anything more was dispatched. +fn nothing_more_dispatched(rx: &Receiver, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool { + drop(server); + for _ in 0..connections { + ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended"); + } + rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected) } /// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of /// the open ones ends, its place serves a new connection. #[trial] fn connections_past_the_limit_are_refused_with_the_reason() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let connect = || { let stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); @@ -150,20 +202,14 @@ fn connections_past_the_limit_are_refused_with_the_reason() { drop(open.pop()); // The server frees the place when it reads the close; a new connection is served once it has. - let started = motion::now(); - let served = loop { - let (mut stream, mut reader) = connect(); - writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); - let reply = read_json(&mut reader).expect("a reply"); - if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) { - break reply; - } - assert_eq!(reply["error"], "connection limit reached", "{reply}"); - std::thread::sleep(Duration::from_millis(20)); - }; + ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended"); + let (mut stream, mut reader) = connect(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + let served = read_json(&mut reader).expect("a reply"); assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + drop((stream, reader)); drop(open); + assert!(nothing_more_dispatched(&rx, server, &ended, MAX_CONNECTIONS), "nothing was dispatched"); } /// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the @@ -191,9 +237,8 @@ fn a_refused_first_frame_closes_the_connection() { /// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. #[trial] fn a_browser_post_never_reaches_the_app() { - // Far longer than the trial, so the close comes from the refusal, not the deadline. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so the close comes from the refusal, not the deadline. + let (rx, server, ended) = serve_counting_ends(); let mut stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); @@ -211,7 +256,8 @@ fn a_browser_post_never_reaches_the_app() { Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), }; assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "nothing reached the app"); } /// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. @@ -325,19 +371,19 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() { let mut client = ControlClient::connect(addr, TOKEN).expect("connected"); capture_state(&mut client, &client_doc, &client_doc["states"][0], "new") }); - let mut channel = ControlChannel::new(requests); + // Each request is waited for as it arrives and then taken through the channel, as the app's frame takes it. + let (forward, forwarded) = channel(); + let mut channel = ControlChannel::new(forwarded); let mut seen: Vec = Vec::new(); - let started = motion::now(); - while seen.len() < 4 && started.elapsed() < Duration::from_secs(10) { - while let Some(req) = channel.next_request() { - seen.push(format!("{} {}", req.method, req.params)); - let reply = match req.method.as_str() { - "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), - _ => Reply::from_result(Ok(Value::Null)), - }; - channel.settle(req, reply, None, 0.0); - } - std::thread::sleep(Duration::from_millis(5)); + while seen.len() < 4 { + forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded"); + let req = channel.next_request().expect("the forwarded request is dispatched"); + seen.push(format!("{} {}", req.method, req.params)); + let reply = match req.method.as_str() { + "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), + _ => Reply::from_result(Ok(Value::Null)), + }; + channel.settle(req, reply, None, 0.0); } let reply = client.join().expect("client ran").expect("the capture replied"); assert_eq!( @@ -440,12 +486,12 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() { /// and shut its end down) still reaches the app and is answered: a client cannot know it was dropped. #[trial] fn a_complete_json_request_at_eof_can_reach_the_app() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let handler = std::thread::spawn(move || { let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app"); assert_eq!(req.method, "test.once"); req.reply.send(json!({"ok": true, "result": "once"})).expect("replied"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "it ran exactly once"); + rx }); let (mut stream, mut reader) = authenticated(server.addr); stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written"); @@ -454,7 +500,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { assert_eq!((&reply["id"], &reply["result"]), (&json!(3), &json!("once"))); let mut rest = String::new(); assert_eq!(reader.read_line(&mut rest).expect("closed, not timed out"), 0, "closed after the last request: {rest:?}"); - handler.join().expect("handler ran"); + let rx = handler.join().expect("handler ran"); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "it ran exactly once"); } /// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new @@ -462,9 +509,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { #[trial] fn idle_unauthenticated_connections_are_limited() { use craft_automation::security::MAX_CONNECTIONS; - // Far longer than the trial, so only the limit refuses. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so only the limit refuses. + let (rx, server, ended) = serve_counting_ends(); let idle: Vec = (0..MAX_CONNECTIONS).map(|_| TcpStream::connect(server.addr).expect("connected")).collect(); // Admission is counted by the accept thread: it is done once the next connection is answered. let refused = |addr| { @@ -477,18 +523,14 @@ fn idle_unauthenticated_connections_are_limited() { assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit")), "{reply}"); drop(idle); // The freed slots go back as the closed connections are noticed. - let started = motion::now(); - loop { - let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); - let mut reader = BufReader::new(stream.try_clone().expect("cloned")); - // A refused connection may already be closed when the request is written (Windows resets it). - let auth = json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}}); - if writeln!(stream, "{auth}").is_ok() && read_json(&mut reader).is_some_and(|r| r["ok"] == true) { - break; - } - assert!(started.elapsed() < Duration::from_secs(10), "no slot came back"); - std::thread::sleep(Duration::from_millis(50)); + for _ in 0..MAX_CONNECTIONS { + ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended"); } - assert!(rx.try_recv().is_err()); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1)); } diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 772f915350..e29d443fea 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -155,14 +155,13 @@ file is committed. | R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) | | R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) | | R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample | -| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | +| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | ## Written fields `src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table lists every field it sets. `own` marks a value the reader does not read, which the writer sets as -the synthetic test files of `src/synth_cmx.rs` set it. The header's bounds and instruction count -at bytes 96 to 116 are not written. +the synthetic test files of `src/synth_cmx.rs` set it. | Field written | Rows | Status | |---|---|---| @@ -170,6 +169,7 @@ at bytes 96 to 116 are not written. | Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) | | `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample | | `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) | +| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) | | `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own | | `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) | | `rlst` for each page: its layers' numbers | R77 | sample | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index e86a8aa393..0bf2c8e8f8 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -131,7 +131,7 @@ by their chunk ids, opens it: the header gives where the master index starts, th layer and group records give their instruction counts. A page's record also gives where its end-page instruction starts, and a group's record gives where the instruction after its end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or -of the page when it has none. The header's bounds and instruction count are not written. +of the page when it has none. The header repeats the first page's edges and instruction count. `PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets. ## Writing diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs index 53d0ec8664..a5c6e00058 100644 --- a/crates/cdr/src/cmx_write.rs +++ b/crates/cdr/src/cmx_write.rs @@ -131,20 +131,20 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result Ok(()) }; // The header's index offset is set once the index is placed. - add(chunk(b"cont", &cont(0))?)?; + add(chunk(b"cont", &cont(0, PageHead::default()))?)?; // Each page chunk and its reference list, with where they start in the file and the start and // name of each of the page's layers. let mut pages = Vec::new(); let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> { let at = w.file_bytes; - let (c, written) = w.page(n, size, layers)?; + let (c, written, head) = w.page(n, size, layers)?; add(c)?; let refs = w.file_bytes; let r = chunk(b"rlst", &reference_list(written.len()))?; w.check_bytes(r.len())?; w.file_bytes += r.len(); add(r)?; - pages.push(PageAt { at, refs, layers: written }); + pages.push(PageAt { at, refs, layers: written, head }); Ok(()) }; for (n, p) in drawing.pages.iter().enumerate() { @@ -181,7 +181,7 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result if total > w.limits.input { return Err(Error::Limit("input size")); } - children[0] = chunk(b"cont", &cont(ixmr))?; + children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?; let mut bytes = Vec::new(); bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; bytes.extend(b"RIFF"); @@ -222,8 +222,9 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result, Error> { /// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64 /// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file /// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the -/// picture of the drawing, which the file does not hold (R77); the rest are zeros. -fn cont(ixmr: u32) -> Vec { +/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and +/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros. +fn cont(ixmr: u32, first: PageHead) -> Vec { let mut c = vec![0u8; 180]; c[48] = b'2'; c[52] = b'4'; @@ -231,9 +232,21 @@ fn cont(ixmr: u32) -> Vec { c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes()); c[84..88].copy_from_slice(&ixmr.to_le_bytes()); c[88..96].fill(0xFF); + for (i, v) in first.edges.iter().enumerate() { + c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + c[112..116].copy_from_slice(&first.instructions.to_le_bytes()); c } +/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom +/// edges and its instruction count, begin and end page included. +#[derive(Clone, Copy, Default)] +struct PageHead { + edges: [i32; 4], + instructions: u32, +} + /// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name. type LayerAt = (usize, Vec); @@ -243,6 +256,8 @@ struct PageAt { /// The page's reference list `rlst`. refs: usize, layers: Vec, + /// What the header repeats of its begin-page record. + head: PageHead, } /// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16 @@ -733,9 +748,10 @@ impl Writer { } /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60), - /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name. - /// The chunk starts at the file offset [`Writer::file_bytes`] gives. - fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec), Error> { + /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and + /// what the header repeats of the begin-page record. The chunk starts at the file offset + /// [`Writer::file_bytes`] gives. + fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec, PageHead), Error> { let mut out = Vec::new(); self.bounds = None; self.instructions = 1; @@ -803,7 +819,7 @@ impl Writer { self.check_bytes(c.len())?; let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect(); self.file_bytes += c.len(); - Ok((c, layers)) + Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions })) } /// An [`Error::Limit`] when the file would be longer than the input size of the limits with @@ -1164,29 +1180,15 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail let mut d = number.to_le_bytes().to_vec(); d.extend(0u32.to_le_bytes()); let mut list = Vec::new(); - let mut size_field = None; - let mut edges = [0i32; 4]; - if let Some((w, h)) = size { - // A negative or NaN side counts as 0. - let (wu, hu) = (width_units(w)?, width_units(h)?); - // A side that rounds to nothing would make the reader drop the page's whole size. - if wu == 0 || hu == 0 { - return Err(Error::Limit("page size")); + let edges = page_edges(size, bounds)?; + let size_field = match size { + Some((w, h)) => { + let mut s = width_units(w)?.to_le_bytes().to_vec(); + s.extend(width_units(h)?.to_le_bytes()); + Some(s) } - edges = match bounds { - Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], - None => { - // The page around its center; an odd size keeps its extra unit on the left and - // bottom, where the edge reaches -2^31. - let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); - let (w, h) = (i64::from(wu), i64::from(hu)); - [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] - } - }; - let mut s = wu.to_le_bytes().to_vec(); - s.extend(hu.to_le_bytes()); - size_field = Some(s); - } + None => None, + }; for v in edges { d.extend(v.to_le_bytes()); } @@ -1200,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail Ok(instr(BEGIN_PAGE, &fields(&list))) } +/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches +/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`]. +fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> { + let Some((w, h)) = size else { return Ok([0; 4]) }; + // A negative or NaN side counts as 0. + let (wu, hu) = (width_units(w)?, width_units(h)?); + // A side that rounds to nothing would make the reader drop the page's whole size. + if wu == 0 || hu == 0 { + return Err(Error::Limit("page size")); + } + Ok(match bounds { + Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], + None => { + // The page around its center; an odd size keeps its extra unit on the left and + // bottom, where the edge reaches -2^31. + let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); + let (w, h) = (i64::from(wu), i64::from(hu)); + [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] + } + }) +} + /// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it. fn windows_1252_byte(c: char) -> u8 { match u8::try_from(u32::from(c)) { diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 4c9ee11bb7..b18029fb25 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -153,8 +153,8 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// page, layer and group records give their instruction counts. A page's record also gives where /// its end-page instruction starts, and a group's record gives where the instruction after its /// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of -/// its curves, or of the page when it has none. The header's bounds and instruction count are not -/// written. +/// its curves, or of the page when it has none. The header repeats the first page's edges and +/// instruction count. pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { cmx_write::write(drawing, limits) } diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs index f25ed11fe2..989205e635 100644 --- a/crates/cdr/tests/it/cmx_write.rs +++ b/crates/cdr/tests/it/cmx_write.rs @@ -1078,6 +1078,35 @@ fn the_index_and_the_records_give_where_everything_is() { assert_eq!(groups, [(0, 3), (1, 7)]); } +#[test] +fn the_header_repeats_the_first_pages_edges_and_instruction_count() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let cont = 12 + 8; + let chunk = page_index(&b)[0][0]; + let page = chunk + 8; + // Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count + // and the instruction count. + let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4))); + assert_eq!(fields[0].0, 1); + let f1 = fields[0].1; + assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]); + // The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down. + let edges: Vec = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect(); + let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32; + assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]); + // Begin and end page, two begin and end layers and three curves. + assert_eq!(u32_at(&b, cont + 112), 9); + assert_eq!(u32_at(&b, f1 + 28), 9); + // A drawing without pages leaves them 0. + let b = write_cmx(&drawing(Vec::new())).unwrap().bytes; + assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0)); +} + /// The page index of a written file of two pages, each entry's page chunk, layer table, picture /// and reference list, checked through the header and the master index. fn page_index(b: &[u8]) -> Vec<[usize; 4]> { diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index 54fb837833..a13003b5c9 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -68,7 +68,7 @@ pub use paint_chip::{ PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords, }; pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well}; -pub use palette::{SwatchPalette, SwatchPaletteOutput}; +pub use palette::{PaletteCell, SwatchPalette, SwatchPaletteOutput}; pub use panel::{ ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow, diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index b5d35ac5c0..7da075f1aa 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -38,6 +38,18 @@ pub struct SwatchPaletteOutput { /// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour. /// The recent row and the Other… cell do not report a swatch index. pub picked_swatch: Option, + /// The cell `picked` came from, so a host can tell apart cells that show the same color. + pub cell: Option, +} + +/// A cell of a [`SwatchPalette`] by its place in the host's lists. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum PaletteCell { + /// The swatch at this index of the palette's swatches. + Swatch(usize), + /// The color at this index of the recent row's colors. + Recent(usize), } impl Outcome for SwatchPaletteOutput { @@ -112,8 +124,8 @@ impl PaletteColor<'_> { /// What the body picked in its pass. #[derive(Clone, Copy)] enum Pick { - /// A swatch or a recent colour. - Color { color: Srgba, swatch: Option }, + /// A swatch or a recent color, and its cell. + Color(Srgba, PaletteCell), /// The Other… cell. Other, } @@ -235,7 +247,7 @@ impl<'a> SwatchPalette<'a> { // The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates // on its release, so only the activation files the request: one request for one click. pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) { - Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }), + Some((_, picked)) => Some(Pick::Color(*picked, PaletteCell::Swatch(at))), None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other), }); } @@ -249,8 +261,8 @@ impl<'a> SwatchPalette<'a> { .space(SpaceAction::ActivateLead) .selection(Bind::bound(&mut current)) .show_all(ui); - if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) { - pick = Some(Pick::Color { color: *picked, swatch: None }); + if let Some((at, (_, picked))) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at).map(|cell| (at, cell))) { + pick = Some(Pick::Color(*picked, PaletteCell::Recent(at))); } } Some((before, pick)) @@ -265,19 +277,23 @@ impl<'a> SwatchPalette<'a> { let key = other.as_ref().map(|(key, _)| key.clone())?; Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None)) } - Pick::Color { color: after, swatch } => { + Pick::Color(after, cell) => { let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba()); let edit = (!unchanged).then(|| { color.write(cx, before, after, name.as_str()); let reported = bound.map_or(Mixed::Mixed, Mixed::Same); EditEvent::set(reported, after, Arc::from(name.as_str()), None) }); - Some((Some(after), edit, None, swatch)) + Some((Some(after), edit, None, Some(cell))) } } }) .flatten(); - let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None)); - SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch } + let (picked, edit, pick_color, cell) = settled.unwrap_or((None, None, None, None)); + let picked_swatch = match cell { + Some(PaletteCell::Swatch(at)) => Some(at), + _ => None, + }; + SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch, cell } } } diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 1363d82c47..dc32f707b1 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -452,6 +452,7 @@ pub struct ColorPanel<'a> { edited: Option>, shown: Option, recent: Option<&'a [Srgba]>, + recent_models: &'a [Option], recent_setup: Option, gamut: Option>, } @@ -476,6 +477,7 @@ struct Inputs<'a> { edited: Option<&'a Option>, shown: &'a ColorPanelShown, recent: Option<&'a [Srgba]>, + recent_models: &'a [Option], recent_setup: Option<&'a RecentSetup>, } @@ -494,6 +496,7 @@ impl<'a> ColorPanel<'a> { edited: None, shown: None, recent: None, + recent_models: &[], recent_setup: None, gamut: None, } @@ -563,6 +566,15 @@ impl<'a> ColorPanel<'a> { self } + /// The model values of each Recent Colors chip, in the order of [`recent`](Self::recent). A pick on a chip that has + /// them reports them with its color (`PickedColor::in_model`), so a CMYK recent color stays CMYK, and a chip + /// that shows the edited color's sRGB in another model still sets it. A chip with `None`, or past the end of + /// `models`, works as without this call: a pick sets its sRGB, and a pick of the color already shown sets nothing. + pub fn recent_models(mut self, models: &'a [Option]) -> Self { + self.recent_models = models; + self + } + /// The payload a Recent Colors chip drags. pub fn recent_payload(mut self, map: impl Fn(usize) -> Option

+ Send + Sync + 'static) -> Self { self.recent_setup = Some(recent_setup(map)); @@ -577,7 +589,8 @@ impl<'a> ColorPanel<'a> { /// Shows the panel and returns this pass's edits and requests. pub fn show(self, ui: &mut Ui) -> ColorPanelOutput { - let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self; + let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_models, recent_setup, gamut } = + self; let env = Env::of(ui); let (words, dialog) = (env.words::(), env.words::()); let mut held = Held::new(state); @@ -617,6 +630,7 @@ impl<'a> ColorPanel<'a> { edited: edited.as_ref(), shown: rows.as_ref().unwrap_or(&default_rows), recent, + recent_models, recent_setup: recent_setup.as_ref(), }, now: before, diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index 183844b574..1e6dd88dd9 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -3,7 +3,7 @@ //! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers. use craft_behavior::{EditEvent, Mixed}; -use craft_theme::Srgba; +use craft_theme::{ModelValues, Srgba}; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::{Shade, Text}; @@ -15,7 +15,7 @@ use craft_ui::text::{HexField, TextField}; use egui::Ui; use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow}; -use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette}; +use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PaletteCell, PickedColor, RampKind, SwatchPalette}; impl Body<'_> { /// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the @@ -156,8 +156,8 @@ impl Body<'_> { } } - /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list - /// is empty, where the first applied color will go. + /// The Recent Colors caption over a spaced palette; a pick sets the color, in the chip's model when the host gave it. + /// The caption shows while the host's list is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { @@ -174,13 +174,34 @@ impl Body<'_> { if let Some(setup) = self.inputs.recent_setup { palette = setup(palette); } - if let Some(event) = palette.show(ui).edit + let out = palette.show(ui); + let values = match out.cell { + Some(PaletteCell::Swatch(at)) => self.inputs.recent_models.get(at).copied().flatten(), + _ => None, + }; + if let (Some(color), Some(values)) = (out.picked, values) { + self.set_in_model(color, values); + } else if let Some(event) = out.edit && let Some(color) = event.value() { self.set_color(self.target, *color); } } + /// Sets the edited color to `color` in the model of `values`, keeping its alpha. It sets nothing when the host's + /// color already has those values and shows that color. + fn set_in_model(&mut self, color: Srgba, values: ModelValues) { + let before = self.picked().copied().unwrap_or_else(|| PickedColor::rgb(self.colors[self.target.index()])); + let after = PickedColor::in_model(color.with_alpha(before.color.a), values); + if before.model == after.model && before.color.to_rgba() == after.color.to_rgba() { + return; + } + // The rows' kept values in the chip's model would win over a host that keeps only sRGB (a grey's HSB hue). + self.kept.values[self.target.index()].retain(|v| v.model != values.model); + let name = self.words.title.as_str(); + self.push(self.target, EditEvent::set(Mixed::Same(before), after, name.into(), None)); + } + /// Sets `target`'s colour to `color`, keeping its alpha. fn set_color(&mut self, target: PanelTarget, color: Srgba) { let before = self.colors[target.index()]; diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 6efa4a64a3..ffcc37b8c5 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection}; use craft_color_ui::palette::{SwatchColor, SwatchGroup}; use craft_color_ui::ui::{ ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel, - PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, - SwatchesWords, swatch_rows, + PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, + SwatchesState, SwatchesWords, swatch_rows, }; use craft_host::target::Os; -use craft_theme::{ColorModel as _, HsbModel, Srgba}; +use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba}; use craft_ui::buttons::Button; use craft_ui::choice::SwatchTable; use craft_ui::contract::Role; @@ -367,6 +367,88 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow()); } +/// A Recent Colors pick in the FillStroke layout reports the chip's model values with its color, also when the chip +/// shows the edited color's sRGB in another model or without one; a chip whose values the edited color already has +/// sets nothing. +#[trial] +fn a_fill_stroke_recent_pick_keeps_the_chips_model() { + let chip = RECENT[0]; + let cmyk = ModelValues::new("cmyk", &[60.0, 90.0, 0.0, 0.0]); + let pick = |edited: PickedColor| { + let edits: Edits = Default::default(); + let seen = Rc::clone(&edits); + let mut fixture = Fixture::new(move |ui| { + let mut state = ColorPanelState::default(); + let out = ColorPanel::new(Bind::bound(&mut state), [edited.color, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(edited)) + .recent(&RECENT) + .recent_models(&[Some(cmyk)]) + .show(ui); + seen.borrow_mut().extend(out.edits); + }); + fixture.room(COLOR_ROOM).settle(); + let recent = fixture.by_label(&chip.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + edits.take() + }; + let rgb_of = |color: Srgba| ModelValues::new("rgb", &[color.r * 255.0, color.g * 255.0, color.b * 255.0]); + for edited in [PickedColor::in_model(RED, rgb_of(RED)), PickedColor::in_model(chip, rgb_of(chip)), PickedColor::rgb(chip)] { + let edits = pick(edited); + assert!( + matches!(edits.as_slice(), [(PanelTarget::Foreground, EditEvent::Set { after, .. })] + if after.model == Some(cmyk) && after.color.to_rgba() == chip.to_rgba()), + "one Set to the chip in CMYK from {edited:?}: {edits:?}" + ); + } + let edits = pick(PickedColor::in_model(chip, cmyk)); + assert!(edits.is_empty(), "the chip's own values set nothing: {edits:?}"); +} + +/// A Recent Colors pick drops the HSB values the rows kept for a grey: after a host that keeps only sRGB applies a grey +/// chip with HSB values, the Hue row reads the grey afresh instead of the hue of the earlier row edits. +#[trial] +fn a_fill_stroke_recent_pick_drops_the_rows_kept_hue() { + let grey = Srgba::rgb(0.5, 0.5, 0.5); + let chip = [grey]; + let chip_hsb = ModelValues::new("hsb", &[0.0, 0.0, 50.0]); + let host = Rc::new(RefCell::new(grey)); + let color = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let current = *color.borrow(); + let mut state = ColorPanelState { mode: ColorPanelMode::HsbSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), [current, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(PickedColor::rgb(current))) + .shown(ColorPanelShown::Mode(ColorPanelMode::HsbSliders)) + .recent(&chip) + .recent_models(&[Some(chip_hsb)]) + .show(ui); + for (_, event) in &shown.edits { + if let Some(picked) = event.landed() { + *color.borrow_mut() = picked.color; + } + } + }); + fixture.room(COLOR_ROOM).settle(); + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + for _ in 0..20 { + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + } + let hue_value = |fixture: &mut Fixture| { + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + let id = fixture.focused().expect("the hue slider takes the focus"); + fixture.tree().value(id).expect("the hue slider reports its value").to_owned() + }; + let stepped = hue_value(&mut fixture); + assert_ne!(stepped, "0", "the steps moved the kept hue of the grey"); + let recent = fixture.by_label(&grey.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + assert_eq!(hue_value(&mut fixture), "0", "the pick drops the kept hue {stepped}"); +} + /// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked, /// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls. #[trial] @@ -471,6 +553,7 @@ struct PaletteReports { edits: Vec>, requests: Vec, picked: Vec, + cells: Vec, swatches: Vec, } @@ -482,6 +565,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) { reports.edits.extend(shown.edit); reports.requests.extend(shown.pick_color); reports.picked.extend(shown.picked); + reports.cells.extend(shown.cell); reports.swatches.extend(shown.picked_swatch); } @@ -539,11 +623,13 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() { taken.edits[0] ); assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written"); + assert_eq!(taken.cells, [PaletteCell::Recent(0)], "the pick names its cell in the recent row"); let violet = fixture.by_label("Violet").expect("violet"); fixture.click(&violet).settle(); - let _ = std::mem::take(&mut *reports.borrow_mut()); + let taken = std::mem::take(&mut *reports.borrow_mut()); assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba()); + assert_eq!(taken.cells, [PaletteCell::Swatch(5)], "the pick names its swatch"); // Past the double-click time, so the repeat is a single click of its own. fixture.advance(1.0); let violet = fixture.by_label("Violet").expect("violet"); diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 444c227e09..fc8a4f0a55 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -226,6 +226,7 @@ craft-gpu-device = { workspace = true, optional = true } craft-gpu-null = { workspace = true, optional = true } craft-gpu-providers = { workspace = true, optional = true } craft-gpu-wgpu = { workspace = true, optional = true } +craft-gpu-yuv = { workspace = true, optional = true } craft-ipp = { workspace = true, optional = true } craft-ppt-binary = { workspace = true, optional = true } craft-sqlite = { workspace = true, optional = true } @@ -552,6 +553,8 @@ gpu-wgpu-native-gles = ["gpu-wgpu", "craft-gpu-wgpu/native-gles"] gpu-wgpu-native-metal = ["gpu-wgpu", "craft-gpu-wgpu/native-metal"] gpu-wgpu-native-vulkan = ["gpu-wgpu", "craft-gpu-wgpu/native-vulkan"] +gpu-yuv = ["dep:craft-gpu-yuv"] + gridcraft-format = ["dep:craft-gridcraft-format"] gzip = ["dep:craft-gzip"] @@ -703,6 +706,8 @@ pages = ["dep:craft-pages", "keymap", "text"] palette = ["dep:craft-palette"] pbr = ["dep:craft-pbr"] +pbr-materialx = ["pbr", "craft-pbr/materialx"] +pbr-mesh = ["pbr", "craft-pbr/mesh"] pbr-parallel = ["pbr", "craft-pbr/parallel"] pcap = ["dep:craft-pcap"] @@ -942,7 +947,12 @@ text-ukrainian = ["text", "craft-text/ukrainian"] texture = ["dep:craft-texture"] texture-dds = ["texture", "craft-texture/dds"] +texture-decode = ["texture", "craft-texture/decode"] +texture-exr = ["texture", "craft-texture/exr"] +texture-hdr = ["texture", "craft-texture/hdr"] texture-parallel = ["texture", "craft-texture/parallel"] +texture-png = ["texture", "craft-texture/png"] +texture-tiff = ["texture", "craft-texture/tiff"] tga = ["dep:craft-tga"] diff --git a/crates/craft/README.md b/crates/craft/README.md index 7ccfce5c1a..e302076568 100644 --- a/crates/craft/README.md +++ b/crates/craft/README.md @@ -17,6 +17,7 @@ craft = { workspace = true, features = ["ui", "color-ui", "draw", "imaging", "ke ## Features - One feature per crate, named after the crate without `craft-`: `color-ui` turns on `craft-color-ui` and re-exports it as `craft::color_ui`. +- `gpu-yuv` enables the GPU YUV provider through `craft::gpu_yuv`. - `ui` turns on `craft-ui` (`craft::ui`), re-exports `egui` (`craft::egui`, the egui the library is built with) and forwards `ui` to every enabled crate. - `screen-testing` implies `ui` and forwards to every enabled crate. - Each crate feature is forwarded as `-` (`platform-appearance`, `text-hyphen`, `ui-window-frame`). diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index f52fb4834a..8290887540 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -169,6 +169,8 @@ pub use craft_gpu_null as gpu_null; pub use craft_gpu_providers as gpu_providers; #[cfg(feature = "gpu-wgpu")] pub use craft_gpu_wgpu as gpu_wgpu; +#[cfg(feature = "gpu-yuv")] +pub use craft_gpu_yuv as gpu_yuv; #[cfg(feature = "gridcraft-format")] pub use craft_gridcraft_format as gridcraft_format; #[cfg(feature = "gzip")] diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml new file mode 100644 index 0000000000..28053d83b1 --- /dev/null +++ b/crates/gpu-yuv/Cargo.toml @@ -0,0 +1,29 @@ +[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, as a craft-gpu provider, 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] +craft-gpu = { workspace = true } +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 } +# 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 new file mode 100644 index 0000000000..9a39ce0ff3 --- /dev/null +++ b/crates/gpu-yuv/README.md @@ -0,0 +1,148 @@ +# craft-gpu-yuv + +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. + +## Contents + +| 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 | +| `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 | + +## 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`) and the RGBA8 input at most +`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 +`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 +(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. + +`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 + +- 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 + +- `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 new file mode 100644 index 0000000000..b96bc90ed3 --- /dev/null +++ b/crates/gpu-yuv/src/cpu.rs @@ -0,0 +1,142 @@ +//! 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. +//! +//! 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}; + +/// 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] + } +} + +/// 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. +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 (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 { + 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))); + } + } + }; + 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 => { + 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..a77e3316c5 --- /dev/null +++ b/crates/gpu-yuv/src/gpu.rs @@ -0,0 +1,360 @@ +//! 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); +}} + +// A half rounds up, as INT and Round do in the recommendations; WGSL's round() takes it to the +// 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 {{ + 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 {{ + 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/job.rs b/crates/gpu-yuv/src/job.rs new file mode 100644 index 0000000000..4f98dccca8 --- /dev/null +++ b/crates/gpu-yuv/src/job.rs @@ -0,0 +1,365 @@ +//! 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 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}; + +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 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(_) | Error::Memory { .. } => 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(); + // 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, 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 })); + } + } + // 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 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)?; + 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`]; 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; + 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 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); + // 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)); + } + 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 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(); + 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> { + // 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 { + 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 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..c1a723da4b --- /dev/null +++ b/crates/gpu-yuv/src/job_tests.rs @@ -0,0 +1,261 @@ +//! `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()); +} + +#[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()); + 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() { + 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/layout.rs b/crates/gpu-yuv/src/layout.rs new file mode 100644 index 0000000000..93b3f77269 --- /dev/null +++ b/crates/gpu-yuv/src/layout.rs @@ -0,0 +1,123 @@ +//! 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, or `u32::MAX` when the fields give more. + pub fn row_bytes(&self) -> u32 { + self.width.saturating_mul(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) +} + +/// 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 { + 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. + /// Fields changed after [`FrameLayout::new`] that give more than `usize::MAX` give + /// `usize::MAX`. + pub fn frame_bytes(&self) -> usize { + 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) + /// 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 !self.is_valid() { + 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 }); + } + 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 layout and size checks above leave 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..24afb1a4aa --- /dev/null +++ b/crates/gpu-yuv/src/lib.rs @@ -0,0 +1,36 @@ +//! 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), 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. +//! - [`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 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..303abad3c7 --- /dev/null +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -0,0 +1,350 @@ +//! 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`. `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.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 +/// 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 near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3; + 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)); + 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). +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 new file mode 100644 index 0000000000..2e311a9401 --- /dev/null +++ b/crates/gpu-yuv/src/spec.rs @@ -0,0 +1,193 @@ +//! 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 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], + 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().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 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 }, + /// 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 }, + /// 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), +} + +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 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"), + 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}"), + } + } +} + +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..b0c601e773 --- /dev/null +++ b/crates/gpu-yuv/src/tests.rs @@ -0,0 +1,468 @@ +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 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(); + 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 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 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 { + 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. + +pub(crate) fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + device_with(|l| l) +} + +/// A device with the adapter's limits as `limits` changes them. +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"); + 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). +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, + 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 } +} + +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)); + 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. +pub(crate) 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. +pub(crate) 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 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. + 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()); +} diff --git a/crates/image-codecs/src/codecs/tiff/decode.rs b/crates/image-codecs/src/codecs/tiff/decode.rs index c365d01581..dcccadde66 100644 --- a/crates/image-codecs/src/codecs/tiff/decode.rs +++ b/crates/image-codecs/src/codecs/tiff/decode.rs @@ -747,8 +747,8 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result, colorspace: Option }, + /// A file from an image node, with the file prefix in effect applied: the `file` input's + /// `fileprefix`, else the node's, its nodegraph's or the document's. `colorspace` is the + /// color space in effect on the node's `file` input, found the same way as for a constant, + /// and `uv_tiling` is the node's `uvtiling` as written. A `uvtiling` value that is not two + /// finite numbers is [`Error::Malformed`]. An image node with a boolean, integer, float or + /// vector type is in the document's working color space. + Image { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, + /// This variant stores an encoded tangent-space image connected through a `normalmap` node. + /// The fields have the same meaning as [`Self::Image`]. + NormalMap { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, +} + /// A surface material resolved from a MaterialX document. #[derive(Clone, Debug, PartialEq)] pub struct Material { @@ -82,12 +107,41 @@ pub struct Material { pub warnings: Vec, } +/// A surface material resolved by [`Document::read_material_strict`]. +#[derive(Clone, Debug, PartialEq)] +pub struct StrictMaterial { + /// Material name, or `Material` when omitted. + pub name: String, + /// Shader dialect represented by the material. + pub shader: Shader, + /// Resolved inputs in the shader table's deterministic order. + pub inputs: Vec<(String, Resolved)>, + /// Resolved scalar displacement input, if present. Vector displacement is reported as unsupported. + pub displacement: Option, + /// First image tiling of two positive numbers, kept in `0.001..=1000`, or `[1, 1]`. + pub uv_tiling: [f32; 2], + /// Unsupported or ignored constructs encountered while resolving values, and shader inputs + /// that are not in the shader's table and so are not read. + pub warnings: Vec, +} + #[derive(Clone, Debug)] struct Found { value: Value, tiling: Option<[f32; 2]>, } +/// The material, its surface shader and the document's nodes, found for a read. +struct Located<'a> { + mat: &'a El, + shader: &'a El, + scope: Option, + kind: Shader, + nodes: HashMap, + graphs: HashMap<&'a str, &'a El>, + outputs: Vec<(String, String)>, +} + const OPEN_PBR_INPUTS: &[&str] = &[ "base_color", "base_metalness", @@ -138,6 +192,76 @@ const GLTF_INPUTS: &[&str] = &[ "transmission", ]; +const OPEN_PBR_STRICT_INPUTS: &[&str] = &[ + "base_color", + "base_metalness", + "specular_roughness", + "geometry_normal", + "geometry_opacity", + "emission_color", + "coat_weight", + "coat_roughness", + "geometry_coat_normal", + "fuzz_weight", + "fuzz_color", + "fuzz_roughness", + "specular_roughness_anisotropy", + "transmission_weight", + "subsurface_weight", + "base_weight", + "specular_weight", + "specular_color", + "specular_ior", + "coat_color", + "coat_ior", + "emission_luminance", +]; +const STANDARD_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metalness", + "specular_roughness", + "normal", + "opacity", + "emission_color", + "coat", + "coat_roughness", + "coat_normal", + "sheen", + "sheen_color", + "sheen_roughness", + "specular_anisotropy", + "transmission", + "subsurface", + "base", + "specular", + "specular_color", + "specular_IOR", + "coat_color", + "coat_IOR", + "emission", +]; +const GLTF_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metallic", + "roughness", + "normal", + "alpha", + "emissive", + "occlusion", + "clearcoat", + "clearcoat_roughness", + "clearcoat_normal", + "sheen_color", + "sheen_roughness", + "transmission", + "emissive_strength", + "ior", + "specular", + "specular_color", + "alpha_mode", + "alpha_cutoff", +]; + /// OpenPBR input kind accepted by [`write_open_pbr`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum InputKind { @@ -253,49 +377,13 @@ impl Document { /// Resolves a surface material into shader inputs, image paths and warnings. pub fn read_material(&self, material: Option<&str>) -> Result { - let materials: Vec<&El> = self.root.children("surfacematerial").collect(); - let mat = match material { - Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, - None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + let Located { mat, shader, kind, nodes, outputs, .. } = self.locate(material, false)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_INPUTS, + Shader::StandardSurface => STANDARD_INPUTS, + Shader::GltfPbr => GLTF_INPUTS, }; - let mut nodes = HashMap::new(); - let mut outputs = Vec::new(); - for child in self.root.elements() { - if child.name == "nodegraph" { - let Some(graph) = child.attr("name") else { continue }; - for node in child.elements() { - let Some(name) = node.attr("name") else { continue }; - if node.name == "output" { - if let Some(from) = node.attr("nodename") { - outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); - } - } else { - nodes.insert(format!("{graph}/{name}"), node); - } - } - } else if let Some(name) = child.attr("name") { - nodes.insert(name.to_owned(), child); - } - } - let shader_name = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")).and_then(|i| i.attr("nodename")); - let shader = shader_name.and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; - let (kind, inputs) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR_INPUTS), - "standard_surface" => (Shader::StandardSurface, STANDARD_INPUTS), - "gltf_pbr" => (Shader::GltfPbr, GLTF_INPUTS), - other => return Err(Error::Unsupported(format!("surface shader is {other}"))), - }; - let emission_gate = match kind { - Shader::OpenPbr => Some(("emission_luminance", true)), - Shader::StandardSurface => Some(("emission", true)), - Shader::GltfPbr => None, - }; - let emission_enabled = emission_gate.is_none_or(|(name, _)| { - shader - .children("input") - .find(|i| i.attr("name") == Some(name)) - .is_some_and(|i| i.attr("value").is_none_or(|v| parse_numbers(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) - }); + let emission_enabled = emission_enabled(kind, shader, parse_numbers); let mut warnings = Vec::new(); let base_weight_name = match kind { Shader::OpenPbr => Some("base_weight"), @@ -343,6 +431,166 @@ impl Document { warnings, }) } + + /// Resolves a surface material like [`Document::read_material`], with a wider input table, the + /// color space in effect and the UV tiling of each image, and stricter checks. + /// + /// The tables add each shader's weight, specular, IOR and coat color inputs, OpenPBR's + /// `emission_luminance`, and glTF PBR's `emissive_strength` and alpha mode inputs; glTF PBR's + /// emission color is read from `emissive`, the name its node definition gives it. Values may + /// be separated by commas, spaces or both, `convert` nodes follow the Standard Nodes rules, + /// and an image inside a nodegraph takes the nodegraph's `fileprefix`. A repeated shader + /// input, a value that is not one to four finite numbers or does not fit its type, and a + /// `uvtiling` that is not two finite numbers are [`Error::Malformed`]. A shader input that is + /// not in the table gives the warning `input is not read`; the base weight warning of + /// [`Document::read_material`] is not given, since the weight is read. A `normalmap` node's + /// `scale` other than 1 and authored `normal`, `tangent`, and `bitangent` inputs are not applied + /// and give warnings. Image inputs of `normalmap` nodes resolve as [`Resolved::NormalMap`]. + /// Three-component literal normal-map inputs are unsupported and give warnings. Other literal + /// sizes return [`Error::Malformed`]. + /// Surface shaders may connect through graph outputs. A graph with several outputs needs a + /// named selection; a graph with one output uses it regardless of the selection attribute. + /// Missing node and graph-output references are errors. Supported numeric `constant` nodes + /// use their typed zero values when `value` is omitted. Emission colors remain resolved when + /// their strength is zero. Nonzero image `uvoffset`, nonidentity displacement `scale`, and + /// vector displacement are reported as unsupported. + pub fn read_material_strict(&self, material: Option<&str>) -> Result { + let Located { mat, shader, scope, kind, nodes, graphs, outputs } = self.locate(material, true)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_STRICT_INPUTS, + Shader::StandardSurface => STANDARD_STRICT_INPUTS, + Shader::GltfPbr => GLTF_STRICT_INPUTS, + }; + let mut warnings = Vec::new(); + let mut seen = HashSet::new(); + for name in shader.children("input").filter_map(|i| i.attr("name")) { + if !seen.insert(name) { + return Err(Error::Malformed(format!("the shader has more than one {name} input"))); + } + if !inputs.contains(&name) { + warnings.push(format!("input {name} is not read")); + } + } + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + let shader_space = resolver.space_of(shader, scope.as_deref()); + let mut resolved = Vec::new(); + let mut tiling = None; + for name in inputs { + let Some(input) = shader.children("input").find(|i| i.attr("name") == Some(*name)) else { continue }; + if let Some(value) = resolver.value(input, scope.as_deref(), shader_space, 0, &mut warnings)? { + if tiling.is_none() { + tiling = image_tiling(&value); + } + resolved.push(((*name).to_owned(), value)); + } + } + let mut displacement = None; + if let Some(connection) = mat.children("input").find(|i| i.attr("name") == Some("displacementshader")) { + let target = resolver.target(connection, None)?; + if let Some(node) = target.as_ref().and_then(|name| nodes.get(name).copied()) { + let node_scope = target.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph); + let space = resolver.space_of(node, node_scope); + if let Some(input) = node.children("input").find(|i| i.attr("name") == Some("displacement")) { + let value = resolver.value(input, node_scope, space, 0, &mut warnings)?; + if resolver.value_type(input, node_scope)? == Some("vector3") + || matches!(&value, Some(Resolved::Constant { values, .. }) if values.len() == 3) + { + warnings.push("vector displacement is not supported; its input was skipped".into()); + } else { + displacement = value; + } + } + if let Some(scale) = node.children("input").find(|i| i.attr("name") == Some("scale")).filter(|i| has_authored_value(i)) { + let value = resolver.value(scale, node_scope, space, 0, &mut warnings)?; + match value { + Some(Resolved::Constant { values, .. }) if values.len() != 1 => { + return Err(Error::Malformed("displacement scale is not one finite number".into())); + } + Some(Resolved::Constant { values, .. }) if values == [1.0] => {} + _ => warnings.push("the scale of the displacement node is not read".into()), + } + } + if tiling.is_none() { + tiling = displacement.as_ref().and_then(image_tiling); + } + } + } + Ok(StrictMaterial { + name: mat.attr("name").unwrap_or("Material").to_owned(), + shader: kind, + inputs: resolved, + displacement, + uv_tiling: tiling.unwrap_or([1.0, 1.0]), + warnings, + }) + } + + /// The surface material named `material` (or the first one), its surface shader, and the + /// document's nodes, nodegraphs and graph outputs. + fn locate(&self, material: Option<&str>, strict: bool) -> Result, Error> { + let materials: Vec<&El> = self.root.children("surfacematerial").collect(); + let mat = match material { + Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, + None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + }; + let mut nodes = HashMap::new(); + let mut graphs = HashMap::new(); + let mut outputs = Vec::new(); + for child in self.root.elements() { + if child.name == "nodegraph" { + let Some(graph) = child.attr("name") else { continue }; + graphs.insert(graph, child); + for node in child.elements() { + let Some(name) = node.attr("name") else { continue }; + if node.name == "output" { + if let Some(from) = node.attr("nodename") { + outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); + } else if strict { + outputs.push((format!("{graph}/{name}"), String::new())); + } + } else { + nodes.insert(format!("{graph}/{name}"), node); + } + } + } else if let Some(name) = child.attr("name") { + nodes.insert(name.to_owned(), child); + } + } + let connection = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")); + let shader_name = if strict { + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + connection.map(|input| resolver.target(input, None)).transpose()?.flatten() + } else { + connection.and_then(|input| input.attr("nodename")).map(str::to_owned) + }; + let shader = + shader_name.as_ref().and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; + let scope = shader_name.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph.to_owned()); + let kind = match shader.name.as_str() { + "open_pbr_surface" => Shader::OpenPbr, + "standard_surface" => Shader::StandardSurface, + "gltf_pbr" => Shader::GltfPbr, + other => return Err(Error::Unsupported(format!("surface shader is {other}"))), + }; + Ok(Located { mat, shader, scope, kind, nodes, graphs, outputs }) + } +} + +/// Whether the shader's emission is on: its strength input (`emission_luminance` or +/// `emission`) is connected or holds a value above 0, read with `parse`. glTF PBR has no such +/// input, so its emission is always on. +fn emission_enabled(kind: Shader, shader: &El, parse: fn(&str) -> Option>) -> bool { + let gate = match kind { + Shader::OpenPbr => Some("emission_luminance"), + Shader::StandardSurface => Some("emission"), + Shader::GltfPbr => None, + }; + gate.is_none_or(|name| { + shader + .children("input") + .find(|i| i.attr("name") == Some(name)) + .is_some_and(|i| i.attr("value").is_none_or(|v| parse(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) + }) } fn numeric_input(shader: &El, name: &str) -> Option { @@ -424,6 +672,373 @@ fn resolve_value( } } +fn image_tiling(value: &Resolved) -> Option<[f32; 2]> { + match value { + Resolved::Image { uv_tiling, .. } | Resolved::NormalMap { uv_tiling, .. } => { + uv_tiling.filter(|n| n.iter().all(|v| *v > 0.0)).map(|n| [n[0].clamp(0.001, 1000.0), n[1].clamp(0.001, 1000.0)]) + } + Resolved::Constant { .. } => None, + } +} + +fn has_authored_value(input: &El) -> bool { + ["value", "nodename", "nodegraph", "interfacename"].iter().any(|name| input.attr(name).is_some()) +} + +/// One to four finite numbers separated by commas, spaces or both, as MaterialX's own value +/// reader splits vector and color values. +fn parse_values(text: &str) -> Option> { + let nums: Option> = text + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|part| !part.is_empty()) + .map(|part| part.parse::().ok().filter(|v| v.is_finite())) + .collect(); + nums.filter(|v| !v.is_empty() && v.len() <= 4) +} + +/// The value of the input `input`, read as a `boolean` (`true` or `false`, as 1 or 0) or an +/// `integer` (one whole number) when its type says so, and as numbers otherwise. A `float`, +/// vector or color type needs as many numbers as it has channels. +fn input_numbers(input: &El, text: &str) -> Option> { + match input.attr("type") { + Some("boolean") => match text.trim() { + "true" => Some(vec![1.0]), + "false" => Some(vec![0.0]), + _ => None, + }, + Some("integer") => text.trim().parse::().ok().map(|v| vec![v as f32]), + ty => parse_values(text).filter(|v| ty.and_then(channels).is_none_or(|n| v.len() == n)), + } +} + +/// The number of channels of a MaterialX numeric type. +fn channels(ty: &str) -> Option { + match ty { + "float" | "integer" | "boolean" => Some(1), + "vector2" => Some(2), + "color3" | "vector3" => Some(3), + "color4" | "vector4" => Some(4), + _ => None, + } +} + +/// Whether `ty` is a numeric MaterialX type that is not a color: a boolean, integer, float or +/// vector. A `colorspace` does not apply to values of these types. +fn is_numeric_non_color(ty: Option<&str>) -> bool { + ty.is_some_and(|ty| channels(ty).is_some() && !matches!(ty, "color3" | "color4")) +} + +/// The type of `count` numbers whose type is not written: a float, or a vector. +fn untyped(count: usize) -> &'static str { + match count { + 1 => "float", + 2 => "vector2", + 3 => "vector3", + _ => "vector4", + } +} + +/// `values` of type `from` converted to type `to` by the `convert` node's rules in the MaterialX +/// Standard Nodes: a boolean becomes a float or integer of 0 or 1, an integer becomes a float or +/// a boolean (1 for any value that is not 0), a boolean, float or integer is copied to every +/// channel of a color or vector, and a color or vector keeps its first channels and fills +/// missing ones with 0 (1 in the fourth). `None` for a pair the node does not define, such as a +/// float to an integer or a color to a float, and for values that do not fit `from`. +fn converted(values: &[f32], from: &str, to: &str) -> Option> { + if channels(from)? != values.len() { + return None; + } + let out = channels(to)?; + match (from, to) { + _ if from == to => Some(values.to_vec()), + ("boolean", "float" | "integer") | ("integer", "float") => Some(values.to_vec()), + ("integer", "boolean") => Some(vec![if values[0] != 0.0 { 1.0 } else { 0.0 }]), + ("boolean" | "float" | "integer", _) if out > 1 => Some(vec![values[0]; out]), + _ if values.len() > 1 && out > 1 => Some((0..out).map(|c| values.get(c).copied().unwrap_or(if c == 3 { 1.0 } else { 0.0 })).collect()), + _ => None, + } +} + +/// The document's nodes, nodegraphs and graph outputs, for following input connections. +struct Resolver<'a> { + root: &'a El, + nodes: &'a HashMap, + graphs: &'a HashMap<&'a str, &'a El>, + outputs: &'a [(String, String)], +} + +impl<'a> Resolver<'a> { + /// The color space in effect on `element`: its own, else its nodegraph's when `scope` names + /// one, else the document's. + fn space_of(&self, element: &'a El, scope: Option<&str>) -> Option<&'a str> { + element + .attr("colorspace") + .or_else(|| scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("colorspace"))) + .or_else(|| self.root.attr("colorspace")) + } + + /// The document's working color space, the root element's `colorspace`. + fn working(&self) -> Option<&'a str> { + self.root.attr("colorspace") + } + + /// The value of `input`, an input of an element in nodegraph `scope` (or at the top level) + /// whose color space in effect is `space`. A `value` that is not one to four finite numbers, + /// or that does not fit a `boolean` or `integer` type, is [`Error::Malformed`]; an + /// unsupported connection is skipped with a warning. + fn value( + &self, + input: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if hops > 16 { + warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); + return Ok(None); + } + if let Some(interface) = input.attr("interfacename") { + warnings.push(format!("interface input {interface:?} is not supported; its value was skipped")); + return Ok(None); + } + if let Some(value) = input.attr("value") { + let Some(values) = input_numbers(input, value) else { + let name = input.attr("name").unwrap_or(""); + return Err(Error::Malformed(format!("input {name} has a value that is not one to four finite numbers or does not fit its type"))); + }; + let colorspace = if is_numeric_non_color(input.attr("type")) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + let target = self.target(input, scope)?; + let Some(node) = target.as_ref().and_then(|t| self.nodes.get(t).copied()) else { return Ok(None) }; + let node_scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g); + let node_space = self.space_of(node, node_scope); + let child = |name: &str| node.children("input").find(|i| i.attr("name") == Some(name)); + let node_name = node.attr("name").unwrap_or(""); + match node.name.as_str() { + "image" | "tiledimage" => { + let file = child("file").and_then(|input| input.attr("value").filter(|file| !file.is_empty()).map(|file| (input, file))); + let Some((file_input, file)) = file else { + warnings.push(format!("image node {node_name:?} has no nonempty literal file value; its image was skipped")); + return Ok(None); + }; + let prefix = file_input + .attr("fileprefix") + .or_else(|| node.attr("fileprefix")) + .or_else(|| node_scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("fileprefix"))) + .or_else(|| self.root.attr("fileprefix")) + .unwrap_or(""); + let uv_tiling = match child("uvtiling").filter(|input| has_authored_value(input)) { + None => None, + Some(input) => match self.value(input, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() == 2 => Some([values[0], values[1]]), + Some(Resolved::Constant { .. }) => { + return Err(Error::Malformed(format!("the uvtiling of image {node_name:?} is not two finite numbers"))); + } + _ => { + warnings.push(format!("the uvtiling of image {node_name:?} is not read")); + None + } + }, + }; + if let Some(offset) = child("uvoffset").filter(|input| has_authored_value(input)) { + match self.value(offset, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() != 2 => { + return Err(Error::Malformed(format!("the uvoffset of image {node_name:?} is not two finite numbers"))); + } + Some(Resolved::Constant { values, .. }) if values == [0.0, 0.0] => {} + _ => warnings.push(format!("the uvoffset of image {node_name:?} is not read")), + } + } + for mode in ["uaddressmode", "vaddressmode"] { + if let Some(input) = child(mode).filter(|input| has_authored_value(input)) { + match input.attr("value") { + Some("periodic") => {} + Some("constant" | "clamp" | "mirror") | None => warnings.push(format!("the {mode} of image {node_name:?} is not read")), + Some(_) => return Err(Error::Malformed(format!("the {mode} of image {node_name:?} is not a supported addressing mode"))), + } + } + } + let colorspace = if is_numeric_non_color(node.attr("type")) { self.working() } else { file_input.attr("colorspace").or(node_space) } + .map(str::to_owned); + Ok(Some(Resolved::Image { file: format!("{prefix}{file}"), colorspace, uv_tiling })) + } + "normalmap" => { + for name in ["normal", "tangent", "bitangent"] { + if child(name).is_some_and(has_authored_value) { + warnings.push(format!("the {name} of normalmap node {node_name:?} is not read")); + } + } + // The normal is passed on without the node's scale, so a scale other than 1 is + // reported. + if let Some(scale) = child("scale").filter(|input| has_authored_value(input)) { + let resolved = self.value(scale, node_scope, node_space, hops + 1, &mut Vec::new())?; + if !matches!(resolved, Some(Resolved::Constant { ref values, .. }) if values.iter().all(|s| *s == 1.0)) { + warnings.push(format!("the scale of normalmap node {node_name:?} is not read")); + } + } + match child("in") { + Some(i) => Ok(match self.value(i, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Image { file, colorspace, uv_tiling }) => Some(Resolved::NormalMap { file, colorspace, uv_tiling }), + Some(Resolved::Constant { values, .. }) if values.len() != 3 => { + return Err(Error::Malformed(format!("the input of normalmap node {node_name:?} is not three finite numbers"))); + } + Some(Resolved::Constant { .. }) => { + warnings.push(format!("the literal input of normalmap node {node_name:?} is not supported; its value was skipped")); + None + } + Some(Resolved::NormalMap { .. }) => { + warnings.push(format!("the nested normalmap input of node {node_name:?} is not supported; its value was skipped")); + None + } + value => value, + }), + None => Ok(None), + } + } + "convert" => { + let Some(i) = child("in").filter(|input| has_authored_value(input)) else { + let definition = node.attr("nodedef").and_then(|name| name.strip_prefix("ND_convert_")).and_then(|name| name.split_once('_')); + if let Some((from, to)) = definition + && from != to + && node.attr("type").is_none_or(|ty| ty == to) + && let Some(count) = channels(from) + && let Some(values) = converted(&vec![0.0; count], from, to) + { + return Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })); + } + warnings.push(format!("the input default of convert node {node_name:?} cannot be identified; its value was skipped")); + return Ok(None); + }; + let Some(value) = self.value(i, node_scope, node_space, hops + 1, warnings)? else { return Ok(None) }; + let to = node.attr("type").unwrap_or(""); + let from = self.value_type(i, node_scope)?; + match value { + Resolved::Constant { values, colorspace } => { + // A value with no type is a float or a vector, so it is in the working + // color space like a typed one. + let colorspace = if from.is_none() && i.attr("value").is_some() { self.working().map(str::to_owned) } else { colorspace }; + let from = from.unwrap_or_else(|| untyped(values.len())); + match converted(&values, from, to) { + Some(values) => Ok(Some(Resolved::Constant { values, colorspace })), + None => { + warnings.push(format!( + "a convert node ({node_name:?}) from type {from:?} to type {to:?} is not supported; its input was skipped" + )); + Ok(None) + } + } + } + // An image keeps its own channels, so only a convert that copies every + // channel as it is passes it on. + image @ (Resolved::Image { .. } | Resolved::NormalMap { .. }) => { + let copies = from.is_some_and(|from| from == to || channels(from).is_some_and(|n| n > 1 && channels(to) == Some(n))); + if copies { + Ok(Some(image)) + } else { + warnings.push(format!( + "a convert node ({node_name:?}) changes an image's channels to type {to:?}, which is not supported; its input was skipped" + )); + Ok(None) + } + } + } + } + "constant" => { + let value = child("value").filter(|input| has_authored_value(input)); + match value { + // A connected value keeps the color space it resolved; only a written value takes + // the working color space. + Some(i) => match self.constant_value(i, node, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if is_numeric_non_color(node.attr("type")) && i.attr("value").is_some() => { + Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })) + } + value => Ok(value), + }, + None => match node.attr("type").and_then(channels) { + Some(count) => { + let space = if is_numeric_non_color(node.attr("type")) { self.working() } else { node_space }; + Ok(Some(Resolved::Constant { values: vec![0.0; count], colorspace: space.map(str::to_owned) })) + } + None => { + warnings.push(format!("the default of constant node {node_name:?} has an unsupported type")); + Ok(None) + } + }, + } + } + other => { + warnings.push(format!("a {other} node ({node_name:?}) is not supported; its input was skipped")); + Ok(None) + } + } + } + + fn constant_value( + &self, + input: &'a El, + node: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if input.attr("type").is_none() + && input.attr("interfacename").is_none() + && let Some(text) = input.attr("value") + && let Some(ty) = node.attr("type") + { + let typed = El::new("input").with_attr("type", ty); + let values = input_numbers(&typed, text) + .ok_or_else(|| Error::Malformed(format!("constant {:?} has a value that does not fit {ty}", node.attr("name").unwrap_or(""))))?; + let colorspace = if is_numeric_non_color(Some(ty)) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + self.value(input, scope, space, hops, warnings) + } + + /// The key in `nodes` of the node that `input`, an input of an element in nodegraph `scope` + /// (or at the top level), connects to. + fn target(&self, input: &El, scope: Option<&str>) -> Result, Error> { + let target = if let Some(graph) = input.attr("nodegraph") { + let prefix = format!("{graph}/"); + let outputs: Vec<_> = self.outputs.iter().filter(|(name, _)| name.starts_with(&prefix)).collect(); + let selected = if outputs.len() == 1 { + outputs.first().copied() + } else { + input.attr("output").and_then(|output| outputs.iter().rev().copied().find(|(name, _)| name == &format!("{graph}/{output}"))) + }; + Some( + selected + .ok_or_else(|| { + Error::Malformed(format!("input {:?} has no selected output in nodegraph {graph:?}", input.attr("name").unwrap_or(""))) + })? + .1 + .clone(), + ) + } else if let Some(name) = input.attr("nodename") { + let qualified = scope.map(|g| format!("{g}/{name}")); + Some(qualified.unwrap_or_else(|| name.to_owned())) + } else { + None + }; + if let Some(name) = target.as_ref() + && !self.nodes.contains_key(name) + { + return Err(Error::Malformed(format!("input {:?} references missing node {name:?}", input.attr("name").unwrap_or("")))); + } + Ok(target) + } + + fn value_type(&self, input: &'a El, scope: Option<&str>) -> Result, Error> { + if input.attr("type").is_some() || input.attr("value").is_some() { + return Ok(input.attr("type")); + } + Ok(self.target(input, scope)?.as_ref().and_then(|name| self.nodes.get(name).copied()).and_then(|node| node.attr("type"))) + } +} + /// Writes an OpenPBR MaterialX document for the supplied textures. /// /// Unknown inputs and duplicate inputs are skipped; the first texture for an input wins. Color @@ -566,9 +1181,13 @@ mod tests { "#; - let material = Document::parse(xml).unwrap().read_material(None).unwrap(); + let doc = Document::parse(xml).unwrap(); + let material = doc.read_material(None).unwrap(); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); assert_eq!(material.uv_tiling, [4.0, 2.0]); + let strict = doc.read_material_strict(None).unwrap(); + assert_eq!(strict.displacement, Some(Resolved::Image { file: "height.png".into(), colorspace: None, uv_tiling: Some([4.0, 2.0]) })); + assert_eq!(strict.uv_tiling, [4.0, 2.0]); } #[test] @@ -594,6 +1213,22 @@ mod tests { assert_eq!(material.inputs[2].1, Value::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); assert_eq!(material.displacement, Some(Value::Constant { values: vec![0.25], colorspace: None })); assert_eq!(material.uv_tiling, [2.0, 4.0]); + assert!(matches!(doc.read_material_strict(None), Err(Error::Malformed(_)))); + let mut explicit = doc.clone(); + let normalmap = explicit.root.elements_mut().find(|node| node.attr("name") == Some("N")).unwrap(); + normalmap.child_mut("input").unwrap().set_attr("output", "first"); + let strict = explicit.read_material_strict(None).unwrap(); + assert_eq!( + strict.inputs[0], + ("base_color".into(), Resolved::Image { file: "tex/albedo.png".into(), colorspace: None, uv_tiling: Some([2.0, 4.0]) }) + ); + assert_eq!( + strict.inputs[1], + ("geometry_normal".into(), Resolved::NormalMap { file: "tex/normal.png".into(), colorspace: None, uv_tiling: None }) + ); + assert_eq!(strict.inputs[2].1, Resolved::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); + assert_eq!(strict.displacement, Some(Resolved::Constant { values: vec![0.25], colorspace: None })); + assert_eq!(strict.uv_tiling, [2.0, 4.0]); } #[test] @@ -612,8 +1247,423 @@ mod tests { assert_eq!(material.inputs[1], ("specular_roughness".into(), Value::Image("rough.png".into()))); assert_eq!(material.inputs[2], ("geometry_normal".into(), Value::Image("normal.png".into()))); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); + let strict = doc.read_material_strict(None).unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(strict.inputs[0], ("base_color".into(), image("albedo<&.png", "srgb_texture"))); + assert_eq!(strict.inputs[1], ("specular_roughness".into(), image("rough.png", "lin_rec709"))); + assert_eq!( + strict.inputs[2], + ("geometry_normal".into(), Resolved::NormalMap { file: "normal.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + assert_eq!(strict.displacement, Some(image("height.png", "lin_rec709"))); assert!(xml.contains("colorspace=\"srgb_texture\"")); assert!(xml.contains("doc=\"Tiles every 100 x 50 cm\"")); assert!(!xml.contains("colorspace=\"ignored\"")); } + + #[test] + fn read_material_keeps_its_input_table_values_and_lenient_checks() { + // `read_material` reads glTF PBR's `emission`, keeps the base weight warning, skips + // repeated inputs, bad values and bad `uvtiling` instead of failing, and gives a + // constant only its own `colorspace`; `read_material_strict` is the stricter read. + let xml = r#" + + + + + + + "#; + let doc = Document::parse(xml.as_bytes()).unwrap(); + let gltf = doc.read_material(Some("M")).unwrap(); + assert_eq!( + gltf.inputs, + vec![ + ("base_color".into(), Value::Image("a.png".into())), + ("roughness".into(), Value::Constant { values: vec![0.25], colorspace: None }), + ("alpha".into(), Value::Constant { values: vec![0.5], colorspace: None }), + ("emission".into(), Value::Constant { values: vec![1.0, 0.5, 0.0], colorspace: None }), + ] + ); + assert_eq!(gltf.uv_tiling, [1.0, 1.0]); + assert!(gltf.warnings.is_empty(), "{:?}", gltf.warnings); + assert!(matches!(doc.read_material_strict(Some("M")), Err(Error::Malformed(_)))); + let open = doc.read_material(Some("N")).unwrap(); + assert_eq!(open.warnings, vec!["the base weight isn't 1; it was ignored".to_owned()]); + assert!(open.inputs.is_empty(), "{:?}", open.inputs); + let strict = doc.read_material_strict(Some("N")).unwrap(); + assert!(strict.warnings.is_empty(), "{:?}", strict.warnings); + assert_eq!(input(&strict, "base_weight"), Some(&constant(&[0.5], Some("srgb_texture")))); + assert_eq!(input(&strict, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + } + + fn read(xml: &str) -> Result { + Document::parse(xml.as_bytes())?.read_material_strict(None) + } + + fn input<'m>(material: &'m StrictMaterial, name: &str) -> Option<&'m Resolved> { + material.inputs.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + + fn constant(values: &[f32], space: Option<&str>) -> Resolved { + Resolved::Constant { values: values.to_vec(), colorspace: space.map(str::to_owned) } + } + + #[test] + fn gltf_pbr_reads_the_emissive_input_its_definition_names() { + // The gltf_pbr node definition calls its emission color `emissive` + // (https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/gltf_pbr.mtlx). + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(input(&m, "emissive"), Some(&constant(&[0.5, 0.25, 0.0], None))); + assert_eq!(input(&m, "emissive_strength"), Some(&constant(&[2.0], None))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + } + + #[test] + fn weights_ior_and_alpha_inputs_are_read_for_each_shader() { + let open = read( + r#" + + + "#, + ) + .unwrap(); + for (name, values) in [ + ("base_weight", &[0.5][..]), + ("specular_weight", &[2.0]), + ("specular_color", &[1.0, 0.5, 0.5]), + ("specular_ior", &[1.33]), + ("coat_color", &[0.9, 0.9, 1.0]), + ("coat_ior", &[1.4]), + ("emission_luminance", &[10.0]), + ] { + assert_eq!(input(&open, name), Some(&constant(values, None)), "{name}"); + } + assert!(open.warnings.is_empty(), "{:?}", open.warnings); + let standard = read( + r#" + + "#, + ) + .unwrap(); + for (name, value) in [("base", 0.8), ("specular", 0.5), ("specular_IOR", 1.6), ("coat_IOR", 1.3), ("emission", 0.0)] { + assert_eq!(input(&standard, name), Some(&constant(&[value], None)), "{name}"); + } + let gltf = read( + r#" + + "#, + ) + .unwrap(); + for (name, values) in + [("alpha_mode", &[1.0][..]), ("alpha_cutoff", &[0.25]), ("ior", &[1.7]), ("specular", &[0.5]), ("specular_color", &[1.0, 1.0, 0.0])] + { + assert_eq!(input(&gltf, name), Some(&constant(values, None)), "{name}"); + } + } + + #[test] + fn constants_and_images_carry_the_color_space_in_effect_where_they_are_written() { + // An untagged value takes the nearest enclosing element's color space, then the + // document's (MaterialX specification, Color Spaces and Color Management Systems). + let m = read( + r#" + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("g22_rec709")))); + assert_eq!( + input(&m, "fuzz_color"), + Some(&Resolved::Image { file: "fuzz.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + let doc = Document::parse( + br#" + "#, + ) + .unwrap(); + let tagged = doc.read_material_strict(Some("N")).unwrap(); + assert_eq!(input(&tagged, "base_color"), Some(&constant(&[0.2; 3], Some("acescg")))); + } + + #[test] + fn duplicate_inputs_and_values_that_are_not_finite_numbers_are_malformed() { + let shader = |inputs: &str| { + format!( + r#"{inputs}"# + ) + }; + let dup = read(&shader(r#""#)); + assert!(matches!(dup, Err(Error::Malformed(ref m)) if m.contains("base_metalness")), "{dup:?}"); + for bad in ["nan", "inf", "-inf", "1e40", "0.5,x", "", "1,2,3,4,5"] { + let r = read(&shader(&format!(r#""#))); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("specular_roughness")), "{bad}: {r:?}"); + } + } + + #[test] + fn a_normalmap_scale_other_than_1_gives_a_warning() { + let with_scale = |scale: &str| { + read(&open_pbr( + r#""#, + &format!(r#"{scale}"#), + )) + .unwrap() + }; + let scaled = with_scale(r#""#); + assert_eq!(scaled.warnings, vec![r#"the scale of normalmap node "N" is not read"#.to_owned()]); + assert!(matches!(input(&scaled, "geometry_normal"), Some(Resolved::NormalMap { .. }))); + for plain in ["", r#""#, r#""#] { + assert!(with_scale(plain).warnings.is_empty(), "{plain}"); + } + // A scale connected to a constant node is read through it. + let connected = |value: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + assert!(connected("1").warnings.is_empty(), "{:?}", connected("1").warnings); + assert_eq!(connected("2").warnings.len(), 1, "{:?}", connected("2").warnings); + } + + #[test] + fn shader_inputs_that_are_not_read_give_a_warning() { + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(m.warnings, vec!["input thin_film_weight is not read".to_owned()]); + assert_eq!(input(&m, "base_metalness"), Some(&constant(&[1.0], None))); + } + + fn open_pbr(inputs: &str, rest: &str) -> String { + format!( + r#"{inputs}{rest}"# + ) + } + + #[test] + fn vector_values_may_be_separated_by_commas_spaces_or_both() { + // MaterialX's value reader splits vector and color values on commas and spaces + // (ARRAY_VALID_SEPARATORS, ", ", in source/MaterialXCore/Types.cpp). + for text in ["0.5 0.25 0.125", "0.5, 0.25, 0.125", "0.5,0.25,0.125", " 0.5 0.25 ,0.125 "] { + let m = read(&open_pbr(&format!(r#""#), "")).unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5, 0.25, 0.125], None)), "{text:?}"); + } + // A color3 holds three numbers. + for bad in ["0.5 x 1", "0.5 0.25 0.125 1 2", " ", "0.5", "0.5, 0.25", "0.5 0.25 0.125 1"] { + let r = read(&open_pbr(&format!(r#""#), "")); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("base_color")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn a_nodegraph_file_prefix_applies_to_the_images_inside_it() { + // The nearest enclosing fileprefix applies (MaterialX specification, File Prefixes). + let m = read(&open_pbr( + r#""#, + r#" + + + + + "#, + ) + .replacen("", r#""#, 1)) + .unwrap(); + let file = |name: &str| match input(&m, name) { + Some(Resolved::Image { file, .. }) => file.clone(), + other => panic!("{name}: {other:?}"), + }; + assert_eq!( + (file("base_color"), file("specular_roughness"), file("base_metalness")), + ("stone/albedo.png".into(), "own/rough.png".into(), "shared/metal.png".into()) + ); + } + + #[test] + fn uv_tiling_is_kept_as_written_and_malformed_tiling_is_an_error() { + let tiled = |tiling: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + }; + let tiling_of = |m: &StrictMaterial| match input(m, "base_color") { + Some(Resolved::Image { uv_tiling, .. }) => *uv_tiling, + other => panic!("{other:?}"), + }; + let wide = tiled("2000, 2").unwrap(); + assert_eq!((tiling_of(&wide), wide.uv_tiling), (Some([2000.0, 2.0]), [1000.0, 2.0])); + let flat = tiled("0 2").unwrap(); + assert_eq!((tiling_of(&flat), flat.uv_tiling), (Some([0.0, 2.0]), [1.0, 1.0])); + for bad in ["x", "1", "1,2,3", "nan,1"] { + let r = tiled(bad); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("uvtiling")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn convert_nodes_change_the_number_of_channels() { + // The convert node's rules in the MaterialX Standard Nodes: a float is copied to every + // channel, a shorter color or vector is filled with 0 (1 in the fourth channel), a + // longer one keeps its first channels, and a boolean is 0 or 1. + let via = |ty: &str, in_ty: &str, value: &str| { + read(&open_pbr( + r#""#, + &format!(r#""#), + )) + .unwrap() + }; + assert_eq!(input(&via("color3", "float", "0.25"), "base_color"), Some(&constant(&[0.25; 3], None))); + assert_eq!(input(&via("color4", "color3", "0.1,0.2,0.3"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3, 1.0], None))); + assert_eq!(input(&via("color3", "color4", "0.1,0.2,0.3,0.4"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3], None))); + assert_eq!(input(&via("vector3", "vector2", "0.1,0.2"), "base_color"), Some(&constant(&[0.1, 0.2, 0.0], None))); + assert_eq!(input(&via("float", "boolean", "true"), "base_color"), Some(&constant(&[1.0], None))); + assert_eq!(input(&via("float", "integer", "3"), "base_color"), Some(&constant(&[3.0], None))); + assert_eq!(input(&via("boolean", "integer", "2"), "base_color"), Some(&constant(&[1.0], None))); + // An input with no type is a float or a vector by its count. + let untyped = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&untyped, "base_color"), Some(&constant(&[0.5; 3], None))); + // A color to a float and a float to an integer are not conversions the node defines. + for (ty, in_ty, value) in [("float", "color3", "0.1,0.2,0.3"), ("integer", "float", "0.5"), ("boolean", "float", "1")] { + let unsupported = via(ty, in_ty, value); + assert_eq!(input(&unsupported, "base_color"), None, "{in_ty} to {ty}"); + assert!(unsupported.warnings.iter().any(|w| w.contains("convert node")), "{:?}", unsupported.warnings); + } + // An integer is one whole number. + for bad in ["1.5", "1.00000001", "1 2"] { + let r = read(&open_pbr( + r#""#, + &format!(r#""#), + )); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("input in ")), "{bad:?}: {r:?}"); + } + let image = |ty: &str, image_ty: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + let g = Resolved::Image { file: "g.png".into(), colorspace: None, uv_tiling: None }; + assert_eq!(input(&image("float", "float"), "base_color"), Some(&g)); + assert_eq!(input(&image("vector3", "color3"), "base_color"), Some(&g)); + for (ty, image_ty) in [("color3", "float"), ("color3", "color4")] { + let changed = image(ty, image_ty); + assert_eq!(input(&changed, "base_color"), None, "{image_ty} to {ty}"); + assert!(changed.warnings.iter().any(|w| w.contains("convert node")), "{:?}", changed.warnings); + } + } + + #[test] + fn a_color_converted_from_another_type_is_in_the_working_color_space() { + // A colorspace applies to color values and color image files (MaterialX specification, + // Color Spaces and Color Management Systems), so a float or vector copied into a color + // by a convert node holds working-space channels; a color keeps its own color space. + let m = read( + r#" + + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("srgb_texture")))); + assert_eq!(input(&m, "fuzz_color"), Some(&image("v.png", "lin_rec709"))); + assert_eq!(input(&m, "emission_color"), Some(&image("c.png", "srgb_texture"))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + // A color passed through a vector, also by way of a vector constant node, keeps its color + // space, and a float constant node or an untyped value is in the working color space. + let chain = read( + r#" + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&chain, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&chain, "specular_color"), Some(&constant(&[0.25; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "coat_color"), Some(&constant(&[0.75; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "fuzz_color"), Some(&constant(&[0.4; 3], Some("srgb_texture")))); + assert!(chain.warnings.is_empty(), "{:?}", chain.warnings); + // A document without a working color space leaves the converted color untagged. + let plain = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&plain, "base_color"), Some(&constant(&[0.5; 3], None))); + } + + #[test] + fn an_emission_color_is_checked_while_the_emission_is_0() { + let standard = |color: &str| { + read(&format!( + r#" + "# + )) + }; + let r = standard("0.5,x,1"); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("emission_color")), "{r:?}"); + let m = standard("0.5,0.5,1").unwrap(); + assert_eq!(input(&m, "emission_color"), Some(&constant(&[0.5, 0.5, 1.0], None))); + assert!(m.warnings.is_empty()); + } } diff --git a/crates/mcp/README.md b/crates/mcp/README.md index 58c487edaa..1fb8d2d7da 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -1,6 +1,8 @@ # craft-mcp Transport-independent MCP server initialization and tool result helpers. +Transport-independent MCP 2025-03-26 server initialization and result helpers for tools, +resources, prompts and completion. Use one `Session` per client connection with `craft-jsonrpc` for message parsing and batch dispatch. The caller owns transport, tool definitions and execution, response size limits, and shutdown. Pass the outer envelope's batch status to `Session::request`. @@ -50,3 +52,25 @@ outside the roots. See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle) and the [2025-06-18 changes](https://modelcontextprotocol.io/specification/2025-06-18/changelog). + +The crate also checks the parameters of the resource, prompt and completion methods and +builds their results, for a server that routes those methods itself: + +- `page` takes one page of a list from the request's `cursor`, and `resource_list`, + `resource_template_list` and `prompt_list` wrap the page with its `nextCursor`. A + cursor must be a canonical positive decimal offset divisible by the page size; + malformed cursors are rejected with -32602. The helper returns an empty last page + for a cursor past the list's end, including after the list shrinks. +- `resource_read` returns the requested URI. `text_contents`, `blob_contents` and + `read_result` build the `resources/read` result, and `resource_not_found` is the + -32002 error with the URI in its data. +- `prompt_get` returns the prompt name and its string arguments. `prompt_result` and + `text_message` build the `prompts/get` result. +- `completion_request` returns the prompt or resource reference and the argument being + completed. `completion_result` keeps the first 100 values and sets `total` and `hasMore`. + +See the [pagination](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/pagination), +[resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources), +[prompts](https://modelcontextprotocol.io/specification/2025-03-26/server/prompts) and +[completion](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/completion) +specifications. diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index d5e1a8b10d..c13cab4d78 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -1,11 +1,14 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! MCP server initialization and tool envelopes, independent of transport and tools. Sessions -//! answer 2025-03-26 by default and can negotiate any of `SUPPORTED_PROTOCOL_VERSIONS`. +//! MCP server initialization and the envelopes of tools, resources, prompts and completion, +//! independent of transport and of what the server serves. Sessions answer 2025-03-26 by default +//! and can negotiate any of `SUPPORTED_PROTOCOL_VERSIONS`. //! The caller owns routing, transport and JSON-RPC batching. Compatibility mode preserves servers //! that accepted calls before initialization and initialize in a batch; strict mode enforces the //! initialization ordering and batch prohibition. Create one session per connection. +use std::collections::BTreeMap; + use craft_jsonrpc::{Limits, Request, RpcError}; use serde_json::{Value, json}; @@ -238,6 +241,196 @@ pub fn text_tool_result(text: &str, is_error: bool) -> Value { json!({"content": [{"type": "text", "text": text}], "isError": is_error}) } +/// Most values one `completion/complete` result may carry. +pub const MAX_COMPLETIONS: usize = 100; + +/// One page of a `resources/list`, `resources/templates/list` or `prompts/list` result. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Page { + pub items: Vec, + /// The cursor a client sends to get the next page; `None` on the last page. + pub next_cursor: Option, +} + +impl Page { + /// Every item in one page, for a server that does not paginate. + pub fn all(items: Vec) -> Self { + Self { items, next_cursor: None } + } +} + +/// Take the page of `items` that starts at the `cursor` in a list request's parameters, with at most +/// `page_size` items (0 puts every item in one page). The helper accepts canonical positive +/// decimal offsets divisible by `page_size`. Parameters that are not an object, and malformed +/// cursors, are rejected with -32602. The helper returns an empty last page for a cursor past +/// the list's end, including after the list shrinks. +pub fn page(params: Option<&Value>, mut items: Vec, page_size: usize) -> Result { + if params.is_some_and(|p| !p.is_object()) { + return Err(RpcError::new(-32602, "List parameters must be an object")); + } + let start = match params.and_then(|p| p.get("cursor")) { + None => 0, + Some(Value::String(cursor)) => match cursor.parse::() { + Ok(offset) if page_size > 0 && offset > 0 && offset % page_size == 0 && offset.to_string() == *cursor => offset, + _ => return Err(invalid_cursor()), + }, + Some(_) => return Err(invalid_cursor()), + }; + let start = start.min(items.len()); + items.drain(..start); + let mut next_cursor = None; + if page_size > 0 && items.len() > page_size { + items.truncate(page_size); + next_cursor = Some((start + page_size).to_string()); + } + Ok(Page { items, next_cursor }) +} + +fn invalid_cursor() -> RpcError { + RpcError::new(-32602, "Invalid cursor") +} + +/// Wrap a page of MCP `Resource` objects in the `resources/list` result. +pub fn resource_list(page: Page) -> Value { + list_result("resources", page) +} + +/// Wrap a page of MCP `ResourceTemplate` objects in the `resources/templates/list` result. +pub fn resource_template_list(page: Page) -> Value { + list_result("resourceTemplates", page) +} + +/// Wrap a page of MCP `Prompt` objects in the `prompts/list` result. +pub fn prompt_list(page: Page) -> Value { + list_result("prompts", page) +} + +fn list_result(key: &str, page: Page) -> Value { + let mut result = serde_json::Map::new(); + result.insert(key.to_owned(), Value::Array(page.items)); + if let Some(cursor) = page.next_cursor { + result.insert("nextCursor".to_owned(), Value::String(cursor)); + } + Value::Object(result) +} + +/// Validate `resources/read` parameters and return the requested URI. +pub fn resource_read(params: &Value) -> Result<&str, RpcError> { + params.get("uri").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing resource URI")) +} + +/// The error MCP specifies for a `resources/read` of a URI the server does not have. +pub fn resource_not_found(uri: &str) -> RpcError { + RpcError { code: -32002, message: "Resource not found".into(), data: Some(json!({"uri": uri})) } +} + +/// Text contents of a resource, for [`read_result`]. +pub fn text_contents(uri: &str, mime_type: Option<&str>, text: &str) -> Value { + contents(uri, mime_type, "text", text) +} + +/// Binary contents of a resource, for [`read_result`]. `base64` is the data in standard base64. +pub fn blob_contents(uri: &str, mime_type: Option<&str>, base64: &str) -> Value { + contents(uri, mime_type, "blob", base64) +} + +fn contents(uri: &str, mime_type: Option<&str>, key: &str, value: &str) -> Value { + let mut result = serde_json::Map::new(); + result.insert("uri".to_owned(), json!(uri)); + if let Some(mime_type) = mime_type { + result.insert("mimeType".to_owned(), json!(mime_type)); + } + result.insert(key.to_owned(), json!(value)); + Value::Object(result) +} + +/// Wrap resource contents in the `resources/read` result. +pub fn read_result(contents: Vec) -> Value { + json!({"contents": contents}) +} + +/// Validate `prompts/get` parameters and return the prompt name and its arguments. MCP prompt +/// arguments are strings, so an argument of any other type is rejected with -32602. +pub fn prompt_get(params: &Value) -> Result<(&str, BTreeMap<&str, &str>), RpcError> { + let name = params.get("name").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing prompt name"))?; + let arguments = match params.get("arguments") { + None => BTreeMap::new(), + Some(Value::Object(map)) => map + .iter() + .map(|(key, value)| value.as_str().map(|v| (key.as_str(), v))) + .collect::>>() + .ok_or_else(|| RpcError::new(-32602, "Prompt arguments must be strings"))?, + Some(_) => return Err(RpcError::new(-32602, "Prompt arguments must be an object")), + }; + Ok((name, arguments)) +} + +/// Wrap prompt messages (MCP `PromptMessage` objects) in the `prompts/get` result. +pub fn prompt_result(description: Option<&str>, messages: Vec) -> Value { + let mut result = json!({"messages": messages}); + if let Some(description) = description { + result["description"] = json!(description); + } + result +} + +/// A prompt message with one text block, from `"user"` or `"assistant"`. +pub fn text_message(role: &str, text: &str) -> Value { + json!({"role": role, "content": {"type": "text", "text": text}}) +} + +/// What a `completion/complete` request refers to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompletionRef<'a> { + /// A prompt, by name (`ref/prompt`). + Prompt(&'a str), + /// A resource or resource template, by URI or URI template (`ref/resource`). + Resource(&'a str), +} + +/// The parameters of a `completion/complete` request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Completion<'a> { + pub reference: CompletionRef<'a>, + /// The name of the argument being completed. + pub argument: &'a str, + /// What the user has typed for it so far. + pub value: &'a str, +} + +/// Validate `completion/complete` parameters. +pub fn completion_request(params: &Value) -> Result, RpcError> { + let invalid = |message: &str| RpcError::new(-32602, message); + let reference = params.get("ref").ok_or_else(|| invalid("Missing completion reference"))?; + let field = |key: &str| reference.get(key).and_then(Value::as_str); + let reference = match reference.get("type").and_then(Value::as_str) { + Some("ref/prompt") => CompletionRef::Prompt(field("name").ok_or_else(|| invalid("Missing prompt name"))?), + Some("ref/resource") => CompletionRef::Resource(field("uri").ok_or_else(|| invalid("Missing resource URI"))?), + _ => return Err(invalid("Unknown completion reference type")), + }; + let argument = params.get("argument"); + let text = |key: &str| argument.and_then(|a| a.get(key)).and_then(Value::as_str); + let (Some(name), Some(value)) = (text("name"), text("value")) else { + return Err(invalid("Completion argument needs a name and a value")); + }; + Ok(Completion { reference, argument: name, value }) +} + +/// Build the `completion/complete` result from every matching value. The result carries the first +/// [`MAX_COMPLETIONS`] values, the number of matches in `total`, and whether any were left out in +/// `hasMore`. +pub fn completion_result(values: impl IntoIterator) -> Value { + let mut kept = Vec::new(); + let mut total = 0usize; + for value in values { + if kept.len() < MAX_COMPLETIONS { + kept.push(value); + } + total += 1; + } + json!({"completion": {"values": kept, "total": total, "hasMore": total > MAX_COMPLETIONS}}) +} + #[cfg(test)] mod tests { use super::*; @@ -423,4 +616,89 @@ mod tests { assert_eq!(reply[1]["result"]["tools"], json!([])); assert_eq!(session.borrow().state(), State::Ready); } + + #[test] + fn list_pages_follow_their_cursors_to_the_end() { + let items: Vec = (0..5).map(|i| json!({"name": i})).collect(); + let mut params = None; + let mut names = Vec::new(); + let mut pages = 0; + loop { + let page = page(params.as_ref(), items.clone(), 2).unwrap(); + let result = prompt_list(page); + pages += 1; + names.extend(result["prompts"].as_array().unwrap().iter().map(|p| p["name"].clone())); + match result.get("nextCursor") { + Some(cursor) => params = Some(json!({"cursor": cursor})), + None => break, + } + } + assert_eq!((pages, names), (3, (0..5).map(|i| json!(i)).collect::>())); + assert_eq!(resource_list(page(None, items.clone(), 0).unwrap()), json!({"resources": items})); + let past_the_end = page(Some(&json!({"cursor": "8"})), items, 2).unwrap(); + assert_eq!(resource_template_list(past_the_end), json!({"resourceTemplates": []})); + } + + #[test] + fn list_cursors_that_were_not_handed_out_are_invalid_params() { + for cursor in [json!(""), json!("-1"), json!("+1"), json!("1.0"), json!("abc"), json!(2), json!(null), json!("99999999999999999999999")] { + let error = page(Some(&json!({"cursor": cursor})), vec![json!(1)], 1).unwrap_err(); + assert_eq!(error.code, -32602, "{cursor}"); + } + for cursor in ["1", "02", "0"] { + assert_eq!(page(Some(&json!({"cursor": cursor})), vec![json!(1); 5], 2).unwrap_err().code, -32602, "{cursor}"); + } + assert_eq!(page(Some(&json!({"cursor": "2"})), vec![json!(1); 5], 0).unwrap_err().code, -32602); + for params in [json!(null), json!([]), json!("0")] { + assert_eq!(page(Some(¶ms), vec![json!(1)], 1).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn resource_reads_validate_the_uri_and_build_contents() { + assert_eq!(resource_read(&json!({"uri": "x://a"})).unwrap(), "x://a"); + assert_eq!(resource_read(&json!({"uri": 1})).unwrap_err().code, -32602); + let missing = resource_not_found("x://b"); + assert_eq!((missing.code, missing.data), (-32002, Some(json!({"uri": "x://b"})))); + let result = read_result(vec![text_contents("x://a", Some("text/markdown"), "# A"), blob_contents("x://c", None, "AAE=")]); + assert_eq!(result, json!({"contents": [{"uri": "x://a", "mimeType": "text/markdown", "text": "# A"}, {"uri": "x://c", "blob": "AAE="}]})); + } + + #[test] + fn prompt_arguments_must_be_strings() { + let params = json!({"name": "describe", "arguments": {"part": "bracket"}}); + let (name, args) = prompt_get(¶ms).unwrap(); + assert_eq!((name, args.get("part").copied()), ("describe", Some("bracket"))); + assert!(prompt_get(&json!({"name": "describe"})).unwrap().1.is_empty()); + for params in [json!({}), json!({"name": "d", "arguments": {"n": 1}}), json!({"name": "d", "arguments": ["x"]})] { + assert_eq!(prompt_get(¶ms).unwrap_err().code, -32602, "{params}"); + } + let result = prompt_result(Some("Describe a part"), vec![text_message("user", "Describe bracket")]); + assert_eq!(result["messages"][0]["content"], json!({"type": "text", "text": "Describe bracket"})); + assert_eq!(result["description"], "Describe a part"); + } + + #[test] + fn completion_requests_name_a_prompt_or_a_resource() { + let prompt = json!({"ref": {"type": "ref/prompt", "name": "describe"}, "argument": {"name": "part", "value": "br"}}); + assert_eq!(completion_request(&prompt).unwrap(), Completion { reference: CompletionRef::Prompt("describe"), argument: "part", value: "br" }); + let resource = json!({"ref": {"type": "ref/resource", "uri": "lib://parts/{part}"}, "argument": {"name": "part", "value": ""}}); + assert_eq!(completion_request(&resource).unwrap().reference, CompletionRef::Resource("lib://parts/{part}")); + for params in [ + json!({"ref": {"type": "ref/tool", "name": "x"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt", "name": "x"}, "argument": {"name": "a"}}), + json!({"argument": {"name": "a", "value": ""}}), + ] { + assert_eq!(completion_request(¶ms).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn completion_results_carry_at_most_a_hundred_values() { + let result = completion_result((0..150).map(|i| i.to_string())); + assert_eq!(result["completion"]["values"].as_array().map(Vec::len), Some(MAX_COMPLETIONS)); + assert_eq!((&result["completion"]["total"], &result["completion"]["hasMore"]), (&json!(150), &json!(true))); + assert_eq!(completion_result(["a".to_owned()]), json!({"completion": {"values": ["a"], "total": 1, "hasMore": false}})); + } } diff --git a/crates/pbr/Cargo.toml b/crates/pbr/Cargo.toml index 31790c372f..3d44054c35 100644 --- a/crates/pbr/Cargo.toml +++ b/crates/pbr/Cargo.toml @@ -10,16 +10,25 @@ repository.workspace = true [features] default = [] parallel = ["dep:rayon"] +# The conversion from craft-mesh's glTF metallic-roughness material. +mesh = ["dep:craft-mesh"] +# The conversion from craft-materialx's resolved shader inputs. +materialx = ["dep:craft-materialx"] [lints] workspace = true [dependencies] +craft-materialx = { workspace = true, optional = true } +craft-mesh = { path = "../mesh", default-features = false, optional = true } craft-texture = { workspace = true } rayon = { workspace = true, optional = true } thiserror = { workspace = true } [dev-dependencies] +craft-materialx = { workspace = true } +craft-mesh = { path = "../mesh", default-features = false } +craft-pbr = { path = ".", features = ["parallel", "mesh", "materialx"] } # The differential tests run verbatim copies of the apps' previous code, which uses glam and rayon. glam = "0.30" # Parses and validates the WGSL text of `SHADE_WGSL`. diff --git a/crates/pbr/README.md b/crates/pbr/README.md index 9d3e836538..fd46864090 100644 --- a/crates/pbr/README.md +++ b/crates/pbr/README.md @@ -109,8 +109,47 @@ It has no UI, does no file or network I/O and has no `unsafe` code. `PbrError::BadDirection`. After size and byte checks pass, a filtering work count above `u64::MAX` returns `PbrError::BadOption`, including when `max_work` is `u64::MAX`. `hammersley` returns coordinates in `0..1`. -- **Features.** `parallel` computes rows on several threads with rayon. The default build is - serial and builds for `wasm32-unknown-unknown`. Results are the same either way. +- **Surfaces.** A `Surface` holds a `Material` and the state a renderer applies around it: alpha + and `AlphaMode`, linear emission, the double-sided and unlit flags, optional `Clearcoat` and + `Sheen` layers, `TextureBinding`s (the image or file, UV set, wrap modes, UV transform, encoding + and a scale) and `other_inputs`. Textures are not loaded. `try_direct` shades only the + `Material`; the layers, textures and other inputs are kept for a renderer that shades them, and + an unlit surface shows its base color without lighting. +- **Conversions.** `try_from_mesh` (feature `mesh`) converts a `craft_mesh::Material` and + `try_from_materialx` (feature `materialx`) converts the `craft_materialx::StrictMaterial` that + `Document::read_material_strict` reads. Each returns + a `Conversion`: the `Surface` and a `ConversionReport` that lists what was kept without being + shaded, what was approximated and how, what was dropped and why, and the MaterialX reader's + warnings. No value is clamped: one that is not finite, is out of its range or has the wrong + number of components gives a `ConvertError` naming the source field. + - From craft-mesh, the glTF 2.0 metallic-roughness material + (): base color, alpha, + metallic, roughness, emissive, alpha mode and cutoff, double-sided and unlit map as they are. + Every texture is kept with its UV state; base color, emissive and sheen color textures are + sRGB and the others linear. Clearcoat (`KHR_materials_clearcoat`) and sheen + (`KHR_materials_sheen`) are kept when on; a clearcoat factor of 0 or a black sheen color turns + the layer off, and its textures are dropped. + - From MaterialX, OpenPBR Surface, Standard Surface and glTF PBR inputs take the defaults of + their node definitions when absent + (). The base + color is multiplied by the base weight, the specular weight becomes the weight times + `((ior − 1) / (ior + 1))² / 0.04` (at most `MAX_SPECULAR`), emission is the color times its + strength, and the coat, fuzz or sheen become the layers. Color constants are decoded to linear + Rec.709 from the color space in effect (`srgb_texture`, `srgb_rec709_scene`, the Rec.709 + gamma spaces, `lin_rec709`, `lin_rec709_scene`, `data`); another color space is an error. An + image becomes a texture binding and the core holds 1 times any weight in its place. A coat or + sheen roughness image binds as `ClearcoatRoughnessFirst` or `SheenRoughnessFirst`, which read + the first channel; the glTF bindings `ClearcoatRoughness` and `SheenRoughness` read G and A. + Tangent-space normal textures require an image connected through a `normalmap` node. + Direct world-space normal images are dropped with a report entry. Literal normal-map + inputs and authored normal-map frames are unsupported and reported. Authored `constant`, + `clamp`, and `mirror` image addressing modes are also reported. Other inputs of the shader's + table are kept in `other_inputs`. +- **Features.** `parallel` computes rows on several threads with rayon. `mesh` and `materialx` + add the conversions and depend on craft-mesh and craft-materialx. The default build has none of + them, is serial and builds for `wasm32-unknown-unknown`, as do `mesh` and `materialx`. Results + are the same either way. + The `craft` facade forwards the conversion features as `pbr-mesh` and `pbr-materialx`. On a 256 × 128 source, the default `try_prefilter` evaluates 1,396,736 samples (10,912 output pixels in levels 1 to 5, 128 samples each). diff --git a/crates/pbr/src/convert_materialx.rs b/crates/pbr/src/convert_materialx.rs new file mode 100644 index 0000000000..339b165ee9 --- /dev/null +++ b/crates/pbr/src/convert_materialx.rs @@ -0,0 +1,600 @@ +//! The conversion from a `craft_materialx::StrictMaterial`: an OpenPBR Surface, Standard Surface +//! or glTF PBR shader with its resolved inputs. + +use craft_materialx::{Resolved, Shader, StrictMaterial}; +use craft_texture::srgb_to_linear; +use std::collections::HashSet; + +use crate::surface::{ + AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding, + TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap, +}; +use crate::{MAX_SPECULAR, Material}; + +/// What a shader input holds and the range its values must be in. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Kind { + /// One number from `lo` to `hi`. + Scalar(f32, f32), + /// Three color components from 0 to the bound, in the color space in effect. + Color(f32), + /// Three finite numbers, such as a normal. + Vector, + /// glTF PBR's alpha mode: 0, 1 or 2. + Mode, +} + +const UNIT_KIND: Kind = Kind::Scalar(0.0, 1.0); +const NON_NEGATIVE_KIND: Kind = Kind::Scalar(0.0, f32::MAX); +const COLOR: Kind = Kind::Color(1.0); + +const COAT_OFF: &str = "the coat weight is 0, which turns the layer off"; +const SHEEN_OFF: &str = "the sheen color is black or its weight is 0, which turns the layer off"; + +/// What an input maps to on the [`Surface`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Role { + BaseColor, + BaseWeight, + Metallic, + Roughness, + SpecularWeight, + Ior, + CoatWeight, + CoatRoughness, + SheenWeight, + SheenColor, + SheenRoughness, + EmissionStrength, + EmissionColor, + Opacity, + AlphaMode, + AlphaCutoff, + Normal, + Occlusion, + /// Kept as an other input or a texture, and not shaded. + Kept, + /// Kept like [`Role::Kept`] while the coat is on, and dropped when it is off. + CoatKept, +} + +/// A shader input the conversion reads, with its default from the shader's node definition. +struct Field { + name: &'static str, + kind: Kind, + role: Role, + default: [f32; 3], +} + +const fn field(name: &'static str, kind: Kind, role: Role, default: f32) -> Field { + Field { name, kind, role, default: [default; 3] } +} + +/// OpenPBR Surface inputs and defaults, from its node definition +/// (). +const OPEN_PBR: &[Field] = &[ + field("base_color", COLOR, Role::BaseColor, 0.8), + field("base_weight", UNIT_KIND, Role::BaseWeight, 1.0), + field("base_metalness", UNIT_KIND, Role::Metallic, 0.0), + field("specular_roughness", UNIT_KIND, Role::Roughness, 0.3), + field("specular_weight", NON_NEGATIVE_KIND, Role::SpecularWeight, 1.0), + field("specular_ior", NON_NEGATIVE_KIND, Role::Ior, 1.5), + field("coat_weight", UNIT_KIND, Role::CoatWeight, 0.0), + field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0), + field("fuzz_weight", UNIT_KIND, Role::SheenWeight, 0.0), + field("fuzz_color", COLOR, Role::SheenColor, 1.0), + field("fuzz_roughness", UNIT_KIND, Role::SheenRoughness, 0.5), + field("emission_luminance", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0), + field("emission_color", COLOR, Role::EmissionColor, 1.0), + field("geometry_opacity", UNIT_KIND, Role::Opacity, 1.0), + field("geometry_normal", Kind::Vector, Role::Normal, 0.0), + field("geometry_coat_normal", Kind::Vector, Role::CoatKept, 0.0), + field("specular_color", COLOR, Role::Kept, 1.0), + field("specular_roughness_anisotropy", UNIT_KIND, Role::Kept, 0.0), + field("transmission_weight", UNIT_KIND, Role::Kept, 0.0), + field("subsurface_weight", UNIT_KIND, Role::Kept, 0.0), + field("coat_color", COLOR, Role::CoatKept, 1.0), + field("coat_ior", NON_NEGATIVE_KIND, Role::CoatKept, 1.6), +]; + +/// Standard Surface 1.0.1 inputs and defaults, from its node definition +/// (). +const STANDARD_SURFACE: &[Field] = &[ + field("base_color", COLOR, Role::BaseColor, 0.8), + field("base", UNIT_KIND, Role::BaseWeight, 1.0), + field("metalness", UNIT_KIND, Role::Metallic, 0.0), + field("specular_roughness", UNIT_KIND, Role::Roughness, 0.2), + field("specular", UNIT_KIND, Role::SpecularWeight, 1.0), + field("specular_IOR", NON_NEGATIVE_KIND, Role::Ior, 1.5), + field("coat", UNIT_KIND, Role::CoatWeight, 0.0), + field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.1), + field("sheen", UNIT_KIND, Role::SheenWeight, 0.0), + field("sheen_color", COLOR, Role::SheenColor, 1.0), + field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.3), + field("emission", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0), + field("emission_color", COLOR, Role::EmissionColor, 1.0), + field("opacity", COLOR, Role::Opacity, 1.0), + field("normal", Kind::Vector, Role::Normal, 0.0), + field("coat_normal", Kind::Vector, Role::CoatKept, 0.0), + field("specular_color", COLOR, Role::Kept, 1.0), + field("specular_anisotropy", UNIT_KIND, Role::Kept, 0.0), + field("transmission", UNIT_KIND, Role::Kept, 0.0), + field("subsurface", UNIT_KIND, Role::Kept, 0.0), + field("coat_color", COLOR, Role::CoatKept, 1.0), + field("coat_IOR", NON_NEGATIVE_KIND, Role::CoatKept, 1.5), +]; + +/// glTF PBR inputs and defaults, from its node definition +/// (). +const GLTF_PBR: &[Field] = &[ + field("base_color", COLOR, Role::BaseColor, 1.0), + field("metallic", UNIT_KIND, Role::Metallic, 1.0), + field("roughness", UNIT_KIND, Role::Roughness, 1.0), + field("specular", UNIT_KIND, Role::SpecularWeight, 1.0), + field("ior", Kind::Scalar(1.0, f32::MAX), Role::Ior, 1.5), + field("clearcoat", UNIT_KIND, Role::CoatWeight, 0.0), + field("clearcoat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0), + field("sheen_color", COLOR, Role::SheenColor, 0.0), + field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.0), + field("emissive_strength", NON_NEGATIVE_KIND, Role::EmissionStrength, 1.0), + field("emissive", COLOR, Role::EmissionColor, 0.0), + field("alpha", UNIT_KIND, Role::Opacity, 1.0), + field("alpha_mode", Kind::Mode, Role::AlphaMode, 0.0), + field("alpha_cutoff", UNIT_KIND, Role::AlphaCutoff, 0.5), + field("normal", Kind::Vector, Role::Normal, 0.0), + field("occlusion", UNIT_KIND, Role::Occlusion, 1.0), + field("clearcoat_normal", Kind::Vector, Role::CoatKept, 0.0), + field("transmission", UNIT_KIND, Role::Kept, 0.0), + field("specular_color", Kind::Color(f32::MAX), Role::Kept, 1.0), +]; + +/// What a conversion found for one field of the table. +#[derive(Clone, Debug, PartialEq)] +enum Got { + Missing, + /// Checked values, linear for a color. + Constant(Vec), + Texture, +} + +/// The table of the material's shader and what each field holds. +struct Inputs { + table: &'static [Field], + got: Vec, +} + +impl Inputs { + fn find(&self, role: Role) -> Option<(&Field, &Got)> { + self.table.iter().zip(&self.got).find(|(f, _)| f.role == role) + } + + /// The field's value: the authored one, 1 for a texture (the factor its samples multiply), + /// or the default when the input is absent. `None` when the shader has no such field. + fn value(&self, role: Role) -> Option<[f32; 3]> { + let (f, got) = self.find(role)?; + Some(match got { + Got::Missing => f.default, + Got::Texture => [1.0; 3], + Got::Constant(v) if v.len() == 1 => [v[0]; 3], + Got::Constant(v) => [v.first().copied().unwrap_or(0.0), v.get(1).copied().unwrap_or(0.0), v.get(2).copied().unwrap_or(0.0)], + }) + } + + fn scalar(&self, role: Role, absent: f32) -> f32 { + self.value(role).map_or(absent, |v| v[0]) + } + + fn textured(&self, role: Role) -> bool { + self.find(role).is_some_and(|(_, g)| *g == Got::Texture) + } + + fn name(&self, role: Role) -> &'static str { + self.table.iter().find(|f| f.role == role).map_or("", |f| f.name) + } +} + +/// Converts a `craft_materialx::StrictMaterial`, as `Document::read_material_strict` reads it, by +/// the input tables of its shader's node definition +/// (). An input +/// that is absent takes the definition's default, so an empty input list gives the shader's +/// default material. +/// +/// - The core's base color is the base color times the base weight (`base_weight`, or `base` in +/// Standard Surface), which both shaders apply to the diffuse and the metal color. Metallic +/// and roughness map as they are. The core's specular weight is the specular weight times +/// Schlick's reflectance at normal incidence for the index of refraction, +/// `((ior − 1) / (ior + 1))²`, divided by 0.04; it is reported as approximated when it is not 1, +/// and a value over [`MAX_SPECULAR`] is an error. +/// - The coat (`coat_*`, or `clearcoat*` in glTF PBR) becomes [`Surface::clearcoat`] when its +/// weight is above 0 or a texture sets it. The fuzz of OpenPBR and the sheen of Standard +/// Surface become [`Surface::sheen`] with the weight times the color as its color, reported as +/// approximated; glTF PBR's sheen maps as it is. A layer is kept only when it is on. +/// - Emission is the emission color times its strength: `emission_luminance` (reported as +/// approximated, since it is in nits), `emission`, or `emissive_strength`. A color whose +/// strength is 0 gives no emission. +/// An authored color at strength 0 is validated and reported as dropped. +/// - Alpha is the opacity. Standard Surface's opacity is a color: equal channels give that value, +/// and different channels give their luminance by the Rec.709 luma coefficients, reported as +/// approximated, as the shader's own node graph reduces it with a `luminance` node. OpenPBR's +/// `geometry_opacity` and glTF PBR's `alpha` are floats in their node definitions, so a color +/// there is [`ConvertError::Components`]. glTF PBR's `alpha_mode` 0, 1 and 2 give opaque, +/// masked at `alpha_cutoff`, and blended; the other shaders blend when the opacity is below 1 +/// or a texture sets it. +/// - Every other input of the table (normals, specular color, anisotropy, transmission, +/// subsurface, coat color and IOR, occlusion) is kept in [`Surface::other_inputs`], or as a +/// texture, and reported as unshaded. The displacement is kept the same way. +/// - An image becomes a [`TextureBinding`] with the file path, the UV tiling as its transform's +/// scale, and an encoding from its color space for a color input (linear for data); the core +/// holds 1 times any weight in its place; Standard Surface's color `opacity` binds as +/// [`TextureInput::OpacityRgb`] and the float opacities as [`TextureInput::Opacity`]; an IOR +/// texture leaves the default IOR, reported +/// as approximated. The inputs and textures of a layer that is off (the coat's roughness, +/// color, IOR and normal among them) are dropped and reported. +/// - Color constants are decoded to linear Rec.709 from the color space in effect, as the +/// MaterialX specification asks +/// (): +/// `srgb_texture` and `srgb_rec709_scene` by the sRGB transfer function, the Rec.709 gamma +/// spaces by their power, and `lin_rec709`, `lin_rec709_scene`, `data`, `none` or no color +/// space as they are. Another color space is [`ConvertError::ColorSpace`]. +/// - The reader's warnings are carried into the report. Inputs outside the table are dropped and +/// reported. +/// +/// Every value is checked and none is clamped: a value that is not finite (a color also after it +/// is decoded to linear), is outside the definition's range (`0..=1` for weights, colors and +/// roughness, at least 0 for strengths and IOR, at least 1 for glTF PBR's `ior`), has the wrong +/// number of components, or is an +/// `alpha_mode` other than 0, 1 or 2 is an error, and so is a texture on `alpha_mode` or +/// `alpha_cutoff`, a UV tiling that is not two positive numbers, or an input named twice. +pub fn try_from_materialx(m: &StrictMaterial) -> Result { + let table = match m.shader { + Shader::OpenPbr => OPEN_PBR, + Shader::StandardSurface => STANDARD_SURFACE, + Shader::GltfPbr => GLTF_PBR, + }; + let mut report = ConversionReport::default(); + let mut inputs = Inputs { table, got: table.iter().map(|_| Got::Missing).collect() }; + let mut textures: Vec<(Role, TextureBinding)> = Vec::new(); + let mut others: Vec<(Role, String, Vec)> = Vec::new(); + let mut seen = HashSet::new(); + for (name, value) in &m.inputs { + if !seen.insert(name.as_str()) { + return Err(ConvertError::Duplicate(name.clone())); + } + let Some(idx) = table.iter().position(|f| f.name == name) else { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "is not an input of the shader that the conversion reads" }); + continue; + }; + let f = &table[idx]; + match value { + Resolved::Constant { values, colorspace } => { + let v = checked_values(f, values, colorspace.as_deref())?; + if matches!(f.role, Role::Kept | Role::CoatKept | Role::Normal | Role::Occlusion) { + others.push((f.role, name.clone(), v)); + } else { + inputs.got[idx] = Got::Constant(v); + } + } + Resolved::Image { file, colorspace, uv_tiling } | Resolved::NormalMap { file, colorspace, uv_tiling } => { + if matches!(f.role, Role::AlphaMode | Role::AlphaCutoff) { + return Err(ConvertError::BadValue { input: name.clone(), reason: "cannot be a texture" }); + } + let binding = image_binding(f, file, colorspace.as_deref(), *uv_tiling)?; + let tangent = matches!(value, Resolved::NormalMap { .. }); + let normal = matches!(f.role, Role::Normal) || (matches!(f.role, Role::CoatKept) && matches!(f.kind, Kind::Vector)); + if normal && !tangent { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "world-space normal images are not supported" }); + continue; + } + if tangent && !normal { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "a normalmap image is not supported on this input" }); + continue; + } + textures.push((f.role, binding)); + inputs.got[idx] = Got::Texture; + } + } + } + let material = core(&inputs, &mut report)?; + let clearcoat = clearcoat(&inputs); + let sheen = sheen(&inputs, m.shader, &mut report); + let emissive = emission(&inputs, m.shader, &mut report); + let (alpha, alpha_mode) = alpha(&inputs, m.shader, &mut report)?; + let off = |role: Role| match role { + Role::CoatWeight | Role::CoatRoughness | Role::CoatKept if clearcoat.is_none() => Some(COAT_OFF), + Role::SheenWeight | Role::SheenColor | Role::SheenRoughness if sheen.is_none() => Some(SHEEN_OFF), + Role::EmissionColor if inputs.scalar(Role::EmissionStrength, 1.0) == 0.0 => Some("the emission strength is 0"), + _ => None, + }; + // Authored constants of a layer that is off, except the weight or color that turns it off. + for (f, got) in table.iter().zip(&inputs.got) { + let Got::Constant(v) = got else { continue }; + let turns_it_off = match f.role { + Role::CoatWeight => true, + Role::SheenWeight | Role::SheenColor => v.iter().all(|c| *c == 0.0), + _ => false, + }; + if let Some(why) = off(f.role).filter(|_| !turns_it_off) { + report.items.push(ReportItem::Dropped { input: f.name.to_owned(), why }); + } + } + let mut other_inputs = Vec::new(); + for (role, input, values) in others { + match off(role) { + Some(why) => report.items.push(ReportItem::Dropped { input, why }), + None => { + report.items.push(ReportItem::Unshaded { input: input.clone() }); + other_inputs.push((input, values)); + } + } + } + let mut kept = Vec::new(); + for (role, binding) in textures { + let off = off(role); + let input = texture_name(&inputs, role, &binding); + match off { + Some(why) => report.items.push(ReportItem::Dropped { input, why }), + None => { + report.items.push(ReportItem::Unshaded { input }); + kept.push(binding); + } + } + } + for (layer, on) in [("clearcoat", clearcoat.is_some()), ("sheen", sheen.is_some())] { + if on { + report.items.push(ReportItem::Unshaded { input: layer.into() }); + } + } + displacement(m.displacement.as_ref(), &mut kept, &mut other_inputs, &mut report)?; + report.items.extend(m.warnings.iter().cloned().map(ReportItem::Warning)); + let surface = Surface { + name: m.name.clone(), + material, + alpha, + alpha_mode, + emissive, + double_sided: false, + unlit: false, + clearcoat, + sheen, + textures: kept, + other_inputs, + }; + Ok(Conversion { surface, report }) +} + +/// The source name of a texture for the report. +fn texture_name(inputs: &Inputs, role: Role, binding: &TextureBinding) -> String { + match &binding.input { + TextureInput::Other(name) => name.clone(), + _ => inputs.name(role).to_owned(), + } +} + +/// The reason text for a value outside `lo..=hi`. +fn reason(lo: f32, hi: f32) -> &'static str { + match (lo, hi) { + (0.0, 1.0) => UNIT, + (0.0, _) => NON_NEGATIVE, + (1.0, _) => "is not a finite number of at least 1", + _ => FINITE, + } +} + +/// The values of a constant for field `f`, checked against its kind and, for a color, decoded +/// to linear from `space`. +fn checked_values(f: &Field, values: &[f32], space: Option<&str>) -> Result, ConvertError> { + let expected = match f.kind { + Kind::Scalar(..) | Kind::Mode => 1, + Kind::Color(_) | Kind::Vector => 3, + }; + if values.len() != expected { + return Err(ConvertError::Components { input: f.name.to_owned(), expected, found: values.len() }); + } + let bad = |reason| ConvertError::BadValue { input: f.name.to_owned(), reason }; + let (lo, hi) = match f.kind { + Kind::Scalar(lo, hi) => (lo, hi), + Kind::Color(hi) => (0.0, hi), + Kind::Vector => (f32::MIN, f32::MAX), + Kind::Mode => (0.0, 2.0), + }; + let in_range = |v: f32| v.is_finite() && (lo..=hi).contains(&v); + for &v in values { + if !in_range(v) { + return Err(bad(reason(lo, hi))); + } + if f.kind == Kind::Mode && v.fract() != 0.0 { + return Err(bad("is not 0, 1 or 2")); + } + } + match f.kind { + Kind::Color(_) => { + let linear = decode(values, space, f.name)?; + if linear.iter().all(|&v| in_range(v)) { Ok(linear) } else { Err(bad("is not a finite color once decoded to linear")) } + } + _ => Ok(values.to_vec()), + } +} + +/// `values` decoded to linear Rec.709 from the color space `space`. +fn decode(values: &[f32], space: Option<&str>, input: &str) -> Result, ConvertError> { + let power = |p: f32| values.iter().map(|v| v.powf(p)).collect(); + Ok(match space { + None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => values.to_vec(), + Some("srgb_texture" | "srgb_rec709_scene") => values.iter().map(|v| srgb_to_linear(*v)).collect(), + Some("g22_rec709" | "g22_rec709_scene") => power(2.2), + Some("g18_rec709" | "g18_rec709_scene") => power(1.8), + Some("g24_rec709_scene") => power(2.4), + Some(other) => return Err(ConvertError::ColorSpace { input: input.to_owned(), colorspace: other.to_owned() }), + }) +} + +/// The binding of an image on field `f`. +fn image_binding(f: &Field, file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Result { + let input = match f.role { + Role::BaseColor => TextureInput::BaseColor, + Role::Metallic => TextureInput::Metallic, + Role::Roughness => TextureInput::Roughness, + Role::Normal => TextureInput::Normal, + Role::Occlusion => TextureInput::Occlusion, + Role::EmissionColor => TextureInput::Emissive, + Role::Opacity if matches!(f.kind, Kind::Color(_)) => TextureInput::OpacityRgb, + Role::Opacity => TextureInput::Opacity, + Role::CoatWeight => TextureInput::Clearcoat, + Role::CoatRoughness => TextureInput::ClearcoatRoughnessFirst, + Role::SheenColor => TextureInput::SheenColor, + Role::SheenRoughness => TextureInput::SheenRoughnessFirst, + _ => TextureInput::Other(f.name.to_owned()), + }; + let encoding = if matches!(f.kind, Kind::Color(_)) { encoding(space) } else { TextureEncoding::Linear }; + let transform = match tiling { + Some(scale) if scale.iter().all(|v| v.is_finite() && *v > 0.0) => Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale }), + Some(_) => return Err(ConvertError::BadValue { input: f.name.to_owned(), reason: "has a UV tiling that is not two positive numbers" }), + None => None, + }; + Ok(TextureBinding { input, source: TextureSource::File(file.to_owned()), encoding, uv_set: 0, wrap: [Wrap::Repeat; 2], transform, scale: 1.0 }) +} + +/// The encoding of a color image in the color space `space`. +fn encoding(space: Option<&str>) -> TextureEncoding { + match space { + None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => TextureEncoding::Linear, + Some("srgb_texture" | "srgb_rec709_scene") => TextureEncoding::Srgb, + Some(other) => TextureEncoding::Named(other.to_owned()), + } +} + +/// The BRDF core. +fn core(inputs: &Inputs, report: &mut ConversionReport) -> Result { + let color = inputs.value(Role::BaseColor).unwrap_or([1.0; 3]); + let weight = inputs.scalar(Role::BaseWeight, 1.0); + let base = color.map(|c| c * weight); + let metallic = inputs.scalar(Role::Metallic, 0.0); + let roughness = inputs.scalar(Role::Roughness, 0.0); + if inputs.textured(Role::Ior) { + report + .items + .push(ReportItem::Approximated { input: inputs.name(Role::Ior).into(), how: "is a texture; the default index of refraction was used" }); + } + let ior = match inputs.find(Role::Ior) { + Some((f, Got::Texture)) => f64::from(f.default[0]), + _ => f64::from(inputs.scalar(Role::Ior, 1.5)), + }; + // The reflectance relative to 0.04, which is 1 within rounding at the default IOR of 1.5. + let mut ratio = ((ior - 1.0) / (ior + 1.0)).powi(2) / 0.04; + if (ratio - 1.0).abs() < 1e-9 { + ratio = 1.0; + } + let specular = f64::from(inputs.scalar(Role::SpecularWeight, 1.0)) * ratio; + let name = inputs.name(Role::SpecularWeight); + if specular > f64::from(MAX_SPECULAR) { + return Err(ConvertError::BadValue { + input: name.into(), + reason: "times the reflectance of the index of refraction is over the 25 the BRDF supports", + }); + } + if specular != 1.0 { + report.items.push(ReportItem::Approximated { + input: name.into(), + how: "times Schlick's reflectance at normal incidence for the index of refraction, over 0.04, is the core's specular weight", + }); + } + Ok(Material::try_new(base, metallic, roughness)?.try_with_weights(specular as f32, 1.0)?) +} + +/// The coat, when its weight is above 0 or a texture sets it. +fn clearcoat(inputs: &Inputs) -> Option { + let weight = inputs.scalar(Role::CoatWeight, 0.0); + (weight > 0.0).then(|| Clearcoat { weight, roughness: inputs.scalar(Role::CoatRoughness, 0.0) }) +} + +/// The sheen, when its color times its weight is not black. +fn sheen(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Option { + let weight = inputs.scalar(Role::SheenWeight, 1.0); + let color = inputs.value(Role::SheenColor)?.map(|c| c * weight); + if color == [0.0; 3] { + return None; + } + if shader != Shader::GltfPbr { + report.items.push(ReportItem::Approximated { input: inputs.name(Role::SheenWeight).into(), how: "times the color is the sheen color" }); + } + Some(Sheen { color, roughness: inputs.scalar(Role::SheenRoughness, 0.0) }) +} + +/// The emission color times its strength. +fn emission(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> [f32; 3] { + let strength = inputs.scalar(Role::EmissionStrength, 1.0); + let color = inputs.value(Role::EmissionColor).unwrap_or([0.0; 3]); + let emissive = color.map(|c| c * strength); + if shader == Shader::OpenPbr && emissive != [0.0; 3] { + report.items.push(ReportItem::Approximated { + input: inputs.name(Role::EmissionStrength).into(), + how: "is in nits and multiplies the emission color", + }); + } + emissive +} + +/// Alpha and its mode. +fn alpha(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Result<(f32, AlphaMode), ConvertError> { + let opacity = inputs.value(Role::Opacity).unwrap_or([1.0; 3]); + let alpha = if shader == Shader::StandardSurface && (opacity[0] != opacity[1] || opacity[1] != opacity[2]) { + report + .items + .push(ReportItem::Approximated { input: inputs.name(Role::Opacity).into(), how: "is a color; its Rec.709 luminance is the alpha" }); + luminance(opacity) + } else { + opacity[0] + }; + let mode = if shader == Shader::GltfPbr { + match inputs.scalar(Role::AlphaMode, 0.0) { + 0.0 => AlphaMode::Opaque, + 1.0 => AlphaMode::Mask(inputs.scalar(Role::AlphaCutoff, 0.5)), + 2.0 => AlphaMode::Blend, + _ => return Err(ConvertError::BadValue { input: "alpha_mode".into(), reason: "is not 0, 1 or 2" }), + } + } else if alpha < 1.0 || inputs.textured(Role::Opacity) { + AlphaMode::Blend + } else { + AlphaMode::Opaque + }; + if shader == Shader::GltfPbr + && !matches!(mode, AlphaMode::Mask(_)) + && inputs.find(Role::AlphaCutoff).is_some_and(|(_, value)| matches!(value, Got::Constant(_))) + { + report.items.push(ReportItem::Dropped { input: inputs.name(Role::AlphaCutoff).into(), why: "the alpha mode does not use a cutoff" }); + } + Ok((alpha, mode)) +} + +/// The luminance of a linear Rec.709 color, by the `rec709` luma coefficients of the MaterialX +/// `luminance` node +/// (), +/// kept between the smallest and largest channel so that rounding cannot leave `0..=1`. +fn luminance(c: [f32; 3]) -> f32 { + let y = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]); + (y as f32).clamp(c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2])) +} + +/// Keeps the displacement as a texture or an other input. +fn displacement( + value: Option<&Resolved>, + textures: &mut Vec, + other_inputs: &mut Vec<(String, Vec)>, + report: &mut ConversionReport, +) -> Result<(), ConvertError> { + const DISPLACEMENT: Field = field("displacement", Kind::Scalar(f32::MIN, f32::MAX), Role::Kept, 0.0); + match value { + None => return Ok(()), + Some(Resolved::Constant { values, .. }) => other_inputs.push(("displacement".into(), checked_values(&DISPLACEMENT, values, None)?)), + Some(Resolved::Image { file, colorspace, uv_tiling }) => { + let mut binding = image_binding(&DISPLACEMENT, file, colorspace.as_deref(), *uv_tiling)?; + binding.input = TextureInput::Displacement; + textures.push(binding); + } + Some(Resolved::NormalMap { .. }) => { + return Err(ConvertError::BadValue { input: "displacement".into(), reason: "cannot be a normalmap image" }); + } + } + report.items.push(ReportItem::Unshaded { input: "displacement".into() }); + Ok(()) +} diff --git a/crates/pbr/src/convert_mesh.rs b/crates/pbr/src/convert_mesh.rs new file mode 100644 index 0000000000..a98e0539b9 --- /dev/null +++ b/crates/pbr/src/convert_mesh.rs @@ -0,0 +1,177 @@ +//! The conversion from a `craft_mesh::Material`, which holds a glTF 2.0 metallic-roughness +//! material. + +use craft_mesh::{AlphaMode as MeshAlpha, Material as MeshMaterial, TextureRef, Wrap as MeshWrap}; + +use crate::Material; +use crate::surface::{ + AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding, + TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap, checked, +}; + +/// The material extensions whose values `craft_mesh` reads into `craft_mesh::Material`'s fields. +/// It reads only part of `KHR_materials_pbrSpecularGlossiness` and of `KHR_materials_clearcoat`. +const CONVERTED_EXTENSIONS: &[&str] = &[ + "KHR_materials_unlit", + "KHR_materials_emissive_strength", + "KHR_materials_pbrSpecularGlossiness", + "KHR_materials_clearcoat", + "KHR_materials_sheen", +]; +const SPECULAR_GLOSSINESS: &str = "KHR_materials_pbrSpecularGlossiness"; + +/// Converts a `craft_mesh::Material` as glTF 2.0 defines its metallic-roughness material +/// (). +/// +/// - Mapped as they are: the linear base color RGB, metallic and roughness into the core with +/// specular and diffuse weights of 1, base color alpha into [`Surface::alpha`], the alpha mode +/// and cutoff, the linear emissive color, the double-sided flag, the unlit flag of +/// `KHR_materials_unlit` and the name. Nothing is converted between color spaces: the source +/// values are linear. +/// - Kept and reported as [`ReportItem::Unshaded`]: every texture, with its image index, UV set, +/// wrap modes and `KHR_texture_transform`, and the normal scale and occlusion strength as the +/// binding's scale; the clearcoat layer of `KHR_materials_clearcoat`; the sheen layer of +/// `KHR_materials_sheen`; and the unlit flag. Base color, emissive and sheen color textures +/// are sRGB-encoded and the others are linear, as glTF and its extensions define them. +/// - Dropped and reported: the clearcoat textures when the clearcoat factor is 0, and the sheen +/// textures when the sheen color factor is black. Each extension turns its layer off then. +/// Every other material extension in `craft_mesh::Material::extensions`, such as +/// `KHR_materials_transmission`, is dropped and reported by its name, and so is the +/// `clearcoatNormalTexture` of `KHR_materials_clearcoat`, which `craft_mesh` does not read. +/// - Reported as [`ReportItem::Approximated`]: `KHR_materials_pbrSpecularGlossiness`, which +/// `craft_mesh` reads as its diffuse color and texture with roughness from the glossiness, +/// without its specular color or specular-glossiness texture. +/// +/// Every value is checked and none is clamped. Base color channels, alpha, metallic, +/// roughness, occlusion strength and the clearcoat and sheen values must be numbers from 0 to 1; +/// emissive channels and the alpha cutoff must be finite and at least 0; the normal scale and +/// every UV transform value must be finite. Otherwise the result is +/// [`ConvertError::BadValue`] naming the `craft_mesh::Material` field. +pub fn try_from_mesh(m: &MeshMaterial) -> Result { + let [r, g, b, a] = m.base_color; + let base = [checked(r, 0.0, 1.0, "base_color", UNIT)?, checked(g, 0.0, 1.0, "base_color", UNIT)?, checked(b, 0.0, 1.0, "base_color", UNIT)?]; + let alpha = checked(a, 0.0, 1.0, "base_color alpha", UNIT)?; + let metallic = checked(m.metallic, 0.0, 1.0, "metallic", UNIT)?; + let roughness = checked(m.roughness, 0.0, 1.0, "roughness", UNIT)?; + let material = Material::try_new(base, metallic, roughness)?; + let mut emissive = [0.0; 3]; + for (out, v) in emissive.iter_mut().zip(m.emissive) { + *out = checked(v, 0.0, f32::MAX, "emissive", NON_NEGATIVE)?; + } + let alpha_mode = match m.alpha_mode { + MeshAlpha::Opaque => AlphaMode::Opaque, + MeshAlpha::Mask(cutoff) => AlphaMode::Mask(checked(cutoff, 0.0, f32::MAX, "alpha cutoff", NON_NEGATIVE)?), + MeshAlpha::Blend => AlphaMode::Blend, + }; + let normal_scale = checked(m.normal_scale, f32::MIN, f32::MAX, "normal_scale", FINITE)?; + let occlusion_strength = checked(m.occlusion_strength, 0.0, 1.0, "occlusion_strength", UNIT)?; + let clearcoat_weight = checked(m.clearcoat, 0.0, 1.0, "clearcoat", UNIT)?; + let clearcoat_roughness = checked(m.clearcoat_roughness, 0.0, 1.0, "clearcoat_roughness", UNIT)?; + let mut sheen_color = [0.0; 3]; + for (out, v) in sheen_color.iter_mut().zip(m.sheen_color) { + *out = checked(v, 0.0, 1.0, "sheen_color", UNIT)?; + } + let sheen_roughness = checked(m.sheen_roughness, 0.0, 1.0, "sheen_roughness", UNIT)?; + + let mut report = ConversionReport::default(); + let mut textures = Vec::new(); + let mut bind = + |name: &str, slot: &Option, input: TextureInput, encoding: TextureEncoding, scale: f32, dropped: Option<&'static str>| { + let Some(t) = slot else { + if scale != 1.0 { + let factor = match input { + TextureInput::Normal => "normal_scale", + TextureInput::Occlusion => "occlusion_strength", + _ => name, + }; + report.items.push(ReportItem::Dropped { input: factor.to_owned(), why: "the corresponding texture is absent" }); + } + return Ok(()); + }; + // The texture is checked before a layer that is off drops it. + let b = binding(name, t, input, encoding, scale)?; + if let Some(why) = dropped { + report.items.push(ReportItem::Dropped { input: name.to_owned(), why }); + return Ok(()); + } + textures.push(b); + report.items.push(ReportItem::Unshaded { input: name.to_owned() }); + Ok::<(), ConvertError>(()) + }; + use TextureEncoding::{Linear, Srgb}; + bind("base_color_texture", &m.base_color_texture, TextureInput::BaseColor, Srgb, 1.0, None)?; + bind("metallic_roughness_texture", &m.metallic_roughness_texture, TextureInput::MetallicRoughness, Linear, 1.0, None)?; + bind("normal_texture", &m.normal_texture, TextureInput::Normal, Linear, normal_scale, None)?; + bind("occlusion_texture", &m.occlusion_texture, TextureInput::Occlusion, Linear, occlusion_strength, None)?; + bind("emissive_texture", &m.emissive_texture, TextureInput::Emissive, Srgb, 1.0, None)?; + let coat_off = (clearcoat_weight == 0.0).then_some("the clearcoat factor is 0, which turns the layer off"); + bind("clearcoat_texture", &m.clearcoat_texture, TextureInput::Clearcoat, Linear, 1.0, coat_off)?; + bind("clearcoat_roughness_texture", &m.clearcoat_roughness_texture, TextureInput::ClearcoatRoughness, Linear, 1.0, coat_off)?; + let sheen_off = (sheen_color == [0.0; 3]).then_some("the sheen color factor is black, which turns the layer off"); + bind("sheen_color_texture", &m.sheen_color_texture, TextureInput::SheenColor, Srgb, 1.0, sheen_off)?; + bind("sheen_roughness_texture", &m.sheen_roughness_texture, TextureInput::SheenRoughness, Linear, 1.0, sheen_off)?; + + let clearcoat = coat_off.is_none().then_some(Clearcoat { weight: clearcoat_weight, roughness: clearcoat_roughness }); + if clearcoat.is_some() { + report.items.push(ReportItem::Unshaded { input: "clearcoat".into() }); + } + let sheen = sheen_off.is_none().then_some(Sheen { color: sheen_color, roughness: sheen_roughness }); + if sheen.is_some() { + report.items.push(ReportItem::Unshaded { input: "sheen".into() }); + } + for (inactive, roughness, input) in + [(clearcoat.is_none(), clearcoat_roughness, "clearcoat_roughness"), (sheen.is_none(), sheen_roughness, "sheen_roughness")] + { + if inactive && roughness != 0.0 { + report.items.push(ReportItem::Dropped { input: input.into(), why: "the layer is off" }); + } + } + if m.unlit { + report.items.push(ReportItem::Unshaded { input: "unlit".into() }); + } + for name in m.extensions.keys().filter(|k| !CONVERTED_EXTENSIONS.contains(&k.as_str())) { + report.items.push(ReportItem::Dropped { input: name.clone(), why: "the extension is not converted" }); + } + if m.extensions.get("KHR_materials_clearcoat").is_some_and(|c| c.get("clearcoatNormalTexture").is_some()) { + report.items.push(ReportItem::Dropped { input: "clearcoatNormalTexture".into(), why: "craft-mesh does not read it" }); + } + if m.extensions.contains_key(SPECULAR_GLOSSINESS) { + report.items.push(ReportItem::Approximated { + input: SPECULAR_GLOSSINESS.into(), + how: "read as its diffuse color and texture with roughness from the glossiness; its specular color and texture are not converted", + }); + } + let surface = Surface { + name: m.name.clone(), + material, + alpha, + alpha_mode, + emissive, + double_sided: m.double_sided, + unlit: m.unlit, + clearcoat, + sheen, + textures, + other_inputs: Vec::new(), + }; + Ok(Conversion { surface, report }) +} + +/// The binding of the texture `t` in the field `name`. +fn binding(name: &str, t: &TextureRef, input: TextureInput, encoding: TextureEncoding, scale: f32) -> Result { + let transform = match t.transform { + Some(x) => { + for v in [x.offset[0], x.offset[1], x.rotation, x.scale[0], x.scale[1]] { + checked(v, f32::MIN, f32::MAX, &format!("{name} transform"), FINITE)?; + } + Some(UvTransform { offset: x.offset, rotation: x.rotation, scale: x.scale }) + } + None => None, + }; + let wrap = t.wrap.map(|w| match w { + MeshWrap::Repeat => Wrap::Repeat, + MeshWrap::Clamp => Wrap::Clamp, + MeshWrap::Mirror => Wrap::Mirror, + }); + Ok(TextureBinding { input, source: TextureSource::Image(t.image), encoding, uv_set: t.uv_set, wrap, transform, scale }) +} diff --git a/crates/pbr/src/lib.rs b/crates/pbr/src/lib.rs index 9413f9c0b2..45c0a28f06 100644 --- a/crates/pbr/src/lib.rs +++ b/crates/pbr/src/lib.rs @@ -36,6 +36,14 @@ //! [`SHADE_WGSL`] is the WGSL text of the same shading functions for an app's own shaders, and //! [`GpuMaterial`] and [`GpuSh9`] lay out the values it reads. //! +//! A [`Surface`] is a [`Material`] with the state a renderer applies around it: alpha and its +//! mode, emission, sidedness, the unlit flag, clearcoat and sheen layers, and texture bindings +//! that are kept but not loaded. With the `mesh` feature, `try_from_mesh` converts a +//! `craft_mesh::Material`, and with the `materialx` feature, `try_from_materialx` converts a +//! `craft_materialx::StrictMaterial`. Each returns the surface and a [`ConversionReport`] of what it +//! kept without shading, approximated or dropped, and a [`ConvertError`] for a value that is not +//! finite or is out of its range. Neither feature is on by default. +//! //! The diffuse coefficients are the nine real SH coefficients of the radiance, convolved with the //! clamped cosine lobe (band factors `π`, `2π/3` and `π/4`, Ramamoorthi and Hanrahan 2001, //! ) and divided by `π`. [`irradiance`] @@ -51,9 +59,14 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod brdf; +#[cfg(feature = "materialx")] +mod convert_materialx; +#[cfg(feature = "mesh")] +mod convert_mesh; mod environment; mod prefilter; mod sh; +mod surface; mod vec3; mod wgsl; @@ -61,9 +74,17 @@ mod wgsl; use rayon::prelude::*; pub use brdf::{MAX_SPECULAR, MIN_DIRECT_ROUGHNESS, Material, Visibility, try_environment_brdf}; +#[cfg(feature = "materialx")] +pub use convert_materialx::try_from_materialx; +#[cfg(feature = "mesh")] +pub use convert_mesh::try_from_mesh; pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, default_environment, dir_of, uv_of}; pub use prefilter::{PrefilterOptions, ggx_distribution, ggx_distribution_between, hammersley, try_prefilter}; pub use sh::{irradiance, sh_basis, try_sh9}; +pub use surface::{ + AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, ReportItem, Sheen, Surface, TextureBinding, TextureEncoding, TextureInput, + TextureSource, UvTransform, Wrap, +}; pub use wgsl::{GpuMaterial, GpuSh9, SHADE_WGSL}; /// Why an environment could not be made, filtered or read, or a material could not be shaded. diff --git a/crates/pbr/src/surface.rs b/crates/pbr/src/surface.rs new file mode 100644 index 0000000000..c418a8f17c --- /dev/null +++ b/crates/pbr/src/surface.rs @@ -0,0 +1,237 @@ +//! A surface material: the BRDF core with the surface state around it, and the report and errors +//! of the conversions into it. + +use crate::{Material, PbrError}; + +/// A material as a renderer needs it: the metallic-roughness [`Material`] that +/// [`Material::try_direct`] shades, and the state a renderer applies around it. Alpha, emission +/// and sidedness are applied by the renderer, not by the BRDF. The clearcoat and sheen layers, +/// the textures and [`Surface::other_inputs`] are kept but not shaded by +/// [`Material::try_direct`]. When [`Surface::unlit`] is set, the surface shows its base color +/// without lighting, and [`Material::try_direct`] does not give its appearance. +/// +/// Made by `try_from_mesh` (the `mesh` feature) and `try_from_materialx` (the `materialx` +/// feature), which check every value. +/// `#[non_exhaustive]`: read and change the fields, but get a value from a conversion. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Surface { + /// The source material's name. + pub name: String, + /// The BRDF core. Where a texture is bound to one of its values, the core holds the factor the + /// texture's samples are multiplied by. + pub material: Material, + /// Coverage from 0 (transparent) to 1 (opaque). + pub alpha: f32, + /// How [`Surface::alpha`] is used. + pub alpha_mode: AlphaMode, + /// Linear RGB emission, each channel at least 0. + pub emissive: [f32; 3], + /// Both faces are drawn and lit. + pub double_sided: bool, + /// The surface is shown as its base color and alpha, without lighting. + pub unlit: bool, + /// A clear layer over the base, when its weight is above 0 or a texture sets it. + pub clearcoat: Option, + /// A sheen layer, when its color is not black or a texture sets it. + pub sheen: Option, + /// Textures bound to the material's values, not loaded or sampled. + pub textures: Vec, + /// Source inputs with no field here, by their source name, as authored. Color values are + /// linear. + pub other_inputs: Vec<(String, Vec)>, +} + +/// How a surface's alpha is used. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum AlphaMode { + /// Alpha is ignored and the surface is opaque. + #[default] + Opaque, + /// The surface is drawn where alpha is at least the cutoff, which is at least 0. + Mask(f32), + /// The surface is blended by alpha. + Blend, +} + +/// A clear layer over the base: weight and perceptual roughness, each from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clearcoat { + pub weight: f32, + pub roughness: f32, +} + +/// A sheen layer: linear RGB color and perceptual roughness, each from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Sheen { + pub color: [f32; 3], + pub roughness: f32, +} + +/// The value a texture sets, and which of its channels it reads. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TextureInput { + /// Base color in RGB; from glTF, alpha in A. + BaseColor, + /// glTF's packed texture: roughness in G and metallic in B. + MetallicRoughness, + /// Metallic in the first channel. + Metallic, + /// Roughness in the first channel. + Roughness, + /// A tangent-space normal map; [`TextureBinding::scale`] scales its X and Y. + Normal, + /// Ambient occlusion in R; [`TextureBinding::scale`] is its strength. + Occlusion, + /// Emission color in RGB. + Emissive, + /// Opacity: alpha in the first channel. + Opacity, + /// A colored opacity in RGB, such as Standard Surface's `opacity`; the alpha is its Rec.709 + /// luminance. + OpacityRgb, + /// Clearcoat weight in R. + Clearcoat, + /// glTF's clearcoat roughness texture: roughness in G. + ClearcoatRoughness, + /// Clearcoat roughness in the first channel. + ClearcoatRoughnessFirst, + /// Sheen color in RGB. + SheenColor, + /// glTF's sheen roughness texture: roughness in A. + SheenRoughness, + /// Sheen roughness in the first channel. + SheenRoughnessFirst, + /// Displacement height in the first channel. + Displacement, + /// A source input with no slot above, by its source name. + Other(String), +} + +/// Where a texture's image is. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TextureSource { + /// An index into the source scene's images (`craft_mesh::Scene::images`). + Image(usize), + /// A file path, as the source document wrote it with any file prefix applied. + File(String), +} + +/// How a texture's samples are encoded. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TextureEncoding { + /// Linear values, or data that is not a color. + Linear, + /// sRGB-encoded color. + Srgb, + /// A color space by the name the source gives it, which the caller converts. + Named(String), +} + +/// How a texture continues outside 0..1. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Wrap { + #[default] + Repeat, + Clamp, + Mirror, +} + +/// A UV transform: scale, then rotate by `rotation` radians, then add `offset`, in the order and +/// with the signs of glTF's `KHR_texture_transform`. Every value is finite. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvTransform { + pub offset: [f32; 2], + pub rotation: f32, + pub scale: [f32; 2], +} + +/// A texture bound to a value of a [`Surface`]. +#[derive(Clone, Debug, PartialEq)] +pub struct TextureBinding { + pub input: TextureInput, + pub source: TextureSource, + pub encoding: TextureEncoding, + /// The UV set the texture reads. + pub uv_set: u32, + /// How the texture continues outside 0..1 along u and v. + pub wrap: [Wrap; 2], + pub transform: Option, + /// A finite scale on the samples: the normal scale of a normal map, the strength of an + /// occlusion map, and 1 otherwise. + pub scale: f32, +} + +/// A converted surface and what the conversion did not carry over exactly. +#[derive(Clone, Debug, PartialEq)] +pub struct Conversion { + pub surface: Surface, + pub report: ConversionReport, +} + +/// What a conversion kept without shading, approximated or dropped, in the order it found them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ConversionReport { + pub items: Vec, +} + +impl ConversionReport { + /// Whether every source value went into a field that [`Material::try_direct`] shades or that + /// a renderer applies (alpha, emission, sidedness), with nothing approximated or dropped. + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } +} + +/// One entry of a [`ConversionReport`]. `input` is the source's name for the value. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ReportItem { + /// Kept on the [`Surface`] (a layer, a texture, an unlit flag or an other input), and not + /// shaded by [`Material::try_direct`]. + Unshaded { input: String }, + /// Mapped with a change of meaning; `how` says what was done. + Approximated { input: String, how: &'static str }, + /// Not kept; `why` says why. + Dropped { input: String, why: &'static str }, + /// A warning the source reader gave. + Warning(String), +} + +/// Why a material could not be converted. Nothing is clamped or replaced: a value out of its +/// range is an error. +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[non_exhaustive] +pub enum ConvertError { + /// A value is not a finite number, or is out of its range; `reason` says which. + #[error("{input} {reason}")] + BadValue { input: String, reason: &'static str }, + /// A value has the wrong number of components. + #[error("{input} has {found} values where {expected} are needed")] + Components { input: String, expected: usize, found: usize }, + /// A color value is in a color space the conversion does not decode. + #[error("{input} is in the color space {colorspace}, which is not converted")] + ColorSpace { input: String, colorspace: String }, + /// The source names an input more than once. + #[error("the material has more than one {0} input")] + Duplicate(String), + /// The BRDF core rejected the converted values. + #[error(transparent)] + Material(#[from] PbrError), +} + +/// `v` when it is finite and in `lo..=hi`, else [`ConvertError::BadValue`] naming `input`. +#[cfg(feature = "mesh")] +pub(crate) fn checked(v: f32, lo: f32, hi: f32, input: &str, reason: &'static str) -> Result { + if v.is_finite() && (lo..=hi).contains(&v) { Ok(v) } else { Err(ConvertError::BadValue { input: input.to_owned(), reason }) } +} + +/// The reason text for a value that must be from 0 to 1. +#[cfg(any(feature = "mesh", feature = "materialx"))] +pub(crate) const UNIT: &str = "is not a number from 0 to 1"; +/// The reason text for a value that must be finite and at least 0. +#[cfg(any(feature = "mesh", feature = "materialx"))] +pub(crate) const NON_NEGATIVE: &str = "is not a finite number of at least 0"; +/// The reason text for a value that must be finite. +#[cfg(any(feature = "mesh", feature = "materialx"))] +pub(crate) const FINITE: &str = "is not a finite number"; diff --git a/crates/pbr/tests/it/conversion_edges.rs b/crates/pbr/tests/it/conversion_edges.rs new file mode 100644 index 0000000000..a34969fed0 --- /dev/null +++ b/crates/pbr/tests/it/conversion_edges.rs @@ -0,0 +1,252 @@ +use craft_materialx::{Document, Resolved}; +use craft_mesh::Material as Mesh; +use craft_pbr::{ConvertError, ReportItem, TextureInput, TextureSource, try_from_materialx, try_from_mesh}; + +fn document(shader: &str, inputs: &str, nodes: &str, material_inputs: &str) -> Document { + let text = format!( + r#"<{shader} name="S">{inputs}{nodes}{material_inputs}"# + ); + Document::parse(text.as_bytes()).unwrap() +} + +#[test] +fn inactive_emission_still_validates_the_color_field() { + let doc = document("standard_surface", r#""#, "", ""); + let material = doc.read_material_strict(None).unwrap(); + assert!(matches!(try_from_materialx(&material), Err(ConvertError::BadValue { input, .. }) if input == "emission_color")); + let legacy = doc.read_material(None).unwrap(); + assert!(!legacy.inputs.iter().any(|(name, _)| name == "emission_color")); + let valid = document("standard_surface", r#""#, "", ""); + let converted = try_from_materialx(&valid.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.emissive, [0.0; 3]); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "emission_color"))); +} + +#[test] +fn displacement_scale_is_reported_when_it_is_not_applied() { + for scale in ["", r#""#, r#""#] { + let node = format!(r#"{scale}"#); + let doc = document("standard_surface", "", &node, r#""#); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.other_inputs, vec![("displacement".into(), vec![0.25])]); + assert_eq!( + converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("scale"))), + scale.contains('2') + ); + } + for scale in ["1,2", "NaN", ""] { + let node = format!(r#""#); + assert!(document("standard_surface", "", &node, r#""#).read_material_strict(None).is_err()); + } +} + +#[test] +fn graph_surface_connections_preserve_the_shader_scope() { + let doc = Document::parse( + br#" + + + + "#, + ) + .unwrap(); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.textures[0].source, TextureSource::File("graph.png".into())); + assert!(doc.read_material(None).is_err()); +} + +#[test] +fn broken_authored_connections_do_not_become_shader_defaults() { + for reference in [r#"nodename="missing""#, r#"nodegraph="missing" output="out""#] { + let doc = document("open_pbr_surface", &format!(r#""#), "", ""); + assert!(doc.read_material_strict(None).is_err(), "{reference}"); + } +} + +#[test] +fn a_nonzero_tiled_image_offset_is_reported() { + for offset in ["0,0", "0.25,0"] { + let nodes = format!( + r#""# + ); + let doc = document("open_pbr_surface", r#""#, &nodes, ""); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.textures[0].transform.unwrap().scale, [2.0, 2.0]); + assert_eq!( + converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("uvoffset"))), + offset != "0,0" + ); + } +} + +#[test] +fn an_omitted_color_constant_value_is_black() { + let doc = document("open_pbr_surface", r#""#, r#""#, ""); + let material = doc.read_material_strict(None).unwrap(); + assert!( + matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &[0.0; 3]) + ); + assert_eq!(try_from_materialx(&material).unwrap().surface.material.base_color(), [0.0; 3]); +} + +#[test] +fn an_authored_cutoff_is_reported_when_the_alpha_mode_does_not_use_it() { + for mode in [0, 1, 2] { + let doc = document("gltf_pbr", &format!(r#""#), "", ""); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff")), mode != 1); + if mode == 1 { + assert_eq!(converted.surface.alpha_mode, craft_pbr::AlphaMode::Mask(0.25)); + } + let absent = document("gltf_pbr", &format!(r#""#), "", ""); + let converted = try_from_materialx(&absent.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff"))); + } +} + +#[test] +fn vector_displacement_is_reported_without_a_scalar_height_binding() { + for source in [r#"type="vector3" value="0.1,0.2,0.3""#, r#"type="vector3" nodename="T""#, r#"value="0.1,0.2,0.3""#] { + let nodes = format!( + r#""# + ); + let doc = document("standard_surface", "", &nodes, r#""#); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.textures.iter().any(|texture| texture.input == TextureInput::Displacement)); + assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "displacement")); + assert!( + converted + .report + .items + .iter() + .any(|item| matches!(item, ReportItem::Warning(message) if message.contains("vector") && message.contains("displacement"))) + ); + } +} + +#[test] +fn inactive_mesh_layers_report_nondefault_roughness() { + assert!(try_from_mesh(&Mesh::default()).unwrap().report.is_empty()); + let converted = try_from_mesh(&Mesh { clearcoat_roughness: 0.5, sheen_roughness: 0.5, ..Mesh::default() }).unwrap(); + for field in ["clearcoat_roughness", "sheen_roughness"] { + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == field)), "{field}"); + } + let active = + try_from_mesh(&Mesh { clearcoat: 1.0, clearcoat_roughness: 0.5, sheen_color: [0.2; 3], sheen_roughness: 0.5, ..Mesh::default() }).unwrap(); + assert_eq!(active.surface.clearcoat.unwrap().roughness, 0.5); + assert_eq!(active.surface.sheen.unwrap().roughness, 0.5); +} + +#[test] +fn omitted_numeric_constants_use_their_typed_zero_values() { + for (kind, count) in [("float", 1), ("integer", 1), ("boolean", 1), ("vector2", 2), ("vector3", 3), ("vector4", 4), ("color3", 3), ("color4", 4)] + { + let doc = document("open_pbr_surface", r#""#, &format!(r#""#), ""); + let material = doc.read_material_strict(None).unwrap(); + assert!( + matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &vec![0.0; count]), + "{kind}" + ); + } + let unsupported = document("open_pbr_surface", r#""#, r#""#, ""); + let material = unsupported.read_material_strict(None).unwrap(); + assert!(material.inputs.is_empty() && !material.warnings.is_empty()); +} + +#[test] +fn strict_graph_output_selection_rejects_ambiguity() { + let read = |outputs: &str, selection: &str| { + Document::parse( + format!( + r#" + + {outputs} + "# + ) + .as_bytes(), + ) + .unwrap() + .read_material_strict(None) + }; + let both = r#""#; + assert!(read(both, "").is_err()); + assert!(read(both, r#"output="missing""#).is_err()); + assert_eq!(try_from_materialx(&read(both, r#"output="b""#).unwrap()).unwrap().surface.material.base_color(), [0.8; 3]); + let sole = read(r#""#, r#"output="unused""#).unwrap(); + assert_eq!(try_from_materialx(&sole).unwrap().surface.material.base_color(), [0.2; 3]); +} + +#[test] +fn omitted_node_parameters_keep_their_identity_defaults() { + let displaced = document( + "standard_surface", + "", + r#""#, + r#""#, + ); + assert!(displaced.read_material_strict(None).unwrap().warnings.is_empty()); + let image = document( + "open_pbr_surface", + r#""#, + r#""#, + "", + ); + assert!(image.read_material_strict(None).unwrap().warnings.is_empty()); + let normal = document( + "open_pbr_surface", + r#""#, + r#""#, + "", + ); + assert!(normal.read_material_strict(None).unwrap().warnings.is_empty()); +} + +#[test] +fn interface_connections_report_the_unsupported_value() { + let doc = Document::parse( + br#" + + + "#, + ) + .unwrap(); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!( + converted + .report + .items + .iter() + .any(|item| matches!(item, ReportItem::Warning(message) if message.contains("interface") && message.contains("tint"))) + ); +} + +#[test] +fn connected_image_tiling_keeps_the_resolved_scale() { + for connection in [r#"nodename="K""#, r#"nodegraph="g""#] { + let nodes = format!( + r#" + + "# + ); + let doc = document("standard_surface", r#""#, &nodes, ""); + let material = doc.read_material_strict(None).unwrap(); + assert!(material.warnings.is_empty(), "{:?}", material.warnings); + assert_eq!(material.uv_tiling, [2.0, 3.0]); + let converted = try_from_materialx(&material).unwrap(); + let binding = converted.surface.textures.iter().find(|binding| binding.input == TextureInput::BaseColor).unwrap(); + assert_eq!(binding.transform.as_ref().map(|transform| transform.scale), Some([2.0, 3.0])); + } +} + +#[test] +fn images_without_literal_file_values_report_the_skipped_texture() { + for kind in ["image", "tiledimage"] { + for file in ["", r#""#, r#""#, r#""#] { + let nodes = format!(r#"<{kind} name="T" type="color3">{file}"#); + let doc = document("standard_surface", r#""#, &nodes, ""); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.surface.textures.is_empty()); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("file")))); + } + } +} diff --git a/crates/pbr/tests/it/conversion_followups.rs b/crates/pbr/tests/it/conversion_followups.rs new file mode 100644 index 0000000000..5c085e800a --- /dev/null +++ b/crates/pbr/tests/it/conversion_followups.rs @@ -0,0 +1,162 @@ +use craft_materialx::Document; +use craft_mesh::Material; +use craft_pbr::{ReportItem, TextureInput, try_from_materialx, try_from_mesh}; + +fn document(input: &str, nodes: &str) -> Document { + Document::parse( + format!( + r#"{input}{nodes}"# + ) + .as_bytes(), + ) + .unwrap() +} + +#[test] +fn a_selected_output_without_a_target_does_not_select_another_output() { + let doc = Document::parse( + br#" + + "#, + ) + .unwrap(); + assert!(doc.read_material_strict(None).is_err()); +} + +#[test] +fn nondefault_image_addressing_modes_are_reported() { + for name in ["uaddressmode", "vaddressmode"] { + for mode in ["constant", "clamp", "mirror"] { + let node = + format!(r#""#); + let doc = document(r#""#, &node); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name)))); + } + } +} + +#[test] +fn an_identified_convert_node_uses_its_omitted_input_default() { + let doc = document(r#""#, r#""#); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(converted.surface.material.base_color(), [0.0; 3]); + assert!(converted.report.is_empty(), "{:?}", converted.report); +} + +#[test] +fn constant_literals_use_the_nodes_type_when_the_input_omits_it() { + for (ty, value) in [("integer", "0.5"), ("float", "1,2"), ("color3", "1,2")] { + let node = format!(r#""#); + let doc = document(r#""#, &node); + assert!(doc.read_material_strict(None).is_err(), "{ty} {value}"); + } +} + +#[test] +fn a_missing_graph_local_node_does_not_bind_a_root_node() { + let doc = Document::parse( + br#" + + + "#, + ) + .unwrap(); + assert!(doc.read_material_strict(None).is_err()); +} + +#[test] +fn direct_normal_vectors_are_not_bound_as_tangent_space_maps() { + let image = r#""#; + let direct = document(r#""#, image); + let converted = try_from_materialx(&direct.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal)); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "geometry_normal"))); + let nodes = format!(r#"{image}"#); + let wrapped = document(r#""#, &nodes); + let converted = try_from_materialx(&wrapped.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal)); +} + +#[test] +fn nondefault_factors_without_textures_are_reported() { + let material = Material { normal_scale: 0.5, occlusion_strength: 0.25, ..Material::default() }; + let converted = try_from_mesh(&material).unwrap(); + for name in ["normal_scale", "occlusion_strength"] { + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == name))); + } + assert!(try_from_mesh(&Material::default()).unwrap().report.is_empty()); +} + +#[test] +fn nested_normalmaps_are_reported_and_skipped() { + let nodes = r#" + + "#; + let doc = document(r#""#, nodes); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal)); + assert!( + converted + .report + .items + .iter() + .any(|item| matches!(item, ReportItem::Warning(message) if message.contains("nested") && message.contains("Outer"))) + ); +} + +#[test] +fn normalmap_literals_do_not_become_untransformed_world_normals() { + for value in ["1,0.5,1", "0.5,0.5,1"] { + let doc = document( + r#""#, + &format!(r#""#), + ); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "geometry_normal")); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("normalmap")))); + } +} + +#[test] +fn authored_normalmap_frames_are_reported() { + for name in ["normal", "tangent", "bitangent"] { + let nodes = format!( + r#" + "# + ); + let doc = document(r#""#, &nodes); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name)))); + } +} + +#[test] +fn coat_normals_keep_tangent_maps_and_report_direct_world_images() { + for (shader, weight, normal) in [ + ("open_pbr_surface", "coat_weight", "geometry_coat_normal"), + ("standard_surface", "coat", "coat_normal"), + ("gltf_pbr", "clearcoat", "clearcoat_normal"), + ] { + for (node, wrapped) in [("T", false), ("N", true)] { + let xml = format!( + r#"<{shader} name="S"> + + + "# + ); + let doc = Document::parse(xml.as_bytes()).unwrap(); + let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!( + converted.surface.textures.iter().any(|binding| matches!(&binding.input, TextureInput::Other(name) if name == normal)), + wrapped, + "{shader} {node}" + ); + assert_eq!( + converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == normal)), + !wrapped, + "{shader} {node}" + ); + } + } +} diff --git a/crates/pbr/tests/it/convert.rs b/crates/pbr/tests/it/convert.rs new file mode 100644 index 0000000000..8ec3d5d70b --- /dev/null +++ b/crates/pbr/tests/it/convert.rs @@ -0,0 +1,724 @@ +//! Conversions into a `Surface`: glTF 2.0 materials from craft-mesh and MaterialX shaders from +//! craft-materialx, checked against the defaults and ranges the public definitions give. + +use craft_materialx::{Document, Resolved as Value, Shader, StrictMaterial as Mx, Texture, write_open_pbr}; +use craft_mesh::{AlphaMode as MeshAlpha, Material as Mesh, TextureRef, UvTransform as MeshUv, Wrap as MeshWrap}; +use craft_pbr::{ + AlphaMode, Clearcoat, Conversion, ConvertError, ReportItem, Sheen, TextureEncoding, TextureInput, TextureSource, UvTransform, Wrap, + try_from_materialx, try_from_mesh, +}; + +fn close(a: f32, b: f32) -> bool { + a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0) +} + +#[test] +fn close_is_false_for_values_that_are_not_finite() { + assert!(close(1.0, 1.0 + 1e-7)); + assert!(!close(f32::INFINITY, 1.0) && !close(f32::INFINITY, f32::INFINITY) && !close(f32::NAN, 1.0)); +} + +#[track_caller] +fn assert_close3(a: [f32; 3], b: [f32; 3]) { + assert!(a.iter().zip(b).all(|(x, y)| close(*x, y)), "{a:?} against {b:?}"); +} + +fn unshaded(c: &Conversion, input: &str) -> bool { + c.report.items.iter().any(|i| matches!(i, ReportItem::Unshaded { input: n } if n == input)) +} + +fn approximated(c: &Conversion, input: &str) -> bool { + c.report.items.iter().any(|i| matches!(i, ReportItem::Approximated { input: n, .. } if n == input)) +} + +fn dropped(c: &Conversion, input: &str) -> bool { + c.report.items.iter().any(|i| matches!(i, ReportItem::Dropped { input: n, .. } if n == input)) +} + +#[track_caller] +fn bad_value(r: Result, input: &str) { + match r { + Err(ConvertError::BadValue { input: n, .. }) => assert!(n.contains(input), "{n} is not {input}"), + other => panic!("{input}: expected a bad value, got {other:?}"), + } +} + +fn tex(image: usize) -> Option { + Some(TextureRef { image, ..TextureRef::default() }) +} + +// ------------------------------------------------------------------ craft-mesh (glTF 2.0) + +#[test] +fn mesh_factors_map_as_they_are() { + let m = Mesh { + name: "Paint".into(), + base_color: [0.25, 0.5, 0.75, 0.6], + metallic: 0.3, + roughness: 0.7, + emissive: [2.0, 0.5, 0.0], + alpha_mode: MeshAlpha::Mask(0.4), + double_sided: true, + ..Mesh::default() + }; + let c = try_from_mesh(&m).unwrap(); + let s = &c.surface; + assert_eq!(s.name, "Paint"); + assert_eq!(s.material.base_color(), [0.25, 0.5, 0.75]); + assert_eq!((s.material.metallic(), s.material.roughness()), (0.3, 0.7)); + assert_eq!((s.material.specular(), s.material.diffuse()), (1.0, 1.0)); + assert_eq!(s.alpha, 0.6); + assert_eq!(s.alpha_mode, AlphaMode::Mask(0.4)); + assert_eq!(s.emissive, [2.0, 0.5, 0.0]); + assert!(s.double_sided && !s.unlit); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(s.textures.is_empty() && s.other_inputs.is_empty()); + assert!(c.report.is_empty(), "{:?}", c.report); +} + +#[test] +fn mesh_defaults_are_the_gltf_defaults() { + // glTF 2.0 gives baseColorFactor [1, 1, 1, 1], metallicFactor 1, roughnessFactor 1, + // emissiveFactor [0, 0, 0] and alphaMode OPAQUE + // (https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-material). + let c = try_from_mesh(&Mesh::default()).unwrap(); + let s = &c.surface; + assert_eq!(s.material.base_color(), [1.0; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.alpha), (1.0, 1.0, 1.0)); + assert_eq!((s.emissive, s.alpha_mode), ([0.0; 3], AlphaMode::Opaque)); + assert!(!s.double_sided); + assert!(c.report.is_empty()); +} + +#[test] +fn mesh_extensions_that_are_not_converted_are_reported_as_dropped() { + let mut m = Mesh::default(); + for name in ["KHR_materials_transmission", "KHR_materials_clearcoat", "KHR_materials_unlit", "KHR_materials_emissive_strength"] { + m.extensions.insert(name.into(), craft_mesh::serde_json::json!({})); + } + let c = try_from_mesh(&m).unwrap(); + assert!(dropped(&c, "KHR_materials_transmission"), "{:?}", c.report); + assert_eq!(c.report.items.len(), 1, "{:?}", c.report); + // craft-mesh reads part of these two. + m.extensions.insert("KHR_materials_clearcoat".into(), craft_mesh::serde_json::json!({ "clearcoatNormalTexture": { "index": 0 } })); + m.extensions.insert("KHR_materials_pbrSpecularGlossiness".into(), craft_mesh::serde_json::json!({ "specularFactor": [1, 0, 0] })); + let c = try_from_mesh(&m).unwrap(); + assert!(dropped(&c, "clearcoatNormalTexture"), "{:?}", c.report); + assert!(approximated(&c, "KHR_materials_pbrSpecularGlossiness"), "{:?}", c.report); + assert_eq!(c.report.items.len(), 3, "{:?}", c.report); +} + +#[test] +fn mesh_textures_keep_their_uv_state_scale_and_encoding() { + let mr = TextureRef { + image: 2, + uv_set: 1, + wrap: [MeshWrap::Clamp, MeshWrap::Mirror], + transform: Some(MeshUv { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] }), + }; + let m = Mesh { + base_color_texture: tex(1), + metallic_roughness_texture: Some(mr), + normal_texture: tex(3), + normal_scale: 0.5, + occlusion_texture: tex(4), + occlusion_strength: 0.25, + emissive_texture: tex(5), + clearcoat: 0.5, + clearcoat_texture: tex(6), + clearcoat_roughness_texture: tex(7), + sheen_color: [0.1, 0.0, 0.0], + sheen_color_texture: tex(8), + sheen_roughness_texture: tex(9), + ..Mesh::default() + }; + let c = try_from_mesh(&m).unwrap(); + // Base color, emissive and sheen color textures are sRGB, the rest linear (glTF 2.0 and + // KHR_materials_sheen); the packed texture holds roughness in G and metallic in B. + let expected = [ + ("base_color_texture", TextureInput::BaseColor, TextureEncoding::Srgb), + ("metallic_roughness_texture", TextureInput::MetallicRoughness, TextureEncoding::Linear), + ("normal_texture", TextureInput::Normal, TextureEncoding::Linear), + ("occlusion_texture", TextureInput::Occlusion, TextureEncoding::Linear), + ("emissive_texture", TextureInput::Emissive, TextureEncoding::Srgb), + ("clearcoat_texture", TextureInput::Clearcoat, TextureEncoding::Linear), + ("clearcoat_roughness_texture", TextureInput::ClearcoatRoughness, TextureEncoding::Linear), + ("sheen_color_texture", TextureInput::SheenColor, TextureEncoding::Srgb), + ("sheen_roughness_texture", TextureInput::SheenRoughness, TextureEncoding::Linear), + ]; + assert_eq!(c.surface.textures.len(), expected.len()); + for (i, ((name, input, encoding), b)) in expected.into_iter().zip(&c.surface.textures).enumerate() { + assert_eq!((&b.input, &b.encoding, &b.source), (&input, &encoding, &TextureSource::Image(i + 1)), "{name}"); + assert!(unshaded(&c, name), "{name}"); + } + let mr = &c.surface.textures[1]; + assert_eq!((mr.uv_set, mr.wrap), (1, [Wrap::Clamp, Wrap::Mirror])); + assert_eq!(mr.transform, Some(UvTransform { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] })); + assert_eq!((c.surface.textures[2].scale, c.surface.textures[3].scale, c.surface.textures[0].scale), (0.5, 0.25, 1.0)); + assert_eq!(c.surface.textures[0].transform, None); + // The core holds the factors the textures multiply: glTF's defaults here. + assert_eq!((c.surface.material.metallic(), c.surface.material.roughness()), (1.0, 1.0)); + assert!(unshaded(&c, "clearcoat") && unshaded(&c, "sheen")); +} + +#[test] +fn mesh_clearcoat_and_sheen_are_kept_and_layers_that_are_off_drop_their_textures() { + let on = Mesh { clearcoat: 0.75, clearcoat_roughness: 0.25, sheen_color: [0.5, 0.25, 0.0], sheen_roughness: 0.6, ..Mesh::default() }; + let c = try_from_mesh(&on).unwrap(); + assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.75, roughness: 0.25 })); + assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.6 })); + // A clearcoat factor of 0 and a black sheen color each turn their layer off + // (KHR_materials_clearcoat, KHR_materials_sheen). + let off = Mesh { + clearcoat_roughness: 0.5, + clearcoat_texture: tex(1), + clearcoat_roughness_texture: tex(2), + sheen_roughness: 0.5, + sheen_color_texture: tex(3), + sheen_roughness_texture: tex(4), + ..Mesh::default() + }; + let c = try_from_mesh(&off).unwrap(); + assert_eq!((c.surface.clearcoat, c.surface.sheen), (None, None)); + assert!(c.surface.textures.is_empty()); + for name in ["clearcoat_texture", "clearcoat_roughness_texture", "sheen_color_texture", "sheen_roughness_texture"] { + assert!(dropped(&c, name), "{name}"); + } + assert!(!unshaded(&c, "clearcoat") && !unshaded(&c, "sheen")); +} + +#[test] +fn mesh_textures_of_a_layer_that_is_off_are_checked_before_they_are_dropped() { + let t = TextureRef { transform: Some(MeshUv { rotation: f32::NAN, ..MeshUv::default() }), ..TextureRef::default() }; + bad_value(try_from_mesh(&Mesh { clearcoat_roughness_texture: Some(t), ..Mesh::default() }), "clearcoat_roughness_texture transform"); + bad_value(try_from_mesh(&Mesh { sheen_color_texture: Some(t), ..Mesh::default() }), "sheen_color_texture transform"); + let fine = TextureRef { transform: Some(MeshUv { rotation: 0.5, ..MeshUv::default() }), ..TextureRef::default() }; + let c = try_from_mesh(&Mesh { clearcoat_texture: Some(fine), ..Mesh::default() }).unwrap(); + assert!(c.surface.textures.is_empty() && dropped(&c, "clearcoat_texture")); +} + +#[test] +fn mesh_unlit_is_kept_and_reported() { + let c = try_from_mesh(&Mesh { unlit: true, base_color: [0.2, 0.4, 0.6, 1.0], ..Mesh::default() }).unwrap(); + assert!(c.surface.unlit); + assert_eq!(c.surface.material.base_color(), [0.2, 0.4, 0.6]); + assert!(unshaded(&c, "unlit")); +} + +#[test] +fn mesh_values_that_are_not_finite_or_out_of_range_are_errors() { + type Set = fn(&mut Mesh, f32); + let unit: [(&str, Set); 8] = [ + ("base_color", |m, v| m.base_color[1] = v), + ("base_color alpha", |m, v| m.base_color[3] = v), + ("metallic", |m, v| m.metallic = v), + ("roughness", |m, v| m.roughness = v), + ("occlusion_strength", |m, v| m.occlusion_strength = v), + ("clearcoat", |m, v| m.clearcoat = v), + ("clearcoat_roughness", |m, v| m.clearcoat_roughness = v), + ("sheen_color", |m, v| m.sheen_color[2] = v), + ]; + for (name, set) in unit.iter().chain([("sheen_roughness", (|m: &mut Mesh, v| m.sheen_roughness = v) as Set)].iter()) { + for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] { + let mut m = Mesh::default(); + set(&mut m, v); + bad_value(try_from_mesh(&m), name); + } + for v in [0.0, 1.0] { + let mut m = Mesh::default(); + set(&mut m, v); + assert!(try_from_mesh(&m).is_ok(), "{name} {v}"); + } + } + for v in [f32::NAN, f32::INFINITY, -1.0] { + bad_value(try_from_mesh(&Mesh { emissive: [0.0, v, 0.0], ..Mesh::default() }), "emissive"); + bad_value(try_from_mesh(&Mesh { alpha_mode: MeshAlpha::Mask(v), ..Mesh::default() }), "alpha cutoff"); + } + for v in [f32::NAN, f32::INFINITY] { + bad_value(try_from_mesh(&Mesh { normal_scale: v, ..Mesh::default() }), "normal_scale"); + let t = TextureRef { transform: Some(MeshUv { rotation: v, ..MeshUv::default() }), ..TextureRef::default() }; + bad_value(try_from_mesh(&Mesh { emissive_texture: Some(t), ..Mesh::default() }), "emissive_texture transform"); + } + // Emission above 1, a cutoff above 1 and a negative normal scale are in range. + let wide = Mesh { emissive: [40.0; 3], alpha_mode: MeshAlpha::Mask(2.0), normal_scale: -1.0, ..Mesh::default() }; + let c = try_from_mesh(&wide).unwrap(); + assert_eq!((c.surface.emissive, c.surface.alpha_mode), ([40.0; 3], AlphaMode::Mask(2.0))); +} + +// ------------------------------------------------------------------ craft-materialx + +fn mx(shader: Shader, inputs: &[(&str, Value)]) -> Mx { + Mx { + name: "M".into(), + shader, + inputs: inputs.iter().map(|(n, v)| ((*n).to_owned(), v.clone())).collect(), + displacement: None, + uv_tiling: [1.0, 1.0], + warnings: Vec::new(), + } +} + +fn k(values: &[f32]) -> Value { + Value::Constant { values: values.to_vec(), colorspace: None } +} + +fn ks(values: &[f32], space: &str) -> Value { + Value::Constant { values: values.to_vec(), colorspace: Some(space.into()) } +} + +fn img(file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Value { + Value::Image { file: file.into(), colorspace: space.map(str::to_owned), uv_tiling: tiling } +} + +/// Schlick's reflectance at normal incidence for an index of refraction, as the specular weight +/// of the core: `((n − 1) / (n + 1))² / 0.04`. +fn specular_for_ior(n: f64) -> f32 { + (((n - 1.0) / (n + 1.0)).powi(2) / 0.04) as f32 +} + +#[test] +fn materialx_empty_inputs_give_each_shaders_defaults() { + // The defaults of the node definitions in MaterialX's libraries/bxdf: open_pbr_surface.mtlx, + // standard_surface.mtlx (version 1.0.1) and gltf_pbr.mtlx + // (https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf). + let open = try_from_materialx(&mx(Shader::OpenPbr, &[])).unwrap(); + let s = &open.surface; + assert_close3(s.material.base_color(), [0.8; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.3, 1.0)); + assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3])); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(open.report.is_empty(), "{:?}", open.report); + + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[])).unwrap(); + let s = &standard.surface; + assert_close3(s.material.base_color(), [0.8; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.2, 1.0)); + assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3])); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(standard.report.is_empty(), "{:?}", standard.report); + + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[])).unwrap(); + let s = &gltf.surface; + assert_eq!(s.material.base_color(), [1.0; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0)); + assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3])); + assert_eq!((s.clearcoat, s.sheen), (None, None)); + assert!(gltf.report.is_empty(), "{:?}", gltf.report); +} + +#[test] +fn materialx_base_weight_scales_the_base_color_and_specular_follows_weight_and_ior() { + let c = + try_from_materialx(&mx(Shader::OpenPbr, &[("base_color", k(&[0.5, 0.4, 0.2])), ("base_weight", k(&[0.5])), ("base_metalness", k(&[0.25]))])) + .unwrap(); + assert_close3(c.surface.material.base_color(), [0.25, 0.2, 0.1]); + assert_eq!(c.surface.material.metallic(), 0.25); + assert!(c.report.is_empty(), "{:?}", c.report); + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("base", k(&[0.5])), ("specular", k(&[0.5]))])).unwrap(); + assert_close3(standard.surface.material.base_color(), [0.4; 3]); + assert!(close(standard.surface.material.specular(), 0.5)); + assert!(approximated(&standard, "specular")); + + let weight = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0]))])).unwrap(); + assert!(close(weight.surface.material.specular(), 2.0)); + assert!(approximated(&weight, "specular_weight")); + let water = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_ior", k(&[1.33]))])).unwrap(); + assert!(close(water.surface.material.specular(), specular_for_ior(1.33)), "{}", water.surface.material.specular()); + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[2.0])), ("specular", k(&[0.5]))])).unwrap(); + assert!(close(gltf.surface.material.specular(), 0.5 * specular_for_ior(2.0))); + // 25 is the largest weight the core takes: at IOR 1.5 a weight of 25 fits, 25.5 does not. + let max = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.0]))])).unwrap(); + assert!(close(max.surface.material.specular(), 25.0)); + bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.5]))])), "specular_weight"); + bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0])), ("specular_ior", k(&[30.0]))])), "specular_weight"); +} + +#[test] +fn materialx_color_constants_are_decoded_from_the_color_space_in_effect() { + let base = |v: Value| try_from_materialx(&mx(Shader::GltfPbr, &[("base_color", v)])).map(|c| c.surface.material.base_color()); + let c = [0.5, 0.2, 0.02]; + // The sRGB transfer function of IEC 61966-2-1, written out here independently. + let srgb = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + for space in ["srgb_texture", "srgb_rec709_scene"] { + let got = base(ks(&c, space)).unwrap(); + assert_close3(got, c.map(srgb)); + assert_close3(got, c.map(craft_texture::srgb_to_linear)); + } + for space in ["lin_rec709", "lin_rec709_scene", "data", "none"] { + assert_eq!(base(ks(&c, space)).unwrap(), c, "{space}"); + } + assert_eq!(base(k(&c)).unwrap(), c); + assert_close3(base(ks(&c, "g22_rec709")).unwrap(), c.map(|v| v.powf(2.2))); + assert_close3(base(ks(&c, "g18_rec709_scene")).unwrap(), c.map(|v| v.powf(1.8))); + assert_close3(base(ks(&c, "g24_rec709_scene")).unwrap(), c.map(|v| v.powf(2.4))); + for space in ["acescg", "lin_ap1_scene", "srgb_p3d65_scene", "bogus"] { + match base(ks(&c, space)) { + Err(ConvertError::ColorSpace { input, colorspace }) => assert_eq!((input.as_str(), colorspace.as_str()), ("base_color", space)), + other => panic!("{space}: {other:?}"), + } + } + // Scalars are never decoded, whatever the color space. + let rough = try_from_materialx(&mx(Shader::GltfPbr, &[("roughness", ks(&[0.5], "srgb_texture"))])).unwrap(); + assert_eq!(rough.surface.material.roughness(), 0.5); +} + +#[test] +fn materialx_images_become_bindings_and_the_core_holds_the_factor() { + let m = mx( + Shader::OpenPbr, + &[ + ("base_color", img("tex/albedo.png", Some("srgb_texture"), Some([2.0, 3.0]))), + ("base_weight", k(&[0.5])), + ("base_metalness", img("metal.png", Some("srgb_texture"), None)), + ("specular_roughness", img("rough.png", None, None)), + ("geometry_opacity", img("cut.png", None, None)), + ("geometry_normal", Value::NormalMap { file: "n.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }), + ("emission_color", img("glow.png", Some("acescg"), None)), + ("emission_luminance", k(&[4.0])), + ("specular_ior", img("ior.png", None, None)), + ], + ); + let c = try_from_materialx(&m).unwrap(); + let s = &c.surface; + assert_close3(s.material.base_color(), [0.5; 3]); + assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0)); + assert_eq!((s.alpha, s.alpha_mode), (1.0, AlphaMode::Blend)); + assert_eq!(s.emissive, [4.0; 3]); + let find = |input: TextureInput| s.textures.iter().find(|b| b.input == input).unwrap(); + let albedo = find(TextureInput::BaseColor); + assert_eq!((&albedo.source, &albedo.encoding), (&TextureSource::File("tex/albedo.png".into()), &TextureEncoding::Srgb)); + assert_eq!(albedo.transform, Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale: [2.0, 3.0] })); + assert_eq!((albedo.uv_set, albedo.wrap, albedo.scale), (0, [Wrap::Repeat; 2], 1.0)); + // Data inputs are linear whatever color space the file carries; color inputs keep theirs. + assert_eq!(find(TextureInput::Metallic).encoding, TextureEncoding::Linear); + assert_eq!(find(TextureInput::Roughness).encoding, TextureEncoding::Linear); + assert_eq!(find(TextureInput::Normal).encoding, TextureEncoding::Linear); + assert_eq!(find(TextureInput::Opacity).source, TextureSource::File("cut.png".into())); + assert_eq!(find(TextureInput::Emissive).encoding, TextureEncoding::Named("acescg".into())); + assert_eq!(find(TextureInput::Other("specular_ior".into())).source, TextureSource::File("ior.png".into())); + for name in ["base_color", "base_metalness", "specular_roughness", "geometry_opacity", "geometry_normal", "emission_color", "specular_ior"] { + assert!(unshaded(&c, name), "{name}"); + } + assert!(approximated(&c, "specular_ior")); +} + +#[test] +fn materialx_coat_and_sheen_are_kept_only_when_they_are_on() { + let c = try_from_materialx(&mx( + Shader::OpenPbr, + &[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.2])), ("fuzz_weight", k(&[0.5])), ("fuzz_color", k(&[1.0, 0.5, 0.0]))], + )) + .unwrap(); + assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.5, roughness: 0.2 })); + // fuzz_roughness defaults to 0.5. + assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.5 })); + assert!(approximated(&c, "fuzz_weight") && unshaded(&c, "clearcoat") && unshaded(&c, "sheen")); + + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("coat", k(&[1.0])), ("sheen", k(&[0.5]))])).unwrap(); + // coat_roughness 0.1, sheen_color white and sheen_roughness 0.3 by default. + assert_eq!(standard.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.1 })); + assert_eq!(standard.surface.sheen, Some(Sheen { color: [0.5; 3], roughness: 0.3 })); + + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_color", k(&[0.2, 0.1, 0.0])), ("sheen_roughness", k(&[0.4]))])).unwrap(); + assert_eq!(gltf.surface.sheen, Some(Sheen { color: [0.2, 0.1, 0.0], roughness: 0.4 })); + assert!(!approximated(&gltf, "sheen_color")); + + let off = try_from_materialx(&mx( + Shader::OpenPbr, + &[("coat_roughness", img("coat_r.png", None, None)), ("fuzz_color", img("fuzz.png", None, None)), ("coat_weight", k(&[0.0]))], + )) + .unwrap(); + assert_eq!((off.surface.clearcoat, off.surface.sheen), (None, None)); + assert!(off.surface.textures.is_empty()); + assert!(dropped(&off, "coat_roughness") && dropped(&off, "fuzz_color")); + let textured = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", img("coat.png", None, None))])).unwrap(); + assert_eq!(textured.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.0 })); + assert_eq!(textured.surface.textures[0].input, TextureInput::Clearcoat); +} + +#[test] +fn materialx_coat_and_sheen_roughness_images_read_their_first_channel() { + let cases = [ + (Shader::OpenPbr, [("coat_weight", k(&[1.0])), ("fuzz_weight", k(&[1.0]))], ["coat_roughness", "fuzz_roughness"]), + (Shader::StandardSurface, [("coat", k(&[1.0])), ("sheen", k(&[1.0]))], ["coat_roughness", "sheen_roughness"]), + (Shader::GltfPbr, [("clearcoat", k(&[1.0])), ("sheen_color", k(&[1.0, 1.0, 1.0]))], ["clearcoat_roughness", "sheen_roughness"]), + ]; + for (shader, [coat, sheen], [coat_roughness, sheen_roughness]) in cases { + let c = try_from_materialx(&mx( + shader, + &[coat, sheen, (coat_roughness, img("coat_r.png", None, None)), (sheen_roughness, img("sheen_r.png", None, None))], + )) + .unwrap(); + let inputs: Vec<_> = c.surface.textures.iter().map(|t| (t.input.clone(), t.source.clone())).collect(); + assert_eq!( + inputs, + [ + (TextureInput::ClearcoatRoughnessFirst, TextureSource::File("coat_r.png".into())), + (TextureInput::SheenRoughnessFirst, TextureSource::File("sheen_r.png".into())), + ], + "{shader:?}" + ); + } +} + +#[test] +fn materialx_coat_only_inputs_are_dropped_while_the_coat_is_off() { + let coat_only = [ + (Shader::OpenPbr, "coat_weight", ["geometry_coat_normal", "coat_color", "coat_ior"]), + (Shader::StandardSurface, "coat", ["coat_normal", "coat_color", "coat_IOR"]), + ]; + for (shader, weight, [normal, color, ior]) in coat_only { + let inputs = [ + (normal, Value::NormalMap { file: "coat_n.png".into(), colorspace: None, uv_tiling: None }), + (color, img("coat_c.png", None, None)), + (ior, k(&[1.4])), + ]; + // The coat weight is left at its default of 0. + let off = try_from_materialx(&mx(shader, &inputs)).unwrap(); + assert_eq!(off.surface.clearcoat, None); + assert!(off.surface.textures.is_empty(), "{:?}", off.surface.textures); + assert!(off.surface.other_inputs.is_empty(), "{:?}", off.surface.other_inputs); + for name in [normal, color, ior] { + assert!(dropped(&off, name) && !unshaded(&off, name), "{name}: {:?}", off.report); + } + // With the coat on, the same inputs are kept and reported as unshaded. + let mut with_coat = inputs.to_vec(); + with_coat.push((weight, k(&[0.5]))); + let on = try_from_materialx(&mx(shader, &with_coat)).unwrap(); + assert!(on.surface.clearcoat.is_some()); + assert_eq!(on.surface.textures.len(), 2); + assert_eq!(on.surface.other_inputs, vec![(ior.to_owned(), vec![1.4])]); + for name in [normal, color, ior] { + assert!(unshaded(&on, name) && !dropped(&on, name), "{name}"); + } + } + let gltf = try_from_materialx(&mx( + Shader::GltfPbr, + &[("clearcoat_normal", Value::NormalMap { file: "cc_n.png".into(), colorspace: None, uv_tiling: None })], + )) + .unwrap(); + assert!(gltf.surface.textures.is_empty() && dropped(&gltf, "clearcoat_normal")); +} + +#[test] +fn materialx_constants_of_a_layer_that_is_off_are_dropped() { + // The coat weight defaults to 0, so the coat is off and its roughness is dropped. + let coat = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_roughness", k(&[0.4]))])).unwrap(); + assert_eq!(coat.surface.clearcoat, None); + assert!(dropped(&coat, "coat_roughness"), "{:?}", coat.report); + // The weight that turns the layer off is not reported as dropped. + let zero = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.0])), ("coat_roughness", k(&[0.4]))])).unwrap(); + assert!(dropped(&zero, "coat_roughness") && !dropped(&zero, "coat_weight"), "{:?}", zero.report); + let on = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.4]))])).unwrap(); + assert!(!dropped(&on, "coat_roughness")); + // fuzz_weight defaults to 0: the fuzz color and roughness are dropped. + let fuzz = try_from_materialx(&mx(Shader::OpenPbr, &[("fuzz_color", k(&[1.0, 0.5, 0.0])), ("fuzz_roughness", k(&[0.2]))])).unwrap(); + assert!(dropped(&fuzz, "fuzz_color") && dropped(&fuzz, "fuzz_roughness"), "{:?}", fuzz.report); + // A black color turns the sheen off, so its weight is dropped and the color is not. + let black = try_from_materialx(&mx(Shader::StandardSurface, &[("sheen", k(&[0.5])), ("sheen_color", k(&[0.0; 3]))])).unwrap(); + assert!(dropped(&black, "sheen") && !dropped(&black, "sheen_color"), "{:?}", black.report); + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_roughness", k(&[0.3]))])).unwrap(); + assert!(dropped(&gltf, "sheen_roughness"), "{:?}", gltf.report); +} + +#[test] +fn materialx_emission_is_the_color_times_its_strength() { + let dark = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0]))])).unwrap(); + assert_eq!(dark.surface.emissive, [0.0; 3]); + assert!(dropped(&dark, "emission_color"), "{:?}", dark.report); + let lit = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0])), ("emission_luminance", k(&[10.0]))])).unwrap(); + assert_eq!(lit.surface.emissive, [10.0, 5.0, 0.0]); + assert!(approximated(&lit, "emission_luminance")); + let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("emission", k(&[2.0])), ("emission_color", k(&[0.5, 0.25, 1.0]))])).unwrap(); + assert_eq!(standard.surface.emissive, [1.0, 0.5, 2.0]); + assert!(standard.report.is_empty()); + let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("emissive", k(&[0.5, 0.25, 0.0])), ("emissive_strength", k(&[2.0]))])).unwrap(); + assert_eq!(gltf.surface.emissive, [1.0, 0.5, 0.0]); +} + +#[test] +fn materialx_standard_surface_opacity_color_gives_its_luminance() { + let standard = |opacity: &[f32]| try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", k(opacity))])); + let gray = standard(&[0.5; 3]).unwrap(); + assert_eq!(gray.surface.alpha, 0.5); + assert!(gray.report.is_empty(), "{:?}", gray.report); + // 0.2126 * 0.2 + 0.7152 * 0.4 + 0.0722 * 0.6, the Rec.709 luminance; the mean would be 0.4. + let colored = standard(&[0.2, 0.4, 0.6]).unwrap(); + assert!(close(colored.surface.alpha, 0.37192), "{}", colored.surface.alpha); + assert_eq!(colored.surface.alpha_mode, AlphaMode::Blend); + assert!(approximated(&colored, "opacity")); + let green = standard(&[0.0, 1.0, 0.0]).unwrap(); + assert!(close(green.surface.alpha, 0.7152), "{}", green.surface.alpha); + let near_white = standard(&[1.0, 1.0, 0.999_999_9]).unwrap(); + assert!(near_white.surface.alpha <= 1.0 && near_white.surface.alpha >= 0.999_999_9); + for v in [f32::NAN, f32::INFINITY, -0.01, 1.01] { + bad_value(standard(&[0.5, v, 0.5]), "opacity"); + } + // An image on the color opacity binds as RGB; the float opacities bind their first channel. + let textured = try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", img("o.png", None, None))])).unwrap(); + assert_eq!(textured.surface.textures[0].input, TextureInput::OpacityRgb); + for (shader, name) in [(Shader::OpenPbr, "geometry_opacity"), (Shader::GltfPbr, "alpha")] { + let c = try_from_materialx(&mx(shader, &[(name, img("o.png", None, None))])).unwrap(); + assert_eq!(c.surface.textures[0].input, TextureInput::Opacity, "{name}"); + } + // OpenPBR's geometry_opacity is a float in its node definition. + assert_eq!( + try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5; 3]))])).unwrap_err(), + ConvertError::Components { input: "geometry_opacity".into(), expected: 1, found: 3 } + ); +} + +#[test] +fn materialx_alpha_and_its_mode() { + let open = try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5]))])).unwrap(); + assert_eq!((open.surface.alpha, open.surface.alpha_mode), (0.5, AlphaMode::Blend)); + + let gltf = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::GltfPbr, inputs)); + assert_eq!(gltf(&[("alpha_mode", k(&[1.0])), ("alpha_cutoff", k(&[0.25]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.25)); + assert_eq!(gltf(&[("alpha_mode", k(&[1.0]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.5)); + assert_eq!(gltf(&[("alpha_mode", k(&[2.0]))]).unwrap().surface.alpha_mode, AlphaMode::Blend); + let opaque = gltf(&[("alpha", k(&[0.5]))]).unwrap(); + assert_eq!((opaque.surface.alpha, opaque.surface.alpha_mode), (0.5, AlphaMode::Opaque)); + for bad in [3.0, 1.5, -1.0] { + bad_value(gltf(&[("alpha_mode", k(&[bad]))]), "alpha_mode"); + } + bad_value(gltf(&[("alpha_mode", img("m.png", None, None))]), "alpha_mode"); + bad_value(gltf(&[("alpha_cutoff", img("c.png", None, None))]), "alpha_cutoff"); +} + +#[test] +fn materialx_bad_inputs_are_errors_and_unknown_ones_are_dropped() { + let open = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::OpenPbr, inputs)); + assert_eq!(open(&[("base_metalness", k(&[0.0])), ("base_metalness", k(&[1.0]))]).unwrap_err(), ConvertError::Duplicate("base_metalness".into())); + assert_eq!(open(&[("base_color", k(&[0.5]))]).unwrap_err(), ConvertError::Components { input: "base_color".into(), expected: 3, found: 1 }); + assert_eq!( + open(&[("base_metalness", k(&[0.5; 3]))]).unwrap_err(), + ConvertError::Components { input: "base_metalness".into(), expected: 1, found: 3 } + ); + for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] { + for name in + ["base_weight", "base_metalness", "specular_roughness", "coat_weight", "fuzz_roughness", "geometry_opacity", "transmission_weight"] + { + bad_value(open(&[(name, k(&[v]))]), name); + } + bad_value(open(&[("base_color", k(&[0.5, v, 0.5]))]), "base_color"); + } + for v in [f32::NAN, f32::INFINITY, -1.0] { + bad_value(open(&[("emission_luminance", k(&[v]))]), "emission_luminance"); + bad_value(open(&[("specular_ior", k(&[v]))]), "specular_ior"); + bad_value(open(&[("geometry_normal", k(&[0.0, 0.0, if v < 0.0 { f32::NAN } else { v }]))]), "geometry_normal"); + } + bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[0.9]))])), "ior"); + // glTF PBR's specular_color has no upper bound, so a large encoded value overflows to + // infinity when it is decoded to linear; that is an error, not an infinite input. + for space in ["g22_rec709", "srgb_texture", "srgb_rec709_scene", "g24_rec709_scene"] { + bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[1e20, 1.0, 1.0], space))])), "specular_color"); + } + let wide = try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[4.0, 1.0, 1.0], "g22_rec709"))])).unwrap(); + assert_eq!(wide.surface.other_inputs.len(), 1); + assert!(close(wide.surface.other_inputs[0].1[0], 4f32.powf(2.2))); + bad_value(open(&[("base_color", img("a.png", None, Some([0.0, 1.0])))]), "base_color"); + bad_value(open(&[("base_color", img("a.png", None, Some([f32::NAN, 1.0])))]), "base_color"); + let unknown = open(&[("thin_film_weight", k(&[0.5])), ("not_an_input", img("x.png", None, None))]).unwrap(); + assert!(dropped(&unknown, "thin_film_weight") && dropped(&unknown, "not_an_input")); + assert!(unknown.surface.textures.is_empty() && unknown.surface.other_inputs.is_empty()); +} + +#[test] +fn materialx_other_inputs_and_the_displacement_are_kept() { + let mut m = mx( + Shader::OpenPbr, + &[ + ("specular_color", ks(&[1.0, 0.5, 0.5], "srgb_texture")), + ("transmission_weight", k(&[0.5])), + ("subsurface_weight", img("sss.png", None, None)), + ], + ); + m.displacement = Some(k(&[0.25])); + let c = try_from_materialx(&m).unwrap(); + let srgb_half = craft_texture::srgb_to_linear(0.5); + assert_eq!( + c.surface.other_inputs, + vec![ + ("specular_color".into(), vec![1.0, srgb_half, srgb_half]), + ("transmission_weight".into(), vec![0.5]), + ("displacement".into(), vec![0.25]) + ] + ); + assert_eq!(c.surface.textures[0].input, TextureInput::Other("subsurface_weight".into())); + for name in ["specular_color", "transmission_weight", "subsurface_weight", "displacement"] { + assert!(unshaded(&c, name), "{name}"); + } + m.displacement = Some(img("h.png", Some("srgb_texture"), Some([4.0, 4.0]))); + let c = try_from_materialx(&m).unwrap(); + let h = c.surface.textures.iter().find(|b| b.input == TextureInput::Displacement).unwrap(); + assert_eq!((&h.source, &h.encoding), (&TextureSource::File("h.png".into()), &TextureEncoding::Linear)); + assert_eq!(h.transform.map(|t| t.scale), Some([4.0, 4.0])); + m.displacement = Some(k(&[f32::NAN])); + bad_value(try_from_materialx(&m), "displacement"); +} + +#[test] +fn materialx_reader_warnings_reach_the_report() { + let mut m = mx(Shader::OpenPbr, &[]); + m.warnings = vec!["input thin_film_weight is not read".into()]; + let c = try_from_materialx(&m).unwrap(); + assert_eq!(c.report.items, vec![ReportItem::Warning("input thin_film_weight is not read".into())]); +} + +#[test] +fn materialx_float_converted_to_a_color_is_not_decoded_from_the_nodes_color_space() { + // The float is not a color value, so the node's srgb_texture does not apply to it. + let doc = Document::parse( + br#" + + + + "#, + ) + .unwrap(); + let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_close3(c.surface.material.base_color(), [0.5; 3]); +} + +#[test] +fn materialx_documents_convert_from_xml() { + let doc = Document::parse( + br#" + + + + + + + + "#, + ) + .unwrap(); + let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap(); + assert_eq!(c.surface.name, "Red"); + assert_close3(c.surface.material.base_color(), [craft_texture::srgb_to_linear(0.5); 3]); + assert_eq!(c.surface.emissive, [3.0, 0.0, 0.0]); + assert_eq!(c.report.items, vec![ReportItem::Warning("input iridescence is not read".into())]); + + // craft-materialx's OpenPBR writer and this conversion agree on every texture it writes. + let textures = [ + Texture { input: "base_color".into(), file: "albedo.png".into(), colorspace: "srgb_texture".into() }, + Texture { input: "specular_roughness".into(), file: "rough.png".into(), colorspace: "srgb_texture".into() }, + Texture { input: "geometry_normal".into(), file: "normal.png".into(), colorspace: "lin_rec709".into() }, + Texture { input: "emission_color".into(), file: "glow.png".into(), colorspace: "lin_rec709".into() }, + Texture { input: "height".into(), file: "height.png".into(), colorspace: "lin_rec709".into() }, + ]; + let written = Document::parse(write_open_pbr("Stone", &textures, None).as_bytes()).unwrap(); + let c = try_from_materialx(&written.read_material_strict(None).unwrap()).unwrap(); + let s = &c.surface; + let by = |input: TextureInput| s.textures.iter().find(|b| b.input == input).map(|b| (b.source.clone(), b.encoding.clone())); + assert_eq!(by(TextureInput::BaseColor), Some((TextureSource::File("albedo.png".into()), TextureEncoding::Srgb))); + assert_eq!(by(TextureInput::Roughness), Some((TextureSource::File("rough.png".into()), TextureEncoding::Linear))); + assert_eq!(by(TextureInput::Normal), Some((TextureSource::File("normal.png".into()), TextureEncoding::Linear))); + assert_eq!(by(TextureInput::Emissive), Some((TextureSource::File("glow.png".into()), TextureEncoding::Linear))); + assert_eq!(by(TextureInput::Displacement), Some((TextureSource::File("height.png".into()), TextureEncoding::Linear))); + // The writer sets emission_luminance to 1 with an emission texture, so the texture shows. + assert_eq!(s.emissive, [1.0; 3]); + assert_eq!(s.name, "Stone"); +} diff --git a/crates/pbr/tests/it/main.rs b/crates/pbr/tests/it/main.rs index af2668dee1..3752e6e2b2 100644 --- a/crates/pbr/tests/it/main.rs +++ b/crates/pbr/tests/it/main.rs @@ -5,6 +5,9 @@ mod bench; mod bounds; mod brdf; +mod conversion_edges; +mod conversion_followups; +mod convert; mod differential; mod moved; mod numeric; diff --git a/crates/pdf/read-only-contract/Cargo.lock b/crates/pdf/read-only-contract/Cargo.lock index cfeccf816f..e999c63e13 100644 --- a/crates/pdf/read-only-contract/Cargo.lock +++ b/crates/pdf/read-only-contract/Cargo.lock @@ -103,8 +103,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d" dependencies = [ "hayro-ccitt", ] diff --git a/crates/pdf/src/cos/content/tests.rs b/crates/pdf/src/cos/content/tests.rs index 4076370cd5..cdedd45aeb 100644 --- a/crates/pdf/src/cos/content/tests.rs +++ b/crates/pdf/src/cos/content/tests.rs @@ -611,7 +611,8 @@ fn renderer_operators(data: &[u8]) -> Vec> { let mut iter = hayro_syntax::content::UntypedIter::new(data); let mut out = Vec::new(); while let Some(instruction) = iter.next() { - out.push(instruction.operator.as_ref().to_vec()); + let operator: &[u8] = instruction.operator.as_ref(); + out.push(operator.to_vec()); } out } diff --git a/crates/prepress/src/flatten/compose.rs b/crates/prepress/src/flatten/compose.rs index b17c302895..c3bebda6b7 100644 --- a/crates/prepress/src/flatten/compose.rs +++ b/crates/prepress/src/flatten/compose.rs @@ -30,6 +30,13 @@ use super::{BlendMode, DisplayList, FillItem, FillRule, GroupItem, Item, Paint}; use crate::ink::{InkColor, InkId, InkSet, Overprint, Process}; /// How [`flatten`] cuts transparent art. +/// +/// `FlattenOptions` can be initialized with its three fields: +/// +/// ``` +/// use craft_prepress::flatten::FlattenOptions; +/// let options = FlattenOptions { sliver: 0.01, max_regions: 5000, raster_dpi: 300.0 }; +/// ``` #[derive(Clone, Copy, Debug, PartialEq)] pub struct FlattenOptions { /// Regions narrower than this (in points) are dropped ([`geom::regions_with`]). @@ -48,6 +55,27 @@ impl Default for FlattenOptions { } } +/// These limits bound each region sweep used by [`flatten_with_limits`]. The PDF entry points +/// with explicit limits also apply them to each even-odd path rebuild during page reading. +/// A stopped rebuild retains the original path and fill rule. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FlattenSweepLimits { + /// The region sweep of one group stops after this many work units. The group then goes to + /// [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. The default is + /// [`geom::DEFAULT_MAX_SWEEP_WORK`]. + pub max_sweep_work: u64, + /// The region sweep of one group stops before holding more than this many output units. + /// The group then goes to [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. + /// The default is [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]. + pub max_sweep_units: usize, +} + +impl Default for FlattenSweepLimits { + fn default() -> Self { + Self { max_sweep_work: geom::DEFAULT_MAX_SWEEP_WORK, max_sweep_units: geom::DEFAULT_MAX_TOPOLOGY_UNITS } + } +} + /// A page with no transparency left. #[derive(Clone, Debug, PartialEq)] pub struct Flattened { @@ -132,6 +160,11 @@ pub enum FlattenError { /// an item that does come back unchanged, and so do opaque items with no transparency painted /// above them where they paint. pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result { + flatten_with_limits(list, opts, &FlattenSweepLimits::default()) +} + +/// `flatten_with_limits` flattens `list` using `opts` and the region sweep `limits`. +pub fn flatten_with_limits(list: &DisplayList, opts: &FlattenOptions, limits: &FlattenSweepLimits) -> Result { let nan = Rect::new(f64::NAN, f64::NAN, f64::NAN, f64::NAN); let bounds: Vec = list.items.iter().map(|i| bounds(i).unwrap_or(nan)).collect(); let transparent: Vec = list.items.iter().map(is_transparent).collect(); @@ -165,7 +198,7 @@ pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result {} - Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, &mut out)?, + Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, limits, &mut out)?, } } out.report.complex_regions = out.complex.len(); @@ -178,6 +211,7 @@ fn flatten_group( bounds: &[Rect], transparent: &[bool], opts: &FlattenOptions, + limits: &FlattenSweepLimits, out: &mut Flattened, ) -> Result<(), FlattenError> { let mut b = Builder::new(&list.inks); @@ -206,7 +240,7 @@ fn flatten_group( out.report.flattened += members.len(); return Ok(()); } - let regions = match geom::regions_with(&b.shapes, &b.clips, opts.sliver) { + let regions = match geom::regions_with_limits(&b.shapes, &b.clips, opts.sliver, limits.max_sweep_work, limits.max_sweep_units) { Ok(r) => r, Err(GeomError::Degenerate) => { // Each member's box is clear of every other group's items. @@ -1046,4 +1080,24 @@ mod tests { let l = list(InkSet::new(), vec![Item::Group(group(0.5, BlendMode::Normal, vec![crowded]))]); assert!(flatten(&l, &FlattenOptions::default()).is_err()); } + + #[test] + fn sweep_limits_send_the_group_to_complex() { + let l = list( + InkSet::new(), + vec![ + solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(M, 1.0)]), + Item::Group(group(0.5, BlendMode::Normal, vec![solid(Rect::new(50.0, 0.0, 150.0, 100.0), &[(C, 1.0)])])), + ], + ); + assert!(flat(&l).report.complex_groups.is_empty()); + + for limits in [ + FlattenSweepLimits { max_sweep_work: 1, ..FlattenSweepLimits::default() }, + FlattenSweepLimits { max_sweep_units: 1, ..FlattenSweepLimits::default() }, + ] { + let f = flatten_with_limits(&l, &FlattenOptions::default(), &limits).unwrap(); + assert_eq!(f.report.complex_groups, [ComplexGroup { items: vec![0, 1], reason: ComplexReason::Degenerate }], "{limits:?}"); + } + } } diff --git a/crates/prepress/src/flatten/document.rs b/crates/prepress/src/flatten/document.rs index 95ef200604..82c32df9b5 100644 --- a/crates/prepress/src/flatten/document.rs +++ b/crates/prepress/src/flatten/document.rs @@ -42,7 +42,7 @@ use kurbo::Rect; use super::pdf::{ReadColor, ReadError, ReadOptions, read_color, read_page_in}; use super::raster::{FlattenPageReport, Rasterizer}; use super::write::{FontMap, WriteError, write_flattened_with_fonts}; -use super::{DisplayList, FlattenError, FlattenOptions, flatten}; +use super::{DisplayList, FlattenError, FlattenOptions, FlattenSweepLimits, flatten_with_limits}; use crate::cms::CmsConversion; use crate::plates::{self, Fallback, pdf_text}; @@ -175,7 +175,16 @@ pub enum FlattenDocumentError { /// `pdf` with the transparency of every page in [`FlattenDocumentOptions::pages`] flattened, as /// one PDF. See the module docs for what carries over. pub fn flatten_document(pdf: &[u8], opts: &FlattenDocumentOptions) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { - flatten_document_with_progress(pdf, opts, &mut |_, _| {}) + flatten_document_with_limits(pdf, opts, &FlattenSweepLimits::default()) +} + +/// [`flatten_document`] with explicit sweep work and output limits. +pub fn flatten_document_with_limits( + pdf: &[u8], + opts: &FlattenDocumentOptions, + limits: &FlattenSweepLimits, +) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { + flatten_document_with_limits_and_progress(pdf, opts, limits, &mut |_, _| {}) } /// [`flatten_document`], calling `progress(done, total)` after each page. @@ -183,6 +192,16 @@ pub fn flatten_document_with_progress( pdf: &[u8], opts: &FlattenDocumentOptions, progress: &mut dyn FnMut(usize, usize), +) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { + flatten_document_with_limits_and_progress(pdf, opts, &FlattenSweepLimits::default(), progress) +} + +/// [`flatten_document_with_limits`], calling `progress(done, total)` after each page. +pub fn flatten_document_with_limits_and_progress( + pdf: &[u8], + opts: &FlattenDocumentOptions, + limits: &FlattenSweepLimits, + progress: &mut dyn FnMut(usize, usize), ) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { let doc = Arc::new(open_slice(pdf, None)?); let count = doc.pages().len(); @@ -213,9 +232,9 @@ pub fn flatten_document_with_progress( report.other_intents.push(page); } let p = doc.pages().get(page).ok_or(FlattenDocumentError::Read { page, source: ReadError::NoPage(page) })?; - match read_page_in(&doc, page, &opts.read, color.read.clone()) { + match read_page_in(&doc, page, &opts.read, color.read.clone(), limits) { Ok((list, read)) => { - let flat = flatten(&list, &opts.flatten).map_err(|source| FlattenDocumentError::Flatten { page, source })?; + let flat = flatten_with_limits(&list, &opts.flatten, limits).map_err(|source| FlattenDocumentError::Flatten { page, source })?; let mut raster = Rasterizer::new(&list, color.settings.clone(), color.condition.clone(), &color.cms, opts.flatten.raster_dpi); let at = |source| FlattenDocumentError::Write { page, source }; let settings = page_settings(p, list.page).ok_or(at(WriteError::Page))?; diff --git a/crates/prepress/src/flatten/geom.rs b/crates/prepress/src/flatten/geom.rs index 72fedeb079..d613c4f365 100644 --- a/crates/prepress/src/flatten/geom.rs +++ b/crates/prepress/src/flatten/geom.rs @@ -21,6 +21,19 @@ use linesweeper::topology::{ContourIdx, Contours, Topology, WindingNumber}; /// numerical debris, such as the lens between two nearly coincident curves. pub const DEFAULT_SLIVER: f64 = 0.01; +/// The default for the most work the sweep may do, counted as segment comparisons plus segment +/// position checks plus one unit for every 16 segments a search of the sweep line passes or probes +/// plus the horizontal segments each step of a sweep line visits, +/// before the shapes count as too degenerate to sweep. Stacked copies of a shape can need billions +/// of comparisons; a release build makes about 17 million a second. +pub const DEFAULT_MAX_SWEEP_WORK: u64 = 100_000_000; + +/// The default for the most output the sweep's topology may hold before the shapes count as too +/// degenerate to sweep, in units: each output segment takes one unit plus one for each entry of its +/// two winding numbers (at least one each), so 2,000,000 segments with single-entry windings fill +/// it. Each segment's windings can hold an entry for every shape that covers it. +pub const DEFAULT_MAX_TOPOLOGY_UNITS: usize = 6_000_000; + /// How a path's winding number decides what is inside it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum FillRule { @@ -125,10 +138,17 @@ pub fn regions(shapes: &[Shape], clips: &[ClipPath]) -> Result, Geom /// [`regions`] with contours narrower than `sliver` dropped. pub fn regions_with(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result, GeomError> { + regions_with_limits(shapes, clips, sliver, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS) +} + +/// [`regions_with`] with the sweep stopped, as [`GeomError::Degenerate`], once it passes +/// `max_work` units of work or its topology passes `max_units` units of output (see +/// [`DEFAULT_MAX_SWEEP_WORK`] and [`DEFAULT_MAX_TOPOLOGY_UNITS`] for the units). +pub fn regions_with_limits(shapes: &[Shape], clips: &[ClipPath], sliver: f64, max_work: u64, max_units: usize) -> Result, GeomError> { if shapes.is_empty() { return Ok(Vec::new()); } - Ok(Arrangement::new(shapes, clips, sliver)?.regions()) + Arrangement::new(shapes, clips, sliver, max_work, max_units)?.regions() } /// The finiteness check [`regions_with`] makes: every point of every shape path and of every clip @@ -268,6 +288,9 @@ impl WindingNumber for Multi { let w = self.get(tag); Multi(Arc::new(if w == 0 { vec![] } else { vec![(tag, w)] })) } + fn storage_units(&self) -> usize { + self.0.len().max(1) + } } /// The sweep of shapes and clips. Tags `0..n` are shapes, `n + c` is clip `c`. @@ -281,7 +304,7 @@ struct Arrangement { } impl Arrangement { - fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result { + fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64, work_limit: u64, output_limit: usize) -> Result { let n = shapes.len(); let mut used = vec![false; clips.len()]; let mut shape_clips = Vec::with_capacity(n); @@ -304,8 +327,11 @@ impl Arrangement { let eps = eps_for(paths.iter().map(|p| &p.0))?; snap_horizontals(&mut paths.iter_mut().map(|p| &mut p.0).collect::>(), eps); // The sweep can panic on rare near-degenerate input; the flattener then rasterizes. - let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::::from_paths(paths.iter().map(|(p, t)| (p, *t)), eps))); - // Every subpath is closed, so a path error is a degenerate input too. + let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + Topology::::from_paths_with_limits(paths.iter().map(|(p, t)| (p, *t)), eps, work_limit, output_limit) + })); + // Every subpath is closed, so a path error or a sweep past its work or output limit is a + // degenerate input too. let top = sweep.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate)?; let rules = shapes.iter().map(|s| s.rule).chain(clips.iter().map(|c| c.rule)).collect(); let tidy = Tidy::keeping(sliver, paths.iter().map(|p| &p.0)); @@ -324,7 +350,7 @@ impl Arrangement { /// sets × edges. Instead the sets go into batches whose faces share no vertex (so no edge /// either): one pass per batch walks each face's contours as its own set's pass would, and the /// set a contour bounds is the one of its batch at its first point. - fn regions(&self) -> Vec { + fn regions(&self) -> Result, GeomError> { let top = &self.top; // The distinct non-empty coverage sets, numbered in the order met, and the set of each // side of each segment. Faces have many sides, so a set is worked out once per winding. @@ -391,7 +417,7 @@ impl Arrangement { } let mut faces: Vec> = vec![Vec::new(); sets.len()]; for b in 0..batches { - let c = top.contours(|w| id(w).is_some_and(|m| batch[m] == b)); + let c = contours(top, |w| id(w).is_some_and(|m| batch[m] == b))?; let owner: Option> = c .contours() .map(|ct| { @@ -403,7 +429,7 @@ impl Arrangement { // Not expected: every contour starts at a vertex of the arrangement. Fall back to // a pass per set for this batch. for m in (0..sets.len()).filter(|&m| batch[m] == b) { - let c = top.contours(|w| id(w) == Some(m)); + let c = contours(top, |w| id(w) == Some(m))?; faces[m].extend(c.grouped().into_iter().map(|g| self.outline(&c, g))); } continue; @@ -439,7 +465,7 @@ impl Arrangement { out.push(Region { path, area, sources: sources.clone() }); } } - out + Ok(out) } /// The contours `idx` of `c` as one path, repaired, without slivers, and with the pieces the @@ -467,6 +493,18 @@ impl Arrangement { } } +/// The contours of `top`'s faces for which `inside` holds. The contour walk returns an error when the +/// sweep left winding numbers that disagree around a point, and can still panic on other degenerate +/// input; either way that input is degenerate. +fn contours(top: &Topology, inside: impl Fn(&Multi) -> bool) -> Result { + walk_result(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| top.try_contours(inside)))) +} + +/// Maps a contour walk that panicked or returned an error to [`GeomError::Degenerate`]. +fn walk_result(walk: std::thread::Result>) -> Result { + walk.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate) +} + /// A point as a map key (the arrangement's vertices are exact). fn vertex_key(p: Point) -> (u64, u64) { (p.x.to_bits(), p.y.to_bits()) @@ -963,6 +1001,20 @@ mod tests { Shape::new(path, FillRule::NonZero) } + #[test] + fn inconsistent_windings_are_degenerate() { + // A walk that returns an error or panics gives `Degenerate`; one that finishes gives its contours. + assert_eq!(walk_result::(Ok(Err(linesweeper::Error::InconsistentWindingNumbers))), Err(GeomError::Degenerate)); + assert_eq!(walk_result::(Err(Box::new("walk panicked"))), Err(GeomError::Degenerate)); + assert_eq!(walk_result(Ok(Ok(7_u8))), Ok(7)); + let shapes = [fill(rect(0.0, 0.0, 10.0, 10.0))]; + let arrangement = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap(); + assert_eq!(contours(&arrangement.top, |w: &Multi| w.get(0) != 0).map(|c| c.contours().count()), Ok(1)); + // A walk that panics, in debug and release builds alike, gives `Degenerate`. + let panicking = |_: &Multi| -> bool { panic!("degenerate walk") }; + assert_eq!(contours(&arrangement.top, panicking).err(), Some(GeomError::Degenerate)); + } + /// The regions with their sources and areas rounded to 1e-6, sorted. fn summary(regions: &[Region]) -> Vec<(Vec, f64)> { let mut v: Vec<(Vec, f64)> = regions.iter().map(|r| (r.sources.clone(), (r.area * 1e6).round() / 1e6)).collect(); @@ -1035,6 +1087,58 @@ mod tests { top.contours(|w| *w != 0).contours().map(|c| c.path.area()).sum::().abs() } + #[test] + fn sweep_past_its_work_limit_is_degenerate() { + let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20]; + assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, 1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate)); + assert_eq!(regions(&shapes, &[]).unwrap().len(), 1); + } + + #[test] + fn regions_with_limits_takes_the_callers_limits() { + let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20]; + let limited = |work, units| regions_with_limits(&shapes, &[], DEFAULT_SLIVER, work, units); + assert_eq!(limited(1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate)); + assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, 10).err(), Some(GeomError::Degenerate)); + assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap().len(), 1); + } + + // 1,100 overlapping shapes made only of horizontal edges at one height. The sweep makes one + // output segment for each run of coincident horizontal pieces and none for a run whose winding + // numbers cancel, as every run does here, so the topology stays under + // DEFAULT_MAX_TOPOLOGY_UNITS. + #[test] + fn coincident_horizontal_edges_stay_under_the_output_limit() { + let n = 1_100; + let shapes: Vec = (0..n) + .map(|i| { + let i = f64::from(i); + let mut path = BezPath::new(); + path.move_to((i, 0.0)); + path.line_to((2.0 * f64::from(n) + i, 0.0)); + path.close_path(); + fill(path) + }) + .collect(); + assert_eq!(regions(&shapes, &[]), Ok(vec![])); + } + + // 200 squares, each one unit down and right of the one before, cross each other's edges and + // make fewer than 2,000,000 output segments, but the winding numbers of those segments hold an + // entry for each square that covers them, which passes DEFAULT_MAX_TOPOLOGY_UNITS. The sweep + // has no work limit here, so the output limit stops it. + #[test] + fn winding_entries_count_toward_the_output_limit() { + let k = 200; + let shapes: Vec = (0..k) + .map(|i| { + let i = f64::from(i); + fill(rect(i, i, f64::from(k) + i, f64::from(k) + i)) + }) + .collect(); + assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, u64::MAX, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate)); + } + #[test] fn stacked_boxes_fold_into_one_group_past_the_comparison_budget() { // Boxes one above the other, all sharing x 0–10: each stays open for every later one. @@ -1054,7 +1158,7 @@ mod tests { fill(rect(i, i + 0.25, i + 8.0, i + 8.25)) }) .collect(); - let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER).unwrap(); + let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap(); let mut sides = 0; let mut lists = std::collections::HashSet::new(); for s in a.top.segment_indices() { diff --git a/crates/prepress/src/flatten/mod.rs b/crates/prepress/src/flatten/mod.rs index 2a657a6701..7755eb0fe9 100644 --- a/crates/prepress/src/flatten/mod.rs +++ b/crates/prepress/src/flatten/mod.rs @@ -14,12 +14,16 @@ use kurbo::{Affine, BezPath, Point, Rect}; use crate::ink::{InkColor, InkId, InkSet, Overprint}; -pub use compose::{ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, Flattened, flatten}; +pub use compose::{ + ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, FlattenSweepLimits, Flattened, flatten, + flatten_with_limits, +}; pub use document::{ - FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_progress, + FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_limits, + flatten_document_with_limits_and_progress, flatten_document_with_progress, }; pub use geom::FillRule; -pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page}; +pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page, flatten_page_with_limits}; mod compose; mod document; diff --git a/crates/prepress/src/flatten/pdf.rs b/crates/prepress/src/flatten/pdf.rs index 229c7c955f..f908478bb9 100644 --- a/crates/prepress/src/flatten/pdf.rs +++ b/crates/prepress/src/flatten/pdf.rs @@ -43,6 +43,8 @@ use craft_pdf::{OpenError, open_slice}; use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke, StrokeOpts}; use super::font::FontCache; +#[cfg(test)] +use super::geom; use super::shade::{self, Canvas, StopInks}; use super::{ BlendMode, DisplayList, FillItem, FillRule, GradientGeometry, GroupItem, ImageItem, ImageSpace, Item, Mask, MaskKind, Paint, PlacedGlyph, @@ -170,7 +172,7 @@ pub enum ReadError { pub fn read_page(pdf: &[u8], page: usize, opts: &ReadOptions) -> Result<(DisplayList, ReadReport), ReadError> { let doc = open_slice(pdf, None)?; let color = read_color(&doc, page, &opts.fallback)?; - read_page_in(&doc, page, opts, color) + read_page_in(&doc, page, opts, color, &super::FlattenSweepLimits::default()) } /// How a page's process color converts: its output intent's simulation, else `fallback`'s. @@ -189,7 +191,13 @@ pub(crate) fn read_color(doc: &Pdf, page: usize, fallback: &Fallback) -> Result< } /// [`read_page`] of an open document, with the page's color already read. -pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: ReadColor) -> Result<(DisplayList, ReadReport), ReadError> { +pub(crate) fn read_page_in( + doc: &Pdf, + page: usize, + opts: &ReadOptions, + color: ReadColor, + limits: &super::FlattenSweepLimits, +) -> Result<(DisplayList, ReadReport), ReadError> { let (simulation, conversion) = color; let pages = doc.pages(); let p = pages.get(page).ok_or(ReadError::NoPage(page))?; @@ -220,6 +228,7 @@ pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: Re masks: HashMap::new(), fonts: FontCache::new(), scale: f64::from(dpi) / 72.0, + sweep_limits: *limits, }; let items = catch_unwind(AssertUnwindSafe(|| { @@ -260,6 +269,7 @@ struct Shared { fonts: FontCache, /// Raster pixels per point. scale: f64, + sweep_limits: super::FlattenSweepLimits, } /// How a paint composites: what wraps it in a group of its own. @@ -344,6 +354,11 @@ fn clip_group((clip, rule): (BezPath, FillRule)) -> GroupItem { } impl<'s, 'a> Reader<'s, 'a> { + fn nonzero(&self, path: &BezPath, rule: FillRule) -> (BezPath, FillRule) { + let limits = self.shared.sweep_limits; + nonzero_within(path, rule, limits.max_sweep_work, limits.max_sweep_units) + } + fn new(shared: &'s mut Shared, glyph: bool, bounds: Rect) -> Self { Self { shared, @@ -621,7 +636,7 @@ impl<'s, 'a> Reader<'s, 'a> { fn area_fill(&mut self, path: BezPath, rule: FillRule, paint: &PdfPaint<'a>, stroke: bool) { let PdfPaint::Pattern(pattern) = paint else { return }; self.flush(); - let (clip, rule) = nonzero(&path, rule); + let (clip, rule) = self.nonzero(&path, rule); let (op, big_op, _) = self.overprint; let flag = if stroke { big_op } else { op }; match pattern.as_ref() { @@ -975,7 +990,7 @@ impl<'s, 'a> Reader<'s, 'a> { let mut outline = BezPath::new(); for item in &items { if let Item::Fill(f) = item { - let (path, rule) = nonzero(&f.path, f.rule); + let (path, rule) = self.nonzero(&f.path, f.rule); if rule != FillRule::NonZero { return None; } @@ -1016,7 +1031,7 @@ impl<'a> Device<'a> for Reader<'_, 'a> { fn push_clip_path(&mut self, clip_path: &ClipPath) { self.flush(); - let clip = nonzero(&clip_path.path, fill_rule(clip_path.fill)); + let clip = self.nonzero(&clip_path.path, fill_rule(clip_path.fill)); self.frames.push(Frame { kind: FrameKind::Clip, group: clip_group(clip) }); } @@ -1317,22 +1332,35 @@ fn dash_pattern(path: &BezPath, dashes: &[f32]) -> Option> { } /// `path` filled by `rule`, as a path and the rule it is filled by. An even-odd path is -/// rebuilt from its boundary as a path filled nonzero; if that fails it is kept closed and -/// filled even-odd. +/// rebuilt from its boundary as a path filled nonzero; if that fails, panics, or passes the +/// flattener's default sweep work or output limit ([`geom::DEFAULT_MAX_SWEEP_WORK`], +/// [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]), it is kept closed and filled even-odd. The same fallback +/// applies when an input subpath fails [`linesweeper::binary_op`]'s automatic-accuracy check. +#[cfg(test)] fn nonzero(path: &BezPath, rule: FillRule) -> (BezPath, FillRule) { + nonzero_within(path, rule, geom::DEFAULT_MAX_SWEEP_WORK, geom::DEFAULT_MAX_TOPOLOGY_UNITS) +} + +/// Rebuilds an even-odd path with the sweep stopped after `work_limit` units of work or before +/// its topology holds more than `output_limit` units. A stopped rebuild keeps the original rule. +fn nonzero_within(path: &BezPath, rule: FillRule, work_limit: u64, output_limit: usize) -> (BezPath, FillRule) { if rule == FillRule::NonZero { return (path.clone(), FillRule::NonZero); } let closed = closed(path); - match linesweeper::binary_op(&closed, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union) { - Ok(contours) => { + let op = catch_unwind(AssertUnwindSafe(|| { + let top = linesweeper::topology::Topology::::from_paths_with_automatic_limits([(&closed, ())], work_limit, output_limit)?; + top.try_contours(|winding| winding % 2 != 0) + })); + match op { + Ok(Ok(contours)) => { let mut out = BezPath::new(); for contour in contours.contours() { out.extend(contour.path.iter()); } (out, FillRule::NonZero) } - Err(_) => (closed, FillRule::EvenOdd), + Ok(Err(_)) | Err(_) => (closed, FillRule::EvenOdd), } } @@ -1363,6 +1391,119 @@ fn closed(path: &BezPath) -> BezPath { mod tests { use super::*; + #[test] + fn page_reader_uses_explicit_sweep_limits_for_even_odd_clips() { + use craft_pdf::write::backend::geom::{PathBuilder, Rect as KRect}; + use craft_pdf::write::backend::page::PageSettings; + use craft_pdf::write::backend::paint::{Fill, FillRule as KFillRule}; + use craft_pdf::write::{Metadata, Writer}; + let mut writer = Writer::new(Default::default(), Metadata::default()); + let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(100.0, 100.0).unwrap()); + let mut surface = page.surface(); + let mut clip = PathBuilder::new(); + clip.push_rect(KRect::from_ltrb(0.0, 0.0, 90.0, 90.0).unwrap()); + clip.push_rect(KRect::from_ltrb(20.0, 20.0, 70.0, 70.0).unwrap()); + surface.push_clip_path(&clip.finish().unwrap(), &KFillRule::EvenOdd); + let mut paint = PathBuilder::new(); + paint.push_rect(KRect::from_ltrb(0.0, 0.0, 100.0, 100.0).unwrap()); + surface.set_fill(Some(Fill::default())); + surface.draw_path(&paint.finish().unwrap()); + surface.pop(); + surface.finish(); + page.finish(); + let bytes = writer.finish().unwrap(); + let doc = open_slice(&bytes, None).unwrap(); + let opts = ReadOptions::default(); + for limits in [ + super::super::FlattenSweepLimits::default(), + super::super::FlattenSweepLimits { max_sweep_work: 1, ..Default::default() }, + super::super::FlattenSweepLimits { max_sweep_units: 1, ..Default::default() }, + ] { + let color = read_color(&doc, 0, &opts.fallback).unwrap(); + let (list, _) = read_page_in(&doc, 0, &opts, color, &limits).unwrap(); + let group = list + .items + .iter() + .find_map(|item| match item { + Item::Group(group) if group.clip.is_some() => Some(group), + _ => None, + }) + .unwrap(); + let expected = if limits == super::super::FlattenSweepLimits::default() { FillRule::NonZero } else { FillRule::EvenOdd }; + assert_eq!(group.clip_rule, expected, "{limits:?}"); + let path = group.clip.as_ref().unwrap(); + let filled = |point| match group.clip_rule { + FillRule::NonZero => path.winding(point) != 0, + FillRule::EvenOdd => path.winding(point) % 2 != 0, + }; + assert!(filled((10.0, 10.0).into())); + assert!(!filled((50.0, 50.0).into())); + } + } + + #[test] + fn even_odd_path_with_inconsistent_windings_is_kept() { + // `nonzero` returns a path for this input whether the sweep succeeds or reports + // winding numbers that disagree around a point. + let path = BezPath::from_svg("M4,-1 C8,1 -7,-2 5,8 L-4,-8 L2,1 L1,1 Z").unwrap(); + assert!(!nonzero(&path, FillRule::EvenOdd).0.elements().is_empty()); + } + + #[test] + fn even_odd_holes_stay_open_beside_a_far_point() { + // A square with a hole drawn in the same direction, a 0.3 wide sliver and a triangle at + // 3e13, which makes the sweep tolerance about 0.43. + let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0); + path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter()); + path.extend(Rect::new(200.0, 0.0, 200.3, 10.0).to_path(0.0).iter()); + path.move_to((3.0e13, 3.0e13)); + path.line_to((3.0e13 + 1.0e3, 3.0e13)); + path.line_to((3.0e13, 3.0e13 + 1.0e3)); + path.close_path(); + // The automatic-accuracy check rejects rebuilding the narrow subpath. + let swept = linesweeper::binary_op(&path, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union); + assert!(matches!(swept, Err(linesweeper::Error::FeatureBelowTolerance { .. }))); + let (out, rule) = nonzero(&path, FillRule::EvenOdd); + let contains = |point| { + let winding = out.winding(point); + match rule { + FillRule::EvenOdd => winding % 2 != 0, + FillRule::NonZero => winding != 0, + } + }; + assert!(contains((200.15, 5.0).into()), "the narrow subpath remains filled"); + assert!(contains((10.0, 10.0).into())); + assert!(!contains((50.0, 50.0).into())); + assert_eq!(rule, FillRule::EvenOdd); + assert_eq!(out, path); + } + + #[test] + fn even_odd_path_past_the_sweep_work_limit_is_kept() { + // 21 stacked copies of one circle: the sweep compares their segments many times over. + let circle = kurbo::Circle::new((50.0, 50.0), 40.0).to_path(0.01); + let mut path = BezPath::new(); + for _ in 0..21 { + path.extend(circle.iter()); + } + let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, 1_000, geom::DEFAULT_MAX_TOPOLOGY_UNITS); + assert_eq!(kept.elements(), closed(&path).elements()); + assert_eq!(rule, FillRule::EvenOdd); + assert_ne!(nonzero(&path, FillRule::EvenOdd).0.elements(), closed(&path).elements()); + } + + #[test] + fn even_odd_path_past_the_sweep_output_limit_is_kept() { + // A square with a hole drawn in the same direction makes 8 output segments. + let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0); + path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter()); + let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, geom::DEFAULT_MAX_SWEEP_WORK, 4); + assert_eq!(kept.elements(), closed(&path).elements()); + assert_eq!(rule, FillRule::EvenOdd); + assert_ne!(kept.winding((50.0, 50.0).into()), 0); + assert_eq!(nonzero(&path, FillRule::EvenOdd).0.winding((50.0, 50.0).into()), 0); + } + #[test] fn even_odd_paths_keep_their_rule_when_the_rebuild_fails() { // Two nested squares drawn in the same direction: even-odd leaves a hole, nonzero fills it. diff --git a/crates/prepress/src/flatten/raster.rs b/crates/prepress/src/flatten/raster.rs index 6ca926d81c..72e9d2075e 100644 --- a/crates/prepress/src/flatten/raster.rs +++ b/crates/prepress/src/flatten/raster.rs @@ -41,7 +41,7 @@ use craft_pdf::interpret::color::CmykConversion; use craft_pdf::write::backend::SerializeSettings; use kurbo::{Affine, Rect, Shape as _}; -use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document}; +use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document_with_limits}; use super::pdf::{ReadError, ReadOptions, ReadReport}; use super::write::{WriteError, page_pdf}; use super::{ @@ -409,11 +409,21 @@ pub enum FlattenPageError { } /// Page `page` (from 0) of `pdf` with its transparency flattened, as a one-page PDF: the -/// one-page case of [`flatten_document`]. +/// one-page case of [`super::flatten_document`]. pub fn flatten_page(pdf: &[u8], page: usize, opts: &FlattenPageOptions) -> Result<(Vec, FlattenPageReport), FlattenPageError> { + flatten_page_with_limits(pdf, page, opts, &super::FlattenSweepLimits::default()) +} + +/// [`flatten_page`] with explicit sweep work and output limits. +pub fn flatten_page_with_limits( + pdf: &[u8], + page: usize, + opts: &FlattenPageOptions, + limits: &super::FlattenSweepLimits, +) -> Result<(Vec, FlattenPageReport), FlattenPageError> { let doc = FlattenDocumentOptions { read: opts.read.clone(), flatten: opts.flatten, pages: Some(page..page.saturating_add(1)), ..Default::default() }; - let (bytes, mut report) = flatten_document(pdf, &doc).map_err(|e| match e { + let (bytes, mut report) = flatten_document_with_limits(pdf, &doc, limits).map_err(|e| match e { FlattenDocumentError::Open(e) => FlattenPageError::Open(e), FlattenDocumentError::PageRange { .. } => FlattenPageError::Read(ReadError::NoPage(page)), FlattenDocumentError::Read { source, .. } => FlattenPageError::Read(source), diff --git a/crates/prepress/tests/flatten_document.rs b/crates/prepress/tests/flatten_document.rs index cd9d14c8df..8cb685f227 100644 --- a/crates/prepress/tests/flatten_document.rs +++ b/crates/prepress/tests/flatten_document.rs @@ -117,6 +117,41 @@ fn opts() -> FlattenDocumentOptions { FlattenDocumentOptions { flatten: FlattenOptions { raster_dpi: 72.0, ..FlattenOptions::default() }, ..FlattenDocumentOptions::default() } } +#[test] +fn pdf_entry_points_keep_explicit_sweep_limits() { + use craft_prepress::flatten::{ + FlattenSweepLimits, flatten_document_with_limits, flatten_document_with_limits_and_progress, flatten_page_with_limits, + }; + let settings = SerializeSettings { no_device_cs: false, group_color_space: GroupColorSpace::Cmyk, ..Default::default() }; + let mut writer = Writer::new(settings, Metadata::default()); + let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(200.0, 160.0).unwrap()); + let mut surface = page.surface(); + rect(&mut surface, 20.0, 20.0, 120.0, 100.0, fill(255, 0, 0, 0)); + surface.push_opacity(NormalizedF32::new(0.5).unwrap()); + rect(&mut surface, 70.0, 60.0, 170.0, 130.0, fill(0, 255, 0, 0)); + surface.pop(); + surface.finish(); + page.finish(); + let source = writer.finish().unwrap(); + let options = opts(); + let (_, ordinary) = flatten_document(&source, &options).unwrap(); + assert_eq!(ordinary.totals.complex_groups, 0); + for limits in [FlattenSweepLimits { max_sweep_work: 1, ..Default::default() }, FlattenSweepLimits { max_sweep_units: 1, ..Default::default() }] { + let (_, document) = flatten_document_with_limits(&source, &options, &limits).unwrap(); + assert_eq!(document.totals.complex_groups, 1); + let mut progress = Vec::new(); + let (_, observed) = flatten_document_with_limits_and_progress(&source, &options, &limits, &mut |done, total| { + progress.push((done, total)); + }) + .unwrap(); + assert_eq!(observed, document); + assert_eq!(progress, [(1, 1)]); + let page_options = FlattenPageOptions { flatten: options.flatten, ..Default::default() }; + let (_, page) = flatten_page_with_limits(&source, 0, &page_options, &limits).unwrap(); + assert_eq!(page.flatten.complex_groups.len(), 1); + } +} + fn separate(pdf: &[u8], page: usize) -> Plates { plates(pdf, page, DPI, &Options::default()).unwrap() } diff --git a/crates/proof/README.md b/crates/proof/README.md index 84d811f811..b838a66211 100644 --- a/crates/proof/README.md +++ b/crates/proof/README.md @@ -20,6 +20,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = " | German | — | — | TeX patterns (embedded, or a Language pack) | | Bulgarian | — | — | syllable rules | | Gujarati, Hindi | the installed Hunspell dictionary (Hindi: nukta letters spelled either way) | generic checks | akshara rules (or a Language pack) | +| Marathi (mr) | its Language pack or Hunspell dictionary, as any pack language | — | akshara rules (or a Language pack) | Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every build. diff --git a/crates/proof/src/gu/mod.rs b/crates/proof/src/gu/mod.rs index d511c4ecd3..c3c6fe483b 100644 --- a/crates/proof/src/gu/mod.rs +++ b/crates/proof/src/gu/mod.rs @@ -130,6 +130,34 @@ mod tests { } } + /// A zero-width joiner or non-joiner in a conjunct (`પુસ્` U+200D `તક`) keeps the word whole, + /// and the word is found under the dictionary's spelling, which has no joiner. + #[test] + fn words_with_joiners_are_one_word_and_spelled() { + test_dict::install(); + for word in ["પુસ્\u{200D}તક", "પુસ્\u{200C}તકોમાં"] { + let text = format!("ઘર {word} ગામ"); + let at = text.find(word).unwrap(); + assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}"); + assert!(is_correct(word), "{word:?}"); + let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Gu)]); + assert!(issues.is_empty(), "{word:?}: {issues:?}"); + } + // Still a misspelling with a joiner, and a joiner at a word's edge is not in the word. + assert!(!is_correct("પુસ્\u{200D}તકક")); + let text = "ઘર\u{200D} ગામ"; + assert!(crate::words(text).contains(&(0, "ઘર".len()))); + // A word with a joiner written twice is a repeated word. + let text = "પુસ્\u{200D}તક પુસ્\u{200D}તક"; + let issues = crate::check_grammar_in(text, crate::ProofLang::Gu); + assert!(issues.iter().any(|i| i.start == 0 && i.end == text.len()), "{issues:?}"); + // A word Gujarati repeats on purpose (`જલ્દી જલ્દી`) still is one when typed with a joiner. + for text in ["જલ્\u{200D}દી જલ્\u{200D}દી", "જલ્\u{200C}દી જલ્\u{200C}દી"] { + let issues = crate::check_grammar_in(text, crate::ProofLang::Gu); + assert!(issues.is_empty(), "{text:?}: {issues:?}"); + } + } + #[test] fn forbidden_words_are_rejected() { test_dict::install(); diff --git a/crates/proof/src/hi/mod.rs b/crates/proof/src/hi/mod.rs index 047f78607a..3adb055c26 100644 --- a/crates/proof/src/hi/mod.rs +++ b/crates/proof/src/hi/mod.rs @@ -143,6 +143,22 @@ mod tests { test_dict::install(); } + /// A zero-width joiner or non-joiner after a virama (`क्` U+200D `ष`) keeps the word whole, and + /// the word is found under the dictionary's spelling, which has no joiner. + #[test] + fn words_with_joiners_are_one_word_and_spelled() { + test_dict::install(); + for word in ["परीक्\u{200D}षण", "परीक्\u{200C}षण", "मित्\u{200D}रों"] { + let text = format!("घर {word} पानी।"); + let at = text.find(word).unwrap(); + assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}"); + assert!(is_correct(word), "{word:?}"); + let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Hi)]); + assert!(issues.is_empty(), "{word:?}: {issues:?}"); + } + assert!(!is_correct("परीक्\u{200D}षणण")); + } + #[test] fn user_dictionary_applies() { test_dict::install(); diff --git a/crates/proof/src/hyphen.rs b/crates/proof/src/hyphen.rs index 45f8118051..f8569a194c 100644 --- a/crates/proof/src/hyphen.rs +++ b/crates/proof/src/hyphen.rs @@ -15,7 +15,7 @@ //! //! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list. //! -//! **Gujarati and Hindi**: breaks between aksharas, never inside a conjunct or between a +//! **Gujarati, Hindi and Marathi**: breaks between aksharas, never inside a conjunct or between a //! consonant and its vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no //! pattern file. //! @@ -120,7 +120,7 @@ pub enum Source { Patterns, /// A heuristic for a language without a dictionary or patterns. Heuristic, - /// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati and Hindi [`crate::indic`]). + /// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati, Hindi and Marathi [`crate::indic`]). Rules, /// No break points: the word is too short or no source applies. None, @@ -167,7 +167,7 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec, Source) { if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) { return (crate::bg::points(core), Source::Rules); } - // Gujarati and Hindi words break between aksharas ([`crate::indic`]); other words in their runs + // Gujarati, Hindi and Marathi words break between aksharas ([`crate::indic`]); other words in their runs // (`WordCraft`) are hyphenated as English. if let Some(script) = crate::indic::Script::of(lang) && core.iter().all(|&c| script.is_letter(c)) @@ -242,8 +242,8 @@ fn composed_chars(core: &[char]) -> (Vec, Vec>) { (nfc, starts) } -/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati and -/// Hindi: a word in their script (the guard their rules use; for Gujarati and Hindi, the script's +/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati, Hindi +/// and Marathi: a word in their script (the guard their rules use; for the Indic ones, the script's /// letters and marks and the joiners inside a conjunct, [`crate::indic`]) whose letters the /// patterns know, so a word with a letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian /// and German: every word, as their embedded patterns do. Any other language: a word whose letters @@ -254,7 +254,7 @@ fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool { ProofLang::Bg => core.iter().all(|&c| crate::bg::is_letter(c)) && pack_knows(pats, core), ProofLang::Tr => core.iter().all(|&c| crate::tr::hyphen::is_letter(c)) && pack_knows(pats, core), ProofLang::Pl | ProofLang::Pt | ProofLang::It | ProofLang::De => true, - ProofLang::Gu | ProofLang::Hi => { + _ if crate::indic::Script::of(lang).is_some() => { crate::indic::Script::of(lang).is_some_and(|s| core.iter().all(|&c| s.is_letter(c))) && pack_knows(pats, core) } _ => pats.values(core).is_some(), diff --git a/crates/proof/src/hyphen/tests.rs b/crates/proof/src/hyphen/tests.rs index 26705716e7..124c265c45 100644 --- a/crates/proof/src/hyphen/tests.rs +++ b/crates/proof/src/hyphen/tests.rs @@ -235,3 +235,12 @@ fn hindi_breaks_between_aksharas_within_the_limits() { assert_eq!(hi("«विद्यार्थी»"), "«वि-द्या-र्थी»", "punctuation around the word"); assert_eq!(hi("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En)); } + +/// storytold/vectorcraft#4947: Marathi, a pack language (`mr`), breaks between aksharas as Hindi +/// does, within the paragraph's limits. +#[test] +fn marathi_breaks_between_aksharas() { + let mr = ProofLang::from_tag(Some("mr-IN")); + assert_eq!(hyphenate_word_in("महाराष्ट्र", &Limits::default(), mr), "महा-रा-ष्ट्र"); + assert_eq!(word_breaks_in("महाराष्ट्र", mr).1, Source::Rules); +} diff --git a/crates/proof/src/indic.rs b/crates/proof/src/indic.rs index 9da779458b..313e9c38bd 100644 --- a/crates/proof/src/indic.rs +++ b/crates/proof/src/indic.rs @@ -14,7 +14,8 @@ //! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is //! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a //! script is its block's start and a few script-specific code points (`Script::kind`). -//! Gujarati ([`ProofLang::Gu`]) and Hindi ([`ProofLang::Hi`], [`Script::Devanagari`]) use them; +//! Gujarati ([`ProofLang::Gu`]), Hindi ([`ProofLang::Hi`]) and Marathi (the pack language `mr`) +//! use them, Hindi and Marathi with [`Script::Devanagari`]; //! another language written in one of these scripts is one more line in [`Script::of`]. //! //! A single akshara left at the end or start of a line is ruled out by the paragraph's @@ -61,6 +62,9 @@ impl Script { match lang { ProofLang::Gu => Some(Script::Gujarati), ProofLang::Hi => Some(Script::Devanagari), + // Marathi has no proofing language of its own: `mr`, `mr-IN` and `mar` are pack + // languages, spelled from their pack or Hunspell dictionary. + ProofLang::Pack(l) if matches!(l.primary(), "mr" | "mar") => Some(Script::Devanagari), _ => None, } } @@ -243,11 +247,16 @@ mod tests { assert_eq!(hi("क्\u{200D}षमा"), "क्\u{200D}ष-मा"); } - /// Gujarati and Hindi are mapped to their scripts, other languages to none. + /// Gujarati, Hindi and Marathi (a pack language, by any of its tags) are mapped to their + /// scripts, other languages (another pack language among them) to none. #[test] fn languages_map_to_their_script() { assert_eq!(Script::of(ProofLang::Gu), Some(Script::Gujarati)); assert_eq!(Script::of(ProofLang::Hi), Some(Script::Devanagari)); + for tag in ["mr", "mr-IN", "mar"] { + assert_eq!(Script::of(ProofLang::from_tag(Some(tag))), Some(Script::Devanagari), "{tag}"); + } + assert_eq!(Script::of(ProofLang::from_tag(Some("ne"))), None); assert_eq!(Script::of(ProofLang::En), None); assert_eq!(Script::of(ProofLang::Bg), None); } diff --git a/crates/proof/src/lib.rs b/crates/proof/src/lib.rs index abc9c8e542..86dd9cb9d8 100644 --- a/crates/proof/src/lib.rs +++ b/crates/proof/src/lib.rs @@ -489,13 +489,32 @@ fn in_dialect(s: &str, word: &str, lang: ProofLang) -> String { } /// Words in `text`: (byte start, byte end). Combining marks belong to the word they follow, so a -/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is. +/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is. A +/// zero-width joiner or non-joiner between two letters, digits or marks is inside the word, as in +/// Unicode's word boundaries (UAX #29): Indic text uses one to choose how a conjunct is drawn +/// (`क्` U+200D `ष`, `પુસ્` U+200D `તક`). A joiner at a word's edge is not part of it. pub fn words(text: &str) -> Vec<(usize, usize)> { + use indic::is_joiner; let mut out = Vec::new(); let mut start: Option = None; - let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '’' || c == '-' || unicode_normalization::char::is_combining_mark(c); + let is_core = |c: char| c.is_alphanumeric() || unicode_normalization::char::is_combining_mark(c); + let is_w = |c: char| is_core(c) || c == '\'' || c == '’' || c == '-'; + // The char before was a letter, digit or mark, or a joiner kept after one. + let mut after_core = false; + // Is the first char after the current run of joiners a letter, digit or mark? Looked up once + // per run, so a long run of joiners costs linear time, not quadratic. + let mut run_ends_core: Option = None; for (i, c) in text.char_indices() { - match (start, is_w(c)) { + let w = if is_joiner(c) { + after_core + && *run_ends_core + .get_or_insert_with(|| text.get(i + c.len_utf8()..).and_then(|rest| rest.chars().find(|&n| !is_joiner(n))).is_some_and(is_core)) + } else { + run_ends_core = None; + is_w(c) + }; + after_core = if is_joiner(c) { w } else { is_core(c) }; + match (start, w) { (None, true) => start = Some(i), (Some(s), false) => { out.push((s, i)); diff --git a/crates/proof/src/script_checks.rs b/crates/proof/src/script_checks.rs index 49f1bdd5c9..76bac2fe7a 100644 --- a/crates/proof/src/script_checks.rs +++ b/crates/proof/src/script_checks.rs @@ -46,10 +46,13 @@ pub(crate) fn is_correct(script: &Script, d: &AffixDict, word: &str, opts: &crat } /// Is one word (no hyphens) in the dictionary or the user dictionary, spelled as it is or as the -/// script's [`Script::variant`]? +/// script's [`Script::variant`]? A word with a zero-width joiner or non-joiner (`પુસ્` U+200D +/// `તક`) is tried as typed, then without its joiners, as a dictionary that ignores them +/// (Hunspell's `IGNORE`) would: they choose how a conjunct is drawn, not how the word is spelled. fn known(script: &Script, d: &AffixDict, w: &str) -> bool { let listed = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase()); - listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v)) + let spelled = |w: &str| listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v)); + spelled(w) || (w.contains(crate::indic::is_joiner) && spelled(&w.replace(crate::indic::is_joiner, ""))) } /// A language's script, messages and choices for [`check`]. @@ -91,9 +94,11 @@ fn repeated_words(text: &str, ws: &[(usize, usize)], rules: &Rules, v: &mut Vec< let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; if !gap.is_empty() && gap.chars().all(char::is_whitespace) - && w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c)) + && w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c) || crate::indic::is_joiner(c)) && w0 == w1 - && (rules.flag_repeat)(w0) + // The words a language repeats on purpose are listed without joiners (`જલ્દી`), so + // `જલ્` U+200D `દી` twice is the same intentional repeat. + && (rules.flag_repeat)(&w0.replace(crate::indic::is_joiner, "")) { v.push(issue(rules, *a0, *b1, format!("{}: “{w1}”", rules.repeated_word), vec![w0.to_string()])); } diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 38ec038b52..0df4842e31 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -9,6 +9,8 @@ description = "Source-level platform regression guards, test deadlines, hostile- publish = false [features] +# `mcp::McpChild`: an MCP stdio test client. +mcp = ["dep:serde_json"] # Pinned-corpus manifests and the `corpus::pinned` test gate (native only). corpus = ["dep:sha2", "dep:libc"] # `font-coverage`: `skip::craft_fonts_cover`, which parses font data with skrifa. @@ -19,10 +21,24 @@ sha2 = { version = "0.10", default-features = false, features = ["std"], optiona [target.'cfg(not(target_arch = "wasm32"))'.dependencies] skrifa = { workspace = true, optional = true } +toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] } +serde_json = { workspace = true, optional = true } [target.'cfg(unix)'.dependencies] libc = { version = "0.2", optional = true } rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } +[dev-dependencies] +tempfile = "3" + +[[test]] +name = "mcp" +required-features = ["mcp"] + +[[test]] +name = "mcp_child" +harness = false +required-features = ["mcp"] + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 863715fb87..b43fa97df3 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -99,25 +99,40 @@ 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/it/fonts.rs` tests the module on faces it assembles from bytes. + ## deadline The `deadline` module is not built for `wasm32`. -`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. When `f` does not -finish within the limit, the test fails with a message that names `label`, the limit and the variable -that sets it. A panic in `f` is raised again in the test with its original payload. The limit counts -from the call, including the time spent starting the thread. When `f` returns or panics after the -limit has passed, the test fails with the label and the limit, and with the panic's message if it has -one. +The limits in this module guard against a hang. Elapsed time does not decide a result: a test fails on +a limit only when nothing has arrived by then. -`wait_until(limit, what, cond)` calls `cond` on the test's thread until it returns `true`. It calls -`cond` at once, then after pauses that start at 1 ms and double up to 50 ms, and does not call it -again once the limit has passed. When the limit passes first, or `cond` returns `true` only after the -limit has passed, the test fails with a message that names `what`. +`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. A panic in `f` is +raised again in the test with its original payload. A value or panic that arrives after the limit is +still the result. When `f` has neither returned nor panicked within the limit, the test fails with a +message that names `label`, the limit and the variable that sets it. The limit counts from the start +of the thread. + +`wait_until(limit, what, &signal, cond)` calls `cond` on the test's thread at once, and again each +time another thread calls `signal.raise()`, until `cond` returns `true`. The thread that changes the +state `cond` reads raises the `Signal` after each change. A raise that comes while `cond` runs makes +`wait_until` call `cond` again straight after. The limit counts from the start of the call. When the +limit has passed and the latest call of `cond` returned `false`, the test fails with a message that +names `what`, even if the signal is still being raised. ```rust use std::time::Duration; -use craft_testkit::deadline::{DeadlineLimit, wait_until, with_deadline}; +use craft_testkit::deadline::{DeadlineLimit, Signal, wait_until, with_deadline}; // The default of 30 s; CRAFT_TEST_TIMEOUT_SECS replaces it. let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || decode(&bytes)); @@ -126,7 +141,9 @@ let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || dec let limit = DeadlineLimit::new(Duration::from_secs(30)).with_variable("FILMCRAFT_HOSTILE_TIMEOUT_SECS"); with_deadline(limit, "hostile input 12", move || parse(&input)); -wait_until(Duration::from_secs(10), "the export to finish", || job.is_done()); +// The export job calls `done.raise()` after it changes its state. +let done = Signal::new(); +wait_until(Duration::from_secs(10), "the export to finish", &done, || job.is_done()); ``` ### The limit variable @@ -150,12 +167,14 @@ calls this module's. ### Limits -- A body that runs past its limit fails the test, but its thread is left running until the test - process exits. A body that never returns can keep the test binary alive after its tests finish. -- `wait_until` checks its limit only between calls of `cond`. A `cond` that blocks is not interrupted, - so it must return promptly. -- Neither function returns elapsed time. Tests of this crate use channel handshakes, and the only time - bounds in them are the limits under test. +- When a body has no result within its limit, the test fails, but the body's thread is left running + until the test process exits. A body that never returns can keep the test binary alive after its + tests finish. +- A `cond` that blocks is not interrupted, so it must return promptly. +- A state change that nobody signals is not seen: when the signal is not raised, `wait_until` fails + at the limit even if `cond` would now return `true`. +- Neither function returns elapsed time. Tests of this crate use channel handshakes and an injected + wait in place of the limits. ## hostile @@ -169,8 +188,10 @@ yields no copies. `mutations` and `Rng` build for `wasm32`. `hammer(&config, seed, parse)` runs `parse` on the unmodified seed, on every truncation of it (lengths 0 to one less than its length), and on `mutations(seed, rounds)`. The cases run one after -another on one worker thread, and the test's thread fails the test when a case runs past its limit. -A case that finishes after its limit also fails the test. The test fails on the first case that +another on one worker thread, and the test's thread fails the test when a case is still running once +its limit has passed since it started. The limit guards against a hang: a case that finishes passes +or fails on what `parse` did, however long it took, and the number of cases depends only on the seed, +the rounds and the divisor. The test fails on the first case that panics or does not finish, with a message that names the config's label, the case (`the unmodified seed`, `truncation to N` or the edits), the input's length and the panic's message. `parse` must be `Fn(&[u8]) + Send + Sync + 'static`, since a case that does not finish keeps running @@ -237,6 +258,77 @@ Changes from `craft-media-testkit`'s `hammer`: - `parse` is owned and runs on a worker thread. A closure that borrows from the test needs its data moved or shared with an `Arc`. +## fixtures + +The `fixtures` module (native targets only) generates missing test fixtures and shares them between test runs and processes: + +- `fixtures_root(var)` is the nonempty value of `var` (default `CRAFT_FIXTURES_DIR`) or `/target/fixtures`. The workspace is the one that holds the package under test, found from the `CARGO_MANIFEST_DIR` that Cargo and nextest set when they run tests: the folder named by the package's `package.workspace` key, or else the nearest folder whose `Cargo.toml` has a `[workspace]` table. A test binary run without `CARGO_MANIFEST_DIR` needs the root variable. `CARGO_TARGET_DIR` does not move the root. `fixtures_dir(sub, var)` creates a folder below the root and rejects an absolute `sub`, one containing `..`, and on Windows one with a drive inside it (`group\C:outside`). It creates the folder one level at a time and returns an error, without creating the rest, when a level resolves outside the root or is not a folder, for example a symbolic link or junction under the root that points elsewhere. The check uses paths, so it does not detect a folder that another process replaces with a link while the call runs or after it returns. +- `temp_path(out)` creates a new, empty sibling of `out` with `create_new`, keeping the extension. A name that already exists is never reused. +- `publish(tmp, out)` moves a nonempty regular file into place while holding a lock on `.fixture-lock`. When `out` is already a nonempty regular file, it is kept and `tmp` is removed; the check reads only the type and length of `out`, so a nonempty `out` that cannot be read is kept too. A directory at `out` is an error, and so are an `out` whose name ends with `.fixture-lock` and a file system that does not support the lock. +- `generate(out, required_var, make)` and `generate_with(out, required, make)` return a cached fixture without calling `make`, or run `make` on a claimed temporary file and publish it. The temporary file is removed when `make` fails, panics, writes nothing or makes `out` name the temporary file, and such an `out` is not returned. When `make` fails after another process published `out`, the published file is returned. A fixture that cannot be made follows the [skip](#skip) rule with the required variable `generate` is given (default `CRAFT_TEST_REQUIRED`): unset or empty prints `SKIPPED: ` on standard error and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. Only `generate` reads the required variable. `generate_with` uses the caller's `required` value instead: `true` fails the test, and `false` prints the skip line and returns `None`. +- `run_generator(cmd, env, max_output)` runs a generator with `env` added to the child's environment only, and keeps at most `max_output` bytes of each output stream (`DEFAULT_MAX_OUTPUT` is 64 KiB). The variables and stream settings stay on `cmd`, so use a new `Command` for each call that needs a clean environment. +- `report(name, status)` and `generate_and_report(name, outputs, generate)` print one of these lines on standard output, which FilmCraft's `cargo xtask fixtures` counts: + + ```text + FIXTURE made + FIXTURE cached + FIXTURE skipped + ``` + +A complete fixture is a nonempty regular file. A consumer that needs a valid media file checks its format after generation. + +## mcp + +The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The module is built on every target except `wasm32`, and it opens no network connection. + +`McpChild::spawn(path, args, env)` starts an MCP server program with its stdin and stdout piped. The variables in `env` are set for the child only; the test process's environment is not changed. `McpChild::connect(reader, writer, limits)` talks to a server that runs in the test process; its reading thread stops when the server drops its end of `reader`, or at the next line the server writes after `close()`. Each message is one line of JSON-RPC 2.0, as the [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) describes. + +| Call | What it does | +|---|---| +| `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), validates the reply, then sends `notifications/initialized`. The result must contain `capabilities` and `serverInfo` objects, with string `serverInfo.name` and `serverInfo.version` fields. Invalid fields return `Protocol` and close the connection. A reply with another version returns `UnsupportedVersion` and closes the connection. | +| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Well-formed replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | +| `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. | +| `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | +| `notify(method, params)` | Sends a notification, which has no id and gets no reply. | +| `take_notifications()` | Returns the notifications kept so far without waiting. | +| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. After the child exits, it waits up to 5 s for the rest of stderr to be read. | + +Tool results require a `content` array. Optional `isError` must be a boolean, and optional +`structuredContent` and `_meta` must be objects. Both tool helpers reject a malformed envelope +with `Protocol` and close the connection. Requests and notifications from the server require +object-valued `params` when that field is present. `close()` drains and discards stdout while +waiting for the child; incoming output does not extend the grace period. + +While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. Server requests require string or integer IDs. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error and close the connection; later calls return `Closed`. A terminal failure discards queued writes and unread messages. A write already in progress may finish. After the end of stdout or an I/O error, `close()` or dropping the connection reaps the child. Other terminal failures stop and reap it immediately. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. + +`McpLimits` holds the limits. These defaults are the crate's own values: + +| Field | Default | Range | +|---|---|---| +| `max_line_bytes` | 64 MiB, for one stdout line, for the whole `list_tools` result, and for the total compact JSON bytes of retained notifications | at least 1 | +| `request_timeout` | 30 s | more than zero, at most 1 hour | +| `initialize_timeout` | 60 s | more than zero, at most 1 hour | +| `close_grace` | 2 s | at most 1 hour | +| `max_pages` | 64 | at least 1 | +| `max_notifications` | 0 (notifications are not kept); oldest entries are dropped to satisfy both this count and the `max_line_bytes` byte budget | at most 4096 | +| `stderr_tail_bytes` | 0 (stderr goes to the null device); otherwise the last bytes written are kept | at most 16 MiB | + +A notification whose compact JSON encoding exceeds `max_line_bytes` is discarded without removing previously retained notifications. + +`McpLimits::timeouts_from_var(name)` sets both deadlines from a variable that holds a whole number of seconds from 1 to 3600; `mcp::TIMEOUT_VAR` (`CRAFT_TEST_MCP_TIMEOUT_SECS`) is the default name. Any other value returns an error. + +```rust +use craft_testkit::mcp::{McpChild, PROTOCOL_VERSION}; + +let mut mcp = McpChild::spawn(env!("CARGO_BIN_EXE_my-cli"), ["mcp"], [("MYCRAFT_CONFIG_DIR", dir.path())])?; +mcp.initialize(PROTOCOL_VERSION)?; +let result = mcp.call_tool("doc.new", serde_json::json!({}))?; +assert!(!result["isError"].as_bool().unwrap_or(false)); +assert!(mcp.close()?.status.is_some_and(|s| s.success())); +``` + +The tests that start a real child are in `tests/mcp_child.rs`, a target with `harness = false`: the child is that test program, and the standard harness writes its own lines on stdout. Both test targets build to nothing on `wasm32`. + ## corpus `craft_testkit::corpus` is behind the `corpus` feature and is native only. It parses a corpus manifest and checks a folder of files against it. @@ -349,6 +441,16 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie |---|---|---|---| | `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 + +| Module | Source | Path | Commit | +|---|---|---|---| +| `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` | + ### deadline | Code | Repository | Path | SHA | @@ -368,6 +470,21 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie |---|---|---|---| | `Rng`, the edits of `mutations` and `hammer` | storytold/craft-libs | `crates/media-testkit/src/hostile.rs` | `75a654f4` | +### fixtures + +| Part | Repository | Path | Commit | +|---|---|---|---| +| Locations, publication with winner reuse, reporting, and the moved tests | storytold/filmcraft | `crates/testkit/src/fixtures.rs` | `e4ab3c6a99` | +| `generate_with` and the required rule, with `failed_generator_skips_when_optional` and `failed_generator_fails_when_required` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` | + +### mcp + +| Code | Repository | Path | SHA | +|---|---|---|---| +| `Conn`, `request`, `call_tool`, `MAX_LINE`, deadlines, and the 14 tests of `child_tests.rs`, written again here | storytold/craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs` | `e8b31cb0` | +| The MCP end-to-end helpers | storytold/vectorcraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | `460d2119` | +| `mcp_recv` | storytold/photocraft | `apps/photocraft-cli/tests/it/cli.rs` | `58d11d91` | + ### corpus | Code | Repository | Path | SHA | @@ -401,6 +518,14 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie | 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 | +### fonts + +| Consumer | Guard | Replaces | State | +|---|---|---|---| +| 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 | + ### rng | Consumer | Code it replaces | State | @@ -434,6 +559,25 @@ An adoption keeps the variable name the app uses today. CADCraft's and TextureCraft's loops make other edits than `mutations`. Their adoptions say which cases change, and keep the test names. +### fixtures + +| Consumer | Copy it replaces | State | +|---|---|---| +| FilmCraft | `crates/testkit/src/fixtures.rs` (passes `FILMCRAFT_FIXTURES_DIR` and `FILMCRAFT_REQUIRE_ORACLES`) | Not switched | +| EffectCraft | `crates/media/tests/it/footage.rs` | Not switched | +| craft-libs `audio` and `video` tests | `crates/audio/tests/codecs/testkit.rs`, `crates/video/tests/vp8/common/mod.rs` | Not switched | +| `craft-media-testkit` | its `fixtures` module and `temp_path` (keeps its public names) | Not switched | + +### mcp + +| Consumer | Code it replaces | State | +|---|---|---| +| VectorCraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | Pending | +| PhotoCraft | `apps/photocraft-cli/tests/it/cli.rs` | Pending | +| CADCraft, DeckCraft, DesignCraft, EffectCraft | the MCP helpers in their CLI tests | Pending | +| FigCraft, FilmCraft, GridCraft, LightCraft, PdfCraft, SoundCraft | the MCP helpers in their CLI tests | Pending | +| craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs`, production code | Kept as it is | + ### corpus | Consumer | Code it replaces | State | diff --git a/crates/testkit/src/deadline.rs b/crates/testkit/src/deadline.rs index 918719e6bc..9e00f9a606 100644 --- a/crates/testkit/src/deadline.rs +++ b/crates/testkit/src/deadline.rs @@ -1,11 +1,18 @@ //! Limits on how long a test waits. //! -//! [`with_deadline`] runs a test body on its own thread and returns its value. When the body does not -//! finish within the limit, the test fails with the call's label, the limit and the variable that sets -//! it. A panic in the body is raised again in the test with its original payload. +//! A limit here guards against a hang and does not decide a result. A value or panic that a body +//! produces is the call's result whenever it arrives, and a test fails on the limit only when nothing +//! has arrived by then. //! -//! [`wait_until`] calls a condition on the test's thread until it returns `true`, pausing between -//! calls, and fails the test with its description when the limit passes first. +//! [`with_deadline`] runs a test body on its own thread and returns its value. A panic in the body is +//! raised again in the test with its original payload. When the body has neither returned nor +//! panicked within the limit, the test fails with the call's label, the limit and the variable that +//! sets it. +//! +//! [`wait_until`] calls a condition on the test's thread, and calls it again each time another +//! thread raises the [`Signal`] the call waits on. It returns when the condition returns `true`, and +//! fails the test with its description when the limit has passed since the call began and the latest +//! call of the condition returned `false`. //! //! A limit is a default [`Duration`] and the name of a variable that replaces it. A plain `Duration` //! reads [`DEFAULT_VARIABLE`]; [`DeadlineLimit::with_variable`] names another one. The variable holds @@ -13,30 +20,23 @@ //! fractional, not Unicode, zero, or larger than a `u64` fails the test that reads it, as does a zero //! default and a limit past the latest time the platform's clock can represent. //! -//! Neither function can stop code that does not return. A body that runs past its limit fails the -//! test, and its thread is left running until the test process exits. A condition that blocks is -//! not interrupted: [`wait_until`] checks its limit only between calls, so a condition must return -//! promptly. +//! Neither function can stop code that does not return. When a body does not finish within its +//! limit, the test fails and the body's thread is left running until the test process exits. A +//! condition that blocks is not interrupted, so a condition must return promptly. use std::any::Any; use std::ffi::OsString; use std::fmt; use std::io; use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; -use std::sync::mpsc::{self, RecvTimeoutError, Sender}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread; use std::time::{Duration, Instant}; /// The variable a limit reads unless [`DeadlineLimit::with_variable`] names another. pub const DEFAULT_VARIABLE: &str = "CRAFT_TEST_TIMEOUT_SECS"; -/// The first pause of [`wait_until`] between two calls of its condition. -const FIRST_PAUSE: Duration = Duration::from_millis(1); - -/// The longest pause of [`wait_until`]: each pause doubles up to this. -const MAX_PAUSE: Duration = Duration::from_millis(50); - /// The name of the thread [`with_deadline`] runs a body on. const WORKER_NAME: &str = "craft-testkit deadline"; @@ -91,15 +91,50 @@ impl From for DeadlineLimit<'static> { } } -/// Runs `f` on its own thread and returns its value, failing the calling test when `f` does not -/// finish within `limit`. +/// A signal that [`wait_until`] waits on: the thread that changes the state a condition reads raises +/// it after each change, and every call waiting on it then calls its condition again. /// -/// The failure names `label`, the limit and the variable that sets it. A panic in `f` is raised -/// again here with its original payload. The limit is read and checked before `f` starts, and a -/// limit that is not valid fails the test without running `f`. The limit counts from the call, so -/// the time spent starting the thread counts against it. When `f` returns or panics after the limit -/// has passed, the test fails with the label and the limit, and with the panic's message if it has -/// one. When the limit passes, the thread running `f` is left running. +/// ``` +/// use craft_testkit::deadline::Signal; +/// +/// let signal = Signal::new(); +/// // A raise with no call waiting is kept: the next wait sees it and calls its condition again. +/// signal.raise(); +/// ``` +#[derive(Debug, Default)] +pub struct Signal { + /// How many times the signal has been raised, wrapping. + raised: Mutex, + changed: Condvar, +} + +impl Signal { + /// A signal that has not been raised. + pub fn new() -> Self { + Self::default() + } + + /// Wakes every [`wait_until`] call waiting on this signal, so that each calls its condition again. + pub fn raise(&self) { + let mut raised = self.lock(); + *raised = raised.wrapping_add(1); + self.changed.notify_all(); + } + + fn lock(&self) -> MutexGuard<'_, u64> { + self.raised.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// Runs `f` on its own thread and returns its value, failing the calling test when `f` has neither +/// returned nor panicked within `limit`. +/// +/// A panic in `f` is raised again here with its original payload. The limit guards against a hang: +/// a value or panic that `f` produces is the result whenever it arrives, and the test fails on the +/// limit only when `f` has produced neither by then. That failure names `label`, the limit and the +/// variable that sets it, and the thread running `f` is left running. The limit is read and checked +/// before `f` starts, and a limit that is not valid fails the test without running `f`. The limit +/// counts from the start of the thread running `f`. /// /// ``` /// use std::time::Duration; @@ -112,46 +147,51 @@ impl From for DeadlineLimit<'static> { #[allow(clippy::panic)] #[track_caller] pub fn with_deadline<'a, T: Send + 'static>(limit: impl Into>, label: &str, f: impl FnOnce() -> T + Send + 'static) -> T { - let start = Instant::now(); - match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, Arc::new(move || start.elapsed())) { + match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, |rx, limit| rx.recv_timeout(limit)) { Ok(value) => value, Err(Failure::Panic(payload)) => resume_unwind(payload), Err(Failure::Message(message)) => panic!("{message}"), } } -/// Calls `cond` on the calling thread until it returns `true`, failing the calling test when the -/// limit passes first. +/// Calls `cond` on the calling thread, and again each time `signal` is raised, until it returns +/// `true`, failing the calling test when the limit has passed since the call began and the latest +/// call of `cond` returned `false`. /// -/// `cond` is called at once, and then after pauses that grow from 1 ms to 50 ms, but not again once -/// the limit has passed. The failure names `what`, the limit and the variable that sets it. A `true` -/// that `cond` returns after the limit has passed also fails the test. A panic in `cond` reaches the -/// caller unchanged. `cond` runs on the calling thread and is not interrupted, so it must return -/// promptly. +/// `cond` is called at once. A raise that comes while `cond` runs is not lost: `cond` is called +/// again straight after. The limit guards against a hang and counts from the start of the call, so +/// a signal that keeps being raised while `cond` stays `false` still fails the test. `cond` is +/// called before the limit is checked, so a condition that holds is never failed by it. The failure +/// names `what`, the limit and the +/// variable that sets it. A panic in `cond` reaches the caller unchanged. `cond` runs on the calling +/// thread and is not interrupted, so it must return promptly. The threads that change what `cond` +/// reads raise `signal` after each change. /// /// ``` /// use std::sync::atomic::{AtomicBool, Ordering}; /// use std::time::Duration; -/// use craft_testkit::deadline::wait_until; +/// use craft_testkit::deadline::{Signal, wait_until}; /// /// let ready = AtomicBool::new(false); +/// let signal = Signal::new(); /// std::thread::scope(|s| { -/// s.spawn(|| ready.store(true, Ordering::SeqCst)); -/// wait_until(Duration::from_secs(30), "the worker to start", || ready.load(Ordering::SeqCst)); +/// s.spawn(|| { +/// ready.store(true, Ordering::SeqCst); +/// signal.raise(); +/// }); +/// wait_until(Duration::from_secs(30), "the worker to start", &signal, || ready.load(Ordering::SeqCst)); /// }); /// ``` // Failing the calling test is what this function is for. #[allow(clippy::panic)] #[track_caller] -pub fn wait_until<'a>(limit: impl Into>, what: &str, mut cond: impl FnMut() -> bool) { +pub fn wait_until<'a>(limit: impl Into>, what: &str, signal: &Signal, mut cond: impl FnMut() -> bool) { let limit = limit.into(); - let start = Instant::now(); - let resolved = match resolve(&limit, read_variable, start) { + let resolved = match resolve(&limit, read_variable, Instant::now()) { Ok(resolved) => resolved, Err(error) => panic!("waiting for {what}: {error}"), }; - let mut elapsed = || start.elapsed(); - if let Err(message) = poll_until(&resolved, what, &mut cond, &mut elapsed, &mut thread::sleep) { + if let Err(message) = wait_for_signal(&resolved, what, signal, &mut cond, Instant::now, wait_for_raise) { panic!("{message}"); } } @@ -265,8 +305,8 @@ fn spawn_worker(job: Job, done: Sender<()>) -> io::Result<()> { .map(drop) } -/// The body's result and the clock reading when it finished, filled in by the worker. -type Slot = Arc, Duration)>>>; +/// The body's result, filled in by the worker. +type Slot = Arc>>>; /// How a [`with_deadline`] call failed. enum Failure { @@ -276,52 +316,32 @@ enum Failure { Message(String), } -/// A clock that returns the time since a [`with_deadline`] call started. -type Clock = Arc Duration + Send + Sync>; - -/// The text of a panic payload that holds a message. -fn panic_text(payload: &(dyn Any + Send)) -> Option<&str> { - payload.downcast_ref::().map(String::as_str).or_else(|| payload.downcast_ref::<&str>().copied()) -} - -/// [`with_deadline`] with the variable lookup, the thread start and the clock passed in. Starting -/// the worker counts against the limit. The worker stores the body's result with the clock reading -/// when it finished, under a lock, and then sends on the channel `spawn` receives. When the wait -/// times out, the stored result is still used if it is there, so a body that finished in time passes -/// even when its thread sends late. +/// [`with_deadline`] with the variable lookup, the thread start and the wait for the worker passed +/// in. The worker stores the body's result under a lock and then sends on the channel `spawn` +/// receives. `wait` waits on that channel for at most the limit. Whatever `wait` returns, a stored +/// result is the call's result, so the limit fails the call only when the body has produced nothing. fn run_with_deadline( limit: DeadlineLimit<'_>, label: &str, f: impl FnOnce() -> T + Send + 'static, lookup: impl FnOnce(&str) -> Option, spawn: impl FnOnce(Job, Sender<()>) -> io::Result<()>, - clock: Clock, + wait: impl FnOnce(&Receiver<()>, Duration) -> Result<(), RecvTimeoutError>, ) -> Result { let resolved = resolve(&limit, lookup, Instant::now()).map_err(|error| Failure::Message(format!("{label}: {error}")))?; let (tx, rx) = mpsc::channel(); let slot: Slot = Arc::new(Mutex::new(None)); let worker_slot = Arc::clone(&slot); - let worker_clock = Arc::clone(&clock); let job: Job = Box::new(move || { let result = catch_unwind(AssertUnwindSafe(f)); - // The clock is read under the lock: once the caller finds the slot empty after its limit, - // any later reading is past the limit too. - let mut stored = worker_slot.lock().unwrap_or_else(PoisonError::into_inner); - *stored = Some((result, worker_clock())); + *worker_slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(result); }); spawn(job, tx).map_err(|error| Failure::Message(format!("{label}: could not start the worker thread: {error}")))?; - let waited = rx.recv_timeout(resolved.limit.saturating_sub(clock())); + let waited = wait(&rx, resolved.limit); let stored = slot.lock().unwrap_or_else(PoisonError::into_inner).take(); match (stored, waited) { - (Some((result, finished)), _) if finished > resolved.limit => { - let panicked = match &result { - Ok(_) => String::new(), - Err(payload) => format!(" (it panicked: {})", panic_text(payload.as_ref()).unwrap_or("a payload that is not a message")), - }; - Err(Failure::Message(format!("{label} finished only after its limit of {resolved}{panicked}"))) - } - (Some((Ok(value), _)), _) => Ok(value), - (Some((Err(payload), _)), _) => Err(Failure::Panic(payload)), + (Some(Ok(value)), _) => Ok(value), + (Some(Err(payload)), _) => Err(Failure::Panic(payload)), (None, Err(RecvTimeoutError::Timeout)) => { Err(Failure::Message(format!("{label} did not finish within {resolved}; its thread is left running"))) } @@ -329,44 +349,49 @@ fn run_with_deadline( } } -/// The loop of [`wait_until`], with the clock and the pause passed in. `elapsed` returns the time -/// since the wait started. -fn poll_until( +/// Waits on `changed` while `raised` still reads `seen`, for at most `limit`. Returns the guard and +/// whether the limit passed with no raise. +fn wait_for_raise<'g>(changed: &Condvar, raised: MutexGuard<'g, u64>, seen: u64, limit: Duration) -> (MutexGuard<'g, u64>, bool) { + let (raised, result) = changed.wait_timeout_while(raised, limit, |count| *count == seen).unwrap_or_else(PoisonError::into_inner); + (raised, result.timed_out()) +} + +/// The loop of [`wait_until`], with the clock and the wait for a raise passed in. The raise count is +/// read before each call of `cond`, so a raise during the call ends the next wait at once. The limit +/// counts from the start of the loop, and each wait lasts at most the time left. +fn wait_for_signal( resolved: &Resolved<'_>, what: &str, + signal: &Signal, cond: &mut dyn FnMut() -> bool, - elapsed: &mut dyn FnMut() -> Duration, - pause: &mut dyn FnMut(Duration), + now: impl Fn() -> Instant, + wait: impl for<'g> Fn(&Condvar, MutexGuard<'g, u64>, u64, Duration) -> (MutexGuard<'g, u64>, bool), ) -> Result<(), String> { - let mut next_pause = FIRST_PAUSE; - let mut first = true; + let start = now(); + let mut seen = *signal.lock(); loop { - // After the first call, the condition is called only while the limit has not passed. - if !first && elapsed() >= resolved.limit { - return Err(format!("timed out waiting for {what} within {resolved}")); - } - first = false; - let held = cond(); - let spent = elapsed(); - if held && spent <= resolved.limit { + if cond() { return Ok(()); } - if held { - return Err(format!("timed out waiting for {what} within {resolved} (it held only after the limit had passed)")); + let remaining = resolved.limit.saturating_sub(now().saturating_duration_since(start)); + if remaining.is_zero() { + return Err(format!("timed out waiting for {what} within {resolved}: the condition still returned false at the limit")); } - if spent < resolved.limit { - pause(next_pause.min(resolved.limit - spent)); + let (raised, timed_out) = wait(&signal.changed, signal.lock(), seen, remaining); + if timed_out { + return Err(format!("timed out waiting for {what} within {resolved}: the signal was not raised after the last check")); } - next_pause = next_pause.saturating_mul(2).min(MAX_PAUSE); + seen = *raised; } } #[cfg(test)] mod tests { use super::*; + use std::cell::RefCell; use std::ffi::OsStr; use std::process::Command; - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::sync::atomic::{AtomicBool, Ordering}; /// A variable no test sets, so the environment cannot lengthen a test's short limit. const UNSET: &str = "CRAFT_TESTKIT_DEADLINE_UNSET_IN_TESTS"; @@ -400,6 +425,27 @@ mod tests { } } + /// A wait for the worker that returns at once, as when the limit passes with nothing received. + fn limit_passes(_: &Receiver<()>, _: Duration) -> Result<(), RecvTimeoutError> { + Err(RecvTimeoutError::Timeout) + } + + /// Runs `run_with_deadline` with its limit passing before the body has a result, and returns the + /// failure's message. The body runs on its own thread and blocks until the call has returned. + fn hung(limit: DeadlineLimit<'_>, label: &str, value: T) -> String { + let (gate, gate_rx) = mpsc::channel::<()>(); + let (done_tx, done) = mpsc::channel(); + let body = move || { + let _ = gate_rx.recv(); + done_tx.send(()).unwrap(); + value + }; + let result = run_with_deadline(limit, label, body, |_| None, spawn_worker, limit_passes); + drop(gate); + done.recv().unwrap(); + failure_message(result) + } + /// Runs `child_reads_its_variable` in a child process with `CHILD_VARIABLE` set to `value`, and /// returns what the child printed. The child must fail. fn run_child(value: &OsStr) -> String { @@ -442,21 +488,9 @@ mod tests { } #[test] - #[should_panic(expected = "seed 7 byte 3 did not finish within 50ms")] fn a_hang_fails_and_names_the_input() { - let (gate, gate_rx) = mpsc::channel::<()>(); - let (done_tx, done) = mpsc::channel(); - let result = catch_unwind(AssertUnwindSafe(|| { - with_deadline(short(), "seed 7 byte 3", move || { - let _ = gate_rx.recv(); - done_tx.send(()).unwrap(); - }) - })); - drop(gate); - done.recv().unwrap(); - if let Err(payload) = result { - resume_unwind(payload); - } + let text = hung(short(), "seed 7 byte 3", ()); + assert!(text.contains("seed 7 byte 3 did not finish within 50ms"), "{text}"); } #[test] @@ -467,14 +501,9 @@ mod tests { } #[test] - #[should_panic(expected = "did not finish within")] fn with_deadline_times_out() { - let (gate, gate_rx) = mpsc::channel::<()>(); - let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "blocked body", move || gate_rx.recv().unwrap_or_default()))); - drop(gate); - if let Err(payload) = result { - resume_unwind(payload); - } + let text = hung(short(), "blocked body", 7u8); + assert!(text.contains("did not finish within") && text.contains("its thread is left running"), "{text}"); } #[test] @@ -492,14 +521,7 @@ mod tests { #[test] fn timeout_names_this_call_only() { - let call = |label: &'static str| { - thread::spawn(move || { - let (gate, gate_rx) = mpsc::channel::<()>(); - let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), label, move || gate_rx.recv().unwrap_or_default()))); - drop(gate); - message(result.unwrap_err()) - }) - }; + let call = |label: &'static str| thread::spawn(move || hung(short(), label, ())); let first = call("first call"); let second = call("second call"); let first = first.join().unwrap(); @@ -517,13 +539,10 @@ mod tests { 7 }) }); - let (gate, gate_rx) = mpsc::channel::<()>(); - let short_call = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "short call", move || gate_rx.recv().unwrap_or_default()))); - let text = message(short_call.unwrap_err()); + let text = hung(short(), "short call", ()); assert!(text.contains("short call") && text.contains("50ms") && !text.contains("long call"), "{text}"); release.send(()).unwrap(); assert_eq!(long_call.join().unwrap(), 7); - drop(gate); } #[test] @@ -533,7 +552,7 @@ mod tests { ran.store(true, Ordering::SeqCst); Err(io::Error::other("no threads left")) }; - let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, Arc::new(|| Duration::ZERO)); + let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, limit_passes); let text = failure_message(result); assert!(ran.load(Ordering::SeqCst)); assert!(text.contains("no thread: could not start the worker thread: no threads left"), "{text}"); @@ -579,10 +598,10 @@ mod tests { ran.store(true, Ordering::SeqCst); Ok(()) }; - let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, Arc::new(|| Duration::ZERO))); + let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, limit_passes)); assert!(text.contains("ends past the latest time"), "{text}"); assert!(!ran.load(Ordering::SeqCst), "the body started"); - let text = message(catch_unwind(|| wait_until(huge, "a huge limit", || true)).unwrap_err()); + let text = message(catch_unwind(|| wait_until(huge, "a huge limit", &Signal::new(), || true)).unwrap_err()); assert!(text.contains("waiting for a huge limit: the limit of") && text.contains("ends past the latest time"), "{text}"); } @@ -619,22 +638,20 @@ mod tests { #[test] fn wait_until_returns_on_condition() { let ready = &AtomicBool::new(false); + let signal = &Signal::new(); let (asked, asked_rx) = mpsc::channel(); - let (stored, stored_rx) = mpsc::channel(); thread::scope(|s| { s.spawn(move || { asked_rx.recv().unwrap(); ready.store(true, Ordering::SeqCst); - stored.send(()).unwrap(); + signal.raise(); }); let mut calls = 0; - wait_until(long(), "the flag", || { + wait_until(long(), "the flag", signal, || { calls += 1; if calls == 1 { - // The flag is set before this call returns, and it still answers false, so the - // condition is called a second time whatever order the threads run in. + // The other thread sets the flag only after this call has started. asked.send(()).unwrap(); - stored_rx.recv().unwrap(); return false; } ready.load(Ordering::SeqCst) @@ -644,145 +661,137 @@ mod tests { } #[test] - #[should_panic(expected = "timed out waiting for the export to finish within 50ms")] - fn wait_until_times_out_with_label() { - wait_until(short(), "the export to finish", || false); + fn a_raise_during_the_condition_ends_the_next_wait_at_once() { + let signal = Signal::new(); + let mut calls = 0; + let mut cond = || { + calls += 1; + if calls == 1 { + signal.raise(); + } + calls == 2 + }; + let result = wait_for_signal(&fake_resolved(Duration::from_secs(600)), "a raise", &signal, &mut cond, Instant::now, |_, raised, seen, _| { + assert_ne!(*raised, seen, "the raise made during the condition was lost"); + (raised, false) + }); + assert_eq!(result, Ok(())); + assert_eq!(calls, 2); } + #[test] + fn wait_until_times_out_with_label() { + let mut calls = 0; + let mut cond = || { + calls += 1; + false + }; + let resolved = fake_resolved(Duration::from_millis(50)); + let text = wait_for_signal(&resolved, "the export to finish", &Signal::new(), &mut cond, Instant::now, |_, raised, _, _| (raised, true)) + .unwrap_err(); + assert!(text.starts_with("timed out waiting for the export to finish within 50ms"), "{text}"); + assert!(text.ends_with("the signal was not raised after the last check"), "{text}"); + assert_eq!(calls, 1); + } + + #[test] + fn raises_that_never_satisfy_the_condition_fail_at_the_limit() { + // A clock that moves 20 s on each reading, and a wait that always reports a raise. + let start = Instant::now(); + let readings = std::cell::Cell::new(0u32); + let now = || { + let n = readings.get(); + readings.set(n + 1); + start + Duration::from_secs(20) * n + }; + let mut calls = 0; + let mut cond = || { + calls += 1; + false + }; + let resolved = fake_resolved(Duration::from_secs(60)); + let text = wait_for_signal(&resolved, "a progress tick", &Signal::new(), &mut cond, now, |_, mut raised, _, _| { + *raised = raised.wrapping_add(1); + (raised, false) + }) + .unwrap_err(); + assert!(text.starts_with("timed out waiting for a progress tick within 60s"), "{text}"); + assert!(text.ends_with("the condition still returned false at the limit"), "{text}"); + assert_eq!(calls, 3); + } + + #[test] + fn a_thread_raising_in_a_loop_cannot_hold_wait_until_past_the_limit() { + let stop = Arc::new(AtomicBool::new(false)); + let signal = Arc::new(Signal::new()); + let raiser = { + let (stop, signal) = (Arc::clone(&stop), Arc::clone(&signal)); + thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + signal.raise(); + thread::yield_now(); + } + }) + }; + let waiter_signal = Arc::clone(&signal); + let guard = DeadlineLimit::new(Duration::from_secs(30)).with_variable(UNSET); + let outcome = with_deadline(guard, "wait_until under constant raises", move || { + catch_unwind(AssertUnwindSafe(|| wait_until(short(), "a condition that never holds", &waiter_signal, || false))).map_err(message) + }); + stop.store(true, Ordering::SeqCst); + raiser.join().unwrap(); + let text = outcome.unwrap_err(); + assert!(text.contains("timed out waiting for a condition that never holds within 50ms"), "{text}"); + } #[test] #[should_panic(expected = "condition boom")] fn wait_until_propagates_condition_panic() { - wait_until(long(), "a panicking condition", || panic!("condition boom")); + wait_until(long(), "a panicking condition", &Signal::new(), || panic!("condition boom")); } #[test] fn wait_until_keeps_a_typed_condition_payload() { #[derive(Debug, PartialEq)] struct Marker(u32); - let payload = catch_unwind(|| wait_until(long(), "a typed panic", || std::panic::panic_any(Marker(9)))).unwrap_err(); + let payload = catch_unwind(|| wait_until(long(), "a typed panic", &Signal::new(), || std::panic::panic_any(Marker(9)))).unwrap_err(); assert_eq!(payload.downcast_ref::(), Some(&Marker(9))); } - /// A default limit for the loop tests, which pass their own clock. + /// A limit for the loop tests, which pass their own wait. fn fake_resolved(limit: Duration) -> Resolved<'static> { Resolved { limit, variable: UNSET, from_variable: false } } - #[test] - fn wait_until_rejects_a_true_after_the_limit() { - let resolved = fake_resolved(Duration::from_millis(10)); - let mut now = Duration::ZERO; - let mut cond = || true; - // The condition took 11 ms to return. - let mut elapsed = || { - now += Duration::from_millis(11); - now - }; - let result = poll_until(&resolved, "a late flag", &mut cond, &mut elapsed, &mut |_| panic!("paused")); - let text = result.unwrap_err(); - assert!(text.contains("timed out waiting for a late flag") && text.contains("held only after the limit"), "{text}"); - } - - #[test] - fn wait_until_pauses_grow_and_stop_at_the_limit() { - let resolved = fake_resolved(Duration::from_millis(100)); - let now = std::cell::Cell::new(Duration::ZERO); - let mut pauses = Vec::new(); - let mut calls = 0; - let mut cond = || { - calls += 1; - false - }; - let mut elapsed = || now.get(); - let mut pause = |d: Duration| { - pauses.push(d); - now.set(now.get() + d); - }; - let result = poll_until(&resolved, "never", &mut cond, &mut elapsed, &mut pause); - assert!(result.is_err()); - let ms: Vec = pauses.iter().map(Duration::as_millis).collect(); - // 1 + 2 + 4 + 8 + 16 + 32 = 63, then the 37 ms left, after which the limit is reached. - assert_eq!(ms, [1, 2, 4, 8, 16, 32, 37]); - // One call before each pause, and none after the last one. - assert_eq!(calls, 7); - } - - #[test] - fn wait_until_stops_calling_after_an_overshooting_pause() { - let resolved = fake_resolved(Duration::from_millis(100)); - let now = std::cell::Cell::new(Duration::from_millis(99)); - let mut calls = 0; - let mut cond = || { - calls += 1; - false - }; - let mut elapsed = || now.get(); - // The thread wakes 50 ms late from the 1 ms pause. - let mut pause = |d: Duration| now.set(now.get() + d + Duration::from_millis(50)); - let result = poll_until(&resolved, "late wake", &mut cond, &mut elapsed, &mut pause); - assert!(result.unwrap_err().contains("timed out waiting for late wake")); - assert_eq!(calls, 1); - } - - /// Runs `run_with_deadline` with a 5 s limit on a fake clock. The worker runs on the calling - /// thread: the clock reads `start_secs` while the body runs and `received_secs` when the result - /// is received. When `sends` is false, the worker stores its result but does not send, as if its - /// thread stopped running between the two. - fn on_fake_clock( - f: impl FnOnce() -> T + Send + 'static, - start_secs: u64, - received_secs: u64, - sends: bool, - ) -> Result { - let now = Arc::new(AtomicU64::new(0)); - let clock_now = Arc::clone(&now); - let clock: Clock = Arc::new(move || Duration::from_secs(clock_now.load(Ordering::SeqCst))); - let unsent = std::cell::RefCell::new(None); + /// Runs `run_with_deadline` on `f` with the body's result arriving only after the limit has + /// passed: the body does not start until the wait for it, which runs it on the calling thread + /// and then reports that the limit passed. The worker never sends. + fn finishing_after_the_limit(f: impl FnOnce() -> T + Send + 'static) -> Result { + let held = RefCell::new(None); let spawn = |job: Job, done: Sender<()>| { - now.store(start_secs, Ordering::SeqCst); - job(); - now.store(received_secs, Ordering::SeqCst); - if sends { - let _ = done.send(()); - } else { - // Kept alive so that the wait times out instead of seeing a closed channel. - *unsent.borrow_mut() = Some(done); - } + *held.borrow_mut() = Some((job, done)); Ok(()) }; - let limit = DeadlineLimit::new(Duration::from_secs(5)).with_variable(UNSET); - run_with_deadline(limit, "fake clock", f, |_| None, spawn, clock) + let wait = |_: &Receiver<()>, _: Duration| { + if let Some((job, _done)) = held.borrow_mut().take() { + job(); + } + Err(RecvTimeoutError::Timeout) + }; + run_with_deadline(short(), "late body", f, |_| None, spawn, wait) } #[test] - fn a_value_returned_after_the_limit_fails() { - let text = failure_message(on_fake_clock(|| 1, 6, 6, true)); - assert!(text.contains("fake clock finished only after its limit of 5s"), "{text}"); + fn a_value_that_arrives_after_the_limit_is_returned() { + assert!(matches!(finishing_after_the_limit(|| 1), Ok(1))); } #[test] - fn a_value_finished_in_time_but_received_late_passes() { - assert!(matches!(on_fake_clock(|| 1, 1, 6, true), Ok(1))); - } - - #[test] - fn a_value_finished_in_time_but_sent_late_passes() { - assert!(matches!(on_fake_clock(|| 1, 1, 6, false), Ok(1))); - } - - #[test] - fn a_panic_finished_in_time_but_sent_late_keeps_its_payload() { - let payload = match on_fake_clock(|| -> u8 { panic!("early boom") }, 1, 6, false) { + fn a_panic_that_arrives_after_the_limit_keeps_its_payload() { + let payload = match finishing_after_the_limit(|| -> u8 { panic!("late boom") }) { Err(Failure::Panic(payload)) => payload, Ok(_) => panic!("the call did not fail"), Err(Failure::Message(text)) => panic!("the payload was replaced: {text}"), }; - assert_eq!(message(payload), "early boom"); - } - - #[test] - fn a_panic_after_the_limit_names_the_limit_and_the_panic() { - let text = failure_message(on_fake_clock(|| -> u8 { panic!("late boom") }, 6, 6, true)); - assert!(text.contains("fake clock finished only after its limit of 5s") && text.ends_with("(it panicked: late boom)"), "{text}"); + assert_eq!(message(payload), "late boom"); } } diff --git a/crates/testkit/src/fixtures.rs b/crates/testkit/src/fixtures.rs new file mode 100644 index 0000000000..9b01b154c6 --- /dev/null +++ b/crates/testkit/src/fixtures.rs @@ -0,0 +1,1319 @@ +//! Fixture locations and race-free generation of fixture files. +//! +//! Generated fixtures live in `/target/fixtures//` whatever `CARGO_TARGET_DIR` is, so test runs +//! with private target folders share one generated set. A variable the caller names (default +//! [`ROOT_VAR`]) overrides the root. A fixture is complete when it is a nonempty regular file; a +//! consumer that needs stronger validation checks the format after generation. +//! +//! [`generate`] and [`generate_with`] return a complete cached fixture without calling the generator. +//! Otherwise the generator writes a temporary sibling claimed by [`temp_path`], and [`publish`] moves it +//! into place under a per-output lock, keeping a complete file that another process published first. +//! A fixture that cannot be made skips or fails the test under the [`skip`](crate::skip) rule, with +//! the required variable the caller names (default [`skip::REQUIRED_VAR`](crate::skip::REQUIRED_VAR)). +//! +//! [`report`] and [`generate_and_report`] print `FIXTURE made `, `FIXTURE cached ` and +//! `FIXTURE skipped ` lines, which FilmCraft's `cargo xtask fixtures` counts. + +use std::ffi::{OsStr, OsString}; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read}; +use std::path::{Component, Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Default variable that overrides the fixtures root. +pub const ROOT_VAR: &str = "CRAFT_FIXTURES_DIR"; + +/// Default number of bytes [`run_generator`] keeps from each of the child's output streams. +pub const DEFAULT_MAX_OUTPUT: usize = 64 * 1024; + +/// Largest `Cargo.toml` that [`workspace_root`] reads while looking for the workspace manifest. +const MAX_MANIFEST_BYTES: u64 = 1024 * 1024; + +/// Number of names [`temp_path`] tries before it gives up. +const TEMP_ATTEMPTS: u32 = 64; + +/// Suffix of the lock file kept beside each published fixture. +const LOCK_SUFFIX: &str = ".fixture-lock"; + +/// The root of the Cargo workspace that is running the tests. +/// +/// The search starts at the `CARGO_MANIFEST_DIR` that Cargo and nextest set for a test process, which +/// names the package under test. When the package's `Cargo.toml` sets `package.workspace`, it returns +/// that folder, resolved against the package folder. Otherwise it returns the nearest folder at or above +/// the package whose `Cargo.toml` has a `[workspace]` table, or the package folder itself when no +/// workspace manifest is found. The process working directory and `CARGO_TARGET_DIR` are not read. The +/// returned path is canonical. +/// +/// # Errors +/// +/// Returns [`io::ErrorKind::NotFound`] when `CARGO_MANIFEST_DIR` is unset or empty (a test binary run +/// outside Cargo) or no `Cargo.toml` is found, [`io::ErrorKind::InvalidData`] when a manifest is +/// larger than 1 MiB or is not valid TOML, and an error when a manifest is not UTF-8 or the folder +/// cannot be canonicalized. +pub fn workspace_root() -> io::Result { + let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR").filter(|v| !v.is_empty()).ok_or_else(|| { + io::Error::new(io::ErrorKind::NotFound, "CARGO_MANIFEST_DIR is not set; run the tests through Cargo or set the fixtures root variable") + })?; + workspace_root_from(Path::new(&manifest_dir)) +} + +fn workspace_root_from(manifest_dir: &Path) -> io::Result { + let mut package = None; + for dir in manifest_dir.ancestors() { + let path = dir.join("Cargo.toml"); + let Some(text) = read_manifest(&path)? else { continue }; + let keys = scan_manifest(&text) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{} is not a valid TOML manifest: {e}", path.display())))?; + if keys.workspace { + return dir.canonicalize(); + } + if package.is_none() + && let Some(workspace) = keys.package_workspace + { + return dir.join(workspace).canonicalize(); + } + package.get_or_insert(dir); + } + match package { + Some(dir) => dir.canonicalize(), + None => Err(io::Error::new(io::ErrorKind::NotFound, format!("no Cargo.toml in {} or above it", manifest_dir.display()))), + } +} + +/// The keys of a manifest that [`workspace_root`] reads. +#[derive(Debug, Default, PartialEq, Eq)] +struct ManifestKeys { + /// The manifest has a `workspace` table, in any TOML form (`[workspace]`, `["workspace"]` or a + /// top-level `workspace = { ... }`). + workspace: bool, + /// The string value of `package.workspace`. + package_workspace: Option, +} + +/// Parse a manifest as TOML and read its workspace keys. +fn scan_manifest(manifest: &str) -> Result { + let table: toml::Table = manifest.parse()?; + let package_workspace = table.get("package").and_then(|p| p.get("workspace")).and_then(toml::Value::as_str).map(str::to_owned); + Ok(ManifestKeys { workspace: table.get("workspace").is_some_and(toml::Value::is_table), package_workspace }) +} + +fn read_manifest(path: &Path) -> io::Result> { + let meta = match std::fs::metadata(path) { + Ok(meta) if meta.is_file() => meta, + Ok(_) => return Ok(None), + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e), + }; + if meta.len() > MAX_MANIFEST_BYTES { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{} is larger than {MAX_MANIFEST_BYTES} bytes", path.display()))); + } + let mut text = String::new(); + File::open(path)?.take(MAX_MANIFEST_BYTES).read_to_string(&mut text)?; + Ok(Some(text)) +} + +/// The root of all generated fixtures: the nonempty value of `var` (default [`ROOT_VAR`]), or +/// `/target/fixtures`. The folder is not created. +/// +/// # Errors +/// +/// Returns the error of [`workspace_root`] when the variable is unset or empty. +pub fn fixtures_root(var: Option<&str>) -> io::Result { + match std::env::var_os(var.unwrap_or(ROOT_VAR)).filter(|v| !v.is_empty()) { + Some(dir) => Ok(PathBuf::from(dir)), + None => Ok(workspace_root()?.join("target").join("fixtures")), + } +} + +/// `/`, created if missing. `sub` may name nested folders (`"opus/oracle"`). +/// +/// # Errors +/// +/// Returns [`io::ErrorKind::InvalidInput`] when `sub` is absolute, contains `..`, or has a part that +/// is not a plain folder name on its own (on Windows, `group\C:outside`), or when a folder on the way +/// resolves outside the root (a symbolic link or junction that points elsewhere), and the error of +/// [`fixtures_root`] or of creating the folder otherwise. +pub fn fixtures_dir(sub: &str, var: Option<&str>) -> io::Result { + let relative = relative_subdir(sub)?; + create_below(&fixtures_root(var)?, &relative) +} + +/// Create `root/relative` one folder at a time, and return an error before creating the next folder +/// when the one before it resolves outside `root`. Returns `root.join(relative)` as given, not the +/// canonical path. Each folder is checked by path when it is reached, so a folder that another process +/// replaces with a link between that check and the next `create_dir` is not detected; callers then use +/// the returned path by name too ([`temp_path`], [`publish`]). +fn create_below(root: &Path, relative: &Path) -> io::Result { + std::fs::create_dir_all(root)?; + let real_root = root.canonicalize()?; + let mut real = real_root.clone(); + for part in relative.components() { + let next = real.join(part); + match std::fs::create_dir(&next) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + real = next.canonicalize()?; + if !real.starts_with(&real_root) || !real.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("fixture folder {} resolves to {}, which is not a folder inside the fixtures root", next.display(), real.display()), + )); + } + } + Ok(root.join(relative)) +} + +fn relative_subdir(sub: &str) -> io::Result { + let outside = || io::Error::new(io::ErrorKind::InvalidInput, format!("fixture folder {sub:?} is not a relative path inside the fixtures root")); + let mut relative = PathBuf::new(); + for component in Path::new(sub).components() { + match component { + Component::Normal(part) => { + // `PathBuf::push` parses the part again, so a part such as `C:outside` would replace the path. + let mut alone = Path::new(part).components(); + if !matches!((alone.next(), alone.next()), (Some(Component::Normal(p)), None) if p == part) { + return Err(outside()); + } + relative.push(part); + } + Component::CurDir => {} + Component::ParentDir | Component::RootDir | Component::Prefix(_) => return Err(outside()), + } + } + Ok(relative) +} + +/// Create a new, empty temporary sibling of `out` and return its path. +/// +/// The name is `.tmp---