diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 66897e207a..b80d10d34c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -70,6 +70,7 @@ workflows: - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' '.github/workflows/nightly.yml': [] + '.github/workflows/pbr.yml': [] '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' diff --git a/.github/workflows/pbr.yml b/.github/workflows/pbr.yml new file mode 100644 index 0000000000..51c3a62daa --- /dev/null +++ b/.github/workflows/pbr.yml @@ -0,0 +1,29 @@ +name: PBR feature tests + +on: + workflow_dispatch: + push: + branches: [main, next] + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + pull_request: + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + +permissions: + contents: read + +jobs: + features: + name: PBR ${{ matrix.mode }} tests + strategy: + fail-fast: false + matrix: + include: + - { mode: serial, arguments: '' } + - { mode: parallel, arguments: '--features parallel' } + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + craft-fonts-ref: '' + require-craft-fonts: false + timeout-minutes: 30 + command: cargo test -p craft-pbr --locked ${{ matrix.arguments }} diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 112bfe4e93..55ff91d455 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -174,6 +174,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. +## GPU device selection + +`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. + ## Dalvik DEX inspection `crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. diff --git a/Cargo.lock b/Cargo.lock index 84c0a3d751..858d8604d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1819,6 +1819,7 @@ dependencies = [ "craft-geom", "craft-gif", "craft-gpu", + "craft-gpu-device", "craft-gpu-null", "craft-gpu-providers", "craft-gpu-wgpu", @@ -1905,6 +1906,7 @@ dependencies = [ "craft-review", "craft-rtf", "craft-sbs", + "craft-scopes", "craft-score", "craft-scraft-format", "craft-settings", @@ -2284,7 +2286,6 @@ dependencies = [ "craft-flags", "craft-platform", "dirs", - "getrandom 0.3.4", "log", "proptest", "serde", @@ -2297,6 +2298,7 @@ dependencies = [ name = "craft-control-protocol" version = "0.1.0" dependencies = [ + "getrandom 0.3.4", "serde_json", "subtle", ] @@ -2921,6 +2923,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gpu-device" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "log", + "pollster 0.4.0", + "serde", + "serde_json", + "wgpu", +] + [[package]] name = "craft-gpu-null" version = "0.1.0" @@ -3581,7 +3595,6 @@ version = "0.1.0" name = "craft-pbr" version = "0.1.0" dependencies = [ - "craft-pbr", "craft-texture", "glam 0.30.10", "naga", @@ -4042,6 +4055,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-scopes" +version = "0.1.0" +dependencies = [ + "craft-color", + "serde", + "serde_json", +] + [[package]] name = "craft-score" version = "0.1.0" @@ -4295,7 +4317,10 @@ dependencies = [ name = "craft-testkit" version = "0.1.0" dependencies = [ + "libc", "rustix 1.1.6", + "sha2 0.10.9", + "skrifa 0.47.0", ] [[package]] @@ -4935,6 +4960,7 @@ dependencies = [ "libc", "serde_json", "tempfile", + "toml_edit", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 3af86eaf40..ea77bf6c48 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-gpu-device = { path = "crates/gpu-device" } craft-wasm = { path = "crates/wasm" } craft-platform = { path = "crates/platform" } craft-png = { path = "crates/png" } @@ -82,6 +83,7 @@ craft-cloud = { path = "crates/cloud" } craft-cloud-local = { path = "crates/cloud-local" } craft-cloud-ui = { path = "crates/cloud-ui" } craft-color = { path = "crates/color" } +craft-scopes = { path = "crates/scopes" } craft-color-ui = { path = "crates/color-ui" } craft-color-transform = { path = "crates/color-transform" } craft-frame = { path = "crates/frame" } diff --git a/README.md b/README.md index 6e841b7157..af82eafac8 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,11 @@ 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-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 + to open; a capability report; device-loss and error recording without panics; and what to reopen + after a loss. Settings pages and the window stay in each app. - [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept unread and written back into a list. The workbook model and what follows a read stay in GridCraft. @@ -416,7 +421,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit 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. Not published. + 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. - [`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 diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index ce6724bb8e..13a2cd7c6e 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -12,8 +12,15 @@ and contains no `unsafe` code. (compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors), delays and reverbs (including convolution and surround), modulation, restoration (denoise, dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion, - dither, a signal generator, a loudness meter, and a pitch shifter for a live voice with 10 ms - of latency. + dither, a signal generator, a loudness meter, a pitch shifter for a live voice with 10 ms of + latency, a formant shifter for a live voice with 10.7 ms of latency, and noise suppression for + a live voice with 5.3 ms of latency that follows the noise floor without first learning it. + These latencies are at 48 kHz (the STFT sizes depend on the sample rate; `latency()` reports + 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, and + neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order @@ -28,6 +35,14 @@ and contains no `unsafe` code. - `biquad` and `design`: biquad filters with their magnitude response, and IIR filter design from Butterworth, Bessel, Chebyshev and elliptic prototypes. +`noise_suppression` estimates the noise floor from minimum spectral power over 1.5 s. The first +noise estimate after a reset starts from the median bin's power. Each bin's value is clamped +between 30 dB below its own estimate and its own estimate. Windows that overlap a run of at +least one hop of zeros (64 samples at 48 kHz) do not enter the noise estimate. The gain floor +moves from 0 dB toward the attenuation set by `reduction` during the first search window +of sound. Continuous voiced or tonal audio present from startup can enter the noise estimate +and be attenuated afterward. + ## Conventions Audio is planar `f32`: one slice per channel, all the same length. `AudioEffect::process`, @@ -79,7 +94,8 @@ The crate combines two crates from the ArtCraft apps, with changes: offline resampler. - [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at `915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch - shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`). + shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`), and the + ring modulator (`src/plugins/modulation.rs`). `NOTICE` keeps the copyright notices of both projects. diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 42ec2261ce..039c6badf0 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -1,6 +1,7 @@ //! Audio effects and their registry. pub(crate) mod channel; +pub(crate) mod character; pub(crate) mod declick; pub(crate) mod dither; pub(crate) mod dynamics; @@ -15,11 +16,13 @@ pub(crate) mod restoration; pub(crate) mod reverbs; pub(crate) mod special; mod stft; +pub(crate) mod suppress; pub(crate) mod time; pub(crate) mod util; pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; +pub use character::{Bitcrusher, RingMod}; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -35,8 +38,9 @@ pub(crate) use restoration::{DeHum, DeNoise}; pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb}; pub use special::LoudnessMeterFx; pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer}; +pub use suppress::NoiseSuppression; pub(crate) use time::{Delay, Reverb}; -pub use voice::VoicePitch; +pub use voice::{VoiceFormant, VoicePitch}; use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate}; @@ -125,8 +129,10 @@ static REGISTRY: &[EffectInfo] = &[ }, entry!("dehum", "DeHum", Restoration, DeHum), entry!("denoise", "DeNoise", Restoration, DeNoise), + entry!("noise_suppression", "Noise Suppression", Restoration, NoiseSuppression), entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter), entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch), + entry!("voice_formant", "Voice Formant", Pitch, VoiceFormant), entry!("deesser", "DeEsser", Restoration, DeEsser), entry!("dereverb", "DeReverb", Restoration, DeReverb), entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance), @@ -144,6 +150,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("chorus_flanger", "Chorus/Flanger", Modulation, ChorusFlanger), entry!("flanger", "Flanger", Modulation, Flanger), entry!("phaser", "Phaser", Modulation, Phaser), + entry!("ring_mod", "Ring Modulator", Modulation, RingMod), entry!("analog_delay", "Analog Delay", Time, AnalogDelay), entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay), entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb), @@ -151,6 +158,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover), entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer), entry!("distortion", "Distortion", Special, Distortion), + entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher), entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite), entry!("mastering", "Mastering", Special, Mastering), entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 662046f75c..8f8a4d9a74 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -132,9 +132,11 @@ fn every_effect_is_deterministic_and_latency_is_constant() { f }; let lat0 = (e.create)(SR, 2).latency(); + // Keep Formants adds voice_pitch's formant stage; no other parameter changes a latency. + let want = if e.id == "voice_pitch" { lat0 + voice::VoiceFormant::new(SR, 2).latency() } else { lat0 }; let mut a = mk(); let mut b = mk(); - assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id); + assert_eq!(a.latency(), want, "{}: latency depends on parameters", e.id); let ya = run(a.as_mut(), &l, &r); let yb = run(b.as_mut(), &l, &r); assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id); @@ -147,7 +149,14 @@ fn latency_is_where_the_impulse_lands() { // settings (FFT filter / convolution / existing STFT effects). The click remover repairs a // lone impulse in silence as a click, so its latency is checked on noise by // `neutral_settings_are_delayed_identity`. - for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("voice_pitch", vec![])] { + for (id, p) in [ + ("fft_filter", vec![]), + ("convolution_reverb", vec![("mix", 0.0)]), + ("voice_pitch", vec![]), + ("voice_pitch", vec![("formant_follow", 1.0)]), + ("voice_formant", vec![]), + ("noise_suppression", vec![("reduction", 0.0)]), + ] { let mut e = fx(id, &p); let lat = e.latency(); assert!(lat > 0, "{id}"); @@ -906,6 +915,8 @@ fn delays_and_reverbs_report_their_tails() { ("chorus_flanger", &[("mode", 1.0), ("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("chorus_flanger", &[("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("flanger", &[("final_delay", 20.0), ("feedback", 100.0), ("mix", 100.0)][..]), + ("ring_mod", &[("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)][..]), + ("ring_mod", &[("effect", 3.0), ("frequency", 60.0), ("resonance", 95.0), ("mod_source", 1.0), ("mod_depth", 100.0)][..]), ] { let mut e = fx(id, params); let tail = e.tail_samples(); @@ -977,6 +988,10 @@ fn direct_constructors_cap_the_channel_count() { filters::FullParametricEq, pitch::PitchShifter, voice::VoicePitch, + voice::VoiceFormant, + suppress::NoiseSuppression, + character::RingMod, + character::Bitcrusher, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs new file mode 100644 index 0000000000..6bc52eeb3e --- /dev/null +++ b/crates/audio-dsp/src/effects/character.rs @@ -0,0 +1,771 @@ +//! Character effects for a live voice. None of them adds latency. +//! +//! The ring modulator (`ring_mod`) has four effects: +//! +//! - Ring multiplies the input by a sine carrier at the frequency, which moves each partial of a +//! voice to the sum and the difference of its frequency and the carrier's. +//! - Frequency Mod reads the input through a delay that the carrier swings between 2 samples and +//! 2 samples plus 2 ms. +//! - Resonator + and Resonator - feed the output back after one period of the frequency, with a +//! positive or a negative sign, so the input rings at the frequency and its multiples (Resonator +//! +) or at its odd half multiples (Resonator -). The output is scaled by `1 - resonance`, so the +//! peak gain at resonance is unity. +//! +//! An LFO, an envelope follower (5 ms attack, 100 ms release) or a sample-and-hold source moves the +//! frequency by up to two octaves either way at 100 % depth. The envelope follower moves it up +//! only. +//! +//! The bitcrusher (`bitcrusher`) takes one input sample every `rate_divide` samples, holds it until +//! the next one, and rounds it to a word length of 1 to 16 bits. + +use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail}; +use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; +use std::f64::consts::TAU; + +fn blend(dry: f64, wet: f64, mix: f64) -> f64 { + (1.0 - mix) * dry + mix * wet +} + +/// Smoothing time of the frequency, resonance, depth and mix, in ms. +const SM: f32 = 20.0; +const RING_EFFECTS: &[&str] = &["Ring", "Frequency Mod", "Resonator +", "Resonator -"]; +const RING_SOURCES: &[&str] = &["LFO", "Envelope", "Sample & Hold"]; +/// Lowest frequency the control reaches. +const MIN_HZ: f32 = 20.0; +/// Octaves the frequency moves at full modulation depth. +const MOD_OCTAVES: f32 = 2.0; +/// Peak delay swing of Frequency Mod, in ms. +const FM_SWING_MS: f32 = 1.0; +/// Shortest delay of Frequency Mod, in samples (room for the interpolated read). +const FM_BASE: f32 = 2.0; +/// Sample-and-hold seed (the same sequence after every reset). +const SEED: u64 = 0x5EED_1234; +/// Highest frequency the modulation reaches, as a fraction of the sample rate. +const MAX_FRACTION: f32 = 0.45; + +/// 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. +pub struct RingMod { + pv: ParamValues, + sr: f32, + lines: Vec, + carrier: Lfo, + lfo: Lfo, + rng: Prng, + env: Envelope, + env_attack: f32, + env_release: f32, + held: f32, + hold_left: usize, + /// Effect the lines hold state for. + effect: usize, + freq: Smoothed, + res: Smoothed, + depth: Smoothed, + mix: Smoothed, +} + +impl RingMod { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::choice("effect", "Effect", RING_EFFECTS, 0), + ParamSpec::log("frequency", "Frequency", MIN_HZ, 5000.0, 440.0, Unit::Hertz), + ParamSpec::new("resonance", "Resonance", 0.0, 95.0, 50.0, Unit::Percent), + ParamSpec::choice("mod_source", "Mod Source", RING_SOURCES, 0), + ParamSpec::log("mod_rate", "Mod Rate", 0.05, 20.0, 1.0, Unit::Hertz), + ParamSpec::new("mod_depth", "Mod Depth", 0.0, 100.0, 0.0, Unit::Percent), + 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); + // One period of the lowest frequency the modulation reaches, or the widest Frequency Mod + // delay, whichever is longer. + let longest_ms = (1000.0 / (MIN_HZ * (-MOD_OCTAVES).exp2())).max(2.0 * FM_SWING_MS) + 1.0; + let len = delay_line_len(longest_ms, sample_rate, ch); + let sm = |v| Smoothed::with_ms(v, sample_rate, SM); + let mut s = RingMod { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + carrier: Lfo::default(), + lfo: Lfo::default(), + rng: Prng::new(SEED), + env: Envelope::default(), + env_attack: coef(5.0, sample_rate), + env_release: coef(100.0, sample_rate), + held: 0.0, + hold_left: 0, + effect: 0, + freq: sm(440.0), + res: sm(0.0), + depth: sm(0.0), + mix: sm(1.0), + }; + s.apply_params(true); + s.effect = s.pv.idx("effect"); + s + } + + fn apply_params(&mut self, snap: bool) { + self.freq.set(self.pv.v("frequency")); + self.res.set(self.pv.v("resonance") / 100.0); + self.depth.set(self.pv.v("mod_depth") / 100.0); + self.mix.set(self.pv.v("mix") / 100.0); + if snap { + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + } + + /// One period of the lowest frequency the modulation reaches, in ms, from the settings and from + /// the values still ramping toward them. The envelope follower moves the frequency up only, so + /// with it the lowest is the frequency. The frequency is held within the same range as in + /// [`AudioEffect::process`]. + fn longest_period_ms(&self) -> f32 { + let down = if self.pv.idx("mod_source") == 1 { 0.0 } else { self.depth.value().max(self.depth.target()) }; + let lowest = self.freq.value().min(self.freq.target()) * (-MOD_OCTAVES * down).exp2(); + 1000.0 / lowest.clamp(1.0, self.sr * MAX_FRACTION) + } +} + +impl AudioEffect for RingMod { + param_plumbing!("ring_mod"); + /// Ring has no tail. Frequency Mod holds up to its widest delay. The resonators ring until + /// the feedback has fallen by 60 dB at the longest period the modulation reaches, at the higher + /// of the resonance setting and the value still ramping toward it. + fn tail_samples(&self) -> usize { + match self.pv.idx("effect") { + 1 => (FM_BASE + 2.0 * FM_SWING_MS * 0.001 * self.sr).ceil() as usize + 1, + 2 | 3 => echo_tail(self.longest_period_ms(), self.res.value().max(self.res.target()), self.sr), + _ => 0, + } + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.carrier.reset(); + self.lfo.reset(); + self.rng = Prng::new(SEED); + self.env.env = 0.0; + self.held = 0.0; + self.hold_left = 0; + self.effect = self.pv.idx("effect"); + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + return; + } + let nch = channels.len().min(self.lines.len()); + let effect = self.pv.idx("effect"); + if effect != self.effect { + // The lines hold the previous effect's state. + self.lines.iter_mut().for_each(DelayLine::reset); + self.effect = effect; + } + let source = self.pv.idx("mod_source"); + let rate = self.pv.v("mod_rate"); + let hold = ((self.sr / rate.max(0.05)) as usize).max(1); + // A faster rate cuts the value being held short, instead of holding it for the old length. + self.hold_left = self.hold_left.min(hold); + let highest = self.sr * MAX_FRACTION; + let swing = FM_SWING_MS * 0.001 * self.sr; + let sign = if effect == 3 { -1.0 } else { 1.0 }; + for i in 0..n { + let level = channels[..nch].iter().map(|c| c[i]).filter(|x| x.is_finite()).fold(0.0f32, |m, x| m.max(x.abs())); + let env = self.env.tick(self.env_attack, self.env_release, level); + let m = match source { + 1 => env.min(1.0), + 2 => { + if self.hold_left == 0 { + self.held = self.rng.uniform(); + self.hold_left = hold; + } + self.hold_left -= 1; + self.held + } + _ => (TAU * self.lfo.phase(0.0)).sin() as f32, + }; + self.lfo.advance(rate, self.sr); + let f = (self.freq.tick() * (MOD_OCTAVES * self.depth.tick() * m).exp2()).clamp(1.0, highest); + let fb = self.res.tick(); + let mix = self.mix.tick(); + let carrier = (TAU * self.carrier.phase(0.0)).sin() as f32; + self.carrier.advance(f, self.sr); + // The read happens before this sample's push, so one period back is `period - 1`. + let back = self.sr / f - 1.0; + 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, + }; + let wet = match effect { + 1 => { + line.push(dry); + line.read(FM_BASE + swing * (1.0 + carrier)) + } + 2 | 3 => { + let y = flush32(dry + sign * fb * line.read(back)); + line.push(y); + y * (1.0 - fb) + } + _ => dry * carrier, + }; + if ch < nch { + let (dry, wet) = (dry as f64, wet as f64); + channels[ch][i] = blend(dry, wet, f64::from(mix)) as f32; + } + } + } + } +} + +/// 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; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn ring(params: &[(&str, f32)], channels: usize) -> RingMod { + let mut r = RingMod::new(SR, channels); + for (id, v) in params { + assert!(r.set_param(id, *v), "{id}"); + } + r.reset(); + r + } + + /// Ring moves a tone to the sum and the difference of its frequency and the carrier's, each + /// at half the tone's amplitude, and leaves nothing at the tone's own frequency. + #[test] + fn ring_moves_a_tone_to_the_sum_and_difference_frequencies() { + let mut r = ring(&[("frequency", 300.0)], 1); + let mut x = sine(1000.0, 0.5, SR as f64, SR as usize, 0.0); + r.process(&mut [&mut x]); + for (f, want) in [(700.0, 0.25), (1300.0, 0.25), (1000.0, 0.0), (300.0, 0.0)] { + let a = tone_amplitude(&x, f, SR as f64); + assert!((a - want).abs() < 0.005, "{f} Hz: {a}, want {want}"); + } + } + + /// Resonator + repeats an impulse once per period of its frequency, each repeat lower by the + /// resonance, and Resonator - flips the sign of each repeat. + #[test] + fn resonators_repeat_an_impulse_once_per_period() { + for (effect, sign) in [(2.0, 1.0f32), (3.0, -1.0)] { + let mut r = ring(&[("effect", effect), ("frequency", 500.0), ("resonance", 80.0)], 1); + let mut x = vec![0.0f32; 1000]; + x[10] = 1.0; + r.process(&mut [&mut x]); + // 96 samples per period at 500 Hz. + for k in 0..8 { + let i = 10 + 96 * k; + let want = 0.2 * (sign * 0.8).powi(k as i32); + assert!((x[i] - want).abs() < 1e-5, "effect {effect}, repeat {k} at {i}: {}, want {want}", x[i]); + } + let others = x.iter().enumerate().filter(|(i, _)| *i < 10 || (*i - 10) % 96 != 0).fold(0.0f32, |m, (_, v)| m.max(v.abs())); + assert!(others < 1e-5, "effect {effect}: {others} between the repeats"); + } + } + + #[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] + fn frequency_mod_swings_the_delay_by_two_ms() { + let mut r = ring(&[("effect", 1.0), ("frequency", 440.0)], 1); + let slope = 1e-4f32; + let mut x: Vec = (0..4800).map(|i| i as f32 * slope).collect(); + r.process(&mut [&mut x]); + let delays: Vec = x.iter().enumerate().skip(200).map(|(i, y)| (i as f32 * slope - y) / slope).collect(); + let (lo, hi) = delays.iter().fold((f32::MAX, f32::MIN), |(lo, hi), d| (lo.min(*d), hi.max(*d))); + assert!((1.99..2.1).contains(&lo), "shortest delay {lo}"); + assert!((97.9..=98.01).contains(&hi), "longest delay {hi}"); + } + + /// With the envelope as the source, a steady input at full level moves the frequency up by + /// the depth: two octaves at 100 %. + #[test] + fn envelope_moves_the_frequency_up_with_the_level() { + let mut r = ring(&[("frequency", 100.0), ("mod_source", 1.0), ("mod_depth", 100.0)], 1); + let n = SR as usize; + let mut x = vec![1.0f32; n]; + r.process(&mut [&mut x]); + let tail = &x[n / 2..]; + assert!(tone_amplitude(tail, 400.0, SR as f64) > 0.99, "400 Hz: {}", tone_amplitude(tail, 400.0, SR as f64)); + assert!(tone_amplitude(tail, 100.0, SR as f64) < 0.01, "100 Hz: {}", tone_amplitude(tail, 100.0, SR as f64)); + } + + /// A resonator's tail covers the longest period the modulation reaches: four times as long at + /// full depth with the LFO or sample and hold, which move the frequency down two octaves, and + /// unchanged with the envelope, which moves it up only. + #[test] + fn resonator_tail_follows_the_lowest_frequency_the_modulation_reaches() { + let tail = |source: f32, depth: f32| { + ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 90.0), ("mod_source", source), ("mod_depth", depth)], 1).tail_samples() as f32 + }; + let still = tail(0.0, 0.0); + for source in [0.0, 2.0] { + let ratio = tail(source, 100.0) / still; + assert!((ratio - 4.0).abs() < 0.01, "source {source}: {ratio}"); + } + assert_eq!(tail(1.0, 100.0), still); + } + + /// While the resonance ramps down to a new setting, the tail still covers the higher value, + /// and it shrinks to the new setting's tail once the ramp has ended. + #[test] + fn resonator_tail_covers_a_resonance_still_ramping_down() { + let mut r = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 95.0)], 1); + let high = r.tail_samples(); + assert!(r.set_param("resonance", 0.0)); + assert_eq!(r.tail_samples(), high); + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + let low = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 0.0)], 1).tail_samples(); + assert_eq!(r.tail_samples(), low); + assert!(low * 10 < high, "{low} vs {high}"); + } + + /// At a low sample rate the resonators ring at the highest frequency processing reaches, not + /// at the setting above it, and the tail covers that ring. A setting below that frequency + /// keeps the tail of its own period. + #[test] + fn resonator_tail_covers_a_frequency_held_at_the_rate_limit() { + let sr = 1000.0f32; + let mut r = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 5000.0), ("resonance", 95.0)] { + assert!(r.set_param(id, v), "{id}"); + } + r.reset(); + let tail = r.tail_samples(); + let mut x = vec![0.0f32; tail + 200]; + x[0] = 1.0; + r.process(&mut [&mut x]); + let after = x[tail + 1..].iter().fold(0.0f32, |m, v| m.max(v.abs())); + assert!(after <= 1e-3 * x[0].abs(), "tail {tail}: {after} after it, against {} at the impulse", x[0]); + let mut below = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 400.0), ("resonance", 95.0)] { + assert!(below.set_param(id, v), "{id}"); + } + below.reset(); + assert_eq!(below.tail_samples(), echo_tail(1000.0 / 400.0, 0.95, sr)); + } + + /// Frequency Mod reads between two of the largest samples of opposite sign without + /// overflowing. + #[test] + fn frequency_mod_reads_between_huge_samples_of_opposite_sign() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0)], 1); + let mut x = vec![0.0f32; 200]; + x[6] = -f32::MAX; + x[7] = f32::MAX; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "{:?}", x.iter().position(|v| !v.is_finite())); + } + + #[test] + fn frequency_mod_full_mix_keeps_a_small_delayed_sample() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0), ("mix", 100.0)], 1); + let mut x = vec![0.5f32; 600]; + x[500] = f32::MAX; + r.process(&mut [&mut x]); + assert_eq!(x[500], 0.5, "the delayed sample was lost at full mix"); + } + + /// Mixing a dry and a wet sample of opposite sign at the largest level stays finite: a mix of + /// 0 gives the input, and every mix gives the result at a level of 1 scaled up. + #[test] + fn mixing_huge_samples_of_opposite_sign_stays_finite() { + for mix in [0.0f32, 50.0, 100.0] { + let run = |level: f32| { + let mut r = ring(&[("frequency", 5000.0), ("mix", mix)], 1); + let mut x = vec![level; 480]; + r.process(&mut [&mut x]); + x + }; + let (huge, unit) = (run(f32::MAX), run(1.0)); + assert!(huge.iter().all(|v| v.is_finite()), "mix {mix}"); + for (i, (h, u)) in huge.iter().zip(&unit).enumerate() { + let want = *u as f64 * f32::MAX as f64; + assert!((*h as f64 - want).abs() <= 1e-5 * f32::MAX as f64, "mix {mix}, sample {i}: {h} against {want}"); + } + if mix == 0.0 { + assert!(huge.iter().all(|v| *v == f32::MAX)); + } + } + } + + /// 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] + fn sample_and_hold_follows_a_faster_rate_at_once() { + let mut r = ring(&[("mod_source", 2.0), ("mod_rate", 0.05), ("mod_depth", 100.0)], 1); + let mut x = vec![0.0f32; 480]; + r.process(&mut [&mut x]); + let first = r.held; + assert!(r.set_param("mod_rate", 20.0)); + // A hold lasts 2,400 samples at 20 Hz and 960,000 at 0.05 Hz. + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + assert_ne!(r.held, first, "the slow hold kept its value"); + } + + /// At a mix of 0 every effect passes the input through unchanged. + #[test] + fn mix_zero_passes_the_input_through() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("mix", 0.0), ("mod_depth", 50.0)], 2); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + assert!(l == x && rr == x, "effect {effect}"); + } + } + + /// A block that leaves a channel out feeds it silence, so a resonator's ring on that channel + /// keeps decaying instead of waiting for the channel to come back. + #[test] + fn channels_a_block_leaves_out_are_fed_silence() { + let p = [("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)]; + let (mut left_out, mut silent) = (ring(&p, 2), ring(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + for r in [&mut left_out, &mut silent] { + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + } + for _ in 0..10 { + let mut l = vec![0.0f32; 480]; + left_out.process(&mut [&mut l]); + let (mut l, mut rr) = (vec![0.0f32; 480], vec![0.0f32; 480]); + silent.process(&mut [&mut l, &mut rr]); + } + let (mut la, mut ra) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + silent.process(&mut [&mut lb, &mut rb]); + assert!(rms(&rb) > 1e-3, "the ring has already died out: {}", rms(&rb)); + let worst = ra.iter().zip(&rb).fold(0.0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(worst < 1e-6, "the left-out channel differs by {worst}"); + assert_eq!(la, lb); + } + + /// A non-finite input sample comes out as silence and leaves no NaN in the resonator. + #[test] + fn a_non_finite_sample_leaves_the_state_finite() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("resonance", 95.0)], 1); + let mut x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + x[100] = f32::NAN; + x[200] = f32::INFINITY; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "effect {effect}"); + } + } + + fn crush(params: &[(&str, f32)], channels: usize) -> Bitcrusher { + let mut c = Bitcrusher::new(SR, channels); + for (id, v) in params { + assert!(c.set_param(id, *v), "{id}"); + } + c.reset(); + c + } + + /// Indices of the samples where the output changes, with the first sample counted. + fn changes(x: &[f32]) -> Vec { + (0..x.len()).filter(|&i| i == 0 || x[i] != x[i - 1]).collect() + } + + /// Every output sample is the multiple of `2^(1 - bits)` nearest the input, and silence stays + /// silence. + #[test] + fn bitcrusher_rounds_to_the_word_length() { + for (bits, step) in [(1.0, 1.0f32), (3.0, 0.25), (5.5, 2f32.powf(-4.5))] { + let mut c = crush(&[("bits", bits), ("rate_divide", 1.0)], 1); + let x: Vec = (0..2000).map(|i| -1.0 + i as f32 / 1000.0).collect(); + let mut y = x.clone(); + c.process(&mut [&mut y]); + for (a, b) in x.iter().zip(&y) { + let k = b / step; + assert!((k - k.round()).abs() < 1e-3, "bits {bits}: {b} is not a multiple of {step}"); + assert!((a - b).abs() <= step / 2.0 + 1e-6, "bits {bits}: {a} became {b}"); + } + let mut z = vec![0.0f32; 480]; + c.process(&mut [&mut z]); + assert!(z.iter().all(|v| *v == 0.0), "bits {bits}"); + } + } + + /// The input is taken once every `rate_divide` samples and held: a whole value holds each + /// sample for exactly that many samples, and 2.5 alternates holds of 3 and 2. + #[test] + fn bitcrusher_holds_each_sample_for_the_rate_divide() { + let x: Vec = (0..200).map(|i| (i + 1) as f32 / 1024.0).collect(); + for (divide, want) in [(1.0, vec![1usize]), (5.0, vec![5]), (2.5, vec![3, 2])] { + let mut c = crush(&[("bits", 16.0), ("rate_divide", divide)], 1); + let mut y = x.clone(); + c.process(&mut [&mut y]); + let 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"); + } + } + + #[test] + fn full_mix_keeps_a_small_wet_sample_beside_a_huge_dry_one() { + let mut c = crush(&[("mix", 100.0), ("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut y = vec![0.5, f32::MAX, f32::MAX, f32::MAX, 0.25]; + c.process(&mut [&mut y]); + assert_eq!(y[1], 0.5, "the held sample was lost at full mix: {y:?}"); + } + + /// A shorter rate divide cuts the hold in progress short, and the holds after it have the new + /// length from the first one on. + #[test] + 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:?}"); + } + } + } +} diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index c4b9ed7070..14d1003dbb 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -402,7 +402,7 @@ mod tests { #[test] fn paired_effects_match_mono_on_transients() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 48_000; let material = |f: f64, amp: f32, phase: f64, click_every: usize, click_at: usize, noise: f32, seed: u64| -> Vec { @@ -427,6 +427,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, ch)), "FftFilter" => Box::new(FftFilter::new(SR, ch)), "DeNoise" => Box::new(DeNoise::new(SR, ch)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, ch)), _ => Box::new(PitchShifter::new(SR, ch)), }; if name == "PitchShifter" { @@ -445,7 +446,7 @@ mod tests { y }; let mut failures = Vec::new(); - for name in ["PitchShifter", "DeNoise", "DeReverb", "FftFilter"] { + for name in ["PitchShifter", "DeNoise", "NoiseSuppression", "DeReverb", "FftFilter"] { for (label, src) in [("identical", &identical), ("different", &different)] { let joint = run(name, src); for (ch, chan) in src.iter().enumerate() { @@ -502,17 +503,18 @@ mod tests { #[test] fn non_finite_sample_stays_in_its_channel() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 24_000; let mut rng = Rng::new(5); let clean_a: Vec = crate::testutil::sine(440.0, 0.4, SR as f64, len, 0.0).iter().map(|v| v + 0.05 * rng.uniform()).collect(); let clean_b: Vec = crate::testutil::sine(1250.0, 0.4, SR as f64, len, 0.3).iter().map(|v| v + 0.05 * rng.uniform()).collect(); type Make = fn() -> Box; - let make: [(&str, Make, usize); 4] = [ + let make: [(&str, Make, usize); 5] = [ ("DeReverb", || Box::new(DeReverb::new(SR, 2)), 1), ("FftFilter", || Box::new(FftFilter::new(SR, 2)), 1), ("DeNoise", || Box::new(DeNoise::new(SR, 2)), 1), + ("NoiseSuppression", || Box::new(NoiseSuppression::new(SR, 2)), 1), ("PitchShifter", || Box::new(PitchShifter::new(SR, 2)), 1), ]; let mono = |name: &str, src: &[f32]| -> Vec { @@ -520,6 +522,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, 1)), "FftFilter" => Box::new(FftFilter::new(SR, 1)), "DeNoise" => Box::new(DeNoise::new(SR, 1)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, 1)), _ => Box::new(PitchShifter::new(SR, 1)), }; if name == "PitchShifter" { diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs new file mode 100644 index 0000000000..acebd93e37 --- /dev/null +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -0,0 +1,984 @@ +//! Noise suppression for a live voice (`noise_suppression`), with 256 samples (5.3 ms) of latency +//! at 48 kHz. +//! +//! The effect runs a short STFT: 256 points at up to 50 kHz (twice that for each doubling of the +//! rate above it), a hop of a quarter of the size, and square-root Hann windows. Each bin's noise +//! power is the smallest value of its smoothed power over the last 1.5 s (minimum statistics, +//! R. Martin, 2001), so the estimate follows a noise floor that changes and needs no "learn noise" +//! step. Each bin's gain is a Wiener gain on the decision-directed a priori SNR (Ephraim and Malah, +//! 1984), held at or above the floor that `reduction` sets, and averaged with its neighbors. At a +//! reduction of 0 every gain is 1 and the effect is a plain delay. +//! +//! A frame enters the noise estimate only after the next four frames have arrived. A frame of +//! digital silence (a mute or a gate) drops the frames still waiting, and the four frames after +//! it do not enter either, so no frame that shares a sample with the silence lowers the estimate +//! and lets the noise pass when the sound resumes, wherever between two hops the silence ends. +//! A mute too short to fill a frame keeps every frame that holds a sample of it out too, down to +//! a run of zeros one hop long (64 samples at 48 kHz); a shorter run of zeros counts as sound. +//! Nor does a frame more than 15 dB below the estimate, until such frames have lasted a whole +//! search window without digital silence between them (the floor has really fallen). +//! The noise power the gains are computed from falls at once and rises by at most 10 dB a +//! second, so a vowel or a note held for longer than the search window keeps its level for a few +//! seconds more, and a noise floor that rises by 12 dB is suppressed again within 3 s. +//! After a reset the gain floor moves from 0 dB toward the attenuation set by `reduction` over +//! the first search window of sound. The first noise estimate after a reset starts from the +//! median bin's power. Each bin's value is clamped between 30 dB below its own estimate and its +//! own estimate. The noise power then rises by at most 10 dB a second. A vowel held from the +//! first sample keeps its level for a few seconds, like one held after a stretch of noise, while +//! steady noise of an even spectrum is suppressed as soon as the floor allows; noise whose +//! spectrum is uneven takes up to 3 s more in the bins well above the median. Continuous voiced +//! or tonal audio present from startup can eventually enter the noise estimate and be attenuated. + +use super::stft::{Pairing, Plan, Spectral, StftChannel, stream}; +use crate::{AudioEffect, MAX_CHANNELS, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; + +/// Length of the minimum-statistics search, and the number of sub-windows it rotates through. +const SEARCH_S: f32 = 1.5; +const SUBWINDOWS: usize = 8; +/// Time constant of the smoothing of each bin's power. +const POWER_MS: f32 = 10.0; +/// Time constant of the decision-directed a priori SNR. +const PRIORI_MS: f32 = 80.0; +/// Ratio of the mean noise power to the minimum of its smoothed power with these windows (see +/// `the_noise_estimate_follows_white_noise`). +const BIAS: f32 = 3.25; +/// Smallest noise power a bin is divided by, so digital silence keeps its gain at the floor. +const MIN_NOISE: f32 = 1.0e-30; +/// A frame whose power is below the estimated noise power by this ratio (15 dB) is quiet. +const QUIET: f32 = 1.0 / 32.0; +/// Frames that share a sample with any one frame: the hop is a quarter of the STFT size. +const OVERLAP: usize = 4; +/// Lowest the first noise power of a bin starts against the bin's own estimate (30 dB). +const SEED_SPAN: f32 = 1.0e-3; +/// Fastest rise of the noise power a bin's gain is computed from, in dB per second. +const RISE_DB_S: f32 = 10.0; + +/// STFT size: 256 at up to 50 kHz (5.3 ms at 48 kHz), doubled for each doubling of the rate above +/// it, up to 8192. +fn suppress_size(sample_rate: f32) -> usize { + let (mut n, mut top) = (256, 50_000.0); + while sample_rate > top && n < 8192 { + n *= 2; + top *= 2.0; + } + n +} + +/// Smoothing and floor shared by every frame, from the parameters and the frame rate. +#[derive(Clone, Copy, Debug)] +struct Coefs { + /// Lowest gain a bin gets. + floor: f32, + /// Weight of the previous smoothed power. + smooth: f32, + /// Weight of the previous frame's clean power in the a priori SNR. + priori: f32, + /// Frames in one minimum-statistics sub-window. + sub_frames: usize, + /// Frames in the whole search window. + window: usize, + /// Largest ratio of one frame's noise power to the previous frame's (`RISE_DB_S`). + rise: f32, +} + +/// One channel's noise estimate and gains. Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Bins { + /// Smoothed power of each bin. + power: Vec, + /// Smallest smoothed power in the current sub-window. + min: Vec, + /// Smallest smoothed power of each of the last `SUBWINDOWS` sub-windows. + ring: Vec, + slot: usize, + frames: usize, + /// Power the previous frame kept (gain² × power). + clean: Vec, + gains: Vec, + /// Smallest smoothed power of the search window for each bin, for the frame being processed. + est: Vec, + /// Noise power of each bin that the gains are computed from: `est` times the bias, rising by + /// at most `RISE_DB_S`. + noise: Vec, + /// Power of each bin of the frames waiting to enter the estimate, `OVERLAP` frames of + /// `bins` values, the oldest at `head`. + queue: Vec, + /// Total power of each waiting frame, and whether it may enter the estimate. + queue_total: [f32; OVERLAP], + queue_ok: [bool; OVERLAP], + /// Whether a mute began between a waiting frame and the one before it. + queue_cut: [bool; OVERLAP], + /// Whether a mute began since the last frame was queued. + cut_pending: bool, + head: usize, + queued: usize, + /// Whether a frame has entered the estimate since the last reset. + started: bool, + /// Frames that entered the estimate since the last reset, up to a search window. + heard: usize, + /// Frames with sound since the last frame of digital silence, up to `OVERLAP + 1`. It starts + /// at 1: the zeros the STFT starts with end on a hop boundary, so `OVERLAP` frames clear them. + since_zero: usize, + /// Quiet frames in a row since the last frame of digital silence, up to a search window. + quiet_run: usize, + /// Whether `noise` has been set from a first estimate since the last reset. + seeded: bool, + /// Room to find the median bin of the first estimate. + scratch: Vec, + /// Zero samples in a row up to the last sample, up to a hop. + zero_run: usize, + /// Samples since the last sample of a mute (a run of at least a hop of zeros), or `usize::MAX` + /// when there has been none since the last reset. + since_mute: usize, + /// Samples since the last frame. + since_frame: usize, +} + +impl Bins { + fn new(bins: usize) -> Self { + Bins { + power: vec![0.0; bins], + min: vec![f32::INFINITY; bins], + ring: vec![f32::INFINITY; bins * SUBWINDOWS], + slot: 0, + frames: 0, + clean: vec![0.0; bins], + gains: vec![1.0; bins], + est: vec![f32::INFINITY; bins], + noise: vec![f32::INFINITY; bins], + queue: vec![0.0; bins * OVERLAP], + queue_total: [0.0; OVERLAP], + queue_ok: [false; OVERLAP], + queue_cut: [false; OVERLAP], + cut_pending: false, + head: 0, + queued: 0, + started: false, + heard: 0, + since_zero: 1, + quiet_run: 0, + seeded: false, + scratch: vec![0.0; bins], + zero_run: 0, + since_mute: usize::MAX, + since_frame: 0, + } + } + + fn reset(&mut self) { + self.power.fill(0.0); + self.min.fill(f32::INFINITY); + self.ring.fill(f32::INFINITY); + self.clean.fill(0.0); + self.gains.fill(1.0); + self.est.fill(f32::INFINITY); + self.noise.fill(f32::INFINITY); + self.slot = 0; + self.frames = 0; + self.head = 0; + self.queued = 0; + self.cut_pending = false; + self.started = false; + self.heard = 0; + self.since_zero = 1; + self.quiet_run = 0; + self.seeded = false; + self.zero_run = 0; + self.since_mute = usize::MAX; + self.since_frame = 0; + } + + /// Takes one input sample before the STFT does, to find mutes too short to give a frame of + /// digital silence. Once `hop` zeros run in a row, the frame still waiting that holds the first + /// of them leaves the queue, and so does every later frame that holds a sample of the run. + fn sample(&mut self, x: f32, hop: usize) { + self.since_frame += 1; + self.zero_run = if x == 0.0 { (self.zero_run + 1).min(hop) } else { 0 }; + if self.zero_run < hop { + self.since_mute = self.since_mute.saturating_add(1); + return; + } + if self.since_mute != 0 { + // The run has just reached a hop. It started `hop - 1` samples ago, so of the frames + // waiting only the newest can hold it: when it ended less than a hop ago. + if self.queued > 0 && self.since_frame < hop { + self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; + } + self.cut_pending = true; + } + self.since_mute = 0; + } + + /// Noise power of bin `k` for the frame last processed: the smallest smoothed power of the + /// search window times the bias, rising by at most `RISE_DB_S`. + fn noise(&self, k: usize) -> f32 { + self.noise[k].max(MIN_NOISE) + } + + /// Moves the oldest waiting frame into the noise estimate, unless it shares a sample with + /// digital silence, or it is quiet and quiet frames have not yet lasted a search window. + fn commit(&mut self, c: &Coefs) { + let bins = self.power.len(); + let at = self.head; + self.head = (at + 1) % OVERLAP; + self.queued -= 1; + if self.queue_cut[at] { + self.quiet_run = 0; + } + if !self.queue_ok[at] { + return; + } + let noise_total = self.est.iter().map(|e| e * BIAS).sum::(); + let quiet = noise_total.is_finite() && self.queue_total[at] < noise_total * QUIET; + self.quiet_run = if quiet { (self.quiet_run + 1).min(c.window) } else { 0 }; + if quiet && self.quiet_run < c.window { + return; + } + let a = if self.started { c.smooth } else { 0.0 }; + for k in 0..bins { + let p = self.queue[at * bins + k]; + self.power[k] = flush32(a * self.power[k] + (1.0 - a) * p); + self.min[k] = self.min[k].min(self.power[k]); + self.est[k] = self.est[k].min(self.power[k]); + } + self.frames += 1; + if self.frames == c.sub_frames { + for k in 0..bins { + self.ring[self.slot * bins + k] = self.min[k]; + self.min[k] = f32::INFINITY; + } + self.slot = (self.slot + 1) % SUBWINDOWS; + self.frames = 0; + } + self.started = true; + self.heard = (self.heard + 1).min(c.window); + } + + /// Takes one frame's half spectrum, updates the noise estimate and the gains, and writes the + /// gains averaged with their neighbors to `out`. A frame with a non-finite bin leaves the + /// state as it is and repeats the last gains. + fn frame(&mut self, re: &[f32], im: &[f32], c: &Coefs, out: &mut [f32]) { + let bins = self.power.len(); + self.since_frame = 0; + let finite = re.iter().zip(im).fold(true, |ok, (a, b)| ok & (a * a + b * b).is_finite()); + if finite { + for k in 0..bins { + self.est[k] = (0..SUBWINDOWS).fold(self.min[k], |m, u| m.min(self.ring[u * bins + k])); + } + let total = (0..bins).map(|k| re[k] * re[k] + im[k] * im[k]).sum::(); + if total == 0.0 { + // Digital silence: the frames still waiting share a sample with it, and so do the + // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between + // two hops. A quiet run ends here too. + self.queued = 0; + self.cut_pending = false; + self.since_zero = 0; + self.quiet_run = 0; + } else { + self.since_zero = (self.since_zero + 1).min(OVERLAP + 1); + if self.queued == OVERLAP { + self.commit(c); + } + let at = (self.head + self.queued) % OVERLAP; + for k in 0..bins { + self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; + } + self.queue_total[at] = total; + self.queue_cut[at] = std::mem::take(&mut self.cut_pending); + // A frame holds the last STFT size of samples, `2 * (bins - 1)`. + self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); + self.queued += 1; + } + if self.started && !self.seeded { + // The first estimate: a bin well above the median bin, such as a harmonic of a + // vowel held from the start, starts from the median and rises from there. + self.seeded = true; + self.scratch.copy_from_slice(&self.est); + let median = *self.scratch.select_nth_unstable_by(bins / 2, f32::total_cmp).1 * BIAS; + for k in 0..bins { + let own = self.est[k] * BIAS; + self.noise[k] = own.min(median.max(own * SEED_SPAN)); + } + } + // The floor moves from 1 to `c.floor` (in dB) over the first search window of sound. + let floor = c.floor.powf(self.heard as f32 / c.window as f32); + for k in 0..bins { + let p = re[k] * re[k] + im[k] * im[k]; + // The noise power falls at once and rises by at most `c.rise` a frame, so a sound + // held longer than the search window is not taken for the noise at once. + self.noise[k] = (self.est[k] * BIAS).min(self.noise[k].max(MIN_NOISE) * c.rise); + let noise = self.noise(k); + let excess = (p / noise - 1.0).max(0.0); + let xi = c.priori * self.clean[k] / noise + (1.0 - c.priori) * excess; + // `1 - 1 / (1 + xi)` is `xi / (1 + xi)`, and stays 1 for an infinite `xi`. + let g = (1.0 - 1.0 / (1.0 + xi)).max(floor); + self.gains[k] = g; + self.clean[k] = flush32(g * g * p); + } + } + for k in 0..bins { + let lo = self.gains[k.saturating_sub(1)]; + let hi = self.gains[(k + 1).min(bins - 1)]; + out[k] = 0.25 * lo + 0.5 * self.gains[k] + 0.25 * hi; + } + } +} + +/// Noise suppression for a live voice: lowers steady background noise (fans, hiss, room tone) by +/// up to `reduction` dB, with no step that learns the noise first. Its latency is the STFT size, +/// 256 samples (5.3 ms) at 48 kHz. Continuous voiced or tonal audio present from startup can +/// enter the noise estimate and be attenuated after the initial search window. +pub struct NoiseSuppression { + pv: ParamValues, + n: usize, + hop: usize, + spec: Spectral, + stft: Vec, + bins: Vec, + /// Gains of the frame being processed, averaged with their neighbors. + smoothed: Vec, + coefs: Coefs, + sample_rate: f32, + /// Samples since the last frame, the same in every channel. + pos: usize, +} + +impl NoiseSuppression { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("reduction", "Reduction", 0.0, 40.0, 24.0, Unit::Decibels)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let n = suppress_size(sample_rate); + let bins = n / 2 + 1; + let ch = crate::sane_channels(channels); + let mut s = NoiseSuppression { + pv: ParamValues::new(Self::PARAMS), + n, + hop: n / OVERLAP, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); ch], + bins: vec![Bins::new(bins); ch], + smoothed: vec![1.0; bins], + coefs: Coefs { floor: 1.0, smooth: 0.0, priori: 0.0, sub_frames: 1, window: SUBWINDOWS, rise: 1.0 }, + sample_rate, + pos: 0, + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + let frame_s = self.hop as f32 / self.sample_rate; + let sub_frames = ((SEARCH_S / frame_s / SUBWINDOWS as f32).round() as usize).max(1); + self.coefs = Coefs { + floor: db_to_gain(-self.pv.v("reduction")), + smooth: (-frame_s * 1000.0 / POWER_MS).exp(), + priori: (-frame_s * 1000.0 / PRIORI_MS).exp(), + sub_frames, + window: sub_frames * SUBWINDOWS, + // A power ratio: twice the dB of an amplitude ratio. + rise: db_to_gain(2.0 * RISE_DB_S * frame_s), + }; + } +} + +impl AudioEffect for NoiseSuppression { + param_plumbing!("noise_suppression"); + fn latency(&self) -> usize { + self.n + } + fn tail_samples(&self) -> usize { + self.n + } + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.bins.iter_mut().for_each(Bins::reset); + self.pos = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + let nch = channels.len().min(self.stft.len()); + // A non-finite sample is taken as silence, so it never reaches the output. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + let (n, hop, coefs) = (self.n, self.hop, self.coefs); + let scale = 1.0 / (n as f32 * 2.0); + let plan = Plan { hop, scale, pairing: Pairing::SynthesisOnly }; + // The block runs in pieces that end at the next frame, so each channel's noise estimate + // takes every sample of a frame before the STFT frames it. + let mut start = 0; + while start < len { + let end = len.min(start + hop - self.pos); + for (b, c) in self.bins.iter_mut().zip(channels.iter()).take(nch) { + c[start..end].iter().for_each(|&x| b.sample(x, hop)); + } + let mut piece: [&mut [f32]; MAX_CHANNELS] = std::array::from_fn(|_| <&mut [f32]>::default()); + for (p, c) in piece.iter_mut().zip(channels.iter_mut()).take(nch) { + *p = &mut c[start..end]; + } + let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); + stream(&mut self.stft, &mut self.spec, &mut piece[..nch], end - start, plan, &mut |ch, _, re, im| { + bins[ch].frame(re, im, &coefs, smoothed); + for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { + *r *= g; + *i *= g; + } + }); + self.pos = (self.pos + end - start) % hop; + start = end; + } + // A channel the block leaves out is fed silence, so it holds none of its earlier audio + // when it comes back. + let half = n / 2 + 1; + let (spec, smoothed) = (&mut self.spec, &mut self.smoothed); + for (st, b) in self.stft.iter_mut().zip(self.bins.iter_mut()).skip(nch) { + for _ in 0..len { + b.sample(0.0, hop); + st.tick(0.0, hop, &mut |input, out| { + spec.analyze(input); + b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); + for k in 0..half { + spec.re[k] *= smoothed[k]; + spec.im[k] *= smoothed[k]; + } + spec.synthesize_add(out, scale); + }); + } + } + // A huge finite input can overflow the inverse FFT. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn suppressor(reduction: f32) -> NoiseSuppression { + let mut s = NoiseSuppression::new(SR, 1); + assert!(s.set_param("reduction", reduction)); + s.reset(); + s + } + + fn white(seed: u64, n: usize, amp: f32) -> Vec { + let mut r = Rng::new(seed); + (0..n).map(|_| r.uniform() * amp).collect() + } + + /// Voiced syllables (seven harmonics of a gliding pitch from 110 to 230 Hz under a sine + /// envelope) with pauses between them, at a peak level of about 0.5. + fn voiced(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.12 + 0.2 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.1 + 0.1 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + let v: f32 = (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum(); + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.25 * sr as f32) as usize; + } + out + } + + /// Runs the suppressor's gains, computed from `speech + noise`, on the speech and the noise + /// apart, so the SNR before and after can be measured. Returns the processed mix, speech and + /// noise. + fn shadow(speech: &[f32], noise: &[f32], reduction: f32) -> (Vec, Vec, Vec) { + let s = suppressor(reduction); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let mut spec = Spectral::new(n, true); + let half = n / 2 + 1; + let scale = 1.0 / (n as f32 * 2.0); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lanes = [StftChannel::new(n), StftChannel::new(n), StftChannel::new(n)]; + let mut out = [vec![0.0f32; speech.len()], vec![0.0f32; speech.len()], vec![0.0f32; speech.len()]]; + for i in 0..speech.len() { + let x = [speech[i] + noise[i], speech[i], noise[i]]; + bins.sample(x[0], hop); + for (lane, (st, o)) in lanes.iter_mut().zip(out.iter_mut()).enumerate() { + o[i] = st.tick(x[lane], hop, &mut |input, frame_out| { + spec.analyze(input); + if lane == 0 { + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + } + for k in 0..half { + spec.re[k] *= gains[k]; + spec.im[k] *= gains[k]; + } + spec.synthesize_add(frame_out, scale); + }); + } + } + let [mix, speech, noise] = out; + (mix, speech, noise) + } + + fn energy(x: &[f32]) -> f64 { + x.iter().map(|&v| v as f64 * v as f64).sum() + } + + /// SNR before and after the suppressor at a reduction of 24 dB, and the change of the voice's + /// own level, in dB, measured from 3 s on (the noise estimate has settled by then). + fn snr_gain(speech: &[f32], noise_amp: f32) -> (f64, f64, f64) { + let len = speech.len(); + let noise = white(17, len, noise_amp); + let (mix, ys, yv) = shadow(speech, &noise, 24.0); + let mut real: Vec = speech.iter().zip(&noise).map(|(a, b)| a + b).collect(); + suppressor(24.0).process(&mut [&mut real]); + assert!(real.iter().zip(&mix).all(|(a, b)| (a - b).abs() < 1e-5), "the shadow run differs from the effect"); + let lat = 256; + let (from, to) = (SR as usize * 3, len - lat); + let after = from + lat..to + lat; + let snr_in = db((energy(&speech[from..to]) / energy(&noise[from..to])).sqrt()); + let snr_out = db((energy(&ys[after.clone()]) / energy(&yv[after.clone()])).sqrt()); + let kept = db((energy(&ys[after]) / energy(&speech[from..to])).sqrt()); + (snr_in, snr_out - snr_in, kept) + } + + /// Voiced syllables in white noise come out with an SNR at least 15 dB higher at an input SNR + /// of 7 dB (13 dB higher at 17 dB), and the voice's level changes by less than 3 dB. + #[test] + fn the_voice_gains_15_db_of_snr_and_keeps_its_level() { + let speech = voiced(SR as f64, 12.0, 4); + for (noise_amp, want) in [(0.06f32, 15.0), (0.02, 13.0)] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= want, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: voice level changed by {kept:.2} dB"); + } + } + + /// Speech with consonants (bursts of broadband noise at the level of the vowels) keeps its + /// level within 3 dB and still gains SNR. Bins where a consonant covers the noise keep both. + #[test] + fn speech_with_consonants_keeps_its_level() { + let speech = speechy(SR as f64, 12.0, 4); + for noise_amp in [0.06f32, 0.02] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= 4.0, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: speech level changed by {kept:.2} dB"); + } + } + + /// Steady noise falls by close to the reduction setting, at 44.1, 48, 96 and 192 kHz, and the + /// latency is 256 samples up to 50 kHz and doubles with each doubling of the rate above it. + #[test] + fn steady_noise_falls_by_the_reduction() { + for (sr, lat) in [(44_100.0f32, 256), (48_000.0, 256), (96_000.0, 512), (192_000.0, 1024)] { + for reduction in [6.0f32, 12.0, 24.0, 40.0] { + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", reduction)); + assert_eq!(s.latency(), lat); + let n = sr as usize * 4; + let x = white(5, n, 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - sr as usize..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + // At 40 dB the Wiener gains of noise-only bins sit above the floor. + let limit = if reduction == 40.0 { 28.0 } else { reduction as f64 - 2.0 }; + assert!(got >= limit && got <= reduction as f64 + 1.0, "{sr} Hz, reduction {reduction}: noise fell by {got:.1} dB"); + } + } + } + + /// At a reduction of 0 the output is the input delayed by the latency. + #[test] + fn zero_reduction_is_a_delay() { + let mut s = suppressor(0.0); + let lat = s.latency(); + let x = speechy(SR as f64, 2.0, 8); + let mut y = x.clone(); + s.process(&mut [&mut y]); + for i in lat..x.len() { + assert!((y[i] - x[i - lat]).abs() < 1e-5, "{i}: {} vs {}", y[i], x[i - lat]); + } + } + + /// The noise estimate follows a noise floor that rises by 12 dB within 3 s, and one that falls + /// by 12 dB at once. + #[test] + fn the_estimate_follows_a_changing_noise_floor() { + let level = |amps: [f32; 2], at: f32| -> f64 { + let mut s = suppressor(24.0); + let n = SR as usize * 8; + let mut rng = Rng::new(31); + let x: Vec = (0..n).map(|i| rng.uniform() * if i < n / 2 { amps[0] } else { amps[1] }).collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let from = n / 2 + (at * SR) as usize; + let range = from..from + SR as usize / 4; + -db(rms(&y[range.clone()]) / rms(&x[range])) + }; + let up = level([0.02, 0.08], 3.0); + assert!(up >= 20.0, "rise: noise fell by {up:.1} dB 3 s later"); + let down = level([0.08, 0.02], 0.25); + assert!(down >= 20.0, "fall: noise fell by {down:.1} dB 0.25 s later"); + } + + /// Noise that starts after digital silence is suppressed again within the search window. + #[test] + fn noise_after_silence_is_suppressed_again() { + let mut s = suppressor(24.0); + let n = SR as usize * 6; + let mut x = white(41, n, 0.05); + x[..SR as usize * 2].fill(0.0); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// Noise that resumes after a pause of digital silence, or of noise 40 dB lower, is suppressed + /// from the start: the pause does not enter the noise estimate. + #[test] + fn noise_after_a_pause_is_suppressed_at_once() { + for pause_amp in [0.0f32, 0.0005] { + let mut s = suppressor(24.0); + let lat = s.latency(); + let n = SR as usize * 5; + let (pause, resume) = (SR as usize * 3, SR as usize * 4); + let mut x = white(43, n, 0.05); + x[pause..resume].iter_mut().for_each(|v| *v *= pause_amp / 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let range = resume + lat + SR as usize / 50..resume + lat + SR as usize / 2; + let got = -db(rms(&y[range.clone()]) / rms(&x[range.start - lat..range.end - lat])); + assert!(got >= 20.0, "pause level {pause_amp}: noise fell by {got:.1} dB after the pause"); + } + } + + /// No frame that shares a sample with digital silence enters the noise estimate: not the + /// frames that run into a mute, nor those that run out of it, whether or not the mute starts + /// or ends on a frame boundary. At most two frames per mute that hold no silence are dropped + /// with them. + #[test] + fn frames_that_touch_a_mute_stay_out_of_the_estimate() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + for offset in [0usize, 17, 40, 63] { + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let len = SR as usize; + let mut x = white(29, len, 0.05); + let mutes = [(SR as usize * 3 / 10 + offset, SR as usize * 4 / 10 + offset), (SR as usize * 7 / 10 + offset, SR as usize * 8 / 10)]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + let mut frames = 0usize; + // A frame enters the estimate when the frame `OVERLAP` after it arrives, which is when + // `heard` grows. + let mut entered = Vec::new(); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + let heard = bins.heard; + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + frames += 1; + if bins.heard > heard { + entered.push(frames - OVERLAP); + } + }); + } + // Frame `j` (from 1) holds samples `j * hop - n .. j * hop`; samples before 0 are + // the zeros the STFT starts with. + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), bins.heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(bins.heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", bins.heard); + } + } + + /// A mute too short to fill a frame, from one hop long up, keeps the frames that hold a sample + /// of it out of the estimate too, wherever it starts and ends between two hops. + #[test] + fn frames_that_touch_a_short_mute_stay_out_of_the_estimate() { + for offset in [0usize, 17, 40, 63] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut x = white(31, SR as usize / 2, 0.05); + // The last mute is one STFT size long and holds no whole frame unless it starts on a hop. + let mutes = [ + (192 + offset, 256 + offset), + (6000 + offset, 6100 + offset), + (12_000 + offset, 12_200 + offset), + (17_984 + offset, 17_984 + offset + n), + ]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + // One hop per block, so each block ends with a frame. A frame enters the estimate when + // the frame `OVERLAP` after it arrives, which is when `heard` grows. + let mut entered = Vec::new(); + for (k, chunk) in x.chunks(hop).enumerate() { + let heard = s.bins[0].heard; + let mut y = chunk.to_vec(); + s.process(&mut [&mut y]); + if s.bins[0].heard > heard { + entered.push(k + 1 - OVERLAP); + } + } + let frames = x.len() / hop; + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < s.coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), s.bins[0].heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(s.bins[0].heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", s.bins[0].heard); + } + } + + /// Quiet stretches that a mute separates do not add up to a search window: the estimate stays + /// at the noise before them, and falls only after a whole search window of quiet in a row. + #[test] + fn a_mute_ends_a_quiet_run() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let window = coefs.window * hop; + let amp = 0.05f32; + let (loud, quiet, mute) = (SR as usize * 2, window * 6 / 10, SR as usize / 5); + let mut x = white(47, loud + 2 * quiet + mute + window + quiet, amp); + x[loud..].iter_mut().for_each(|v| *v *= 0.01); + x[loud + quiet..loud + quiet + mute].fill(0.0); + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mut feed = |part: &[f32]| -> f64 { + for &v in part { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + (1..half - 1).map(|k| db((bins.est[k] as f64 * BIAS as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64 + }; + let split = loud + 2 * quiet + mute; + let kept = feed(&x[..split]); + assert!(kept > -6.0, "after two quiet stretches split by a mute the estimate fell by {:.1} dB", -kept); + let fell = feed(&x[split..]); + assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); + } + + #[test] + fn a_short_mute_ends_the_queued_quiet_run() { + for offset in [0, 17] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut loud = white(47, SR as usize * 2, 0.05); + s.process(&mut [&mut loud]); + let mut quiet = white(51, 20 * hop + offset, 0.0005); + s.process(&mut [&mut quiet]); + assert!(s.bins[0].quiet_run > 0); + let mute_end = loud.len() + quiet.len() + hop; + let first_clean_frame = (mute_end + n).div_ceil(hop); + let commit_end = (first_clean_frame + OVERLAP) * hop; + let mut after = white(53, commit_end - loud.len() - quiet.len(), 0.0005); + after[..hop].fill(0.0); + let before_mute = s.bins[0].quiet_run; + s.process(&mut [&mut after[..hop]]); + assert_eq!(s.bins[0].quiet_run, before_mute + 1, "offset {offset}: queued pre-mute frames lost their quiet run"); + s.process(&mut [&mut after[hop..]]); + assert_eq!(s.bins[0].quiet_run, 1, "offset {offset}: pre-mute quiet frames contributed to the new run"); + } + } + + /// A voice that starts with the stream keeps its level within 3 dB over its first 0.25 s and + /// its first 1.5 s, while the suppressor has no noise estimate yet. One of the voices starts on + /// its first sample with a vowel held for 0.25 s. + #[test] + fn a_voice_at_the_start_keeps_its_level() { + let mut abrupt = voiced(SR as f64, 2.0, 7); + let vowel = SR as usize / 4; + let len = abrupt.len(); + abrupt.copy_within(..len - vowel, vowel); + for (i, v) in abrupt[..vowel].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + for speech in [abrupt, voiced(SR as f64, 2.0, 6), speechy(SR as f64, 2.0, 6)] { + let noise = white(19, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for to in [SR as usize / 4, SR as usize * 3 / 2] { + let kept = db((energy(&ys[lat..to + lat]) / energy(&speech[..to])).sqrt()); + assert!(kept.abs() < 3.0, "voice level changed by {kept:.2} dB in the first {to} samples"); + } + } + } + + /// A steady vowel held for 3 s in noise, longer than the search window, keeps its level within + /// 3 dB over its last second. + #[test] + fn a_held_vowel_keeps_its_level() { + let (lead, held) = (SR as usize * 2, SR as usize * 3); + let mut speech = vec![0.0f32; lead + held + SR as usize / 2]; + for (i, v) in speech[lead..lead + held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + let fade = (i as f32 / 480.0).min(1.0); + *v = fade * (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum::(); + } + let noise = white(37, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + let last = lead + held - SR as usize..lead + held; + let kept = db((energy(&ys[last.start + lat..last.end + lat]) / energy(&speech[last])).sqrt()); + assert!(kept.abs() < 3.0, "the held vowel's level changed by {kept:.2} dB in its last second"); + } + + /// A steady vowel held from the first sample, with no noise before it, keeps its level within + /// 3 dB over its first 2 s, after the floor has reached the reduction. + #[test] + fn a_vowel_held_from_the_start_keeps_its_level() { + let held = SR as usize * 3; + let mut speech = vec![0.0f32; held + SR as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let noise = white(53, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for range in [0..SR as usize * 2, SR as usize * 3 / 2..SR as usize * 2] { + let kept = db((energy(&ys[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the vowel's level changed by {kept:.2} dB over {range:?}"); + } + } + + #[test] + fn a_hop_periodic_startup_vowel_keeps_its_level_at_16_khz() { + let sr = 16_000.0; + let held = sr as usize * 3; + let mut speech = vec![0.0f32; held + sr as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 250.0 * i as f64 / sr as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", 24.0)); + s.reset(); + assert_eq!(s.hop, sr as usize / 250); + let lat = s.latency(); + let mut y = speech.clone(); + s.process(&mut [&mut y]); + for range in [0..sr as usize * 2, sr as usize * 3 / 2..sr as usize * 2] { + let kept = db((energy(&y[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the 250 Hz startup vowel at 16 kHz changed by {kept:.2} dB over {range:?}"); + } + } + + /// Steady noise whose spectrum falls with frequency (white noise through a one-pole low-pass + /// at 500 Hz) is suppressed by at least 20 dB from 4 s on. + #[test] + fn steady_low_passed_noise_falls_by_the_reduction() { + let mut s = suppressor(24.0); + let n = SR as usize * 5; + let a = (-std::f32::consts::TAU * 500.0 / SR).exp(); + let mut state = 0.0f32; + let x: Vec = white(59, n, 0.2) + .into_iter() + .map(|v| { + state = a * state + (1.0 - a) * v; + state + }) + .collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let lat = s.latency(); + let from = SR as usize * 4; + let got = -db(rms(&y[from + lat..n]) / rms(&x[from..n - lat])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// NaN, infinite and the largest finite samples give finite output, and the noise is still + /// suppressed afterwards. + #[test] + fn non_finite_and_huge_samples_give_finite_output() { + let mut s = suppressor(24.0); + let n = SR as usize * 4; + let x = white(13, n, 0.05); + let mut y = x.clone(); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + y[3000 + i * 1500] = bad; + y[3001 + i * 1500] = bad; + } + s.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite())); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset none of their earlier audio sounds. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let noise = white(23, 4_000, 0.5); + let mut s = NoiseSuppression::new(SR, 3); + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + s.process(&mut [&mut a, &mut b, &mut c]); + // The first channel is silent too, so the paired inverse FFT carries none of its audio + // into the second channel. + let mut a = vec![0.0f32; 4_000]; + s.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + s.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "earlier audio came back"); + } + + /// On steady white noise, the noise estimate, averaged over the bins, lands within 1 dB of the + /// noise's mean power once the search window has filled. + #[test] + fn the_noise_estimate_follows_white_noise() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let amp = 0.1f32; + let x = white(3, SR as usize * 4, amp); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + // uniform noise of amplitude `amp` has a variance of amp²/3; each bin of the + // square-root-Hann windowed FFT gets n/2 of that + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mean = (1..half - 1).map(|k| db((bins.noise(k) as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64; + assert!(mean.abs() < 1.0, "the noise estimate is {mean:.2} dB from the mean power"); + } +} diff --git a/crates/audio-dsp/src/effects/util.rs b/crates/audio-dsp/src/effects/util.rs index eb19d70d72..e16654994e 100644 --- a/crates/audio-dsp/src/effects/util.rs +++ b/crates/audio-dsp/src/effects/util.rs @@ -81,7 +81,14 @@ impl DelayLine { let i0 = self.w + len - 1 - di as usize; let i0 = if i0 >= len { i0 - len } else { i0 }; let i1 = if i0 == 0 { len - 1 } else { i0 - 1 }; - self.buf[i0] + (self.buf[i1] - self.buf[i0]) * frac + let (a, b) = (self.buf[i0], self.buf[i1]); + let y = a + (b - a) * frac; + if y.is_finite() { + y + } else { + // Two large samples of opposite sign overflow `b - a` in f32. + (a as f64 + (b as f64 - a as f64) * frac as f64) as f32 + } } /// Integer read (`d` samples ago, 0 = newest). #[inline] diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index af487cdbbb..72a6ddf2ed 100644 --- a/crates/audio-dsp/src/effects/voice.rs +++ b/crates/audio-dsp/src/effects/voice.rs @@ -1,5 +1,8 @@ -//! Voice pitch shifter for live use: two read taps sweep through a short delay line and crossfade -//! (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. +//! Effects for a live voice: a pitch shifter with 10 ms of latency and a formant shifter with +//! 10.7 ms of latency (at 48 kHz). +//! +//! The pitch shifter (`voice_pitch`) has two read taps that sweep through a short delay line and +//! crossfade (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. //! //! The taps sit half a sweep apart and are centered on the latency, so the delay of each one //! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and @@ -11,8 +14,21 @@ //! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift //! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting //! is a plain delay. +//! +//! The formant shifter (`voice_formant`) moves the spectral envelope of the voice up or down while +//! its harmonics stay where they are. It runs a short STFT (512 points at up to 50 kHz, hop 128). +//! For each frame it fits a linear predictor (one coefficient per kHz plus 2, at most 96) to the +//! last two frame lengths of input (1,024 samples at 48 kHz), which end with the frame and add no +//! latency, and takes the +//! envelope from the predictor. It then multiplies every bin by the envelope read at +//! `bin / ratio` over the envelope at the bin, with at most 24 dB of boost. Its latency is the +//! STFT size. `voice_pitch` uses the same stage for Keep Formants: the stage moves the shifted +//! voice's envelope back by the inverse of the pitch ratio, so the pitch changes and the formants +//! stay, and the latency grows by the STFT size. +use super::stft::{Spectral, StftChannel, fft_size}; use crate::biquad::{Biquad, Coeffs, FilterType}; +use crate::fft::Fft; use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing}; use std::f64::consts::PI; @@ -33,13 +49,31 @@ const MARGIN: f64 = 2.0; const MAX_STEP: f64 = 0.45; /// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker. const TRACK_CLIP: f64 = 1.0e4; +/// Fewest and most predictor coefficients of the formant envelope (one per kHz plus 2 between). +const MIN_ORDER: usize = 8; +const MAX_ORDER: usize = 96; +/// Width of the Gaussian lag window, which widens each envelope peak to about this many hertz. +const LAG_HZ: f64 = 40.0; +/// White noise added to the autocorrelation (60 dB down), so a pure tone still gives a stable +/// predictor. +const WHITE: f64 = 1.0e-6; +/// Largest boost the envelope warp gives one bin: ln 16, about 24 dB. +const MAX_BOOST: f64 = 2.772_588_722_239_781; + +/// STFT size of the formant stage: 512 at up to 50 kHz (10.7 ms at 48 kHz), 1024 up to 100 kHz, +/// 2048 above. +fn formant_size(sample_rate: f32) -> usize { + fft_size(sample_rate) / 4 +} /// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a /// low-passed, decimated copy. Every buffer is sized at creation. /// -/// It keeps two copies: the mean of the channels, and the first channel alone. A frame whose -/// mean holds less than a quarter of the first channel's energy (channels of opposite polarity -/// cancel in the mean) is analyzed on the first channel. +/// It keeps two copies: the mean of the channels, and one channel alone. A frame whose mean holds +/// less than a quarter of that channel's energy (channels of opposite polarity cancel in the +/// mean) is analyzed on that channel. The channel is the first one until another channel holds +/// over four times its energy through one hop; the tracker then moves to the loudest channel, and +/// analyzes that channel's copy only once a whole frame of it has come in. #[derive(Clone, Debug)] struct Tracker { /// Input samples per analysis sample. @@ -56,10 +90,16 @@ struct Tracker { max_tau: usize, /// Period in input samples, or `None` when the last frame was unvoiced. period: Option, + /// Channel the second copy holds. + channel: usize, + /// Energy of each channel's clipped input since the last analysis. + energy: Vec, + /// Analysis samples of `channel` in the second copy, up to the frame length. + filled: usize, } impl Tracker { - fn new(sample_rate: f32) -> Self { + fn new(sample_rate: f32, channels: usize) -> Self { let factor = (sample_rate / TRACK_RATE).round().max(1.0) as usize; let rate = sample_rate / factor as f32; let max_hz = MAX_HZ.min(rate / 4.0); @@ -82,6 +122,10 @@ impl Tracker { min_tau, max_tau, period: None, + channel: 0, + energy: vec![0.0; channels.max(1)], + // The zeros the copy starts with are the first channel's silence. + filled: len, } } @@ -91,12 +135,23 @@ impl Tracker { self.at = 0; self.since = 0; self.period = None; + self.channel = 0; + self.energy.fill(0.0); + self.filled = self.frame.len(); } - /// Takes one input sample, as the mean of the channels and the first channel; runs an - /// analysis every `hop` analysis samples. - fn push(&mut self, mean: f32, first: f32) { - let clipped = [mean, first].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP)); + /// Adds one input sample of channel `c` to that channel's energy. + fn measure(&mut self, c: usize, x: f32) { + if let Some(e) = self.energy.get_mut(c) { + let x = (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP); + *e += x * x; + } + } + + /// Takes one input sample, as the mean of the channels and the sample of the channel in + /// `self.channel`; runs an analysis every `hop` analysis samples. + fn push(&mut self, mean: f32, single: f32) { + let clipped = [mean, single].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP)); for (feed, x) in self.feeds.iter_mut().zip(clipped) { feed.filter(&self.coeffs, x); } @@ -110,16 +165,34 @@ impl Tracker { feed.ring[self.at] = feed.last as f32; } self.at = (self.at + 1) & mask; + self.filled = (self.filled + 1).min(self.frame.len()); self.since += 1; if self.since >= self.hop { self.since = 0; self.analyze(); + self.choose_channel(); } } + /// Moves the second copy to the loudest channel when that channel held over four times the + /// energy of the one in use since the last analysis. The first of equally loud channels wins. + fn choose_channel(&mut self) { + let loudest = (0..self.energy.len()).fold(0, |b, c| if self.energy[c] > self.energy[b] { c } else { b }); + if self.energy[self.channel] < 0.25 * self.energy[loudest] { + self.channel = loudest; + self.feeds[1].reset(); + self.filled = 0; + } + self.energy.fill(0.0); + } + fn analyze(&mut self) { - let [mean, first] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); - let feed = if mean < 0.25 * first { &self.feeds[1] } else { &self.feeds[0] }; + let [mean, single] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); + if mean < 0.25 * single && self.filled < self.frame.len() { + // The channel's copy holds less than a frame since the move: keep the last period. + return; + } + let feed = if mean < 0.25 * single { &self.feeds[1] } else { &self.feeds[0] }; let mask = self.frame.len() - 1; for (i, v) in self.frame.iter_mut().enumerate() { *v = feed.ring[(self.at + i) & mask]; @@ -229,10 +302,16 @@ struct Taps { delay_b: f64, } -/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). +/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). Keep Formants +/// (`formant_follow`) adds the formant stage's latency, 10.7 ms at 48 kHz, and `latency` reports +/// it while the switch is on. pub struct VoicePitch { pv: ParamValues, latency: usize, + /// Formant stage of Keep Formants, and the share of its output against the shifted voice. + follow: Stage, + follow_mix: f64, + follow_on: bool, /// Widest tap spacing that keeps both taps inside the line, in samples. max_spacing: f64, lines: Vec>, @@ -252,6 +331,7 @@ impl VoicePitch { pub const PARAMS: &'static [ParamSpec] = &[ ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones), ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None), + ParamSpec::new("formant_follow", "Keep Formants", 0.0, 1.0, 0.0, Unit::Toggle), ]; pub fn new(sample_rate: f32, channels: usize) -> Self { @@ -262,11 +342,14 @@ impl VoicePitch { let mut s = VoicePitch { pv: ParamValues::new(Self::PARAMS), latency, + follow: Stage::new(sample_rate, ch), + follow_mix: 0.0, + follow_on: false, max_spacing: latency as f64 - MARGIN, lines: vec![vec![0.0; len]; ch], mask: len - 1, pos: 0, - tracker: Tracker::new(sample_rate), + tracker: Tracker::new(sample_rate, ch), ratio: 1.0, phase: 0.5, spacing: latency as f64 - MARGIN, @@ -280,11 +363,17 @@ impl VoicePitch { fn apply_params(&mut self, snap: bool) { let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0; self.ratio = 2f64.powf(shift / 12.0); + self.follow_on = self.pv.v("formant_follow") >= 0.5; if snap { self.wet = self.target_wet(); + self.follow_mix = self.follow_target(); } } + fn follow_target(&self) -> f64 { + if self.follow_on { 1.0 } else { 0.0 } + } + fn target_wet(&self) -> f64 { if self.ratio == 1.0 { 0.0 } else { 1.0 } } @@ -341,12 +430,13 @@ impl VoicePitch { impl AudioEffect for VoicePitch { param_plumbing!("voice_pitch"); fn latency(&self) -> usize { - self.latency + self.latency + if self.follow_on { self.follow.n } else { 0 } } fn tail_samples(&self) -> usize { // A tap reads up to `latency + max_spacing` samples back and the cubic read two samples - // more, which is twice the latency in all. - self.latency + // more, which is twice the latency in all. Keep Formants spreads a frame over up to the + // formant stage's size more. A render drains `latency() + tail_samples()` samples. + self.latency + if self.follow_on { self.follow.n } else { 0 } } fn reset(&mut self) { self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0)); @@ -355,23 +445,43 @@ impl AudioEffect for VoicePitch { self.phase = 0.5; self.spacing = self.max_spacing; self.wet = self.target_wet(); + self.follow.reset(); + self.follow_mix = self.follow_target(); } fn process(&mut self, channels: &mut [&mut [f32]]) { let len = block_len(channels); - let ch = channels.len().min(self.lines.len()); + let ch = self.lines.len(); let dry_at = self.mask + 1 - self.latency; + let follow_target = self.follow_target(); + // The formant stage moves the envelope by the inverse of the pitch ratio. + let back = (1.0 / self.ratio) as f32; for i in 0..len { let mut sum = 0.0f32; - for (line, io) in self.lines.iter_mut().zip(channels.iter()) { - // A non-finite sample is stored as silence, so it never reaches the output. - let x = flush32(io[i]); + 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 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; + self.tracker.measure(c, x); } - let first = self.lines[0][self.pos]; - self.tracker.push(sum / ch as f32, first); + let single = self.lines[self.tracker.channel][self.pos]; + self.tracker.push(sum / ch as f32, single); let t = self.advance(); - for (line, io) in self.lines.iter().zip(channels.iter_mut()) { + let mix = if self.follow_mix < follow_target { + (self.follow_mix + self.wet_step).min(follow_target) + } else { + (self.follow_mix - self.wet_step).max(follow_target) + }; + self.follow_mix = mix; + // While Keep Formants is off and faded out, the stage's frames copy the shifted voice, + // so switching it on crossfades from a delayed copy instead of from silence. + let warp = if mix > 0.0 { back } else { 1.0 }; + // A channel the block leaves out still reads its line into the formant stage, so the + // audio its line holds reaches the stage on time; only its output is dropped. + for (c, line) in self.lines.iter().enumerate() { let dry = line[(self.pos + dry_at) & self.mask] as f64; let y = if t.wet == 0.0 { dry @@ -380,13 +490,290 @@ impl AudioEffect for VoicePitch { t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b); t.wet * shifted + (1.0 - t.wet) * dry }; - io[i] = y.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + let y = y.clamp(-f32::MAX as f64, f32::MAX as f64); + let z = self.follow.tick(c, y as f32, warp); + // The stage's output is `n` samples later than `y`, so a switch fades one out + // before the other comes in instead of mixing them. + let out = if mix < 0.5 { (1.0 - 2.0 * mix) * y } else { (2.0 * mix - 1.0) * z as f64 }; + if let Some(io) = channels.get_mut(c) { + io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } } self.pos = (self.pos + 1) & self.mask; } } } +/// Spectral envelope of the recent input from linear prediction, and the warp that moves it. +/// Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Envelope { + fft: Fft, + /// Hann window over the analyzed history. + window: Vec, + /// Gaussian lag window, one value per autocorrelation lag (`order + 1`). + lags: Vec, + frame: Vec, + r: Vec, + /// Predictor coefficients, `a[0] = 1`. + a: Vec, + prev: Vec, + re: Vec, + im: Vec, + /// Natural log of the envelope's magnitude, bins 0..=n/2 of the STFT. + log: Vec, +} + +impl Envelope { + /// An envelope for STFT frames of `n` points, read from the last `2 n` samples. + fn new(n: usize, sample_rate: f32) -> Self { + let order = ((sample_rate / 1000.0).round() as usize + 2).clamp(MIN_ORDER, MAX_ORDER); + let w = 2 * n; + let window = (0..w).map(|i| 0.5 - 0.5 * (2.0 * PI * (i as f64 + 0.5) / w as f64).cos()).collect(); + let lags = (0..=order) + .map(|i| { + let x = 2.0 * PI * LAG_HZ * i as f64 / sample_rate as f64; + (-0.5 * x * x).exp() + }) + .collect(); + Envelope { + fft: Fft::new(n), + window, + lags, + frame: vec![0.0; w], + r: vec![0.0; order + 1], + a: vec![0.0; order + 1], + prev: vec![0.0; order + 1], + re: vec![0.0; n], + im: vec![0.0; n], + log: vec![0.0; n / 2 + 1], + } + } + + /// Reads the envelope of the newest `2 n` samples of `history`. Returns `false` for silence, + /// which has no envelope. + fn measure(&mut self, history: &History) -> bool { + let mask = history.ring.len() - 1; + for (i, (v, w)) in self.frame.iter_mut().zip(&self.window).enumerate() { + *v = history.ring[(history.pos + i) & mask] as f64 * w; + } + let len = self.frame.len(); + self.r[0] = dot(&self.frame, &self.frame) * self.lags[0]; + if !(self.r[0] > 0.0 && self.r[0].is_finite()) { + return false; + } + for (lag, (r, w)) in self.r.iter_mut().zip(&self.lags).enumerate().skip(1) { + *r = dot(&self.frame[..len - lag], &self.frame[lag..]) * w; + } + self.r[0] *= 1.0 + WHITE; + levinson(&self.r, &mut self.a, &mut self.prev); + // The envelope is 1 / |A| on the bins of the STFT. + self.re.fill(0.0); + self.im.fill(0.0); + for (v, a) in self.re.iter_mut().zip(&self.a) { + *v = *a as f32; + } + self.fft.forward(&mut self.re, &mut self.im); + for (l, (re, im)) in self.log.iter_mut().zip(self.re.iter().zip(&self.im)) { + *l = (-0.5 * (*re as f64 * *re as f64 + *im as f64 * *im as f64 + 1e-30).ln()) as f32; + } + true + } + + /// Multiplies the half spectrum `re`/`im` (bins 0..=n/2) by the envelope read at `bin / + /// ratio` over the envelope at the bin, so the envelope moves up by `ratio` and the + /// harmonics stay. A frame with a non-finite bin is replaced with silence. + fn warp(&self, re: &mut [f32], im: &mut [f32], ratio: f32) { + let half = self.log.len(); + let (re, im) = (&mut re[..half], &mut im[..half]); + if !re.iter().chain(im.iter()).fold(true, |ok, v| ok & v.is_finite()) { + re.fill(0.0); + im.fill(0.0); + return; + } + let last = (half - 1) as f32; + for k in 0..half { + let src = (k as f32 / ratio).min(last); + let i = src as usize; + let e = match self.log.get(i + 1) { + Some(next) => self.log[i] + (src - i as f32) * (next - self.log[i]), + None => self.log[i], + }; + let g = ((e - self.log[k]) as f64).min(MAX_BOOST).exp() as f32; + re[k] *= g; + im[k] *= g; + } + } +} + +/// Dot product of two slices of the same length, in four running sums so it vectorizes. +fn dot(a: &[f64], b: &[f64]) -> f64 { + let mut sums = [0.0f64; 4]; + let ((ca, ra), (cb, rb)) = (a.as_chunks::<4>(), b.as_chunks::<4>()); + for (x, y) in ca.iter().zip(cb) { + for ((s, x), y) in sums.iter_mut().zip(x).zip(y) { + *s += x * y; + } + } + let rest: f64 = ra.iter().zip(rb).map(|(x, y)| x * y).sum(); + (sums[0] + sums[1]) + (sums[2] + sums[3]) + rest +} + +/// Levinson-Durbin recursion: the predictor `a` (`a[0] = 1`) of the autocorrelation `r`. It +/// stops at the first reflection coefficient that would make the predictor unstable. +fn levinson(r: &[f64], a: &mut [f64], prev: &mut [f64]) { + a.fill(0.0); + a[0] = 1.0; + let mut err = r[0]; + for i in 1..a.len() { + let acc = r[i] + (1..i).map(|j| a[j] * r[i - j]).sum::(); + let k = -acc / err; + // NaN (from a zero error) also stops the recursion. + if k.is_nan() || k.abs() >= 1.0 { + return; + } + prev[..i].copy_from_slice(&a[..i]); + for j in 1..i { + a[j] = prev[j] + k * prev[i - j]; + } + a[i] = k; + err *= 1.0 - k * k; + } +} + +/// The newest samples of one channel, for the envelope. +#[derive(Clone, Debug)] +struct History { + ring: Vec, + /// Where the next sample goes, which is also the oldest sample. + pos: usize, +} + +impl History { + fn push(&mut self, x: f32) { + self.ring[self.pos] = x; + self.pos = (self.pos + 1) & (self.ring.len() - 1); + } + + fn reset(&mut self) { + self.ring.fill(0.0); + self.pos = 0; + } +} + +/// STFT stage that moves each channel's envelope, fed one sample at a time: the formant +/// shifter, and the formant stage of `voice_pitch`'s Keep Formants. +#[derive(Clone, Debug)] +struct Stage { + n: usize, + hop: usize, + scale: f32, + spec: Spectral, + stft: Vec, + history: Vec, + env: Envelope, +} + +impl Stage { + fn new(sample_rate: f32, channels: usize) -> Self { + let n = formant_size(sample_rate); + Stage { + n, + hop: n / 4, + // √Hann on both sides is Hann, which sums to 2 at a hop of n/4; the inverse FFT is + // unscaled. + scale: 1.0 / (2 * n) as f32, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); channels], + history: vec![History { ring: vec![0.0; 2 * n], pos: 0 }; channels], + env: Envelope::new(n, sample_rate), + } + } + + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.history.iter_mut().for_each(History::reset); + } + + /// Pushes one sample of a channel and returns the stage's output for it, `n` samples later. + /// A frame moves the envelope by `ratio`, which can spread a sound over the frame, so the + /// output can go on for up to `n` samples more (the tail). At a ratio of 1, and for silence, a frame only + /// windows and adds its input, which needs no FFT. + fn tick(&mut self, channel: usize, x: f32, ratio: f32) -> f32 { + let Stage { n, hop, scale, spec, stft, history, env } = self; + let half = *n / 2 + 1; + history[channel].push(x); + let history = &history[channel]; + let z = stft[channel].tick(x, *hop, &mut |input, out| { + if ratio != 1.0 && env.measure(history) { + spec.analyze(input); + env.warp(&mut spec.re[..half], &mut spec.im[..half], ratio); + spec.synthesize_add(out, *scale); + } else { + for ((o, x), w) in out.iter_mut().zip(input).zip(&spec.window) { + *o += x * w * w * 0.5; + } + } + }); + // A huge finite input can overflow the inverse FFT. + flush32(z) + } +} + +/// Formant shifter for a live voice: moves the spectral envelope by -12 to +12 semitones (a ratio +/// of 0.5 to 2) and keeps the harmonics. Its latency is the STFT size, 512 samples (10.7 ms) at +/// 48 kHz. +pub struct VoiceFormant { + pv: ParamValues, + stage: Stage, + ratio: f32, +} + +impl VoiceFormant { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("semitones", "Formant Shift", -12.0, 12.0, 0.0, Unit::Semitones)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = VoiceFormant { pv: ParamValues::new(Self::PARAMS), stage: Stage::new(sample_rate, crate::sane_channels(channels)), ratio: 1.0 }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + self.ratio = 2f32.powf(self.pv.v("semitones") / 12.0); + } +} + +impl AudioEffect for VoiceFormant { + param_plumbing!("voice_formant"); + fn latency(&self) -> usize { + self.stage.n + } + fn tail_samples(&self) -> usize { + self.stage.n + } + fn reset(&mut self) { + self.stage.reset(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + 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 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 => { + self.stage.tick(c, 0.0, self.ratio); + } + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -455,6 +842,24 @@ mod tests { } } + /// With a silent first channel, a voice on the other two channels in opposite polarity is + /// still tracked from one of them and crossfades without beating. + #[test] + fn opposite_polarity_beside_a_silent_first_channel_is_still_tracked() { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 7.0)); + p.reset(); + let n = SR as usize * 2; + let mut silent = vec![0.0f32; n]; + let mut l = sine(220.0, 0.5, SR as f64, n, 0.0); + let mut r: Vec = l.iter().map(|v| -v).collect(); + p.process(&mut [&mut silent, &mut l, &mut r]); + assert!(silent.iter().all(|v| *v == 0.0)); + assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b)); + let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0)); + assert!(rest < -40.0, "{rest:.1} dB beside the tone"); + } + /// A voice whose two channels have opposite polarity, which cancel in their mean, is still /// tracked and crossfades without beating. #[test] @@ -557,18 +962,330 @@ mod tests { assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail)); } + /// Two-pole resonance magnitude at `f`, 1 at `center`. + fn resonance(f: f64, center: f64, bandwidth: f64) -> f64 { + center * bandwidth / ((center * center - f * f).powi(2) + (f * bandwidth).powi(2)).sqrt() + } + + /// A vowel: harmonics of `f0` up to 6 kHz shaped by two formants (`f1` with an 80 Hz + /// bandwidth, `f2` with 120 Hz and half the level) over a floor 34 dB down. + fn vowel(f0: f64, f1: f64, f2: f64, sr: f64, n: usize) -> Vec { + let harmonics: Vec<(f64, f64)> = (1..) + .map(|k| k as f64 * f0) + .take_while(|f| *f < 6000.0) + .map(|f| (f, 0.02 + resonance(f, f1, 80.0) + 0.5 * resonance(f, f2, 120.0))) + .collect(); + (0..n) + .map(|i| { + let t = i as f64 / sr; + (0.08 * harmonics.iter().map(|(f, a)| a * (2.0 * std::f64::consts::PI * f * t).sin()).sum::()) as f32 + }) + .collect() + } + + /// The envelope peak of `y` between `lo` and `hi` Hz, read from the amplitudes of the + /// harmonics of `f0` with a parabola through the strongest one and its neighbors (in dB). + fn envelope_peak(y: &[f32], f0: f64, lo: f64, hi: f64, sr: f64) -> f64 { + let amp = |k: usize| tone_amplitude(y, k as f64 * f0, sr).max(1e-12).ln(); + let ks = (lo / f0).ceil() as usize..=(hi / f0).floor() as usize; + let k = ks.max_by(|a, b| amp(*a).total_cmp(&(*b))).unwrap_or(1); + let (a, b, c) = (amp(k - 1), amp(k), amp(k + 1)); + let denom = a - 2.0 * b + c; + let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }; + (k as f64 + shift) * f0 + } + + /// The second of `y` after its first half second, at the rate `sr`. + fn settled_at(y: &[f32], sr: f64) -> &[f32] { + &y[sr as usize / 2..sr as usize * 3 / 2] + } + + /// The two formants of the vowel test signal (600 and 2000 Hz) in `y`, each looked for within + /// a window moved by `ratio`, with `y`'s harmonics at multiples of `f0`. + fn formants(y: &[f32], f0: f64, ratio: f64, sr: f64) -> (f64, f64) { + let tail = settled_at(y, sr); + (envelope_peak(tail, f0, 400.0 * ratio, 1000.0 * ratio, sr), envelope_peak(tail, f0, 1400.0 * ratio, 3000.0 * ratio, sr)) + } + + /// Level of everything off the harmonics of `f0` in `y`'s settled second, against the whole, + /// in dB. + fn off_harmonics_db(y: &[f32], f0: f64, sr: f64) -> f64 { + let tail = settled_at(y, sr); + let total = rms(tail).powi(2); + let on: f64 = (1..).map(|k| k as f64 * f0).take_while(|f| *f < sr / 2.0 - f0).map(|f| tone_amplitude(tail, f, sr).powi(2) / 2.0).sum(); + 10.0 * ((total - on).max(1e-30) / total).log10() + } + + /// A formant shift moves both formants of a vowel by the ratio, within a tenth of the move for + /// the first and 5% for the second, while every partial stays on the harmonics of the + /// unchanged fundamental. Checked at three voice pitches and three sample rates. + #[test] + fn a_formant_shift_moves_the_envelope_and_keeps_the_harmonics() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + for f0 in [110.0, 150.0, 220.0] { + let x = vowel(f0, 600.0, 2000.0, sr, sr as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for semis in [-4.0f32, 4.0] { + let mut f = VoiceFormant::new(sr as f32, 1); + assert!(f.set_param("semitones", semis)); + let mut y = x.clone(); + f.process(&mut [&mut y]); + let r = 2f64.powf(semis as f64 / 12.0); + let (q1, q2) = formants(&y, f0, r, sr); + let at = format!("{sr} Hz, f0 {f0}, {semis:+} st: formants {p1:.0} and {p2:.0} moved to {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * r) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * r) - 1.0).abs() < 0.05, "{at}"); + let off = off_harmonics_db(&y, f0, sr); + assert!(off < -30.0, "{at}: {off:.1} dB off the harmonics"); + } + } + } + } + + /// Keep Formants: the pitch moves up a fourth, and the formants of the vowel stay where they + /// were (where without it they move with the pitch). + #[test] + fn keep_formants_holds_the_envelope_while_the_pitch_moves() { + let (sr, f0) = (SR as f64, 150.0); + let x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + let r = 2f64.powf(5.0 / 12.0); + for keep in [false, true] { + let mut p = shifter(5.0, 0.0); + assert!(p.set_param("formant_follow", if keep { 1.0 } else { 0.0 })); + p.reset(); + let y = run(&mut p, &x); + let want = if keep { 1.0 } else { r }; + let (q1, q2) = formants(&y, f0 * r, want, sr); + let at = format!("keep {keep}: formants {p1:.0} and {p2:.0} read {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * want) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * want) - 1.0).abs() < 0.05, "{at}"); + assert!(cents(peak_hz(settled(&y), f0 * r * 0.98, f0 * r * 1.02), f0 * r).abs() < 2.0, "keep {keep}: pitch"); + } + } + + /// Keep Formants adds the formant shifter's latency to the pitch shifter's while it is on, at + /// each rate. + #[test] + fn the_latency_reports_the_formant_stage() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + let n = VoiceFormant::new(sr, 2).latency(); + assert!(n > 0, "{sr}"); + let mut p = VoicePitch::new(sr, 2); + let base = p.latency(); + assert!(p.set_param("formant_follow", 1.0)); + assert_eq!(p.latency(), base + n, "{sr}"); + assert!(p.set_param("formant_follow", 0.0)); + assert_eq!(p.latency(), base, "{sr}"); + } + } + + /// After a burst of noise ends, the formant shifter and the pitch shifter with Keep Formants + /// fall silent within `latency + tail_samples`, so an offline render that drains that long + /// keeps all of the output. + #[test] + fn formant_output_ends_within_the_reported_tail() { + let (n, at, len) = (12_000, 1_777, 1_000); + let mut rng = Rng::new(17); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let mut f = VoiceFormant::new(SR, 1); + assert!(f.set_param("semitones", 7.0)); + let mut p = shifter(-5.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let fxs: [&mut dyn AudioEffect; 2] = [&mut f, &mut p]; + for fx in fxs { + let mut y = x.clone(); + fx.process(&mut [&mut y]); + let end = at + len + fx.latency() + fx.tail_samples(); + assert!(y[end..].iter().all(|v| *v == 0.0), "{}: output after {end}", fx.id()); + } + } + + /// Switching Keep Formants on fades the shifter's own output out over 10 ms and then fades the + /// formant stage's output, 512 samples later, in over 10 ms: the two never sound together, + /// so their different delays cannot comb-filter the voice. Checked at a shift of 0, where the + /// stage passes the voice unchanged. + #[test] + fn switching_keep_formants_fades_through_silence() { + let x = vowel(170.0, 650.0, 1900.0, SR as f64, 12_000); + let at = 4_000; + let mut plain = shifter(0.0, 0.0); + let y = run(&mut plain, &x); + let mut p = shifter(0.0, 0.0); + let mut out = x.clone(); + p.process(&mut [&mut out[..at]]); + assert!(p.set_param("formant_follow", 1.0)); + p.process(&mut [&mut out[at..]]); + let n = p.follow.n; + let step = 1.0 / (SR as f64 * BYPASS_MS as f64 / 1000.0); + for i in at..x.len() { + let m = ((i - at + 1) as f64 * step).min(1.0); + let want = if m < 0.5 { (1.0 - 2.0 * m) * y[i] as f64 } else { (2.0 * m - 1.0) * y[i - n] as f64 }; + assert!((out[i] as f64 - want).abs() < 1e-4, "sample {i}: {} against {want}", out[i]); + } + } + + /// The formant shifter with a shift change part way, and the pitch shifter with Keep Formants + /// switched on and off part way, give the same output however the stream is cut into blocks. + #[test] + fn formant_output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x = vowel(130.0, 700.0, 1800.0, SR as f64, n); + let changes: [(usize, &str, f32); 3] = [(9_001, "semitones", 3.0), (17_321, "formant_follow", 1.0), (29_999, "formant_follow", 0.0)]; + let run_cut = |make: &dyn Fn() -> Box, sizes: &mut dyn FnMut() -> usize| { + let mut fx = make(); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + for (at, id, v) in changes { + if pos == at { + fx.set_param(id, v); + } + } + let next = changes.iter().map(|c| c.0).find(|at| *at > pos).unwrap_or(n); + let len = sizes().min(next - pos); + fx.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let makers: [&dyn Fn() -> Box; 2] = [ + &|| { + let mut f = VoiceFormant::new(SR, 1); + f.set_param("semitones", -5.0); + Box::new(f) + }, + &|| Box::new(shifter(-3.0, 0.0)), + ]; + for make in makers { + let whole = run_cut(make, &mut || usize::MAX); + let mut rng = Rng::new(13); + let cut = run_cut(make, &mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + assert!(whole.iter().any(|v| v.abs() > 0.05)); + } + } + + /// NaN, infinite and the largest finite samples in a vowel give finite output from the formant + /// shifter and from Keep Formants, and the formants are still moved afterwards. + #[test] + fn formant_stage_output_stays_finite() { + let (sr, f0) = (SR as f64, 150.0); + let mut x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + x[3000 + i * 1500] = bad; + x[3001 + i * 1500] = bad; + } + let mut f = VoiceFormant::new(SR, 2); + assert!(f.set_param("semitones", 4.0)); + let (mut l, mut r) = (x.clone(), x.clone()); + f.process(&mut [&mut l, &mut r]); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); + let ratio = 2f64.powf(4.0 / 12.0); + let (q1, _) = formants(&l, f0, ratio, sr); + assert!((q1 / (p1 * ratio) - 1.0).abs() < 0.12, "{q1}"); + let mut p = shifter(-7.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + assert!(rms(settled(&y)) > 0.01); + let shifted_f0 = f0 * 2f64.powf(-7.0 / 12.0); + let (q1, q2) = formants(&y, shifted_f0, 1.0, sr); + assert!((q1 / p1 - 1.0).abs() < 0.12, "Keep Formants: {p1} read {q1}"); + assert!((q2 / p2 - 1.0).abs() < 0.05, "Keep Formants: {p2} read {q2}"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// 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); + let noise: Vec = (0..4_000).map(|_| 0.5 * rng.uniform()).collect(); + let mut f = VoiceFormant::new(SR, 3); + assert!(f.set_param("semitones", 4.0)); + let mut plain = VoicePitch::new(SR, 3); + assert!(plain.set_param("semitones", 5.0)); + plain.reset(); + let mut keep = VoicePitch::new(SR, 3); + assert!(keep.set_param("semitones", 5.0) && keep.set_param("formant_follow", 1.0)); + 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(); + fx.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + fx.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "{}: earlier audio came back", fx.id()); + } + } + + /// With Keep Formants on, a channel left out of a short block while its line still holds an + /// impulse passes that impulse to the formant stage, so after it comes back its output matches + /// a channel that was never left out. + #[test] + fn a_short_gap_keeps_the_formant_stage_fed() { + for semitones in [0.0, 5.0] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut a, mut b) = (vec![0.0f32; 480], vec![0.0f32; 480]); + a[0] = 1.0; + b[0] = 1.0; + p.process(&mut [&mut a, &mut b]); + // The impulse leaves the delay line during samples 480 to 735, while `b` is left out. + let mut a = vec![0.0f32; 256]; + p.process(&mut [&mut a]); + let (mut a, mut b) = (vec![0.0f32; 2_000], vec![0.0f32; 2_000]); + p.process(&mut [&mut a, &mut b]); + assert!(a.iter().any(|v| v.abs() > 0.01), "{semitones}: the impulse never came out"); + assert_eq!(a, b, "{semitones}: the left-out channel lost the impulse"); + } + } + + /// 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] + fn a_silent_channel_left_out_keeps_the_tracked_pitch() { + let n = SR as usize; + let (low, high) = (sine(187.5, 0.2, SR as f64, n, 0.0), sine(375.0, 0.24, SR as f64, n, 0.0)); + let left: Vec = low.iter().zip(&high).map(|(a, b)| a + b).collect(); + let right: Vec = low.iter().zip(&high).map(|(a, b)| -a + b).collect(); + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 5.0)); + p.reset(); + let (mut l, mut r, mut s) = (left.clone(), right.clone(), vec![0.0f32; n]); + if omit { + p.process(&mut [&mut l, &mut r]); + } else { + p.process(&mut [&mut l, &mut r, &mut s]); + } + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving a silent channel out changed the tracked pitch"); + } + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. #[test] fn the_tracker_reaches_70_hz() { for f in [72.0, 110.0, 440.0, 950.0] { - let mut t = Tracker::new(SR); + let mut t = Tracker::new(SR, 1); for v in sine(f, 0.3, SR as f64, SR as usize / 4, 0.0) { t.push(v, v); } let period = t.period.unwrap_or(0.0); assert!((SR as f64 / period / f - 1.0).abs() < 0.005, "{f} Hz read as {} Hz", SR as f64 / period); } - let mut t = Tracker::new(SR); + let mut t = Tracker::new(SR, 1); (0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0)); assert!(t.period.is_none()); } diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index 59bfaa1741..42018ade17 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -171,8 +171,10 @@ pub trait AudioEffect: Send { /// Parameter descriptions (same as the registry entry's). fn params(&self) -> &'static [ParamSpec]; /// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids. - /// Takes effect from the next processed sample. Gains, mix amounts and equalizer bands move to - /// the new value smoothly; the crate documentation lists which other parameters change at once. + /// Updates the target immediately. Sample-based effects use the target from the next processed + /// sample. Frame-based effects may apply it at the next frame callback while earlier output + /// remains queued. Gains, mix amounts and equalizer bands move to the new value smoothly; the + /// crate documentation lists which other parameters change at once. fn set_param(&mut self, id: &str, value: f32) -> bool; /// Current (target) value of a parameter. fn param(&self, id: &str) -> Option; @@ -182,7 +184,11 @@ pub trait AudioEffect: Send { /// Process one block in place. All channel slices must have the same length (the shortest /// length is used otherwise). Zero-length blocks are allowed. fn process(&mut self, channels: &mut [&mut [f32]]); - /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. + /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. It does + /// not change with the parameters, except for `voice_pitch`'s `formant_follow` (Keep + /// Formants), which adds the formant stage's latency while it is on. The value changes as + /// soon as the switch changes, while the output crossfades between the two delays over the + /// next 20 ms, so during that fade the output does not match the reported latency. fn latency(&self) -> usize { 0 } @@ -197,7 +203,13 @@ pub trait AudioEffect: Send { None } /// How long the output keeps sounding after the input stops, in samples (reverb and delay - /// tails), so an offline render can run past the end of its input. + /// tails), so an offline render can run past the end of its input. The count starts after + /// the latency: a render that keeps the tail runs `latency() + tail_samples()` samples past + /// 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 } @@ -460,6 +472,37 @@ pub(crate) mod testutil { } } + /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), + /// noise bursts (consonants) and pauses. + pub fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let kind = rng.uniform(); + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let v = if kind > 0.3 { + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() + } else if kind > -0.4 { + rng.uniform() + } else { + 0.0 + }; + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; + } + out + } + pub fn sine(freq: f64, amp: f64, sr: f64, n: usize, phase: f64) -> Vec { (0..n).map(|i| (amp * (2.0 * std::f64::consts::PI * freq * i as f64 / sr + phase).sin()) as f32).collect() } diff --git a/crates/audio-dsp/src/sync.rs b/crates/audio-dsp/src/sync.rs index d117ecba3f..2ea3b75aac 100644 --- a/crates/audio-dsp/src/sync.rs +++ b/crates/audio-dsp/src/sync.rs @@ -354,38 +354,7 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) - #[cfg(test)] mod tests { use super::*; - use crate::testutil::Rng; - - /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), - /// noise bursts (consonants) and pauses. - fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { - let n = (sr * secs) as usize; - let mut rng = Rng::new(seed); - let mut out = vec![0.0f32; n]; - let mut i = 0usize; - while i < n { - let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; - let kind = rng.uniform(); - let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); - let glide = 1.0 + 0.3 * rng.uniform() as f64; - let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); - for k in 0..len.min(n - i) { - let t = k as f64 / sr; - let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; - let v = if kind > 0.3 { - let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); - (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() - } else if kind > -0.4 { - rng.uniform() - } else { - 0.0 - }; - out[i + k] = v * env * amp; - } - i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; - } - out - } + use crate::testutil::{Rng, speechy}; /// `x` delayed by `delay` samples (fractional: windowed-sinc interpolation), scaled by `gain`, /// optionally colored by a zero-phase low-pass (`[k, 1-2k, k]`, so the delay stays exact), with diff --git a/crates/audio/README.md b/crates/audio/README.md index 4588c88e74..3b868392a8 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`; `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`; `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 d57baa6b59..6cc18ab901 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`]), 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`] 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 //! `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, @@ -209,8 +209,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; feature = "eac3-encode" ))] pub use write::FileEncoder; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -224,6 +222,8 @@ pub use write::wav_float_header; 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}; +#[cfg(feature = "pcm-encode")] +pub use write::{wav_float_header, wav_float_header_with_bwf}; /// Errors from probing, decoding and encoding. #[non_exhaustive] diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs index 205741c529..09f5d6a4c3 100644 --- a/crates/audio/src/s302m.rs +++ b/crates/audio/src/s302m.rs @@ -53,6 +53,9 @@ pub struct Header { impl Header { /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow. pub fn frame_bytes(&self) -> usize { + if !matches!(self.channels, 2 | 4 | 6 | 8) { + return 0; + } let pair_bytes = match self.bits { 16 => 5, 20 => 6, @@ -243,6 +246,17 @@ mod tests { assert_eq!(h.frame_bytes(), 0); } + #[test] + fn header_frame_bytes_rejects_unsupported_channels() { + for bits in [16, 20, 24] { + for channels in [0, 1, 3, 5, 7, 9, 10, usize::MAX] { + let header = Header { channels, channel_id: 0, bits, alignment: 0, audio_bytes: 0 }; + assert!(Encoder::new(channels, bits).is_err()); + assert_eq!(header.frame_bytes(), 0, "{channels} channels, {bits} bits"); + } + } + } + #[test] fn header_frame_bytes_rejects_unsupported_depth() { let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 }; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 18beab7872..25267e9a05 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -449,8 +449,32 @@ impl EncodeOptions { /// ``` #[cfg(feature = "pcm-encode")] pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result> { + float_header(sample_rate, channels, None, frames) +} + +/// [`wav_float_header`] with a BWF `bext` chunk holding `bwf` before the format chunk. The length +/// still doesn't depend on `frames`, so the header is rewritten in place the same way. +/// +/// ``` +/// use craft_audio::{BwfInfo, wav_float_header_with_bwf}; +/// +/// let bwf = BwfInfo::default().with_originator("Recorder").with_time_reference(48_000 * 3_600); +/// let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); +/// let samples = [0.25f32, -0.25, 0.5, -0.5]; +/// file.extend(samples.iter().flat_map(|s| s.to_le_bytes())); +/// let header = wav_float_header_with_bwf(48_000, 2, 2, &bwf).unwrap(); +/// file[..header.len()].copy_from_slice(&header); +/// assert!(header.windows(4).any(|id| id == b"bext")); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn wav_float_header_with_bwf(sample_rate: u32, channels: u16, frames: u64, bwf: &crate::BwfInfo) -> Result> { + float_header(sample_rate, channels, Some(bwf), frames) +} + +#[cfg(feature = "pcm-encode")] +fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, frames: u64) -> Result> { if channels == 0 || sample_rate == 0 { return Err(AudioError::Encode("a WAV needs channels and a sample rate".into())); } - wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false) + wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false) } diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 2e58cd6332..dd7005fbfb 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -1,4 +1,7 @@ -use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe}; +use craft_audio::{ + AudioBuffer, BitDepth, BwfInfo, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, wav_float_header, + wav_float_header_with_bwf, +}; fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer { let mut b = AudioBuffer::new(sr, channels as u16, frames); @@ -64,3 +67,26 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() { } } } + +#[test] +fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() { + let take = sine(48_000, 2, 1_000); + let bwf = BwfInfo::default() + .with_description("take 3") + .with_originator("recorder") + .with_origination("2026-11-20", "18:30:00") + .with_time_reference(48_000 * 66_600); + let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); + let len = file.len(); + assert!(len > wav_float_header(48_000, 2, 0).unwrap().len()); + file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes())); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 600, &bwf).unwrap()); + let (info, decoded) = decode(&file, None).unwrap(); + assert_eq!((info.bwf.as_ref(), decoded.frames()), (Some(&bwf), 600)); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 1_000, &bwf).unwrap()); + let opts = EncodeOptions::default().with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()); + assert_eq!(file, encode(&take, &opts).unwrap()); + let big = wav_float_header_with_bwf(48_000, 2, 600_000_000, &bwf).unwrap(); + assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len)); + assert!(wav_float_header_with_bwf(48_000, 0, 0, &bwf).is_err()); +} diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 6cca4325a2..9238151b96 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -3,8 +3,8 @@ use std::net::TcpListener; use std::path::PathBuf; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, mpsc}; use std::time::Duration; use craft_automation::agents::AgentLinkStatus; @@ -17,7 +17,6 @@ use craft_automation::ui::agents::AgentsPage; use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles}; use craft_ui::contract::Role; use craft_ui::patterns::preferences::SettingsDraft; -use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::Fixture; use craft_ui::testing::trial; @@ -29,16 +28,40 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = motion::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns once the thread has +/// finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), } - std::thread::sleep(Duration::from_millis(5)); + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() } - true } /// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. @@ -52,8 +75,8 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than once per poll, and -/// its thread ends once the last clone is dropped. +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather than once per poll, +/// and its thread ends at the first poll after the last clone is dropped. #[trial] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); @@ -72,28 +95,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); // Many polls with nothing changed. - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - // The thread sees the switch gone at its next poll and stops probing. - std::thread::sleep(Duration::from_millis(50)); - let after_drop = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(50)); - assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } /// A published connection reads back in its documented shape, and only the process that wrote it removes it. diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index e83b868ce2..4251b79efb 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -351,7 +351,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { return Some(Format::SubViewer); } - if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) { + if !first_lines.is_empty() + && head.lines().map(str::trim_start).filter(|line| !line.trim().is_empty()).take(3).all(|line| vplayer::split_line(line).is_some()) + { return Some(Format::VPlayer); } if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs index 169e4f24a0..bcc834f58a 100644 --- a/crates/captions/src/vplayer.rs +++ b/crates/captions/src/vplayer.rs @@ -49,7 +49,7 @@ pub fn parse(text: &str) -> Result { if line.trim().is_empty() { continue; } - match split_line(line.trim()) { + match split_line(line.trim_start()) { Some((t, raw)) => { let lines: Vec = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect(); starts.push((t, lines.join("\n"))); @@ -121,6 +121,38 @@ pub fn write(doc: &Document) -> String { mod tests { use super::*; + #[test] + fn empty_clearing_lines_keep_each_separator() { + for separator in [":", "=", " "] { + for indent in ["", " \t"] { + let input = format!("{indent}00:00:01{separator} hello \n{indent}00:00:02{separator} \n"); + assert_eq!(crate::detect(input.as_bytes(), None), Some(crate::Format::VPlayer), "{input:?}"); + let doc = parse(&input).unwrap(); + assert_eq!(doc.cues.len(), 1, "{input:?}"); + assert_eq!(doc.cues[0].text, "hello", "{input:?}"); + assert_eq!(doc.cues[0].end, ms_to_tick(2000), "{input:?}"); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + } + } + } + + #[test] + fn detection_keeps_clearing_lines_at_each_sampled_position() { + for separator in [":", "=", " "] { + for at in 0..3 { + let mut lines = ["00:00:01=one".to_owned(), "00:00:02=two".to_owned(), "00:00:03=three".to_owned()]; + lines[at] = format!(" \t00:00:0{}{separator} \t", at + 1); + let input = format!("\u{feff}\n \t\n{}\n", lines.join("\n")); + let format = crate::detect(input.as_bytes(), None).unwrap(); + assert_eq!(format, crate::Format::VPlayer, "{input:?}"); + let document = crate::parse(input.as_bytes(), format).unwrap(); + assert_eq!(document.cues.len(), 2, "{input:?}"); + assert!(document.warnings.is_empty(), "{:?}", document.warnings); + } + } + assert_eq!(crate::detect(b"00:00:01 hello\n00:00:02\n", None), None); + } + #[test] fn short_duration_cue_preserves_positive_duration_on_write_and_read() { let mut doc = Document::default(); diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index a9e4635b09..e29d443fea 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -56,11 +56,13 @@ Sources: https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, was read for the order of fields that the notes do not spell out (the table entries, the rendering attributes and the curve body); no code was copied from it -- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp` and `src/lib/CMXParser.h` - at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`, - https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp - and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h, - read for the header's offsets and the index chunks; no code was copied from it +- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp`, `src/lib/CMXParser.h` + and `src/lib/CMXDocumentStructure.h` at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h + and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXDocumentStructure.h, + read for the header's offsets, the index chunks and the fields of a color entry; no code was + copied from it Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks confirmed that no CX file shows), `public-reader` (a layout LC reads), `unconfirmed` (a point no source states and no sample file shows; @@ -134,7 +136,7 @@ file is committed. | R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | | R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | -| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); LC `CMXParser.cpp` L1698-L1749 (a file with 32-bit coordinates: the model byte and a byte in tag 1, the values in tag 2, other tags passed over), L2254-L2371 (the values of each model: 2 and 3 four bytes, 5 red, green and blue, 9 one byte), `CMXDocumentStructure.h` L138-L139 (the tags); S: every color of the nine CX files is model 2 in the older fields, with the second byte of field 1 5 | sample (model 2), public-reader (the tags and the values of models 2, 5 and 9), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | | R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | | R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample | | R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | @@ -172,6 +174,7 @@ the synthetic test files of `src/synth_cmx.rs` set it. | `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 | | Table counts and field lists | R55 | sample | +| `rclr` fields 1 and 2, before field 10: the model and 5, then four value bytes; model 2 (CMYK in percent), 5 (red, green, blue, then 0) and 9 (gray, then three zero bytes); a spot color as model 5 with its look at its tint, and the registration color as model 2 with four values of 100 | R56 | sample (the fields, model 2 and the 5), public-reader (models 5 and 9), the writer's choice (the models of spot and registration colors, the zero bytes and the order of the fields) | | `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) | | `rpen` field 1: the width | R57 | public-notes | | `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 5e6d07efd3..0bf2c8e8f8 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -107,7 +107,10 @@ corners, not stretched ones. Hidden layers, groups and shapes, guide and grid la and master layers are left out; opacity, blend modes, fill rules and locked states are not written, desktop layers are written as drawing layers, and a spot color with no name opens as a process color; every use of a named spot color takes the look of its use at the strongest tint -among the uses whose look is known. +among the uses whose look is known. Each color entry holds the color twice: as the property list +`read_cmx` reads, and as the model and value fields that other readers, such as libcdr, read. In +those fields a spot color is written as its look at its tint, and the registration color as 100 +percent cyan, magenta, yellow and black. `write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than @@ -125,8 +128,9 @@ unclipped or unlocked. The file holds an index, so that a reader that finds the tables and pages through it, rather than by their chunk ids, opens it: the header gives where the master index starts, the index list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the page, -layer and group records give their instruction counts and where they end; a group's record also -gives the edges of its curves. The record of a page with a size holds the edges of its curves, or +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 repeats the first page's edges and instruction count. `PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets. diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs index 4ad818638e..a5c6e00058 100644 --- a/crates/cdr/src/cmx_write.rs +++ b/crates/cdr/src/cmx_write.rs @@ -535,9 +535,25 @@ fn color_key(c: &Color) -> ColorKey { } } -/// A color entry (R56): field 10 holds a property list, a u32 length then parts of a u8 kind, a u32 -/// length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, the -/// values; R14), and for a named color part 3, a u32 count and UTF-16 units. +/// The color of `k` in the fields 1 and 2 of a color entry (R56): the model and the palette 5, +/// then four value bytes. A spot color is written as its look at its tint in red, green and blue, +/// and the registration color as cyan, magenta, yellow and black at 100 percent, since the +/// models of these fields hold neither. +fn older_fields(k: &ColorKey) -> (u8, [u8; 4]) { + let [v0, v1, v2, v3] = k.values; + match k.model { + 2 => (2, [v0, v1, v2, v3]), + // Red, green and blue, where the color record holds blue, green and red. + 5 | 21 => (5, [v2, v1, v0, 0]), + 9 => (9, [v0, 0, 0, 0]), + _ => (2, [100; 4]), + } +} + +/// A color entry (R56): field 1 the model and the palette, field 2 the values, as +/// [`older_fields`] gives them, then field 10, a property list: a u32 length then parts of a u8 +/// kind, a u32 length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, +/// the values; R14), and for a named color part 3, a u32 count and UTF-16 units. fn color_entry(k: &ColorKey) -> Result, Error> { let mut list = vec![1u8]; list.extend(12u32.to_le_bytes()); @@ -554,7 +570,9 @@ fn color_entry(k: &ColorKey) -> Result, Error> { } let mut rec = (list.len() as u32).to_le_bytes().to_vec(); rec.extend(list); - Ok(fields(&[field(10, &rec).ok_or(Error::Limit("table entry size"))?])) + let (model, values) = older_fields(k); + let size = || Error::Limit("table entry size"); + Ok(fields(&[field(1, &[model, 5]).ok_or_else(size)?, field(2, &values).ok_or_else(size)?, field(10, &rec).ok_or_else(size)?])) } /// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file. diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 10f41d9967..b18029fb25 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -143,11 +143,16 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// written with round corners of its radii times the square root of the scales' product, not with /// stretched corners, and is not reported. /// +/// Each color entry holds the color twice: as the property list [`read_cmx`] reads, and as the +/// model and value fields that other readers read. In those fields a spot color is written as its +/// look at its tint, and the registration color as 100 percent cyan, magenta, yellow and black. +/// /// The file holds an index, so that a reader that finds the tables and pages through it, rather /// than by their chunk ids, opens it: the header gives where the master index starts, the index /// list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the -/// page, layer and group records give their instruction counts and where they end; a group's -/// record also gives the edges of its curves. The record of a page with a size holds the edges of +/// 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 repeats the first page's edges and /// instruction count. pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs index 89e1889384..d104bb4280 100644 --- a/crates/cdr/tests/it/cmx_write.rs +++ b/crates/cdr/tests/it/cmx_write.rs @@ -283,9 +283,15 @@ fn pages_are_numbered_in_their_order() { assert_eq!(numbers, [1, 2]); } -/// Field 1 of each entry of the table chunk `id`: a u16 count, then a field list per entry (a tag, -/// a u16 length counting the 3 header bytes, the data; 0xff after the last field). +/// Field 1 of each entry of the table chunk `id`. fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { + table_fields(bytes, id).into_iter().map(|e| e.into_iter().find(|(tag, ..)| *tag == 1).map(|(.., data)| data).expect("field 1")).collect() +} + +/// The fields of each entry of the table chunk `id`, each its tag, where it starts in the file and +/// its data: a u16 count, then a field list per entry (a tag, a u16 length counting the 3 header +/// bytes, the data; 0xff after the last field). +fn table_fields(bytes: &[u8], id: &[u8; 4]) -> Vec)>> { let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8; // The chunk's body runs for the size after its id. let end = at + u32::from_le_bytes(bytes[at - 4..at].try_into().unwrap()) as usize; @@ -294,7 +300,7 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { let mut p = at + 2; let mut out = Vec::new(); for _ in 0..count { - let mut first = None; + let mut entry = Vec::new(); loop { assert!(p < end, "entry runs past the {id:?} chunk at {p}"); if bytes[p] == 0xff { @@ -304,13 +310,11 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]])); // A length shorter than its header, or past the chunk, would stop the walk. assert!(len >= 3 && p + len <= end, "field at {p} has length {len}"); - if bytes[p] == 1 { - first = Some(bytes[p + 3..p + len].to_vec()); - } + entry.push((bytes[p], p, bytes[p + 3..p + len].to_vec())); p += len; } p += 1; - out.push(first.expect("field 1")); + out.push(entry); } // The size counts the u16 count and the entries; the pad byte comes after it. assert_eq!(p, end, "{id:?} chunk has bytes left after its entries"); @@ -348,6 +352,61 @@ fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() { assert_eq!(patterns, vec![(false, vec![]), (true, vec![3, 1])]); } +#[test] +fn colors_are_also_written_in_the_model_and_value_fields() { + let colors = [ + Color::Rgb([1.0, 0.2, 0.0]), + Color::Cmyk([0.6, 0.0, 0.13, 0.05]), + Color::Gray(0.75), + Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }, + Color::Registration, + ]; + let objects = colors + .iter() + .enumerate() + .map(|(i, c)| Object::Shape(Box::new(Shape::new(square(20.0 * i as f64, 0.0, 10.0), Matrix::IDENTITY, Some(c.clone()), None)))) + .collect(); + let d = drawing(vec![Page { size: Some((200.0, 100.0)), layers: vec![layer("Art", objects)] }]); + let mut bytes = write_cmx(&d).unwrap().bytes; + let entries = table_fields(&bytes, b"rclr"); + // Each entry holds the model and the palette 5 in field 1 and four values in field 2, before + // the property list of field 10. + let mut older: Vec<(Vec, Vec)> = entries + .iter() + .map(|e| { + assert_eq!(e.iter().map(|(tag, ..)| *tag).collect::>(), [1, 2, 10]); + (e[0].2.clone(), e[1].2.clone()) + }) + .collect(); + older.sort(); + let mut want = vec![ + // Red, green and blue. + (vec![5, 5], vec![255, 51, 0, 0]), + // Cyan, magenta, yellow and black in percent. + (vec![2, 5], vec![60, 0, 13, 5]), + // Gray, 255 white. + (vec![9, 5], vec![64, 0, 0, 0]), + // The spot color's look at its tint of 40 percent. + (vec![5, 5], vec![153, 194, 235, 0]), + // The registration color as every ink at 100 percent. + (vec![2, 5], vec![100, 100, 100, 100]), + ]; + want.sort(); + assert_eq!(older, want); + // With field 10 retagged, the reader takes each color from fields 1 and 2. + for e in &entries { + bytes[e[2].1] = 11; + } + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let fills: Vec = back.pages[0].layers[0].objects.iter().map(|o| shape(o).fill.clone().unwrap()).collect(); + let opened = [colors[0].clone(), colors[1].clone(), colors[2].clone(), Color::Rgb([0.6, 0.76, 0.92]), Color::Cmyk([1.0; 4])]; + assert_eq!(fills.len(), opened.len()); + for (got, want) in fills.iter().zip(&opened) { + assert!(near_color(got, want), "{got:?} for {want:?}"); + } +} + #[test] fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() { let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]); @@ -976,16 +1035,31 @@ fn chunk_ids(b: &[u8]) -> std::collections::HashMap { ids } -/// The field list at `at` of `b`: each field's tag and where its data starts. -fn field_starts(b: &[u8], mut at: usize) -> Vec<(u8, usize)> { +/// The field list at `at` of `b`, in an instruction that ends at `end`: each field's tag and where +/// its data starts. A field shorter than its 3 header bytes, or past `end`, fails the test. +fn field_starts(b: &[u8], mut at: usize, end: usize) -> Vec<(u8, usize)> { let mut out = Vec::new(); while b[at] != 0xff { + let len = u16_at(b, at + 1); + assert!(len >= 3 && at + len <= end, "a field of length {len} at {at}, in an instruction that ends at {end}"); out.push((b[at], at + 3)); - at += u16_at(b, at + 1); + at += len; } out } +#[test] +#[should_panic(expected = "a field of length 0")] +fn a_field_of_length_0_fails_the_check() { + field_starts(&[1, 0, 0, 0xff], 0, 4); +} + +#[test] +#[should_panic(expected = "a field of length 9")] +fn a_field_past_its_instruction_fails_the_check() { + field_starts(&[1, 9, 0, 0, 0xff], 0, 5); +} + #[test] fn the_index_and_the_records_give_where_everything_is() { let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); @@ -1143,12 +1217,12 @@ fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec, Vec<(usiz let mut open: Vec = Vec::new(); let mut count = 0; while at < end { - let size = u16_at(b, at); + let size = instruction_size(b, at, end); let code = u16_at(b, at + 2); count += 1; match code { 9 | 11 | 13 => { - let f1 = field_starts(b, at + 4).iter().find(|(t, _)| *t == 1).unwrap().1; + let f1 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 1).unwrap().1; if code == 11 { seen_layers.push(at); } @@ -1159,7 +1233,7 @@ fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec, Vec<(usiz open.push((code, f1, count - 1, 0, None)); } 67 => { - let f2 = field_starts(b, at + 4).iter().find(|(t, _)| *t == 2).unwrap().1; + let f2 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 2).unwrap().1; for i in 0..u16_at(b, f2) { let p = f2 + 2 + 8 * i; let (x, y) = (u32_at(b, p) as i32, u32_at(b, p + 4) as i32); @@ -1178,6 +1252,33 @@ fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec, Vec<(usiz (seen_layers, groups) } +/// The size of the instruction at `at` of `b`, in a page that ends at `end`. These files hold +/// only short instructions, so the long form (0xFFFF), a size shorter than the 4-byte header or +/// one past `end` fails the test. +fn instruction_size(b: &[u8], at: usize, end: usize) -> usize { + let size = u16_at(b, at); + assert!(size != 0xFFFF && size >= 4 && at + size <= end, "an instruction of size {size} at {at}, in a page that ends at {end}"); + size +} + +#[test] +#[should_panic(expected = "an instruction of size 0")] +fn an_instruction_of_size_0_fails_the_check() { + instruction_size(&[0, 0, 67, 0], 0, 4); +} + +#[test] +#[should_panic(expected = "an instruction of size 65535")] +fn a_long_instruction_fails_the_check() { + instruction_size(&[0xff, 0xff, 67, 0, 8, 0, 0, 0], 0, 8); +} + +#[test] +#[should_panic(expected = "an instruction of size 8")] +fn an_instruction_past_its_page_fails_the_check() { + instruction_size(&[8, 0, 67, 0], 0, 4); +} + #[test] fn a_uniform_fill_names_the_screen_the_file_holds() { let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; diff --git a/crates/color-ui/README.md b/crates/color-ui/README.md index 9c81d3d68b..a38b1f9827 100644 --- a/crates/color-ui/README.md +++ b/crates/color-ui/README.md @@ -7,3 +7,8 @@ Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, sample Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`). The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`. + +`ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components, +even when the host renders the colour through a different working-space transform. Current host components take +precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening +colour, including its display colour, alpha and native components. diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index d647c65307..1363d82c47 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -5,7 +5,7 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; -use craft_behavior::{EditEvent, GesturePhase, IconId, Mixed}; +use craft_behavior::{EditEvent, GestureId, GesturePhase, IconId, Mixed}; use craft_cms::convert::CmykConverter; use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Srgba}; use craft_ui::buttons::IconButton; @@ -414,6 +414,8 @@ struct Kept { tracks: Vec<(&'static str, usize, ModelValues)>, /// A channel gesture is running. dragging: bool, + /// The host's complete colour before a model gesture, independent of the panel's transform. + opening: Option<(GestureId, PanelTarget, PickedColor)>, /// The ramp gesture in progress picks for the colour not edited. other: bool, } @@ -541,6 +543,8 @@ impl<'a> ColorPanel<'a> { /// The colour the rows edit, with its model values; `None` disables the rows (mixed, None, a pattern). The edited /// well's colour by default. + /// Explicit components take precedence over remembered values for their model, including when the host uses a + /// different working-space transform to render the colour. pub fn edited(mut self, color: Option) -> Self { self.edited = Some(color); self @@ -1052,12 +1056,11 @@ impl Body<'_> { /// The model's values for the edited colour, unrounded: an edit of one channel leaves the others as they are. fn values(&self, model: &dyn ColorModel) -> ModelValues { let color = self.color(); - // The host's own values of the colour (typed CMYK, a working space's numbers) stand when they give the colour. - let given = self.picked().and_then(|picked| picked.model); - let kept = self.kept.values[self.target.index()] - .iter() - .chain(given.as_ref()) - .find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); + // Current host values are authoritative: its working-space transform may differ from the panel's. + if let Some(values) = self.picked().and_then(|picked| picked.model).filter(|values| values.model == model.id()) { + return finite_values(values); + } + let kept = self.kept.values[self.target.index()].iter().find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); finite_values(kept.copied().unwrap_or_else(|| self.read(model, color))) } @@ -1096,11 +1099,39 @@ impl Body<'_> { fn model_event(&mut self, model: &dyn ColorModel, event: EditEvent) { let event = event.map(finite_values); self.kept.dragging = matches!(event.phase(), Some(GesturePhase::Begin | GesturePhase::Update)); + if let EditEvent::Begin { id, .. } = &event { + self.kept.opening = self.picked().copied().map(|picked| (*id, self.target, picked)); + } if let Some(values) = event.value() { self.remember(model, *values); } let alpha = self.color().a; - let event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) }); + let mut event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) }); + let opening = self.kept.opening.filter(|(id, target, _)| Some(*id) == event.id() && *target == self.target).map(|(_, _, picked)| picked); + match &mut event { + EditEvent::Begin { before, .. } | EditEvent::Commit { before, .. } => { + if let (Mixed::Same(value), Some(picked)) = (before, opening) { + *value = picked; + } + } + EditEvent::Cancel { before: Some(Mixed::Same(value)), .. } => { + if let Some(picked) = opening { + *value = picked; + if let Some(values) = picked.model.filter(|values| values.model == model.id()) { + self.remember(model, values); + } + } + } + EditEvent::Set { before: Mixed::Same(value), .. } => { + if let Some(picked) = self.picked() { + *value = *picked; + } + } + _ => {} + } + if matches!(event.phase(), Some(GesturePhase::Commit | GesturePhase::Cancel) | None) { + self.kept.opening = None; + } self.push(self.target, event); } diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index bb8d7a514d..6efa4a64a3 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -197,6 +197,98 @@ fn a_channel_step_keeps_the_other_channels_unrounded() { } } +/// A Color panel whose host supplies authoritative native CMYK components. +fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc>, Edits) { + let host = Rc::new(RefCell::new(picked)); + let edits: Edits = Default::default(); + let (color, output) = (host.clone(), edits.clone()); + let mut fixture = Fixture::new(move |ui| { + let picked = *color.borrow(); + let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), [picked.color; 2]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(picked)) + .shown(ColorPanelShown::Mode(ColorPanelMode::CmykSliders)) + .show(ui); + for (_, event) in &shown.edits { + if let Some(picked) = event.landed() { + *color.borrow_mut() = *picked; + } + } + output.borrow_mut().extend(shown.edits); + }); + fixture.room(COLOR_ROOM).settle(); + (fixture, host, edits) +} + +fn step_cyan(fixture: &mut Fixture) { + let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider"); + fixture.access(AccessActionKind::Focus, &cyan).settle(); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); +} + +fn last_native_pick(edits: &Edits) -> PickedColor { + edits.borrow().iter().rev().find_map(|(_, event)| event.value().copied()).expect("the channel edit") +} + +/// A host may render its native CMYK through a different working-space transform. Editing one ink still keeps +/// the other explicit components, rather than deriving them from the rendered RGB. +#[trial] +fn a_channel_edit_keeps_native_host_components_with_a_different_transform() { + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::rgb(0.2, 0.4, 0.6), native); + let (mut fixture, _, edits) = native_cmyk_panel(picked); + step_cyan(&mut fixture); + let after = last_native_pick(&edits).model.expect("native component values"); + assert!(after.values[0] > native.values[0], "Cyan changed"); + assert_eq!(&after.values[1..4], &native.values[1..4], "the other native inks stay exact"); +} + +/// Fresh host components win over remembered components even when both still give the same display pixel. +#[trial] +fn fresh_host_components_replace_the_panels_remembered_components() { + let model = craft_color_ui::CmykModel::new(craft_cms::convert::CmykConverter::coated().clone()); + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(model.to_srgb(&native.values), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + step_cyan(&mut fixture); + let kept = last_native_pick(&edits); + let mut fresh = kept.model.expect("remembered native values"); + fresh.values[1] += 0.001; + assert!(model.to_srgb(&fresh.values).same_rgb8(kept.color), "the host update keeps the display pixel"); + *host.borrow_mut() = PickedColor::in_model(kept.color, fresh); + fixture.settle(); + step_cyan(&mut fixture); + let after = last_native_pick(&edits).model.expect("the next channel edit"); + assert!(after.values[0] > fresh.values[0], "Cyan changed again"); + assert_eq!(&after.values[1..4], &fresh.values[1..4], "fresh host inks replace the older cache"); +} + +/// Cancel restores both the native inks and the host's display colour, even after the host applies live updates. +#[trial] +fn a_canceled_native_channel_drag_restores_the_hosts_original_color() { + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider"); + fixture.drag_hold_at(cyan.center(), Vec2::new(25.0, 0.0)).settle(); + assert_ne!(*host.borrow(), picked, "the host applies the live channel preview"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + let canceled = edits + .borrow() + .iter() + .rev() + .find_map(|(_, event)| match event { + EditEvent::Cancel { before: Some(Mixed::Same(before)), .. } => Some(*before), + _ => None, + }) + .expect("the channel drag cancels"); + assert_eq!(canceled, picked, "Cancel carries the host's exact opening colour and model"); + assert_eq!(*host.borrow(), picked, "the host restores the complete opening colour"); + fixture.release_at(cyan.center() + Vec2::new(25.0, 0.0)).settle(); + assert_eq!(*host.borrow(), picked, "release after Cancel cannot reapply the preview"); +} + /// The rect of the FillStroke spectrum in Web Color for a foreground of `color`. fn spectrum_rect(color: Srgba) -> egui::Rect { let mut fixture = Fixture::new(move |ui| { diff --git a/crates/control-protocol/Cargo.toml b/crates/control-protocol/Cargo.toml index f00bbc1c66..80f7d5af64 100644 --- a/crates/control-protocol/Cargo.toml +++ b/crates/control-protocol/Cargo.toml @@ -13,3 +13,7 @@ workspace = true [dependencies] serde_json = { workspace = true } subtle = "2" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The session token: 32 random bytes from the operating system (MIT OR Apache-2.0). +getrandom = "0.3" diff --git a/crates/control-protocol/src/lib.rs b/crates/control-protocol/src/lib.rs index 8194dc8e96..4bd0582853 100644 --- a/crates/control-protocol/src/lib.rs +++ b/crates/control-protocol/src/lib.rs @@ -1,7 +1,10 @@ //! Authenticated JSON-lines request framing and dispatch for local control services. #![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] use serde_json::{Value, json}; +use std::cell::Cell; use std::io::{BufRead, BufReader, BufWriter, Read, Write}; +use std::net::TcpStream; +use std::time::{Duration, Instant}; use subtle::ConstantTimeEq; /// Whether a session token has the control protocol's 64 hexadecimal character form. @@ -9,6 +12,15 @@ pub fn valid_token(token: &str) -> bool { token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()) } +/// A new session token that [`valid_token`] accepts: 32 bytes from the operating system's random +/// source, as lowercase hexadecimal. `None` when the system cannot supply random bytes. +#[cfg(not(target_arch = "wasm32"))] +pub fn new_token() -> Option { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).ok()?; + Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + /// Encode one client request, including its terminating newline. pub fn request_line(id: u64, token: Option<&str>, method: &str, params: &Value) -> String { format!("{}\n", json!({"id": id, "token": token, "method": method, "params": params})) @@ -103,9 +115,112 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usiz /// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is /// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and /// returns the reply object (the request's `id` is added here). -pub fn serve_lines(read: R, mut out: W, token: &str, max_line: usize, mut handle: impl FnMut(String, Value) -> Option) { - let mut reader = BufReader::new(read); +pub fn serve_lines(read: R, out: W, token: &str, max_line: usize, handle: impl FnMut(String, Value) -> Option) { + serve(BufReader::new(read), out, token, max_line, |_| Ok(()), |_| false, handle); +} + +/// Serve one TCP connection as [`serve_lines`] does, but give the peer `first_request` from now +/// to send its first authenticated request. Until then every read shares that one deadline, so +/// blank lines or a line sent a byte at a time do not extend it; when it passes, the connection +/// closes without a reply and nothing is dispatched. After the first authenticated request, each +/// read waits at most `idle` (`None` waits without limit). A `first_request` too long for the +/// clock to represent waits without limit. The connection is closed when this returns. +/// +/// Returns an `InvalidInput` error, before reading anything, when `first_request` or `idle` is +/// zero, and any error from setting the socket's read timeout. +pub fn serve_tcp( + stream: TcpStream, + token: &str, + max_line: usize, + first_request: Duration, + idle: Option, + handle: impl FnMut(String, Value) -> Option, +) -> std::io::Result<()> { + if first_request.is_zero() || idle.is_some_and(|d| d.is_zero()) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "control wait times must be longer than zero")); + } + let deadline = Instant::now().checked_add(first_request); + if deadline.is_none() { + // No deadline to apply on each read: clear any read timeout the stream already has. + stream.set_read_timeout(None)?; + } + let timeout_error = Cell::new(None); + let input = FirstRequestDeadline { socket: &stream, deadline, timeout_error: &timeout_error }; + serve( + BufReader::new(input), + &stream, + token, + max_line, + |input: &mut FirstRequestDeadline<'_>| input.admit(idle), + FirstRequestDeadline::expired, + handle, + ); + timeout_error.take().map_or(Ok(()), Err) +} + +/// A TCP connection's input whose reads share one deadline until the peer is admitted. +struct FirstRequestDeadline<'a> { + socket: &'a TcpStream, + deadline: Option, + /// The error from setting the socket's read timeout, which [`serve_tcp`] returns. + timeout_error: &'a Cell>, +} + +impl FirstRequestDeadline<'_> { + fn set_timeout(&self, timeout: Option) -> std::io::Result<()> { + self.socket.set_read_timeout(timeout).map_err(|e| { + let kind = e.kind(); + self.timeout_error.set(Some(e)); + kind.into() + }) + } + + /// The peer sent an authenticated request: from now on each read waits at most `idle`. A + /// request admitted after the first-request deadline returns `TimedOut` instead, and the + /// deadline stays in place. + fn admit(&mut self, idle: Option) -> std::io::Result<()> { + if self.expired() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.deadline = None; + self.set_timeout(idle) + } + + /// Whether the first-request deadline has passed and no request was admitted before it. + fn expired(&self) -> bool { + self.deadline.is_some_and(|deadline| Instant::now() >= deadline) + } +} + +impl Read for FirstRequestDeadline<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if let Some(deadline) = self.deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.set_timeout(Some(left))?; + } + let mut socket = self.socket; + socket.read(buf) + } +} + +/// The request loop of [`serve_lines`] and [`serve_tcp`]: `admit` runs once, on the input, after +/// the first authenticated request and before it is dispatched; an error from it closes the +/// connection. Before the first request is admitted, a rejection closes the connection without a +/// reply when `expired` returns true for the input. +fn serve( + mut reader: BufReader, + mut out: W, + token: &str, + max_line: usize, + mut admit: impl FnMut(&mut R) -> std::io::Result<()>, + expired: impl Fn(&R) -> bool, + mut handle: impl FnMut(String, Value) -> Option, +) { let mut buf = Vec::new(); + let mut admitted = false; loop { let reject = match read_bounded_line(&mut reader, &mut buf, max_line) { Ok(false) => return, @@ -117,6 +232,12 @@ pub fn serve_lines(read: R, mut out: W, token: &str, max_line Line::Blank => continue, Line::Reject(e) => e, Line::Request { id, method, params } => { + if !admitted { + if admit(reader.get_mut()).is_err() { + return; + } + admitted = true; + } let Some(mut r) = handle(method, params) else { return }; if let Some(o) = r.as_object_mut() { o.insert("id".into(), id); @@ -128,6 +249,9 @@ pub fn serve_lines(read: R, mut out: W, token: &str, max_line } }, }; + if !admitted && expired(reader.get_ref()) { + return; + } let _ = write_line(&mut out, &json!({"ok": false, "error": reject})); return; } @@ -249,6 +373,19 @@ mod tests { assert!(!valid_token(&"g".repeat(64))); } #[test] + #[cfg(not(target_arch = "wasm32"))] + fn new_tokens_are_valid_and_distinct() { + let first = new_token().unwrap(); + let second = new_token().unwrap(); + assert!(valid_token(&first)); + assert!(valid_token(&second)); + assert_ne!(first, second); + let input = request_line(1, Some(&first), "status", &json!({})); + let mut output = Vec::new(); + serve_lines(input.as_bytes(), &mut output, &first, 4096, |_, _| Some(json!({"ok": true}))); + assert_eq!(serde_json::from_slice::(&output).unwrap(), json!({"ok": true, "id": 1})); + } + #[test] fn authenticates_each_request_and_closes_after_failure() { let input = b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n{\"id\":2,\"method\":\"second\"}\n{\"method\":\"third\",\"token\":\"secret\"}\n"; @@ -263,6 +400,115 @@ mod tests { assert_eq!(lines[0], json!({"ok": true, "id": 1})); assert_eq!(lines[1]["error"], "control authentication failed; closing the connection"); } + /// The serving thread: what `serve_tcp` returned and the methods it dispatched. + type Server = std::thread::JoinHandle<(std::io::Result<()>, Vec)>; + /// A loopback connection whose client sent `input` before `serve_tcp` starts serving it on + /// another thread, so the server has read everything the client sends when a wait runs out. + fn tcp_session(input: &[u8], first_request: Duration, idle: Option) -> (TcpStream, Server) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + // Guards the test against a server that never closes; the assertions do not depend on it. + client.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + client.write_all(input).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let server = std::thread::spawn(move || { + let mut calls = Vec::new(); + let result = serve_tcp(stream, "secret", 1024, first_request, idle, |method, _| { + calls.push(method); + Some(json!({"ok": true})) + }); + (result, calls) + }); + (client, server) + } + #[test] + fn tcp_peer_without_a_request_loses_the_connection() { + let (mut client, server) = tcp_session(b"\n{\"method\":", Duration::from_millis(50), None); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).expect("the server closes the connection"); + assert!(rest.is_empty()); + let (result, calls) = server.join().unwrap(); + assert!(result.is_ok()); + assert!(calls.is_empty()); + } + #[test] + fn tcp_input_waiting_after_the_deadline_is_not_read() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + client.write_all(b"\n\n").unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert_eq!(input.read(&mut [0; 8]).unwrap_err().kind(), std::io::ErrorKind::TimedOut); + assert!(timeout_error.take().is_none()); + } + #[test] + fn tcp_request_read_after_the_deadline_is_not_admitted() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert_eq!(input.admit(None).unwrap_err().kind(), std::io::ErrorKind::TimedOut); + assert!(input.deadline.is_some()); + assert!(timeout_error.take().is_none()); + } + #[test] + fn rejection_read_after_the_deadline_gets_no_reply() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert!(input.expired()); + input.deadline = None; + assert!(!input.expired()); + let long = format!("{}\n", "x".repeat(100)); + for line in [&b"{broken}\n"[..], &b"{\"method\":\"x\",\"token\":\"wrong\"}\n"[..], long.as_bytes()] { + let mut out = Vec::new(); + serve(BufReader::new(line), &mut out, "secret", 64, |_| Ok(()), |_| true, |_, _| panic!("must not dispatch")); + assert!(out.is_empty()); + } + } + #[test] + fn tcp_peer_waits_idle_time_after_its_first_request() { + let input = b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n"; + let (mut client, server) = tcp_session(input, Duration::from_secs(600), Some(Duration::from_millis(50))); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).expect("the server closes the idle connection"); + assert_eq!(serde_json::from_slice::(&rest).unwrap(), json!({"ok": true, "id": 1})); + let (result, calls) = server.join().unwrap(); + assert!(result.is_ok()); + assert_eq!(calls, ["first"]); + } + #[test] + fn tcp_peer_sending_blank_lines_still_loses_the_connection_at_the_deadline() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let server = + std::thread::spawn(move || serve_tcp(stream, "secret", 1024, Duration::from_millis(200), None, |_, _| panic!("must not dispatch"))); + // Every read finds a new line, so a deadline that restarted on each read would never expire. + // The loop ends when the server closes the connection; the guard only stops a hung test. + client.set_write_timeout(Some(Duration::from_secs(30))).unwrap(); + let guard = Instant::now() + Duration::from_secs(30); + while client.write_all(b"\n").is_ok() { + assert!(Instant::now() < guard, "the server kept reading past the first-request deadline"); + std::thread::yield_now(); + } + assert!(Instant::now() < guard, "the server stopped reading but kept the connection open"); + assert!(server.join().unwrap().is_ok()); + } + #[test] + fn tcp_rejects_zero_wait_times() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + for (first, idle) in [(Duration::ZERO, None), (Duration::from_secs(1), Some(Duration::ZERO))] { + let err = serve_tcp(stream.try_clone().unwrap(), "secret", 1024, first, idle, |_, _| panic!("must not dispatch")).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + } + } #[test] fn bounds_requests_and_preserves_last_unterminated_line() { let mut buf = Vec::new(); diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index e71a0e364b..4b128a370b 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -22,9 +22,8 @@ serde_json = { workspace = true } # The loopback server is for desktop apps; the web app is driven through the page instead. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -# The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). -getrandom = "0.3" -# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours). +# The request-line reader, the reply's result and the per-launch token generator, shared with servers +# built on it (MIT OR Apache-2.0, ours). craft-control-protocol = { workspace = true } # The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). craft-ai-agents = { workspace = true, optional = true } diff --git a/crates/control/src/agents/live.rs b/crates/control/src/agents/live.rs index fd975fd283..2818e7fad6 100644 --- a/crates/control/src/agents/live.rs +++ b/crates/control/src/agents/live.rs @@ -147,6 +147,16 @@ pub struct LiveConfig { pub launch_timeout: Duration, /// How often a starting app is looked for ([`LAUNCH_POLL`]; kept between 1 ms and 1 s). pub poll: Duration, + /// The clock the launch timeout is measured on ([`Instant::now`]). + #[doc(hidden)] + pub now: Box Instant + Send + Sync>, + /// Waits one poll while a started app is looked for ([`std::thread::sleep`]). + #[doc(hidden)] + pub sleep: Box, + /// Called by each [`Live::resolve`] once it has noted how many starts have finished, before it + /// waits for the lookup. + #[doc(hidden)] + pub on_queued: Option>, consent: ConsentFn, connect: ConnectFn, headless: HeadlessFn, @@ -173,6 +183,9 @@ impl LiveConfig { launch: None, launch_timeout: LAUNCH_TIMEOUT, poll: LAUNCH_POLL, + now: Box::new(Instant::now), + sleep: Box::new(std::thread::sleep), + on_queued: None, consent: Box::new(consent), connect: Box::new(connect), headless: Box::new(headless), @@ -246,6 +259,9 @@ impl Live { /// result. pub fn resolve(&self) -> Result, String> { let queued_at = self.finished.load(Ordering::Acquire); + if let Some(queued) = &self.cfg.on_queued { + queued(); + } let mut last_failure = self.lookup.lock().unwrap_or_else(PoisonError::into_inner); let consent = (self.cfg.consent)(&self.cfg.config_dir); // Allow Agent Control off refuses agents, as the app does: it doesn't listen then. @@ -310,15 +326,15 @@ impl Live { }; launch().map_err(|e| format!("couldn't start {app}: {e}"))?; let timeout = self.cfg.launch_timeout.min(MAX_LAUNCH_TIMEOUT); - let started = Instant::now(); + let started = (self.cfg.now)(); let deadline = started.checked_add(timeout).unwrap_or(started); let poll = self.cfg.poll.clamp(POLL_RANGE.0, POLL_RANGE.1); loop { - std::thread::sleep(poll); + (self.cfg.sleep)(poll); if let Some(window) = self.find_app()? { return self.use_window(window); } - if Instant::now() >= deadline { + if (self.cfg.now)() >= deadline { return Err(format!( "{app} didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", timeout.as_secs() diff --git a/crates/control/src/agents/switch.rs b/crates/control/src/agents/switch.rs index 9165879dc3..b5cabcc7fb 100644 --- a/crates/control/src/agents/switch.rs +++ b/crates/control/src/agents/switch.rs @@ -44,7 +44,11 @@ impl AgentSwitch { if !flag { return Self::fixed(false, false); } - Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake) + let tick = || { + std::thread::sleep(POLL); + true + }; + Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), tick, wake) } /// A switch that never changes: tests, the web, an app without agents. @@ -52,14 +56,20 @@ impl AgentSwitch { Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) } } - /// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`. + /// [`Self::watch`] with the flag given and `probe` asked once now. The watch thread then calls + /// `tick`, which returns when the next poll is due ([`Self::watch`] sleeps [`POLL`]), and asks + /// `probe` again; the watch ends when `tick` returns `false`. #[doc(hidden)] - pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: impl Fn() + Send + 'static) -> Self { + pub fn watch_with( + mcp_flag: bool, + probe: impl Fn() -> bool + Send + 'static, + mut tick: impl FnMut() -> bool + Send + 'static, + wake: impl Fn() + Send + 'static, + ) -> Self { let on = Arc::new(AtomicBool::new(probe())); let seen: Weak = Arc::downgrade(&on); let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { - loop { - std::thread::sleep(poll); + while tick() { let now = probe(); let Some(seen) = seen.upgrade() else { return }; if seen.swap(now, Ordering::Relaxed) != now { diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index e20bada163..32f757ac8e 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -4,11 +4,12 @@ use super::*; use crate::ControlRequest; use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; use socket2::{Domain, Socket, Type}; +use std::cell::RefCell; use std::ffi::OsString; use std::net::TcpListener; use std::path::PathBuf; use std::sync::Arc; -use std::sync::mpsc::channel; +use std::sync::mpsc::{Receiver, Sender, channel}; const TOKEN: &str = "0123456789abcdef0123456789abcdef"; @@ -51,22 +52,17 @@ impl Protocol for Probe { } } -/// The app on `port` (0: an ephemeral one) behind [`TOKEN`]: its window answers each request after -/// `delay` with the request's method and parameters, and the server says a request is still -/// running after `wait`. -fn serve(port: u16, delay: Duration, wait: Duration) -> Stop { - // A port just closed may take a moment to be free again on a loaded machine. - let started = Instant::now(); - let mut bound = TcpListener::bind(("127.0.0.1", port)); - while bound.is_err() && started.elapsed() < Duration::from_secs(2) { - std::thread::sleep(Duration::from_millis(10)); - bound = TcpListener::bind(("127.0.0.1", port)); - } - let listener = bound.unwrap(); +/// The app on `listener` behind [`TOKEN`]: its window answers each request with the request's +/// method and parameters. With a `gate`, it answers each request only once the gate is opened (a +/// message, or the sender dropped), and the server says at once that the request is still running. +fn serve(listener: TcpListener, gate: Option>) -> Stop { + let wait = if gate.is_some() { Duration::ZERO } else { Duration::from_secs(10) }; let (tx, rx) = channel::(); std::thread::spawn(move || { for req in rx { - std::thread::sleep(delay); + if let Some(gate) = &gate { + let _ = gate.recv(); + } let _ = req.reply.send(json!({"ok": true, "result": {"method": req.method, "params": req.params}})); } }); @@ -75,6 +71,60 @@ fn serve(port: u16, delay: Duration, wait: Duration) -> Stop { hub.listen_stoppable(listener, TOKEN.into(), tx, false).unwrap() } +/// A listener on an ephemeral loopback port. +fn any_port() -> TcpListener { + TcpListener::bind("127.0.0.1:0").unwrap() +} + +/// `port` bound as [`TcpListener::bind`] binds it, but not listening yet: the port stays held, and +/// a connection to it is refused until [`listen`]. A listener just stopped may still hold the port +/// on a loaded machine ([`Stop::stop`] waits at most a couple of seconds), so the bind is retried +/// for up to two seconds. +fn hold(port: u16) -> Socket { + let started = Instant::now(); + hold_after(port, || { + if started.elapsed() >= Duration::from_secs(2) { + return false; + } + std::thread::sleep(Duration::from_millis(10)); + true + }) +} + +/// [`hold`], calling `busy` each time the port is still taken; the bind is tried again while +/// `busy` returns true. +fn hold_after(port: u16, mut busy: impl FnMut() -> bool) -> Socket { + let address = std::net::SocketAddr::from(([127, 0, 0, 1], port)).into(); + loop { + let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap(); + #[cfg(not(windows))] + socket.set_reuse_address(true).unwrap(); + match socket.bind(&address) { + Ok(()) => return socket, + Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && busy() => {} + Err(e) => panic!("binding 127.0.0.1:{port}: {e}"), + } + } +} + +fn listen(socket: Socket) -> TcpListener { + socket.listen(128).unwrap(); + socket.into() +} + +thread_local! { + /// Opened by [`open_gate`] when the client first reports a wait. + static GATE: RefCell>> = const { RefCell::new(None) }; +} + +/// A client's progress report: the app said its request is still running, so its window may +/// answer now. +fn open_gate(_: &str) { + if let Some(gate) = GATE.with(|g| g.borrow_mut().take()) { + let _ = gate.send(()); + } +} + fn addr(port: u16) -> String { format!("127.0.0.1:{port}") } @@ -91,7 +141,7 @@ fn reserve_non_listening_port() -> (Socket, u16) { #[test] fn a_call_is_one_round_trip_with_the_token() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); assert!(!c.is_connected()); let r = c.call(Request::new("document.inspect", json!({"a": 1}))).unwrap(); @@ -109,7 +159,7 @@ fn a_call_is_one_round_trip_with_the_token() { #[test] fn a_wrong_token_or_none_is_refused() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); for token in [Some("fedcba9876543210fedcba9876543210"), None] { let mut c = Connection::new(APP, &addr(app.port()), token); match c.call(Request::new("document.inspect", json!({}))) { @@ -139,20 +189,36 @@ fn the_not_running_fixture_keeps_its_port_from_another_listener() { drop(reserved); } +/// A port a listener still holds is bound once that listener closes, not refused at the first try. +#[test] +fn holding_a_port_waits_for_the_listener_on_it_to_close() { + let mut listener = Some(any_port()); + let port = listener.as_ref().unwrap().local_addr().unwrap().port(); + let mut tries = 0; + let held = hold_after(port, || { + tries += 1; + listener.take().is_some() + }); + assert_eq!(tries, 1, "the port was free while its listener was open"); + assert_eq!(held.local_addr().unwrap().as_socket().unwrap().port(), port); +} + /// An app that goes away during a call is lost, not "not running"; the next call says it is not /// running, and once it runs again the next call reaches it. #[test] fn an_app_gone_during_a_call_is_lost_and_reached_again_once_back() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); let port = app.port(); let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); c.call(Request::new("document.inspect", json!({}))).unwrap(); app.stop(); + // Held, not listening, until the app is back, so no other listener takes the port meanwhile. + let held = hold(port); let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err(); let CallError::Lost(m) = &e else { panic!("{e:?}") }; assert!(m.contains("may have quit") && m.contains("Inspect the design") && m.contains(&format!("`probe --control {port}`")), "{m}"); assert!(matches!(c.call(Request::new("document.inspect", json!({}))), Err(CallError::NotRunning(_)))); - let _back = serve(port, Duration::ZERO, Duration::from_secs(10)); + let _back = serve(listen(held), None); assert_eq!(c.call(Request::new("ui.view", json!({}))).unwrap()["method"], json!("ui.view")); } @@ -178,10 +244,13 @@ fn a_connection_closed_without_a_reply_is_lost() { /// connection, and its own reply is the call's result. #[test] fn a_request_still_running_is_waited_for_through_pending() { - let app = serve(0, Duration::from_millis(400), Duration::from_millis(50)); - let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); + let (gate, held) = channel(); + let app = serve(any_port(), Some(held)); + GATE.with(|g| *g.borrow_mut() = Some(gate)); + let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)).with_progress(open_gate); c.set_waits(Waits { pending: Duration::from_secs(10), settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); let r = c.call(Request::new("solid.slow", json!({"n": 2}))).unwrap(); + assert!(GATE.with(|g| g.borrow().is_none()), "the app never said the request was still running"); assert_eq!(r, json!({"method": "solid.slow", "params": {"n": 2}})); assert!(!c.has_outstanding()); assert_eq!(c.pending(), json!({"pending": null})); @@ -190,15 +259,17 @@ fn a_request_still_running_is_waited_for_through_pending() { /// Past the wait, the call says the request is still running, and `pending` later has its end. #[test] fn a_request_still_running_past_the_wait_is_reported_and_its_end_kept() { - let app = serve(0, Duration::from_millis(400), Duration::from_millis(20)); + let (gate, held) = channel(); + let app = serve(any_port(), Some(held)); let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)); - c.set_waits(Waits { pending: Duration::from_millis(30), settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); + c.set_waits(Waits { pending: Duration::ZERO, settle: Duration::from_secs(10), poll: Duration::from_millis(5) }); let mut slow = Request::new("solid.slow", json!({})); slow.what = "`solid.slow` (now)".into(); let e = c.call(slow).unwrap_err(); let CallError::StillRunning(m) = &e else { panic!("{e:?}") }; assert!(m.starts_with(STILL_RUNNING) && m.contains("`solid.slow` (now)") && m.contains("will still apply"), "{m}"); assert!(c.has_outstanding()); + gate.send(()).unwrap(); let end = c.pending(); assert_eq!(end["done"], json!(true), "{end}"); assert_eq!(end["reply"]["result"]["method"], json!("solid.slow"), "{end}"); diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs index a276060c81..1346d68d89 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -7,7 +7,7 @@ use std::io::{BufRead, BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; -use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; use craft_control_protocol::ReadFailure; @@ -60,11 +60,16 @@ pub struct Hub { /// Longest request line accepted. max_line: usize, waits: Waits, + clock: Clock, watch: &'static DocumentWatch, running: Arc, open: AtomicUsize, } +/// The time a connection's token deadline is measured on: [`Instant::now`], or a clock a test +/// moves. +pub type Clock = Arc Instant + Send + Sync>; + impl Hub { /// A server for `protocol`'s requests; `wake` makes the window look at its requests now. pub fn new(protocol: impl Protocol + 'static, wake: impl Fn() + Send + Sync + 'static, max_line: usize) -> Self { @@ -73,6 +78,7 @@ impl Hub { wake: Box::new(wake), max_line, waits: Waits::default(), + clock: Arc::new(Instant::now), watch: &DOCUMENT_WATCH, running: Arc::new(Running::new()), open: AtomicUsize::new(0), @@ -85,6 +91,12 @@ impl Hub { self } + /// Another clock for the token deadline than [`Instant::now`] (tests). + pub fn with_clock(mut self, clock: Clock) -> Self { + self.clock = clock; + self + } + /// Another document watch than the app's [`DOCUMENT_WATCH`] (tests). pub fn with_watch(mut self, watch: &'static DocumentWatch) -> Self { self.watch = watch; @@ -187,12 +199,17 @@ impl Stop { } /// Stop accepting, close the port and end every connection it accepted. Returns once the - /// port is closed (at most a couple of seconds), so the same port can be bound again at once. + /// port is closed, so the same port can be bound again at once. When no connection can be + /// made to wake the listener, it waits at most two seconds for the port to close. pub fn stop(self) { self.shared.stopped.store(true, Ordering::SeqCst); - // The listener waits in `accept`: a connection of our own wakes it to see the flag. - let _ = TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)); - let _ = self.closed.recv_timeout(Duration::from_secs(2)); + // The listener waits in `accept`: a connection of our own wakes it to see the flag. Once + // that connection is made, the listener accepts it and ends however busy the machine is. + if TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)).is_ok() { + let _ = self.closed.recv(); + } else { + let _ = self.closed.recv_timeout(Duration::from_secs(2)); + } self.shared.close_all(); } } @@ -209,12 +226,9 @@ const EVENT_GAP: Duration = Duration::from_millis(100); /// [`MAX_CONNECTIONS`] goes to someone else. const TOKEN_WAIT: Duration = Duration::from_secs(5); -/// A new random token: 32 bytes from the operating system, as hex. -pub fn new_token() -> Option { - let mut bytes = [0u8; 32]; - getrandom::fill(&mut bytes).ok()?; - Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) -} +/// A new random token: 32 bytes from the operating system, as hex. The generator lives in +/// [`craft_control_protocol`], so this crate and servers built on that crate make the same tokens. +pub use craft_control_protocol::new_token; /// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read /// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes, not @@ -283,7 +297,8 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader, docs: &str) use std::io::Read; let _ = send(out, &unauthorized(docs)); let _ = out.shutdown(std::net::Shutdown::Write); - reader.get_mut().deadline = Some(Instant::now() + Duration::from_millis(500)); + let input = reader.get_mut(); + input.deadline = Some((input.clock)() + Duration::from_millis(500)); let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); } @@ -293,6 +308,8 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader, docs: &str) struct ClientInput { socket: TcpStream, deadline: Option, + /// What the deadline is measured on. + clock: Clock, } impl ClientInput { @@ -306,7 +323,7 @@ impl ClientInput { impl std::io::Read for ClientInput { 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::ErrorKind::TimedOut.into()); } @@ -402,6 +419,8 @@ fn cancel(pending: &mut Option, late: Option, id: Option<&Value> /// a running request. struct Running { list: Mutex>, + /// Notified each time a request leaves the list. + left: Condvar, connections: AtomicU64, keys: AtomicU64, } @@ -420,7 +439,7 @@ struct InFlight { impl Running { fn new() -> Self { - Running { list: Mutex::new(Vec::new()), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } + Running { list: Mutex::new(Vec::new()), left: Condvar::new(), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } } fn lock(&self) -> MutexGuard<'_, Vec> { @@ -482,6 +501,7 @@ impl Drop for Listing { fn drop(&mut self) { let key = self.key; self.running.lock().retain(|e| e.key != key); + self.running.left.notify_all(); } } @@ -660,7 +680,8 @@ impl Hub { let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1; let Ok(read) = stream.try_clone() else { return }; let mut out = stream; - let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(Instant::now() + waits.token) }); + let clock = Arc::clone(&self.clock); + let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(clock() + waits.token), clock }); let mut bad = 0usize; let mut authenticated = false; let mut pending: Option = None; @@ -844,6 +865,52 @@ mod tests { Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_watch(watch)) } + /// [`Plain`], except that only `slow` and `queued` take the short wait. + struct Holding; + + impl Protocol for Holding { + fn summary(&self, method: &str, params: &Value) -> Summary { + Summary { long: !matches!(method, "slow" | "queued"), ..Plain.summary(method, params) } + } + fn document(&self) -> &'static str { + Plain.document() + } + fn change_event(&self) -> &'static str { + Plain.change_event() + } + fn revision_method(&self) -> &'static str { + Plain.revision_method() + } + fn docs(&self) -> &'static str { + Plain.docs() + } + fn capabilities(&self) -> Value { + Plain.capabilities() + } + } + + /// A server for [`Holding`] whose test window holds `slow` and `queued` back: they time out at + /// once, as neither has its reply yet, and every other request waits for its reply. The hour + /// only stops a hung test. + fn holding_hub() -> Arc { + let waits = Waits { short: Duration::ZERO, long: Duration::from_secs(3600), token: TOKEN_WAIT }; + Arc::new(Hub::new(Holding, || {}, MAX_LINE).with_waits(waits)) + } + + /// Wait until `hub` lists no request in `control.running`. A request that timed out leaves the + /// list once its connection's `control.pending` has its reply. Each wait ends when the list + /// tells the test that a request left it; one that runs out its ten seconds fails the test, + /// even if the list has emptied since without telling it. + fn wait_until_nothing_runs(hub: &Hub) { + let mut list = hub.running.lock(); + while !list.is_empty() { + let (now, waited) = hub.running.left.wait_timeout(list, Duration::from_secs(10)).unwrap_or_else(PoisonError::into_inner); + list = now; + assert!(!waited.timed_out(), "no request was reported leaving the list"); + } + assert!(list.is_empty(), "a request still runs"); + } + /// The channel never goes on the network: a listener on any address but loopback is refused, /// and nothing is served on it. #[test] @@ -863,55 +930,91 @@ mod tests { fn the_token_has_a_time_limit_and_an_authenticated_client_may_idle() { use std::io::Read; let token = "0123456789abcdef0123456789abcdef"; - let limit = Duration::from_millis(500); - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let (tx, rx) = channel::(); - std::thread::spawn(move || { - for req in rx { - let _ = req.reply.send(json!({"ok": true, "result": req.method})); - } - }); - let waits = Waits { short: Duration::from_secs(10), long: Duration::from_secs(10), token: limit }; - let hub = hub(waits, &DOCUMENT_WATCH); - std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); - std::thread::spawn(move || hub.serve(stream, token, tx, false)); - } - }); - let open = || { - let s = TcpStream::connect(addr).unwrap(); - s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); - s - }; - // Sends `drip` every 50 ms until the server closes; what it read, and when it closed. - let closed_after = |drip: &[u8]| { - let mut s = open(); + let limit = Duration::from_secs(3600); + // A server for one connection, whose clock stands still until the test moves it with the + // returned `at` (the time since the connection's deadline was set). It returns once that + // deadline is set: the clock's first reading. + let serve_one = |limit: Duration| { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); let start = Instant::now(); - s.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let now = Arc::new(Mutex::new(start)); + let (read_tx, read) = channel::<()>(); + let clock: Clock = { + let now = Arc::clone(&now); + Arc::new(move || { + let t = *now.lock().unwrap(); + // Told only once the time is read, so the test moves the clock after it. + let _ = read_tx.send(()); + t + }) + }; + let waits = Waits { short: Duration::from_secs(3600), long: Duration::from_secs(3600), token: limit }; + let hub = Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_clock(clock)); + std::thread::spawn(move || { + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + } + }); + let s = TcpStream::connect(addr).unwrap(); + // Only stops a hung test. + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + read.recv_timeout(Duration::from_secs(20)).expect("the connection's deadline is set"); + let at = move |after: Duration| *now.lock().unwrap() = start + after; + (s, at) + }; + // What the server sent until it closed the connection. + let until_closed = |s: &mut TcpStream| { let mut got = Vec::new(); loop { let mut buf = [0u8; 256]; match s.read(&mut buf) { Ok(0) => break, Ok(n) => got.extend_from_slice(buf.get(..n).unwrap()), - Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { - assert!(start.elapsed() < Duration::from_secs(20), "still open"); - let _ = s.write_all(drip); + Err(e) => { + assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "still open"); + break; } - Err(_) => break, } } - (got, start.elapsed()) + got }; - for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] { - let (got, took) = closed_after(drip); + // A connection that sends nothing is closed when the limit runs out on the socket's own + // read timeout, without a word. + let (mut s, _) = serve_one(Duration::from_millis(100)); + let got = until_closed(&mut s); + assert!(got.is_empty(), "a silent connection was answered: {}", String::from_utf8_lossy(&got)); + for drip in [&b"\n"[..], b"\r\n \n", b" ", b"{"] { + // Once the limit has passed, the next thing sent closes the connection without a + // word, however the time before it was filled. + let (mut s, at) = serve_one(limit); + s.write_all(drip).unwrap(); + at(limit / 2); + s.write_all(drip).unwrap(); + at(limit); + let _ = s.write_all(drip); + let got = until_closed(&mut s); assert!(got.is_empty(), "{drip:?} was answered: {}", String::from_utf8_lossy(&got)); - assert!(took >= limit.saturating_sub(Duration::from_millis(50)), "{drip:?} closed after {took:?}"); + // Before the limit, the connection is still open: a request finished then is answered. + // A `{` is the request's own first byte. + let request = format!("{}\n", json!({"id": 1, "method": "ui.view", "token": token})); + let rest = request.strip_prefix(std::str::from_utf8(drip).unwrap()).unwrap_or(&request); + let (mut s, at) = serve_one(limit); + s.write_all(drip).unwrap(); + at(limit - Duration::from_secs(60)); + s.write_all(rest.as_bytes()).unwrap(); + let mut l = String::new(); + BufReader::new(&s).read_line(&mut l).unwrap(); + assert!(serde_json::from_str::(&l).is_ok_and(|r| r["ok"] == true), "{drip:?} closed before the limit: {l}"); } - let mut s = open(); + let (mut s, at) = serve_one(limit); let mut lines = BufReader::new(s.try_clone().unwrap()); let mut ask = |line: Value| -> Value { writeln!(s, "{line}").unwrap(); @@ -920,11 +1023,11 @@ mod tests { serde_json::from_str(&l).unwrap() }; assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true); - std::thread::sleep(limit * 3); + at(limit * 3); assert_eq!(ask(json!({"id": 2, "method": "ui.view"}))["ok"], true, "idle for longer than the limit"); // A wrong token is still answered, at once. - let mut wrong = open(); + let (mut wrong, _) = serve_one(limit); writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap(); let mut l = String::new(); BufReader::new(wrong).read_line(&mut l).unwrap(); @@ -942,6 +1045,8 @@ mod tests { let addr = listener.local_addr().unwrap(); let (tx, rx) = channel::(); let (gate_tx, gate_rx) = channel::<()>(); + // `()` once the window has taken `slow` to run it. + let (started_tx, started) = channel::<()>(); let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); let seen = ran.clone(); // A stand-in for the window thread: `queued` waits behind the others (never taken until @@ -958,6 +1063,7 @@ mod tests { } seen.lock().unwrap().push(req.method.clone()); if req.method == "slow" { + let _ = started_tx.send(()); let _ = gate_rx.recv(); } let _ = req.reply.send(json!({"ok": true, "result": req.method})); @@ -970,11 +1076,11 @@ mod tests { } } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; - let hub = hub(waits, &DOCUMENT_WATCH); + let hub = holding_hub(); + let server = Arc::clone(&hub); std::thread::spawn(move || { for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + let (tx, hub) = (tx.clone(), Arc::clone(&server)); std::thread::spawn(move || hub.serve(stream, token, tx, false)); } }); @@ -1007,6 +1113,8 @@ mod tests { // Already running in the app: it can't be, and it still answers. let r = ask(&mut a, json!({"id": 4, "method": "slow"})); assert_eq!(r["running"], true, "{r}"); + // The ten seconds only stop a hung test. + started.recv_timeout(Duration::from_secs(10)).expect("the window took `slow`"); let r = ask(&mut b, json!({"id": 2, "method": "control.cancel", "params": {"id": 4}})); assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.contains("its own requests")), "another connection's: {r}"); let r = ask(&mut a, json!({"id": 5, "method": "control.cancel", "params": {"id": 99}})); @@ -1015,14 +1123,8 @@ mod tests { assert!(r["ok"] == false && r["cancellable"] == false, "{r}"); assert!(r["error"].as_str().is_some_and(|e| e.starts_with("cannot be cancelled") && e.contains("control.pending")), "{r}"); gate_tx.send(()).unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - let r = loop { - let r = ask(&mut a, json!({"id": 7, "method": "control.pending"})); - if r["result"]["done"] == true || Instant::now() > deadline { - break r; - } - std::thread::sleep(Duration::from_millis(10)); - }; + wait_until_nothing_runs(&hub); + let r = ask(&mut a, json!({"id": 7, "method": "control.pending"})); assert_eq!(r["result"]["reply"]["result"], "slow", "{r}"); let r = ask(&mut a, json!({"id": 8, "method": "control.cancel"})); assert!(r["ok"] == true && r["result"]["cancelled"].is_null(), "{r}"); @@ -1052,11 +1154,11 @@ mod tests { let _ = req.reply.send(json!({"ok": true, "result": req.method})); } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; - let hub = hub(waits, &DOCUMENT_WATCH); + let hub = holding_hub(); + let server = Arc::clone(&hub); std::thread::spawn(move || { if let Some(stream) = listener.incoming().flatten().next() { - hub.serve(stream, token, tx, false); + server.serve(stream, token, tx, false); } }); let s = TcpStream::connect(addr).unwrap(); @@ -1076,14 +1178,8 @@ mod tests { let r = ask(json!({"id": 3, "method": "control.pending"})); assert_eq!((&r["result"]["pending"], &r["result"]["done"]), (&json!(1), &json!(false)), "{r}"); gate_tx.send(()).unwrap(); - let deadline = std::time::Instant::now() + Duration::from_secs(10); - let r = loop { - let r = ask(json!({"id": 4, "method": "control.pending"})); - if r["result"]["done"] == true || std::time::Instant::now() > deadline { - break r; - } - std::thread::sleep(Duration::from_millis(10)); - }; + wait_until_nothing_runs(&hub); + let r = ask(json!({"id": 4, "method": "control.pending"})); assert_eq!( (&r["result"]["pending"], &r["result"]["done"], &r["result"]["reply"]["result"]), (&json!(1), &json!(true), &json!("slow")), @@ -1122,10 +1218,15 @@ mod tests { } }); let hub = hub(Waits::default(), &WATCH); + // `()` each time a connection's own thread is done with it. + let (ended_tx, ended) = channel::<()>(); std::thread::spawn(move || { for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); - std::thread::spawn(move || hub.serve(stream, token, tx, false)); + let (tx, hub, ended) = (tx.clone(), Arc::clone(&hub), ended_tx.clone()); + std::thread::spawn(move || { + hub.serve(stream, token, tx, false); + let _ = ended.send(()); + }); } }); let open = || { @@ -1176,18 +1277,10 @@ mod tests { assert_eq!(next(&mut lines), json!({"id": 3, "ok": true, "result": "ui.view"})); writeln!(quiet_out, "{}", json!({"id": 2, "method": "ui.view"})).unwrap(); assert_eq!(next(&mut quiet), json!({"id": 2, "ok": true, "result": "ui.view"}), "no events without subscribing"); - // Closed, it is no longer counted. Each publish asks the events thread for one more line, - // and its write to the closed connection is what retires the seat; that keeps the wait off - // the connection's own thread, which anything else this process is doing may hold up past - // the deadline (#7226). + // Closed, it is no longer counted once its own thread is done with it (the quiet one is + // still open). The ten seconds only stop a hung test. drop((out, lines)); - let mut revision = 11; - let deadline = Instant::now() + Duration::from_secs(10); - while WATCH.subscribed() && Instant::now() < deadline { - WATCH.publish("d-1", revision); - revision += 1; - std::thread::sleep(Duration::from_millis(20)); - } + ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended"); assert!(!WATCH.subscribed()); } @@ -1215,10 +1308,12 @@ mod tests { } }); let hub = hub(Waits::default(), &WATCH); + // `()` once the connection's own thread is done with it. + let (ended_tx, ended) = channel::<()>(); std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); - std::thread::spawn(move || hub.serve(stream, token, tx, false)); + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + let _ = ended_tx.send(()); } }); let s = TcpStream::connect(addr).unwrap(); @@ -1231,18 +1326,47 @@ mod tests { let reply: Value = serde_json::from_str(&l).unwrap(); assert!(reply["ok"] == true, "{reply}"); assert!(WATCH.subscribed(), "the connection is subscribed"); - // Let the events thread settle into its wait: the design stands still, so it has nothing - // to write, and only the end of the connection can retire it. - std::thread::sleep(Duration::from_millis(200)); - // The client goes away without asking anything else. + // The client goes away without asking anything else. The design stands still, so the + // events thread has nothing to write: the seat must be gone when the connection's own + // thread is done, not when the events thread next wakes. The ten seconds only stop a hung + // test. drop((out, lines)); - let deadline = Instant::now() + Duration::from_millis(400); - while WATCH.subscribed() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); - } + ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended"); assert!(!WATCH.subscribed(), "a closed connection is not counted on the watch"); } + /// #7226: the events thread leaves the watch at the first write its socket refuses, while the + /// connection's own thread still holds the seat and has not seen the end of the stream. + #[test] + fn the_events_thread_leaves_the_watch_when_a_write_fails() { + static WATCH: DocumentWatch = DocumentWatch::new(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (socket, _) = listener.accept().unwrap(); + // The socket takes no more writes, as one to a client that closed: the next line fails. + socket.shutdown(std::net::Shutdown::Write).unwrap(); + let lines = Arc::new(Lines { socket, turn: Mutex::new(()) }); + let stop = Arc::new(AtomicBool::new(false)); + WATCH.publish("d-1", 3); + let seat = Arc::new(Seat::new(WATCH.join())); + // The connection's own thread, which keeps its share of the seat throughout. + let held = Arc::clone(&seat); + assert!(WATCH.subscribed(), "the connection is subscribed"); + // `()` once the events thread has ended. + let (ended_tx, ended) = channel::<()>(); + let (l, s) = (Arc::clone(&lines), Arc::clone(&stop)); + std::thread::spawn(move || { + send_events(&WATCH, "design.changed", &l, &s, ("d-1".to_string(), 3), seat); + let _ = ended_tx.send(()); + }); + WATCH.publish("d-1", 4); + // The ten seconds only stop a hung test. + ended.recv_timeout(Duration::from_secs(10)).expect("the events thread ended at the failed write"); + assert!(!stop.load(Ordering::Relaxed), "nothing stopped the events thread but the write"); + assert!(!WATCH.subscribed(), "the seat left with the events thread"); + drop((held, client)); + } + /// The token is read from a request object without building the rest of it: other fields, /// however large or nested, are only skipped. Anything but an object with a string token is /// no token. @@ -1449,19 +1573,26 @@ mod tests { #[test] fn a_stopped_listener_closes_its_port_and_its_connections() { use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); let port = listener.local_addr().unwrap().port(); - let (tx, _rx) = channel(); - let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, "0123456789abcdef0123456789abcdef".into(), tx, false).unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, token.into(), tx, false).unwrap(); assert_eq!(stop.port(), port); let mut client = TcpStream::connect(("127.0.0.1", port)).unwrap(); - client.set_read_timeout(Some(Duration::from_secs(4))).unwrap(); - // Wait until the server holds the connection, so stopping has one to close. - let held = Instant::now(); - while stop.shared.lock().is_empty() && held.elapsed() < Duration::from_secs(4) { - std::thread::sleep(Duration::from_millis(5)); - } - let started = Instant::now(); + // Only stops a hung test. + client.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + // Once its first request is answered, the server holds the connection, so stopping has one + // to close. It has shown the token, so the token wait cannot end it: only stopping can. + writeln!(client, "{}", json!({"id": 1, "method": "ui.view", "token": token})).unwrap(); + let mut l = String::new(); + BufReader::new(&client).read_line(&mut l).unwrap(); + assert!(serde_json::from_str::(&l).is_ok_and(|r| r["ok"] == true), "{l}"); stop.stop(); let mut byte = [0u8; 1]; match client.read(&mut byte) { @@ -1470,15 +1601,8 @@ mod tests { assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "the connection ends, not waits: {e}") } } - assert!(started.elapsed() < Duration::from_secs(3), "before the token wait runs out"); - // The listener thread closes its socket when it notices the stop; on a loaded machine that can - // take a moment after `stop()` returns. Wait for the port to be free, not for one instant. - let freed = Instant::now(); - let mut bound = TcpListener::bind(("127.0.0.1", port)); - while bound.is_err() && freed.elapsed() < Duration::from_secs(2) { - std::thread::sleep(Duration::from_millis(10)); - bound = TcpListener::bind(("127.0.0.1", port)); - } + // `stop` returns once the port is closed. + let bound = TcpListener::bind(("127.0.0.1", port)); assert!(bound.is_ok(), "the port is free again: {:?}", bound.err()); } } diff --git a/crates/control/tests/agents.rs b/crates/control/tests/agents.rs index 5dfaa90c27..5895caf8df 100644 --- a/crates/control/tests/agents.rs +++ b/crates/control/tests/agents.rs @@ -6,7 +6,7 @@ use std::net::TcpListener; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; use craft_control::agents::{ @@ -18,18 +18,6 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = Instant::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; - } - std::thread::sleep(Duration::from_millis(5)); - } - true -} - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; /// Writes `text` as an owner-only token file, as an app's own token writer does. @@ -65,19 +53,53 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than -/// once per poll, and its thread ends once the last clone is dropped. +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns +/// once the thread has finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run + // that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), + } + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() + } +} + +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather +/// than once per poll, and its thread ends at the first poll after the last clone is dropped. #[test] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); let probes = Arc::new(AtomicUsize::new(0)); let wakes = Arc::new(AtomicUsize::new(0)); - // Held by the watch thread through its probe: gone once the thread has ended. - let alive = Arc::new(()); let probe = { - let (launcher, probes, alive) = (launcher.clone(), probes.clone(), alive.clone()); + let (launcher, probes) = (launcher.clone(), probes.clone()); move || { - let _ = &alive; probes.fetch_add(1, Ordering::Relaxed); launcher.load(Ordering::Relaxed) } @@ -88,26 +110,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + // Many polls with nothing changed. + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - assert!(wait_for(|| Arc::strong_count(&alive) == 1), "the watch ended with the last switch"); - let after_end = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(20)); - assert_eq!(probes.load(Ordering::Relaxed), after_end, "nothing probes after the watch ended"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } // ---- The connection file ------------------------------------------------------------------------ @@ -238,6 +269,21 @@ fn paths(p: &[&str]) -> Vec { p.iter().map(PathBuf::from).collect() } +/// Gives `cfg`'s launch wait a clock that moves only when the wait sleeps: each sleep calls +/// `gate`, then adds its length to the time and returns. Returns the lengths slept. +fn virtual_clock(cfg: &mut LiveConfig, gate: impl Fn() + Send + Sync + 'static) -> Arc>> { + let slept = Arc::new(Mutex::new(Vec::new())); + let start = Instant::now(); + let s = slept.clone(); + cfg.now = Box::new(move || start + s.lock().unwrap().iter().sum::()); + let s = slept.clone(); + cfg.sleep = Box::new(move |d| { + gate(); + s.lock().unwrap().push(d); + }); + slept +} + /// An app accepting agents takes the call; the same port, token and process keep the client, a /// restarted app (another process on the same port and token) gets a new one. #[test] @@ -444,8 +490,10 @@ fn a_launch_that_cannot_happen_or_never_finishes_says_what_to_do() { let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); cfg.launch = Some(Box::new(|| Ok(()))); cfg.launch_timeout = Duration::from_millis(40); + let slept = virtual_clock(&mut cfg, || {}); let err = TestLive::new(cfg).resolve().err().unwrap(); assert!(err.starts_with("Test didn't accept agents within 0 s of starting."), "{err}"); + assert_eq!(*slept.lock().unwrap(), [Duration::from_millis(5); 8], "the app is looked for every poll until the timeout"); } /// "Launch" starts the app once, also for calls that arrive together, and the calls go to its @@ -455,19 +503,24 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { let dir = temp_dir("launch"); let made = Arc::new(Made::default()); let launches = Arc::new(AtomicUsize::new(0)); - let app: Arc>> = Arc::new(Mutex::new(None)); let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); - let (d, n, slot) = (dir.path().to_path_buf(), launches.clone(), app.clone()); + let (queued_tx, queued) = mpsc::channel(); + cfg.on_queued = Some(Box::new(move || { + let _ = queued_tx.send(()); + })); + let (launched_tx, launched) = mpsc::channel(); + let n = launches.clone(); cfg.launch = Some(Box::new(move || { n.fetch_add(1, Ordering::Relaxed); - let (d, slot) = (d.clone(), slot.clone()); - // The app takes a moment before it accepts agents. - std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(60)); - *slot.lock().unwrap() = Some(publish(&d).0); - }); + let _ = launched_tx.send(()); Ok(()) })); + // The started app's first poll waits until the test has published the app. + let (open, opened) = mpsc::channel::<()>(); + let opened = Mutex::new(opened); + virtual_clock(&mut cfg, move || { + let _ = opened.lock().unwrap().recv(); + }); let live = Arc::new(TestLive::new(cfg)); let calls: Vec<_> = (0..4) .map(|_| { @@ -475,6 +528,13 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { std::thread::spawn(move || window(live.resolve())) }) .collect(); + // Every call is under way before the app is started and accepts agents. + for _ in 0..4 { + queued.recv().unwrap(); + } + launched.recv().unwrap(); + let _app = publish(dir.path()); + drop(open); let ports: Vec = calls.into_iter().map(|c| c.join().unwrap().port).collect(); assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for every call"); assert!(ports.windows(2).all(|p| p[0] == p[1]), "{ports:?}"); @@ -489,26 +549,30 @@ fn calls_queued_behind_a_failed_start_share_its_error() { let made = Arc::new(Made::default()); let launches = Arc::new(AtomicUsize::new(0)); let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); - let entered = Arc::new(AtomicUsize::new(0)); - let (n, e) = (launches.clone(), entered.clone()); - // The app is started but never accepts agents within the timeout. The start waits until every - // call is under way and then a while longer, so a call that hasn't reached its lookup by the - // time the start ends is very unlikely (there is no hook between the two). + let (queued_tx, queued) = mpsc::channel(); + cfg.on_queued = Some(Box::new(move || { + let _ = queued_tx.send(()); + })); + let queued = Mutex::new(queued); + let n = launches.clone(); + // The app is started but never accepts agents within the timeout. The first start returns only + // once every call has queued behind it. cfg.launch = Some(Box::new(move || { - n.fetch_add(1, Ordering::Relaxed); - assert!(wait_for(|| e.load(Ordering::Relaxed) == 4), "every call starts"); - std::thread::sleep(Duration::from_millis(250)); + if n.fetch_add(1, Ordering::Relaxed) == 0 { + let queued = queued.lock().unwrap(); + for _ in 0..4 { + queued.recv().unwrap(); + } + } Ok(()) })); cfg.launch_timeout = Duration::from_millis(150); + virtual_clock(&mut cfg, || {}); let live = Arc::new(TestLive::new(cfg)); let calls: Vec<_> = (0..4) .map(|_| { - let (live, entered) = (live.clone(), entered.clone()); - std::thread::spawn(move || { - entered.fetch_add(1, Ordering::Relaxed); - live.resolve() - }) + let live = live.clone(); + std::thread::spawn(move || live.resolve()) }) .collect(); let answers: Vec<_> = calls.into_iter().map(|c| c.join().unwrap()).collect(); @@ -596,7 +660,19 @@ fn a_huge_launch_timeout_or_poll_neither_panics_nor_hangs() { })); cfg.launch_timeout = Duration::MAX; cfg.poll = Duration::MAX; - let started = Instant::now(); + let slept = virtual_clock(&mut cfg, || {}); window(TestLive::new(cfg).resolve()); - assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); + assert_eq!(*slept.lock().unwrap(), [Duration::from_secs(1)], "the poll is cut to a second"); + + // An app that never accepts agents: the wait ends after the longest launch timeout. + let dir = temp_dir("huge-never"); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Ok(()))); + cfg.launch_timeout = Duration::MAX; + cfg.poll = Duration::MAX; + let slept = virtual_clock(&mut cfg, || {}); + let err = TestLive::new(cfg).resolve().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within 600 s of starting."), "{err}"); + let slept = slept.lock().unwrap(); + assert_eq!((slept.len(), slept.iter().max()), (600, Some(&Duration::from_secs(1)))); } diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index f62cda215b..444c227e09 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -138,6 +138,7 @@ craft-raster-codecs = { workspace = true, optional = true } craft-raw = { workspace = true, optional = true } craft-rtf = { workspace = true, optional = true } craft-scraft-format = { workspace = true, optional = true } +craft-scopes = { workspace = true, optional = true } craft-sf2 = { workspace = true, optional = true } craft-sheet = { workspace = true, optional = true } craft-silhouette-studio = { workspace = true, optional = true } @@ -221,6 +222,7 @@ craft-geom = { workspace = true, optional = true } craft-suite-account = { workspace = true, optional = true } craft-xfa = { workspace = true, optional = true } craft-gpu = { workspace = true, optional = true } +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 } @@ -532,6 +534,13 @@ gif-frames = ["gif", "craft-gif/frames"] gpu = ["dep:craft-gpu"] gpu-startup = ["gpu", "craft-gpu/startup"] +gpu-device = ["dep:craft-gpu-device"] +gpu-device-native-dx12 = ["gpu-device", "craft-gpu-device/native-dx12"] +gpu-device-native-gles = ["gpu-device", "craft-gpu-device/native-gles"] +gpu-device-native-metal = ["gpu-device", "craft-gpu-device/native-metal"] +gpu-device-native-vulkan = ["gpu-device", "craft-gpu-device/native-vulkan"] +gpu-device-serde = ["gpu-device", "craft-gpu-device/serde"] + gpu-null = ["dep:craft-gpu-null"] gpu-providers = ["dep:craft-gpu-providers"] @@ -810,6 +819,8 @@ rtf-outlook = ["rtf", "craft-rtf/outlook"] sbs = ["dep:craft-sbs"] +scopes = ["dep:craft-scopes"] + score = ["dep:craft-score"] scraft-format = ["dep:craft-scraft-format"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index f02a0ce022..f52fb4834a 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -161,6 +161,8 @@ pub use craft_geom as geom; pub use craft_gif as gif; #[cfg(feature = "gpu")] pub use craft_gpu as gpu; +#[cfg(feature = "gpu-device")] +pub use craft_gpu_device as gpu_device; #[cfg(feature = "gpu-null")] pub use craft_gpu_null as gpu_null; #[cfg(feature = "gpu-providers")] @@ -331,6 +333,8 @@ pub use craft_review as review; pub use craft_rtf as rtf; #[cfg(feature = "sbs")] pub use craft_sbs as sbs; +#[cfg(feature = "scopes")] +pub use craft_scopes as scopes; #[cfg(feature = "score")] pub use craft_score as score; #[cfg(feature = "scraft-format")] diff --git a/crates/dialogs/src/ui/chooser/tests.rs b/crates/dialogs/src/ui/chooser/tests.rs index 0e38060c32..ac148378e0 100644 --- a/crates/dialogs/src/ui/chooser/tests.rs +++ b/crates/dialogs/src/ui/chooser/tests.rs @@ -228,7 +228,12 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() { std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("report.docx"), b"x").unwrap(); - let (service, panels) = FileService::scripted(Wake::none(), [Answer::Unavailable("no portal".to_owned())]); + // The service lists the real folder on its own threads and wakes the app when each listing is in. + let (woke, wakes) = std::sync::mpsc::channel(); + let wake = Wake::new(move || { + let _ = woke.send(()); + }); + let (service, panels) = FileService::scripted(wake, [Answer::Unavailable("no portal".to_owned())]); let panels = Rc::new(RefCell::new(panels)); let host = Rc::new(RefCell::new(DialogHost::new())); let (pumped, shown) = (panels.clone(), host.clone()); @@ -236,18 +241,15 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() { pumped.borrow_mut().pump_with(&mut shown.borrow_mut(), NONE); shown.borrow_mut().run(ui); }); - // The service lists the real folder on its own threads: wait until the chooser is listed. - let listed = |fixture: &mut Fixture| { - for _ in 0..400 { - fixture.idle(1); - if fields(&host).get("listed") == Some(&Value::Bool(true)) { - // The chooser lays out its listing in the next passes: a click reads where the controls rest. - fixture.settle(); - return; - } - std::thread::sleep(Duration::from_millis(5)); + // A pass takes in the listings that are in; until the chooser is listed, the next pass waits for the next wake. + let listed = |fixture: &mut Fixture| loop { + fixture.idle(1); + if fields(&host).get("listed") == Some(&Value::Bool(true)) { + // The chooser lays out its listing in the next passes: a click reads where the controls rest. + fixture.settle(); + return; } - panic!("the chooser listed the folder"); + wakes.recv_timeout(Duration::from_secs(10)).expect("a finished listing wakes the app"); }; let click = |fixture: &mut Fixture, label: &str| { let target = fixture.by_label(label).unwrap_or_else(|| panic!("`{label}` is shown")); diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 178084bdcc..2169a87453 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -493,7 +493,8 @@ pub struct TransformBox<'a> { #[prop] round_handles: bool, /// The side of the corner and side handles in points, for a host with a handle size preference; `None` uses the - /// theme's (`size.handle.md`). A handle's reach grows with a larger side and stays at least the theme's. + /// theme's (`size.handle.md`), as does a side that is zero, negative or not finite. A handle's reach grows with a + /// larger side and stays at least the theme's. #[prop(quantity = "points, from the host's handle size preference")] handle_side: Option, /// Draws the box as a live line's controls (the Line tool's live line as the whole selection). Only the two ends @@ -585,14 +586,19 @@ impl<'a> TransformBox<'a> { self.color.map_or(StrokeColor::from(theme), StrokeColor::from) } + /// The host's handle side when it is a finite side above zero; `None` for none or any other value. + fn host_handle_side(&self) -> Option { + self.handle_side.filter(|side| side.is_finite() && *side > 0.0) + } + /// The side of a corner or side handle: the host's, else the theme's. fn side_of_handles(&self, style: &TransformBoxStyle) -> f32 { - self.handle_side.unwrap_or(style.handle.side) + self.host_handle_side().unwrap_or(style.handle.side) } /// The hit radius of a corner or side handle: the theme's, or more for a host's larger handle. fn reach_of_handles(&self, style: &TransformBoxStyle) -> f32 { - self.handle_side.map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES)) + self.host_handle_side().map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES)) } /// Whether the middle of the box is a move part: the reference point is hidden, so it does not take that place. diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 90c8f0568e..9448dbb9f3 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1678,6 +1678,43 @@ fn a_host_handle_side_sets_the_drawn_handle_square() { assert!(large > small, "a larger side draws a larger square: {large} against {small}"); } +/// A host handle side that is zero, negative or not finite draws the theme's handle and keeps the theme's reach. +#[trial] +fn an_unusable_host_handle_side_uses_the_themes() { + let corner_side = |side: Option| { + let mut h = harness(BoxState::from_rect(RECT), |config| config.handle_side = side); + let corner = h.screen(Point::new(RECT.x1, RECT.y1)); + h.fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + Shape::Rect(square) if (square.rect.center() - corner).length() < 0.5 => Some(square.rect.width()), + _ => None, + }) + .collect::>() + }; + let theme = corner_side(None); + assert!(!theme.is_empty(), "the theme's corner handle is drawn"); + // 3 points in from the bottom right corner on both axes: inside the theme's handle reach. + let near = Point::new(RECT.x1 - 3.0, RECT.y1 - 3.0); + for side in [0.0, -6.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(corner_side(Some(side)), theme, "a side of {side} draws the theme's corner handle"); + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules(); + config.handle_side = Some(side); + }); + hover(&mut h, near); + assert_eq!(h.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} keeps the theme's reach"); + // Far outside the theme's reach: an infinite side must not widen the reach to the whole canvas. + let mut far = harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules(); + config.handle_side = Some(side); + }); + hover(&mut far, Point::new(RECT.x1 + 60.0, RECT.y1 + 60.0)); + assert_ne!(far.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} does not widen the reach"); + } +} + /// A large host handle takes a press anywhere on its square, also past the theme's reach, and the press drags it. #[trial] fn a_press_just_inside_a_large_handles_edge_grabs_it() { diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index d2027c029f..01692fc984 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -588,12 +588,20 @@ impl Catalog { /// it. Does nothing once it has started or run, or when no thread can be started (the first /// lookup then scans). pub fn scan_in_background(self: &Arc) { - if self.ready.get().is_none() && !self.scanning.swap(true, Ordering::AcqRel) { - let me = Arc::clone(self); - if std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan()).is_err() { - self.scanning.store(false, Ordering::Release); - } + drop(self.start_background_scan()); + } + + /// [`Catalog::scan_in_background`], returning the thread it started, if it started one. + pub(crate) fn start_background_scan(self: &Arc) -> Option> { + if self.ready.get().is_some() || self.scanning.swap(true, Ordering::AcqRel) { + return None; } + let me = Arc::clone(self); + let thread = std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan()); + if thread.is_err() { + self.scanning.store(false, Ordering::Release); + } + thread.ok() } /// The background thread's scan. A scan that panics leaves the catalog unscanned and not diff --git a/crates/font-catalog/src/tests.rs b/crates/font-catalog/src/tests.rs index 54c044fd0b..e8b438154e 100644 --- a/crates/font-catalog/src/tests.rs +++ b/crates/font-catalog/src/tests.rs @@ -586,11 +586,11 @@ fn a_background_scan_that_panics_lets_the_next_call_scan_again() { }); let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister)); // Each call starts a scan only when none is running; the second starts once the failed one has ended. - let deadline = std::time::Instant::now() + Duration::from_secs(10); - while !cat.is_ready() && std::time::Instant::now() < deadline { - cat.scan_in_background(); - std::thread::sleep(Duration::from_millis(1)); - } + let failed = cat.start_background_scan().expect("the first call starts a scan"); + assert!(failed.join().is_err(), "the first scan fails"); + assert!(!cat.is_ready()); + let again = cat.start_background_scan().expect("a failed scan must not leave the catalog waiting on it"); + again.join().unwrap(); assert!(cat.is_ready(), "a failed scan must not leave the catalog waiting on it"); assert_eq!(calls.load(Ordering::Relaxed), 2); } @@ -605,13 +605,10 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() { let (entered, scan_entered) = mpsc::channel(); let (release, scan_released) = mpsc::channel::<()>(); let scan_released = std::sync::Mutex::new(scan_released); - let waited_out = Arc::new(AtomicUsize::new(0)); - let flag = Arc::clone(&waited_out); let lister: Lister = Arc::new(move || { let _ = entered.send(()); - if let Err(mpsc::RecvTimeoutError::Timeout) = scan_released.lock().unwrap().recv_timeout(Duration::from_secs(10)) { - flag.fetch_add(1, Ordering::Relaxed); - } + // The first scan stays here until the test sends on `release`; once it is dropped, scans go straight through. + let _ = scan_released.lock().unwrap().recv(); Vec::new() }); let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister)); @@ -619,12 +616,19 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() { assert!(!cat.is_ready(), "adding started no scan"); cat.scan_in_background(); scan_entered.recv_timeout(Duration::from_secs(10)).unwrap(); - cat.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default()).unwrap(); + let adding = Arc::clone(&cat); + let (added, add_returned) = mpsc::channel(); + std::thread::spawn(move || { + let _ = added.send(adding.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default())); + }); + // The scan cannot end before `release` sends, so an add that returns now did not wait for it. The limit only stops a + // test whose add waits. + let returned = add_returned.recv_timeout(Duration::from_secs(10)); release.send(()).unwrap(); // Later scans (the rescans below) go straight through. drop(release); + returned.expect("the add during the scan returned before the scan did").unwrap(); assert_eq!(cat.styles("App Face").len(), 1); - assert_eq!(waited_out.load(Ordering::Relaxed), 0, "the add during the scan returned before the scan did"); // The added Bold comes first; the installed file's Bold is another version of it, not another face. assert_eq!(cat.resolve("Test Sans", "Bold").map(|(f, _)| f), bold.first().cloned()); assert_eq!(cat.versions(&bold[0]).len(), 2); diff --git a/crates/font-manager/tests/it/panel.rs b/crates/font-manager/tests/it/panel.rs index b321381712..363dab42c6 100644 --- a/crates/font-manager/tests/it/panel.rs +++ b/crates/font-manager/tests/it/panel.rs @@ -4,8 +4,8 @@ use std::cell::RefCell; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::rc::Rc; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::time::Duration; use craft_font_manager::craft_font_catalog::Os; @@ -73,6 +73,36 @@ struct Rig { fx: Fixture, panel: Rc>, store: Arc, + woken: Arc, +} + +/// How long a test waits for another thread before it fails as hung. A result that comes does not depend on it. +const HANG: Duration = Duration::from_secs(10); + +/// Counts the repaints asked for from threads other than the test's, as the preview workers ask for one after each +/// result. +#[derive(Default)] +struct Woken { + count: Mutex, + changed: Condvar, +} + +impl Woken { + fn count(&self) -> u64 { + *self.count.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn wake(&self) { + *self.count.lock().unwrap_or_else(PoisonError::into_inner) += 1; + self.changed.notify_all(); + } + + /// Waits until a repaint is asked for after [`Woken::count`] was `seen`. + fn wait_past(&self, seen: u64) { + let count = self.count.lock().unwrap_or_else(PoisonError::into_inner); + let (count, _) = self.changed.wait_timeout_while(count, HANG, |count| *count == seen).unwrap_or_else(PoisonError::into_inner); + assert!(*count > seen, "previews kept loading"); + } } fn root(name: &str) -> PathBuf { @@ -132,9 +162,16 @@ fn show(panel: FontsPanel, store: Arc, host: Arc) -> Rig { let mut fx = Fixture::new(move |ui| { FontsPanelView::new(&mut shown.borrow_mut()).show(ui); }); + let woken = Arc::new(Woken::default()); + let (counted, test) = (Arc::clone(&woken), std::thread::current().id()); + fx.ctx().set_repaint_observer(move |_| { + if std::thread::current().id() != test { + counted.wake(); + } + }); fx.in_room(Room::Window).host(host); fx.settle(); - Rig { fx, panel, store } + Rig { fx, panel, store, woken } } impl Rig { @@ -367,8 +404,9 @@ fn a_cards_install_menu_chooses_where_the_fonts_go() { struct FakeService { answered: Mutex>, cancelled: Mutex>, - /// Requests that reached the service. - started: AtomicUsize, + /// Requests that reached the service, notified on `arrived` as each one does. + started: Mutex, + arrived: Condvar, held: AtomicBool, /// Answers sample subsets with HTTP 404, as for a sample text the service doesn't have. no_samples: AtomicBool, @@ -378,7 +416,8 @@ struct FakeService { impl Fetch for FakeService { fn get(&self, url: &str, _: u64, cancel: &Cancel) -> Result, FetchError> { - self.started.fetch_add(1, Ordering::SeqCst); + *self.started.lock().unwrap_or_else(PoisonError::into_inner) += 1; + self.arrived.notify_all(); while self.held.load(Ordering::SeqCst) && !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(2)); } @@ -403,6 +442,18 @@ impl FakeService { std::mem::take(&mut *self.answered.lock().unwrap_or_else(PoisonError::into_inner)) } + /// The requests that reached the service. + fn started(&self) -> usize { + *self.started.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Waits until a request has reached the service. + fn wait_started(&self) { + let started = self.started.lock().unwrap_or_else(PoisonError::into_inner); + let (started, _) = self.arrived.wait_timeout_while(started, HANG, |started| *started == 0).unwrap_or_else(PoisonError::into_inner); + assert!(*started > 0, "the service was asked"); + } + /// The numbers of the families whose `subset` the URLs of `answered` name: `sample`, `ascii`, or `u/` for typed /// characters. fn numbers(answered: &[String], subset: &str) -> Vec { @@ -468,16 +519,22 @@ impl Rig { self.fx.settle(); } - /// Runs passes until the panel has fetched what it asks for and asks for nothing more. + /// Runs passes until the panel has fetched what it asks for and asks for nothing more. While a preview is on its + /// way, the next pass waits for the repaint its worker asks for once the result is ready. fn load(&mut self) { let mut quiet = 0; for _ in 0..500 { + let seen = self.woken.count(); self.fx.frame(Vec::new()); - quiet = if self.panel.borrow().loading_previews() { 0 } else { quiet + 1 }; + if self.panel.borrow().loading_previews() { + quiet = 0; + self.woken.wait_past(seen); + continue; + } + quiet += 1; if quiet == 3 { return; } - std::thread::sleep(Duration::from_millis(1)); } panic!("previews kept loading"); } @@ -563,13 +620,7 @@ fn a_resize_and_a_search_cancel_no_preview() { service.held.store(true, Ordering::SeqCst); let mut rig = service_rig("previews-kept", &service, latin_index()); rig.set_previews(true); - for _ in 0..500 { - if service.started.load(Ordering::SeqCst) > 0 { - break; - } - std::thread::sleep(Duration::from_millis(1)); - } - assert!(service.started.load(Ordering::SeqCst) > 0, "the service was asked"); + service.wait_started(); let shown = rig.numbers(); rig.fx.room(Room::Window.size() + Vec2::new(40.0, 120.0)).settle(); rig.type_into("Search", "Family"); @@ -602,7 +653,7 @@ fn a_family_of_an_added_source_is_not_asked_of_the_service() { rig.open("Added"); rig.load(); rig.named(Role::BUTTON, "Preview"); - assert_eq!(service.started.load(Ordering::SeqCst), 0, "{:?}", service.urls()); + assert_eq!(service.started(), 0, "{:?}", service.urls()); } /// A sample the service has not (another text) is asked for as the sample's characters, once. diff --git a/crates/font-manager/tests/remote.rs b/crates/font-manager/tests/remote.rs index e8c1062ea0..59413800bd 100644 --- a/crates/font-manager/tests/remote.rs +++ b/crates/font-manager/tests/remote.rs @@ -9,8 +9,9 @@ use std::collections::HashMap; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::path::PathBuf; +use std::sync::mpsc::{Receiver, channel}; use std::sync::{Arc, Condvar, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use craft_font_manager::craft_font_catalog::Os; use craft_font_manager::store::{FakeStore, Installer, SuiteStore}; @@ -118,7 +119,8 @@ enum Reply { struct Service { base: String, routes: Arc>>, - log: Arc>>, + /// The paths asked for, notified as each one arrives. + log: Arc<(Mutex>, Condvar)>, gate: Arc<(Mutex, Condvar)>, } @@ -143,7 +145,14 @@ impl Service { } fn requests(&self) -> Vec { - self.log.lock().unwrap().clone() + self.log.0.lock().unwrap().clone() + } + + /// Waits until `n` requests have reached the service. + fn wait_for_requests(&self, n: usize) { + let log = self.log.0.lock().unwrap(); + let (log, _) = self.log.1.wait_timeout_while(log, HANG, |log| log.len() < n).unwrap(); + assert!(log.len() >= n, "{} of {n} requests reached the service", log.len()); } fn release(&self) { @@ -152,7 +161,7 @@ impl Service { } } -fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex>, gate: &(Mutex, Condvar)) { +fn answer(mut s: TcpStream, routes: &Mutex>, log: &(Mutex>, Condvar), gate: &(Mutex, Condvar)) { let mut head = Vec::new(); let mut b = [0u8; 1]; while !head.ends_with(b"\r\n\r\n") { @@ -162,7 +171,8 @@ fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex< } } let path = String::from_utf8_lossy(&head).split_whitespace().nth(1).unwrap_or("/").to_string(); - log.lock().unwrap().push(path.clone()); + log.0.lock().unwrap().push(path.clone()); + log.1.notify_all(); let reply = routes.lock().unwrap().get(&path).cloned(); let body = match reply { Some(Reply::Ok(body)) => body, @@ -182,22 +192,28 @@ fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex< let _ = s.write_all(&body); } -/// The results until `n` have come, or two seconds. -fn wait_for(previews: &Previews, n: usize) -> Vec { - let deadline = Instant::now() + Duration::from_secs(2); - let mut out = Vec::new(); - while out.len() < n && Instant::now() < deadline { - out.extend(previews.poll()); - std::thread::sleep(Duration::from_millis(5)); - } - out +/// How long a test waits for a result or a request before it fails as hung. A result that comes does not depend on it. +const HANG: Duration = Duration::from_secs(10); + +/// `previews` and a channel that gets `()` after each result it delivers ([`Previews::on_ready`]). +fn watched(previews: Previews) -> (Previews, Receiver<()>) { + let (ready, results) = channel(); + let previews = previews.on_ready(move || { + let _ = ready.send(()); + }); + (previews, results) } -fn wait_until(mut done: impl FnMut() -> bool) { - let deadline = Instant::now() + Duration::from_secs(2); - while !done() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(5)); +/// The results until `n` have come. +fn wait_for(previews: &Previews, ready: &Receiver<()>, n: usize) -> Vec { + let mut out = previews.poll(); + while out.len() < n { + if ready.recv_timeout(HANG).is_err() { + panic!("{} of {n} previews came", out.len()); + } + out.extend(previews.poll()); } + out } #[test] @@ -209,12 +225,12 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { let broken = PreviewKey::new(&sha(2), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); service.serve(&sample, Reply::Ok(WOFF2.to_vec())); service.serve(&broken, Reply::Ok(b"wOF2 but not really".to_vec())); - let previews = Previews::new(store.clone()); + let (previews, ready) = watched(Previews::new(store.clone())); // No service: nothing happens. assert!(!previews.available()); previews.request(sample.clone(), 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NoService)); // A service, but previews off: no request. @@ -222,7 +238,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { store.set_previews_enabled(false).unwrap(); assert!(!previews.available()); previews.request(sample.clone(), 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::PreviewsOff)); assert!(service.requests().is_empty()); @@ -231,7 +247,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { assert!(previews.available() && !store.downloads_allowed()); previews.request(sample.clone(), 1); previews.request(broken.clone(), 1); - let got = wait_for(&previews, 2); + let got = wait_for(&previews, &ready, 2); let font = |key: &PreviewKey| got.iter().find(|p| &p.key == key).map(|p| p.font.clone()); assert!(font(&sample).unwrap().is_ok_and(|f| is_font(&f))); assert_eq!(font(&broken), Some(Err(PreviewError::NotAFont))); @@ -241,9 +257,9 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { // A new session reads the disk cache, even with previews off. store.set_previews_enabled(false).unwrap(); - let later = Previews::new(store.clone()); + let (later, later_ready) = watched(Previews::new(store.clone())); later.request(sample.clone(), 1); - assert!(wait_for(&later, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f)))); + assert!(wait_for(&later, &later_ready, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f)))); assert_eq!(service.requests().len(), 2); let _ = std::fs::remove_dir_all(dir); } @@ -276,9 +292,9 @@ fn a_service_marked_down_gets_no_requests() { // The client is shared with, say, the store's installs, which found the service unreachable. let client = Client::default(); client.mark_service_down(&service.base); - let previews = Previews::new(store.clone()).with_fetcher(Arc::new(client)); + let (previews, ready) = watched(Previews::new(store.clone()).with_fetcher(Arc::new(client))); previews.request(key, 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert!(matches!(got.first().map(|p| p.font.clone()), Some(Err(PreviewError::Failed(_))))); assert!(service.requests().is_empty()); let _ = std::fs::remove_dir_all(dir); @@ -297,10 +313,10 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() { for key in [low, high, dropped] { service.serve(key, Reply::Ok(WOFF2.to_vec())); } - let previews = Previews::new(store.clone()).with_cache(None).with_workers(1); + let (previews, ready) = watched(Previews::new(store.clone()).with_cache(None).with_workers(1)); previews.request(held.clone(), 9); - wait_until(|| !service.requests().is_empty()); + service.wait_for_requests(1); previews.request(low.clone(), 1); previews.request(dropped.clone(), 1); previews.request(high.clone(), 5); @@ -310,11 +326,12 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() { // The running request stops while the service still sends nothing. previews.cancel(held); - let got = wait_for(&previews, 2); + let got = wait_for(&previews, &ready, 2); assert_eq!(got.iter().map(|p| &p.key).collect::>(), [high, low]); let path = |k: &PreviewKey| format!("/{}", k.path()); assert_eq!(service.requests(), [path(held), path(high), path(low)]); - std::thread::sleep(Duration::from_millis(100)); + // The one worker delivers in the order it takes requests, and it had ended the held one before it asked for `high`, + // so nothing more can come. assert!(previews.poll().is_empty()); assert_eq!(previews.pending(), 0); service.release(); @@ -343,9 +360,9 @@ fn a_404_comes_back_as_not_found() { let store = Arc::new(FakeStore::new(&dir, HashMap::new())); store.set_preview_service(Some(&service.base)).unwrap(); let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); - let previews = Previews::new(store.clone()); + let (previews, ready) = watched(Previews::new(store.clone())); previews.request(key, 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NotFound)); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/gpu-device/Cargo.toml b/crates/gpu-device/Cargo.toml new file mode 100644 index 0000000000..19f6cfa356 --- /dev/null +++ b/crates/gpu-device/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "craft-gpu-device" +description = "Choosing and opening a wgpu device: an adapter choice the user can set (Auto, high performance, low power, a named adapter, software), fixes for drivers that crash, a software fallback, a capability report, and device health with recovery after a device loss" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["serde"] +# Reading and writing `Preference` and `AdapterKey` with serde. +serde = ["dep:serde"] +# Native wgpu backends, as in craft-gpu-wgpu. None is on by default; the app turns on the ones it +# ships, through this crate or through craft-gpu-wgpu. +native-vulkan = ["wgpu/vulkan"] +native-dx12 = ["wgpu/dx12"] +native-metal = ["wgpu/metal"] +native-gles = ["wgpu/gles"] + +[dependencies] +craft-gpu = { workspace = true } +log = { workspace = true } +serde = { workspace = true, optional = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true } +wgpu = { workspace = true } + +[dev-dependencies] +# The noop backend opens devices without a GPU in the tests. +wgpu = { workspace = true, features = ["noop"] } +serde_json = { workspace = true } diff --git a/crates/gpu-device/NOTICE b/crates/gpu-device/NOTICE new file mode 100644 index 0000000000..e7ca2f2c92 --- /dev/null +++ b/crates/gpu-device/NOTICE @@ -0,0 +1,10 @@ +craft-gpu-device +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The adapter rule and its driver corrections (src/adapter.rs) come from FilmCraft's +`crates/gpu/src/adapter.rs` (https://github.com/storytold/filmcraft, commit +93a88a839aae370740b09434fdec410abb8c24ca), MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and +the FilmCraft contributors. +Device health (src/health.rs) comes from PhotoCraft's `crates/gpu/src/health.rs` +(https://github.com/storytold/photocraft, commit 01a5b5a389acc93f081e5ce6a8d0580d6438774a), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md new file mode 100644 index 0000000000..bb083932ad --- /dev/null +++ b/crates/gpu-device/README.md @@ -0,0 +1,128 @@ +# craft-gpu-device + +Choosing and opening a wgpu device for a Craft app: an adapter choice the user can set, fixes for +drivers that crash, a software fallback, a capability report, and device health with recovery +after a device loss. The crate depends on `craft-gpu`, `wgpu` 30, `pollster` and `log`, with +`serde` as an optional feature (on by default). It depends on no app crate. + +It uses the workspace's `wgpu`, which turns on no native backend, and the WebGPU backend on +`wasm32`. The `native-vulkan`, `native-dx12`, `native-metal` and `native-gles` features turn on +wgpu's backends, as the features of the same names in `craft-gpu-wgpu` do. Cargo merges the +features, so an app can turn them on through either crate. + +The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`. + +`native_instance` shares one instance across calls on native targets. It reads wgpu's environment +settings for flags and backend options when that instance is first created. `native_descriptor` +reads those settings on every call. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface | +| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s | +| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply | +| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) | +| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` | +| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids | +| `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | +| `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | +| `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | +| `list_async`, `open_async` | `list` and `open` as futures, for a `wasm32` web worker as well as native; in a browser `list_async` gives the high-performance adapter, the one `open_async` opens for `Auto` and a named adapter | +| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector`; the error is an `OpenError` (convert it with `map_err(\|e\| e.to_string())` for that selector) | +| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one, read from the `craft_gpu::DeviceCaps` it holds (its fields are readable through `Deref`; `From` converts both ways) | +| `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | +| `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | +| `device_caps(device)`, `Opened::device_caps` | the `craft_gpu::DeviceCaps` of a device: its own limits, enabled feature names, vendor id and software flag, in the form `craft-gpu-wgpu` reports | +| `DeviceHealth::device_status` | a recorded loss as `craft_gpu::GpuFault::DeviceLost`, in the form of `GpuContext::device_status`; `Fault` converts to `GpuFault` (a loss to `DeviceLost`, an error to `Operation`) | +| `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log | + +## Failure cases + +- With no usable adapter, `select` returns `None`, and `open` and `pick` return + `OpenError::NoAdapter`, or `OpenError::UnsafeDriver` when only a driver that can end the + process can draw. +- In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be + chosen. `open_async` asks for the adapter with `Preference::power()` as the power preference, + and gives the automatic choice with `Notice::AdapterMissing` for a named adapter. wgpu 30 + does not pass the fallback-adapter option to the browser, so `Preference::Software` opens the + browser's adapter, with `Notice::NoSoftwareAdapter` unless that adapter is a software one, and + `Recovery` cannot move drawing to software there. `Capabilities` and + `Recovery` otherwise work there as they do on native, and so does `DeviceHealth` apart from `wait`, + `wait_timeout` and `wait_timeout_cancelable`, which are native only. On the browser backend, + wgpu 30 panics on an uncaptured `GPUInternalError` before the handler `DeviceHealth::watch` + installs runs, so such an error is not recorded. Validation and out-of-memory errors are. +- An adapter that lacks `Request::required_features`, whose limits are lower than + `Request::limits`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` + tries the next one. When every adapter fails, the error lists each failure. +- A named adapter that is no longer listed, or can no longer draw to the surface, gives the + automatic choice and `Notice::AdapterMissing`. +- A driver that ends the process cannot be caught. `choose` and `ranked` never use an older + version of a driver that lists one GPU twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 + GPU on Intel's Windows driver. When those are the only adapters that can draw and wgpu's + fallback adapter does not open either, `open` returns `OpenError::UnsafeDriver` with their + names. When a + driver reports no bus id, a second GPU of the same model on the same driver looks like an + older version, and is used through its other backend (DirectX 12 on Windows, OpenGL + elsewhere). +- Only an error whose cause is wgpu's "Parent device is lost" counts as a loss. The same words in + a resource's label do not count. An error about a destroyed buffer or texture is recorded as an + error. +- `wait`, `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for + everything submitted so far, pass `queue.submit([])`; work submitted later does not extend the + wait. +- `wait` has no deadline. It polls in slices of at most 100 ms, and a loss or an error other than + out of memory that another clone of the `DeviceHealth` records ends it after the current slice. +- `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that + `Device::poll` raises on a lost device and record the loss. +- wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback` + replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads + `DeviceHealth::device_status` instead of setting its own callback. +- After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed. + The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and + passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again, + unless it was lost, another error was recorded, or a new out-of-memory error came in after the + count was read. + +## After a device loss + +`DeviceHealth::device_status` returns `GpuFault::DeviceLost` once a loss is recorded, and the +caller starts recovery then. `DeviceHealth::device_lost` turns true only when wgpu itself reported +the loss; it stays false for a loss the health layer recorded on its own, such as a bounded wait +that reached its deadline. Nothing made with the lost device can be used again, and wgpu keeps +none of its contents. The caller then: + +1. Drops the old `Opened` and everything made with its device: buffers, textures and their + views, samplers, bind group layouts and bind groups, shader modules, pipeline layouts and + pipelines, query sets, unsubmitted command encoders, and any renderer that holds them (an + egui-wgpu `Renderer`, for example). Work submitted before the loss does not complete, and + waits on it return `false`. +2. Calls `Recovery::lost` with the time and opens a new device with `open` or `open_async`, + using the returned preference and the same `Request`. When the step has a notice + (`Notice::SoftwareAfterLosses`), the app shows it only if the new `Opened::caps.software()` is + true. Otherwise no software adapter opened (in a browser, or with none listed), and the new + `Opened::notices` say what was opened instead. +3. Reads the new `Opened::caps` before choosing pipelines again. The new device can be another + adapter, or a software one, with other features and limits: for example, without NV12 the + planes are drawn into `R8Unorm` and `Rg8Unorm` textures instead. +4. Configures each window surface again with the new device (`Surface::configure`). The surface + itself is kept when it was passed to `open`, which then opens only an adapter that can draw + to it. The new adapter may not support the old configuration (an HDR format, for example), so + the caller reads `Surface::get_capabilities` with the new adapter and picks a format, present + mode and alpha mode from it. +5. Builds the pipelines for the surface format picked in step 4, and the bind groups and + renderers, again, and uploads the textures and buffers again from the app's own copies of + their data. +6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and + submits again the jobs and frames that did not complete. +7. Uses the new `Opened::health`. The old `DeviceHealth` keeps reporting the loss. + +## Tests + +The selection tests run on `Candidate` lists from real machines. The `open` tests use wgpu's noop +backend (the `noop` feature, enabled for tests only), so they do not need a GPU. One test compares +`choose` with wgpu's own `request_adapter` on the machine that runs it, and passes when no adapter +is listed. diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs new file mode 100644 index 0000000000..b837d47b1b --- /dev/null +++ b/crates/gpu-device/src/adapter.rs @@ -0,0 +1,647 @@ +//! Which adapter wgpu's own rule would draw with, and two corrections to it for drivers that crash. +//! +//! On Windows the Vulkan loader takes one driver from each display adapter's driver package. A PC +//! whose GPUs were installed from different packages of one vendor (a laptop with an integrated +//! and a discrete AMD GPU, the first on the manufacturer's old package and the second on a current +//! one) loads two versions of that driver, and the newer GPU is listed once through each. wgpu +//! takes the first entry of the device type it prefers, which is whichever version the loader +//! listed first; a window drawn through the stale one ends the process inside the driver +//! (`amdvlk64.dll`, 0xc0000005), where no Rust error handling runs. +//! +//! [`choose`] is wgpu's own rule (`Instance::request_adapter`: the adapters that can draw to the +//! surface, by device type for the power preference, then as enumerated) with one addition: when +//! the adapter that rule picks is listed again by the same driver, the entry exposing the most +//! features is used, which is the newer version. Without such a duplicate the choice is wgpu's own. +//! Entries of one GPU from different drivers (RADV and AMDVLK, a vendor's driver and Dozen) are +//! left alone, and wgpu's order between them stays. +//! +//! An Intel Gen 9 to Gen 11 integrated GPU draws through its DirectX 12 entry rather than Vulkan +//! ([`intel_gen9_to_gen11`]). Intel's Vulkan driver for them (`igvk64.dll`) ends the process with +//! 0xc0000005 when the device is created, after the adapters are listed. + +use std::cmp::Reverse; +use std::fmt; + +use wgpu::{Adapter, Backend, DeviceType, PowerPreference, Surface}; + +/// One enumerated adapter as plain data, so that [`choose`] and [`crate::select`] are pure +/// functions that tests run without a GPU. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Candidate { + pub name: String, + pub backend: Backend, + pub device_type: DeviceType, + /// PCI vendor and device ids; both zero when the backend reports none (OpenGL). + pub vendor: u32, + pub device: u32, + /// PCI bus id such as `0000:03:00.0`; empty when the driver reports none. + pub pci_bus_id: String, + /// The driver's name (Vulkan) or version (DirectX 12). + pub driver: String, + /// More about the driver, for the log. + pub driver_info: String, + /// How many wgpu features the driver exposes; a newer version of one driver exposes more. + pub features: u32, + /// Whether the surface can be drawn through this adapter (true without a surface). + pub usable: bool, +} + +impl Candidate { + pub fn of(adapter: &Adapter, surface: Option<&Surface<'_>>) -> Self { + let info = adapter.get_info(); + Candidate { + name: info.name, + backend: info.backend, + device_type: info.device_type, + vendor: info.vendor, + device: info.device, + pci_bus_id: info.device_pci_bus_id, + driver: info.driver, + driver_info: info.driver_info, + features: adapter.features().bits().0.iter().map(|word| word.count_ones()).sum(), + usable: surface.is_none_or(|s| adapter.is_surface_supported(s)), + } + } + + /// Whether the adapter draws on the CPU (WARP, llvmpipe, lavapipe, SwiftShader). + pub fn is_software(&self) -> bool { + self.device_type == DeviceType::Cpu + } +} + +impl fmt::Display for Candidate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.device_type { + DeviceType::DiscreteGpu => "discrete GPU", + DeviceType::IntegratedGpu => "integrated GPU", + DeviceType::VirtualGpu => "virtual GPU", + DeviceType::Cpu => "software", + DeviceType::Other => "unknown type", + }; + let driver = format!("{} {}", self.driver, self.driver_info); + write!(f, "\"{}\" ({:?}, {kind}, driver {}, {} features", self.name, self.backend, driver.trim(), self.features)?; + if !self.pci_bus_id.is_empty() { + write!(f, ", bus {}", self.pci_bus_id)?; + } + if !self.usable { + write!(f, ", cannot draw to the window")?; + } + write!(f, ")") + } +} + +/// Whether `a` and `b` are one GPU listed twice by one driver, through two installed versions of +/// it: the same backend, device type, PCI vendor and device and driver name, and the same bus id +/// when both report one. Adapters without PCI ids (OpenGL reports zeros) are never the same: two +/// of them cannot be told apart. +pub(crate) fn same_gpu_and_driver(a: &Candidate, b: &Candidate) -> bool { + let identified = a.vendor != 0 || a.device != 0; + let same_bus = a.pci_bus_id.is_empty() || b.pci_bus_id.is_empty() || a.pci_bus_id == b.pci_bus_id; + identified + && a.backend == b.backend + && a.device_type == b.device_type + && a.vendor == b.vendor + && a.device == b.device + && a.driver == b.driver + && same_bus +} + +/// wgpu's device type order for `power` (wgpu-core's `Instance::request_adapter`): lower first. +/// Without a preference the adapters stay as enumerated. +pub(crate) fn type_order(device_type: DeviceType, power: PowerPreference) -> u8 { + let prefer_integrated = match power { + PowerPreference::LowPower => true, + PowerPreference::HighPerformance => false, + PowerPreference::None => return 0, + }; + match device_type { + DeviceType::DiscreteGpu if prefer_integrated => 2, + DeviceType::IntegratedGpu if prefer_integrated => 1, + DeviceType::DiscreteGpu => 1, + DeviceType::IntegratedGpu => 2, + DeviceType::Other => 3, + DeviceType::VirtualGpu => 4, + DeviceType::Cpu => 5, + } +} + +/// The index of the adapter wgpu's `request_adapter` picks: the first usable one of the best +/// device type for `power`. `None` without a usable adapter. +pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> Option { + let usable = candidates.iter().enumerate().filter(|(_, c)| c.usable); + usable.min_by_key(|(index, c)| (type_order(c.device_type, power), *index)).map(|(index, _)| index) +} + +/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on +/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's +/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices +/// dropped at the same time can then deadlock in that driver. +/// +/// On native targets, the first call creates one shared instance and reads wgpu's environment +/// settings for flags and backend options. Later calls return clones of that instance. +pub fn native_instance() -> wgpu::Instance { + #[cfg(not(target_arch = "wasm32"))] + { + static SHARED: std::sync::OnceLock = std::sync::OnceLock::new(); + SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone() + } + #[cfg(target_arch = "wasm32")] + { + wgpu::Instance::new(native_descriptor()) + } +} + +/// [`native_instance`]'s descriptor. wgpu's environment variables apply to its flags and backend +/// options: `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER=1` lists a Vulkan driver that reports no +/// conformance version, such as Mesa's Dozen (the only one on WSL2), and `WGPU_VALIDATION`, +/// `WGPU_DX12_COMPILER` and the others work too. The backends stay as above whatever +/// `WGPU_BACKEND` says. +/// +/// The descriptor has no display handle, which a headless instance does not need. OpenGL on +/// Wayland needs one to draw to a window: add it with `InstanceDescriptor::with_display_handle`, +/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe +/// fills in the window's display handle. +pub fn native_descriptor() -> wgpu::InstanceDescriptor { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + desc.flags = desc.flags.with_env(); + desc.backend_options = desc.backend_options.with_env(); + desc +} + +/// The index of the adapter to draw with for `power`: `wgpu_choice`, or the entry exposing the +/// most features among those that are the same GPU listed by the same driver (the first of them +/// when several expose as many), repeated until the entry is its own newest version. For an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows Vulkan driver it is the same GPU's DirectX 12 entry, or +/// without one the best other usable adapter. `None` without a usable adapter, and when that +/// Intel Vulkan entry is the only one. The result is never an entry `avoided` excludes. +pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { + let first = wgpu_choice(candidates, power)?; + let index = settled(candidates, first); + if candidates.get(index).is_some_and(intel_vulkan_crashes) { + // No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take. + let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c)); + let (other, _) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; + return Some(settled(candidates, other)); + } + Some(index) +} + +/// [`corrected`] applied until it returns the entry it was given. An entry without a bus id can +/// be the same GPU as two entries on different buses, so one correction can land on an entry that +/// has a newer version of its own. Each step moves to an entry exposing more features (or the +/// same number at a lower index), or to a DirectX 12 entry, so the loop ends. +pub(crate) fn settled(candidates: &[Candidate], mut index: usize) -> usize { + for _ in 0..=candidates.len() { + let Some(c) = candidates.get(index) else { + return index; + }; + let next = corrected(candidates, index, c); + if next == index { + return index; + } + index = next; + } + index +} + +/// `index` (the entry `preferred`), or the entry to draw with instead of it. +pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize { + if let Some(dx12) = dx12_instead(candidates, preferred) { + return dx12; + } + let versions = candidates.iter().enumerate().filter(|(_, c)| c.usable && same_gpu_and_driver(preferred, c)); + versions.max_by_key(|(index, c)| (c.features, Reverse(*index))).map_or(index, |(index, _)| index) +} + +/// Whether the entry at `index` is one [`choose`] never draws with: the Vulkan entry of an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows driver, or an older version of a driver that lists one +/// GPU twice. Creating a device or drawing through either can end the process, so it is never +/// tried as a fallback either. A second GPU of the same model on the same driver, when the +/// driver reports no bus id for either, looks like an older version; it is still listed through +/// the other backends (DirectX 12 on Windows, OpenGL elsewhere). +pub(crate) fn avoided(candidates: &[Candidate], index: usize) -> bool { + let Some(c) = candidates.get(index) else { + return true; + }; + intel_vulkan_crashes(c) || corrected(candidates, index, c) != index +} + +/// PCI vendor id of Intel. +pub(crate) const INTEL: u32 = 0x8086; + +/// Whether `device` is an Intel Gen 9 to Gen 11 integrated GPU: 6th to 10th generation Core, and +/// the Atom, Pentium and Celeron graphics of those years (Skylake, Broxton, Gemini Lake, Kaby +/// Lake, Coffee Lake, Whiskey Lake, Comet Lake, Cannon Lake, Ice Lake, Elkhart Lake, Jasper Lake), +/// by the PCI device ids of Linux's `include/drm/intel/pciids.h`: these prefixes hold those +/// families and no others, except `0x0a84` (Broxton), whose prefix Haswell shares. +/// +/// Their Windows Vulkan driver ends the process with 0xc0000005 in `igvk64.dll` when a device is +/// created, on every version reported, from 25.20.100.6576 (2019) to 31.0.101.2145, the legacy +/// branch that is the last driver Intel ships for them. DirectX 12 works on the same GPUs. +pub fn intel_gen9_to_gen11(device: u32) -> bool { + matches!(device >> 8, 0x19 | 0x1a | 0x31 | 0x3e | 0x45 | 0x4e | 0x59 | 0x5a | 0x87 | 0x8a | 0x9b) || device == 0x0a84 +} + +/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan +/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a +/// driver name with "Mesa" in it and is not included. +pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool { + c.backend == Backend::Vulkan + && c.device_type == DeviceType::IntegratedGpu + && c.vendor == INTEL + && intel_gen9_to_gen11(c.device) + && !c.driver.to_ascii_lowercase().contains("mesa") +} + +/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the +/// index of the same GPU's usable DirectX 12 entry, if there is one. +fn dx12_instead(candidates: &[Candidate], preferred: &Candidate) -> Option { + if !intel_vulkan_crashes(preferred) { + return None; + } + candidates.iter().position(|c| c.usable && c.backend == Backend::Dx12 && c.vendor == INTEL && c.device == preferred.device) +} + +/// Write the adapters and the choice to the log, with a warning when a correction applied. +pub(crate) fn log_choice(candidates: &[Candidate], index: usize, power: PowerPreference) { + for candidate in candidates { + log::info!("graphics adapter available: {candidate}"); + } + let Some(chosen) = candidates.get(index) else { + return; + }; + let others = candidates.iter().enumerate().filter(|(i, c)| *i != index && c.usable && same_gpu_and_driver(chosen, c)).count(); + if others > 0 { + log::warn!( + "{:?} lists \"{}\" {} times: several versions of its driver are installed, and a window drawn through a stale one can crash. Using the one with the most features; installing one driver package for every GPU removes the others.", + chosen.backend, + chosen.name, + others.saturating_add(1) + ); + } + if let Some(wgpu_own) = wgpu_choice(candidates, power).and_then(|i| candidates.get(i)) + && wgpu_own.backend == Backend::Vulkan + && chosen.backend == Backend::Dx12 + && wgpu_own.vendor == INTEL + && wgpu_own.device == chosen.device + { + log::warn!("Intel's Vulkan driver for \"{}\" crashes when the device is created: drawing through DirectX 12", wgpu_own.name); + } + log::info!("graphics adapter chosen: {chosen}"); +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use wgpu::Backend::{Dx12, Gl, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other}; + use wgpu::PowerPreference::{HighPerformance, LowPower}; + + pub(crate) const AMD: u32 = 0x1002; + pub(crate) const RX_6800M: u32 = 0x73df; + pub(crate) const RADEON_IGPU: u32 = 0x1638; + const POWERS: [PowerPreference; 3] = [PowerPreference::None, LowPower, HighPerformance]; + + #[expect(clippy::too_many_arguments, reason = "one line per adapter in the listings below")] + pub(crate) fn gpu( + name: &str, + backend: Backend, + device_type: DeviceType, + vendor: u32, + device: u32, + bus: &str, + driver: &str, + driver_info: &str, + features: u32, + ) -> Candidate { + Candidate { + name: name.into(), + backend, + device_type, + vendor, + device, + pci_bus_id: bus.into(), + driver: driver.into(), + driver_info: driver_info.into(), + features, + usable: true, + } + } + + /// A laptop with an integrated Radeon on a 2021 driver package and an RX 6800M on a 2026 one, + /// as wgpu 30 lists it: the Vulkan loader has both versions of AMD's driver, and the 2021 one + /// lists the RX 6800M first. A window drawn through that entry ended inside `amdvlk64.dll` + /// (0xc0000005) on every launch. + pub(crate) fn two_amd_drivers() -> Vec { + let amd = "AMD proprietary driver"; + vec![ + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2", 60), + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2 (AMD proprietary shader compiler)", 68), + gpu("AMD Radeon(TM) Graphics", Vulkan, IntegratedGpu, AMD, RADEON_IGPU, "", amd, "21.30.02.13", 56), + gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, AMD, RX_6800M, "0000:03:00.0", "32.0.21045.11001", "", 36), + gpu("AMD Radeon(TM) Graphics", Dx12, IntegratedGpu, AMD, RADEON_IGPU, "0000:08:00.0", "30.0.13002.13003", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9549", "", 36), + ] + } + + #[test] + fn a_gpu_listed_through_two_versions_of_its_driver_draws_with_the_newer_one() { + let adapters = two_amd_drivers(); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(wgpu_choice(&adapters, power), Some(0), "wgpu takes the stale entry, which crashed"); + assert_eq!(choose(&adapters, power), Some(1)); + } + // whichever version the loader lists first + let mut newer_first = adapters.clone(); + newer_first.swap(0, 1); + assert_eq!(choose(&newer_first, HighPerformance), Some(0)); + // two entries exposing as much: wgpu's, the first + let mut equal = adapters.clone(); + if let Some(c) = equal.get_mut(1) { + c.features = 60; + } + assert_eq!(choose(&equal, HighPerformance), Some(0)); + // three versions: the one exposing the most + let mut three = adapters.clone(); + three.insert(1, gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", "AMD proprietary driver", "24.1.1", 64)); + assert_eq!(choose(&three, HighPerformance), Some(2)); + // the stale entries are avoided, the newest is not + assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2)); + } + + #[test] + fn an_entry_without_a_bus_between_two_cards_is_never_drawn_with_when_avoided() { + // two cards of one model on their own buses, and an entry of the same driver without a bus + // id, which can be either card's other version + let radeon = |bus, features| gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, bus, "AMD proprietary driver", "", features); + let adapters = vec![radeon("0000:03:00.0", 60), radeon("", 70), radeon("0000:04:00.0", 80)]; + for power in POWERS { + let chosen = choose(&adapters, power); + assert_eq!(chosen, Some(2), "{power:?}"); + assert!(chosen.is_some_and(|i| !avoided(&adapters, i)), "{power:?}"); + } + assert!(avoided(&adapters, 0) && avoided(&adapters, 1) && !avoided(&adapters, 2)); + } + + #[test] + fn a_newer_version_never_overtakes_another_gpu_or_backend() { + assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2)); + let mut dx12_first = two_amd_drivers(); + dx12_first.rotate_left(3); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(choose(&dx12_first, power), Some(0)); + } + assert_eq!(choose(&dx12_first, LowPower), wgpu_choice(&dx12_first, LowPower)); + } + + #[test] + fn without_two_versions_of_one_driver_the_choice_is_wgpus() { + let nvidia = |backend, bus, driver, features| gpu("NVIDIA GeForce RTX 4070", backend, DiscreteGpu, 0x10de, 0x2786, bus, driver, "", features); + let intel = + |backend, bus, driver, features| gpu("Intel(R) UHD Graphics 770", backend, IntegratedGpu, 0x8086, 0x4680, bus, driver, "", features); + let radeon = |bus, driver, features| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, AMD, 0x744c, bus, driver, "", features); + let gl = |name: &str, features| gpu(name, Gl, Other, 0, 0, "", "", "", features); + let without = |skip: usize| two_amd_drivers().into_iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, c)| c).collect::>(); + let listings: Vec> = vec![ + vec![], + vec![nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // a laptop with two GPUs, through Vulkan and DirectX 12 + vec![ + intel(Vulkan, "0000:00:02.0", "Intel Corporation", 60), + nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70), + nvidia(Dx12, "0000:01:00.0", "32.0.15.6094", 36), + intel(Dx12, "0000:00:02.0", "31.0.101.5186", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.1", "", 36), + ], + // one GPU through two different drivers: Linux with AMDVLK and RADV + vec![radeon("0000:03:00.0", "AMD open-source driver", 58), radeon("0000:03:00.0", "radv", 71)], + // a vendor's driver and Dozen (Vulkan on DirectX 12) + vec![nvidia(Vulkan, "", "Dozen", 75), nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // two cards of one model, on their own buses + vec![radeon("0000:03:00.0", "AMD proprietary driver", 60), radeon("0000:04:00.0", "AMD proprietary driver", 68)], + // OpenGL reports no ids: two adapters cannot be told apart + vec![gl("ANGLE", 20), gl("ANGLE", 30)], + vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)], + without(0), + without(1), + ]; + for adapters in &listings { + for power in POWERS { + assert_eq!(choose(adapters, power), wgpu_choice(adapters, power), "{power:?} over {adapters:#?}"); + } + } + assert_eq!(choose(&[], HighPerformance), None); + } + + /// An Intel UHD Graphics 630 (Coffee Lake) on driver 25.20.100.6576 as wgpu 30 lists it. A + /// Vulkan device on it ended inside `igvk64.dll` (0xc0000005) as it was created. + pub(crate) fn uhd_630() -> Vec { + vec![ + gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Intel Corporation", "Intel driver", 44), + gpu("Intel(R) UHD Graphics 630", Dx12, IntegratedGpu, INTEL, 0x3e91, "0000:00:02.0", "25.20.100.6576", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9711", "", 36), + ] + } + + fn uhd_630_as(name: &str, device: u32) -> Vec { + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { name: name.into(), device, ..c } } else { c }).collect() + } + + #[test] + fn an_intel_gen9_to_gen11_gpu_draws_through_directx_12() { + for power in POWERS { + assert_eq!(wgpu_choice(&uhd_630(), power), Some(0), "wgpu takes Vulkan, which crashed"); + assert_eq!(choose(&uhd_630(), power), Some(1), "{power:?}"); + } + for (name, device) in [("Intel(R) HD Graphics 520", 0x1916), ("Intel(R) Iris(R) Plus Graphics", 0x8a5a)] { + assert_eq!(choose(&uhd_630_as(name, device), HighPerformance), Some(1), "{name}"); + } + let mut dx12_first = uhd_630(); + dx12_first.swap(0, 1); + assert_eq!(choose(&dx12_first, HighPerformance), Some(0)); + // without a usable DirectX 12 entry, the Vulkan entry is still never drawn with + let vulkan_only: Vec = uhd_630().into_iter().take(1).collect(); + assert_eq!(choose(&vulkan_only, HighPerformance), None); + assert!(avoided(&vulkan_only, 0)); + let mut dx12_unusable = uhd_630(); + if let Some(c) = dx12_unusable.get_mut(1) { + c.usable = false; + } + assert_eq!(choose(&dx12_unusable, HighPerformance), Some(2), "the software adapter"); + // Mesa's Vulkan driver for the same GPU on Linux is drawn with + let mesa = vec![gpu( + "Intel(R) UHD Graphics 630 (CFL GT2)", + Vulkan, + IntegratedGpu, + INTEL, + 0x3e91, + "0000:00:02.0", + "Intel open-source Mesa driver", + "Mesa 25.2.4", + 44, + )]; + assert_eq!(choose(&mesa, HighPerformance), Some(0)); + assert!(!avoided(&mesa, 0)); + // beside a discrete GPU: high performance keeps it; low power takes the Intel GPU's DirectX 12 entry + let mut laptop = uhd_630(); + laptop.insert(1, gpu("NVIDIA GeForce MX250", Vulkan, DiscreteGpu, 0x10de, 0x1d13, "0000:01:00.0", "NVIDIA", "", 70)); + assert_eq!(choose(&laptop, HighPerformance), Some(1)); + assert_eq!(choose(&laptop, LowPower), Some(2)); + assert!(avoided(&laptop, 0)); + } + + #[test] + fn later_intel_gpus_keep_wgpus_choice() { + for (name, device) in [("Intel(R) Iris(R) Xe Graphics", 0x9a49), ("Intel(R) UHD Graphics 770", 0x4680), ("Intel(R) Arc(TM) Graphics", 0x7d55)] + { + let adapters = uhd_630_as(name, device); + for power in POWERS { + assert_eq!(choose(&adapters, power), Some(0), "{name} {power:?}"); + } + } + let discrete: Vec = + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { device_type: DiscreteGpu, ..c } } else { c }).collect(); + assert_eq!(choose(&discrete, HighPerformance), Some(0)); + } + + #[test] + fn gen9_to_gen11_ids() { + for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] { + assert!(intel_gen9_to_gen11(id), "{id:#06x}"); + } + for id in [0x0a16, 0x0a1e, 0x1616, 0x9a49, 0x4c8a, 0x4680, 0x46a6, 0xa780, 0x4905, 0x56a0, 0x7d55, 0x64a0, 0xe20b, 0xb080] { + assert!(!intel_gen9_to_gen11(id), "{id:#06x}"); + } + } + + #[test] + fn two_entries_are_one_gpu_only_with_the_same_ids_type_driver_and_bus() { + let stale = two_amd_drivers().swap_remove(0); + let newer = two_amd_drivers().swap_remove(1); + assert!(same_gpu_and_driver(&stale, &newer) && same_gpu_and_driver(&stale, &stale)); + let on_bus = |bus: &str| Candidate { pci_bus_id: bus.into(), ..newer.clone() }; + assert!(same_gpu_and_driver(&stale, &on_bus("0000:03:00.0"))); + assert!(same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:03:00.0"))); + assert!(!same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:04:00.0"))); + for other in [ + Candidate { backend: Dx12, ..newer.clone() }, + Candidate { device_type: IntegratedGpu, ..newer.clone() }, + Candidate { vendor: 0x10de, ..newer.clone() }, + Candidate { device: RADEON_IGPU, ..newer.clone() }, + Candidate { driver: "radv".into(), ..newer.clone() }, + ] { + assert!(!same_gpu_and_driver(&stale, &other), "{other}"); + } + let unidentified = Candidate { vendor: 0, device: 0, ..newer }; + assert!(!same_gpu_and_driver(&unidentified, &unidentified)); + } + + #[test] + fn adapters_that_cannot_draw_to_the_window_are_left_out() { + let unusable = |which: &dyn Fn(usize, &Candidate) -> bool| { + let mut adapters = two_amd_drivers(); + for (i, c) in adapters.iter_mut().enumerate() { + c.usable = !which(i, c); + } + adapters + }; + assert_eq!(choose(&unusable(&|i, _| i == 1), HighPerformance), Some(0)); + assert_eq!(choose(&unusable(&|i, _| i == 0), HighPerformance), Some(1)); + assert_eq!(choose(&unusable(&|_, c| c.backend == Vulkan), HighPerformance), Some(3)); + assert_eq!(choose(&unusable(&|_, _| true), HighPerformance), None); + } + + #[test] + fn candidates_describe_themselves_for_the_log() { + let adapters = two_amd_drivers(); + let text = adapters.get(1).map(ToString::to_string).unwrap_or_default(); + assert_eq!( + text, + "\"AMD Radeon RX 6800M\" (Vulkan, discrete GPU, driver AMD proprietary driver 26.9.2 (AMD proprietary shader compiler), 68 features)" + ); + let offscreen = adapters.get(4).map(|c| Candidate { usable: false, ..c.clone() }.to_string()).unwrap_or_default(); + assert_eq!( + offscreen, + "\"AMD Radeon(TM) Graphics\" (Dx12, integrated GPU, driver 30.0.13002.13003, 36 features, bus 0000:08:00.0, cannot draw to the window)" + ); + assert!(adapters.get(5).is_some_and(Candidate::is_software)); + assert!(!adapters.first().is_some_and(Candidate::is_software)); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn native_instance_is_shared_across_callers() { + let gate = std::sync::Barrier::new(3); + std::thread::scope(|scope| { + let first = scope.spawn(|| { + gate.wait(); + native_instance() + }); + let second = scope.spawn(|| { + gate.wait(); + native_instance() + }); + gate.wait(); + let first = first.join().unwrap(); + assert_eq!(first, second.join().unwrap()); + assert_eq!(first, native_instance()); + }); + } + + /// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND` + /// says. Runs in a child process, which has them set. + #[test] + fn native_descriptor_reads_wgpu_flags_but_keeps_its_backends() { + const CHILD: &str = "CRAFT_GPU_DEVICE_TEST_NATIVE_DESCRIPTOR_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "adapter::tests::native_descriptor_reads_wgpu_flags_but_keeps_its_backends", "--nocapture"]) + .env(CHILD, "1") + .env("WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER", "1") + .env("WGPU_BACKEND", "gl") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "{stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + return; + } + let desc = native_descriptor(); + assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags); + let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + assert_eq!(desc.backends, backends); + } + + /// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's + /// `request_adapter` returns, and [`choose`] returns that adapter too, or, when wgpu's choice + /// is one [`avoided`] excludes, an adapter it does not exclude: a version exposing more + /// features, an Intel Gen 9 to Gen 11 GPU's DirectX 12 entry, or the best other adapter. + /// `None` only when every usable adapter is that Intel Vulkan entry. Passes without adapters. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() { + let backends = wgpu::Backends::PRIMARY; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle() }); + let adapters = pollster::block_on(instance.enumerate_adapters(backends)); + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, None)).collect(); + for power in POWERS { + let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() }; + let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None)); + assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}"); + let own_index = wgpu_choice(&candidates, power); + let chosen = choose(&candidates, power); + let picked = chosen.and_then(|i| candidates.get(i)); + match (own_index, chosen) { + (Some(own), Some(index)) if own != index => { + assert!(avoided(&candidates, own), "{power:?}: {picked:?} instead of {wgpu_own:?}, which is not avoided"); + assert!(!avoided(&candidates, index), "{power:?}: {picked:?} is avoided"); + } + (Some(own), None) => { + let only_intel_vulkan = candidates.iter().filter(|c| c.usable).all(intel_vulkan_crashes); + assert!(only_intel_vulkan, "{power:?}: nothing instead of {:?}", candidates.get(own)); + } + _ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"), + } + } + } +} diff --git a/crates/gpu-device/src/caps.rs b/crates/gpu-device/src/caps.rs new file mode 100644 index 0000000000..ea72379bbe --- /dev/null +++ b/crates/gpu-device/src/caps.rs @@ -0,0 +1,311 @@ +//! What an adapter can do, for choosing a pipeline and for the settings and the log. + +use std::fmt; +use std::ops::Deref; + +use craft_gpu::DeviceCaps; +use wgpu::{AdapterInfo, DeviceType, Features, Limits}; + +/// The maker of a GPU, from its PCI vendor id (or the Khronos vendor id some Vulkan drivers +/// report instead). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Vendor { + Nvidia, + Amd, + Intel, + Apple, + Qualcomm, + Arm, + ImgTec, + /// Microsoft's software adapter (WARP) and its virtual GPUs. + Microsoft, + /// Mesa's software drivers (llvmpipe, lavapipe). + Mesa, + /// Another id, or none (0). + Other(u32), +} + +impl Vendor { + pub fn from_id(id: u32) -> Vendor { + match id { + 0x10de => Vendor::Nvidia, + 0x1002 | 0x1022 => Vendor::Amd, + 0x8086 => Vendor::Intel, + 0x106b => Vendor::Apple, + 0x5143 => Vendor::Qualcomm, + 0x13b5 => Vendor::Arm, + 0x1010 => Vendor::ImgTec, + 0x1414 => Vendor::Microsoft, + 0x10005 => Vendor::Mesa, + other => Vendor::Other(other), + } + } +} + +impl fmt::Display for Vendor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Vendor::Nvidia => "NVIDIA", + Vendor::Amd => "AMD", + Vendor::Intel => "Intel", + Vendor::Apple => "Apple", + Vendor::Qualcomm => "Qualcomm", + Vendor::Arm => "Arm", + Vendor::ImgTec => "Imagination", + Vendor::Microsoft => "Microsoft", + Vendor::Mesa => "Mesa", + Vendor::Other(0) => return f.write_str("unknown vendor"), + Vendor::Other(id) => return write!(f, "vendor {id:#06x}"), + }; + f.write_str(name) + } +} + +/// What a device (or an adapter) can do, read from the [`DeviceCaps`] a `craft-gpu` context +/// reports. It holds only that `DeviceCaps`: the video formats, `f16` and timestamps come from its +/// feature names, the vendor from its vendor id, and its fields (the name, the backend and the +/// limits) can be read through `Deref`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Capabilities(DeviceCaps); + +impl Capabilities { + /// From an adapter's (or a device's) info, features and limits. + pub fn from_parts(info: &AdapterInfo, features: Features, limits: &Limits) -> Self { + Capabilities(device_caps_of(info, features, limits)) + } + + /// What `adapter` offers, for a settings page before a device is opened. A `craft-gpu` + /// context reports [`of_device`](Self::of_device) instead: a device can be granted less. + pub fn of_adapter(adapter: &wgpu::Adapter) -> Self { + Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits()) + } + + /// What `device` can do: the features and limits it was opened with. + pub fn of_device(device: &wgpu::Device) -> Self { + Self::from_parts(&device.adapter_info(), device.features(), &device.limits()) + } + + /// The `DeviceCaps` these capabilities read. + pub fn device_caps(&self) -> &DeviceCaps { + &self.0 + } + + pub fn into_device_caps(self) -> DeviceCaps { + self.0 + } + + /// Whether every feature in `features` is named in the caps. + fn has(&self, features: Features) -> bool { + features.iter_names().all(|(name, _)| self.0.has_feature(name)) + } + + /// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created + /// and sampled through plane views. wgpu 30 does not render to them: draw the planes into + /// `R8Unorm` and `Rg8Unorm` textures instead. + pub fn nv12(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_NV12) + } + + /// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane + /// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm` + /// textures ([`norm16`](Self::norm16)) instead. + pub fn p010(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_P010) + } + + /// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without + /// P010. + pub fn norm16(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_16BIT_NORM) + } + + /// `f16` in shaders. + pub fn shader_f16(&self) -> bool { + self.has(Features::SHADER_F16) + } + + /// Timestamp queries, for measuring GPU time per pass. + pub fn timestamps(&self) -> bool { + self.has(Features::TIMESTAMP_QUERY) + } + + pub fn vendor(&self) -> Vendor { + Vendor::from_id(self.0.vendor_id) + } + + /// The adapter draws on the CPU. + pub fn software(&self) -> bool { + self.0.software + } + + /// Whether a `width` × `height` texture fits. + pub fn fits(&self, width: u32, height: u32) -> bool { + let max = self.0.max_texture_dimension_2d; + width > 0 && height > 0 && width <= max && height <= max + } + + /// Whether 10-bit planes can be drawn: 16-bit normalized textures. P010 textures can only be + /// sampled. + pub fn ten_bit(&self) -> bool { + self.norm16() + } + + /// The features from `wanted` this adapter has, to ask for when opening a device. + pub fn available(adapter_features: Features, wanted: Features) -> Features { + adapter_features & wanted + } +} + +impl Deref for Capabilities { + type Target = DeviceCaps; + + fn deref(&self) -> &DeviceCaps { + &self.0 + } +} + +impl From for Capabilities { + fn from(caps: DeviceCaps) -> Self { + Capabilities(caps) + } +} + +impl From for DeviceCaps { + fn from(caps: Capabilities) -> Self { + caps.0 + } +} + +impl fmt::Display for Capabilities { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({}, {}", self.0.device_name, self.vendor(), self.0.backend_name)?; + if self.software() { + f.write_str(", software")?; + } + let flags = [ + (self.nv12(), "NV12"), + (self.p010(), "P010"), + (self.norm16(), "16-bit norm"), + (self.shader_f16(), "f16"), + (self.timestamps(), "timestamps"), + ]; + for (on, name) in flags { + if on { + write!(f, ", {name}")?; + } + } + write!(f, ", textures up to {} px)", self.0.max_texture_dimension_2d) + } +} + +/// The [`DeviceCaps`] a `craft-gpu` context reports for `device`: the limits and features the +/// device was opened with, not the adapter's, in the same form `craft-gpu-wgpu` reports for a +/// device it opens itself. +pub fn device_caps(device: &wgpu::Device) -> DeviceCaps { + Capabilities::of_device(device).into_device_caps() +} + +fn device_caps_of(info: &AdapterInfo, features: Features, limits: &Limits) -> DeviceCaps { + DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name.clone(), + max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, + max_buffer_size: limits.max_buffer_size, + max_texture_dimension_2d: limits.max_texture_dimension_2d, + features: features.iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == DeviceType::Cpu, + } +} + +#[cfg(test)] +mod tests { + use wgpu::Backend; + + use super::*; + + fn info(name: &str, vendor: u32, device_type: DeviceType) -> AdapterInfo { + AdapterInfo { name: name.into(), vendor, ..AdapterInfo::new(device_type, Backend::Vulkan) } + } + + #[test] + fn vendors_from_pci_and_khronos_ids() { + assert_eq!(Vendor::from_id(0x10de), Vendor::Nvidia); + assert_eq!(Vendor::from_id(0x1002), Vendor::Amd); + assert_eq!(Vendor::from_id(0x8086), Vendor::Intel); + assert_eq!(Vendor::from_id(0x10005), Vendor::Mesa); + assert_eq!(Vendor::from_id(0x1414), Vendor::Microsoft); + assert_eq!(Vendor::from_id(0), Vendor::Other(0)); + assert_eq!(Vendor::Other(0).to_string(), "unknown vendor"); + assert_eq!(Vendor::from_id(0x1234).to_string(), "vendor 0x1234"); + } + + #[test] + fn features_and_limits_become_capabilities() { + let features = Features::TEXTURE_FORMAT_NV12 | Features::TEXTURE_FORMAT_16BIT_NORM | Features::TIMESTAMP_QUERY; + let limits = Limits { max_texture_dimension_2d: 16384, ..Limits::default() }; + let c = Capabilities::from_parts(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert!(c.nv12() && !c.p010() && c.norm16() && c.timestamps() && !c.shader_f16() && !c.software()); + assert!(c.ten_bit()); + assert_eq!(c.vendor(), Vendor::Nvidia); + assert!(c.fits(7680, 4320) && c.fits(16384, 16384)); + assert!(!c.fits(16385, 1) && !c.fits(0, 1080) && !c.fits(1920, 0)); + assert_eq!(c.to_string(), "\"NVIDIA GeForce RTX 4070\" (NVIDIA, Vulkan, NV12, 16-bit norm, timestamps, textures up to 16384 px)"); + } + + #[test] + fn a_software_adapter_without_extras() { + let limits = Limits::downlevel_defaults(); + let c = Capabilities::from_parts(&info("llvmpipe (LLVM 19.1.0, 256 bits)", 0x10005, DeviceType::Cpu), Features::empty(), &limits); + assert!(c.software() && !c.ten_bit() && !c.nv12()); + // P010 alone is sampled, not drawn to + let p010 = Capabilities::from_parts(&info("x", 0x8086, DeviceType::IntegratedGpu), Features::TEXTURE_FORMAT_P010, &limits); + assert!(p010.p010() && !p010.ten_bit()); + assert_eq!(c.max_texture_dimension_2d, 2048); + assert!(!c.fits(3840, 2160)); + assert!(c.to_string().contains("software")); + let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16; + assert_eq!(Capabilities::available(Features::SHADER_F16 | Features::TIMESTAMP_QUERY, wanted), Features::SHADER_F16); + } + + #[test] + fn device_caps_carry_the_device_limits_and_feature_names() { + let limits = + Limits { max_texture_dimension_2d: 16384, max_buffer_size: 1 << 30, max_storage_buffer_binding_size: 1 << 28, ..Limits::default() }; + let features = Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY; + let caps = device_caps_of(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert_eq!(caps.backend_name, "Vulkan"); + assert_eq!(caps.device_name, "NVIDIA GeForce RTX 4070"); + assert_eq!((caps.max_texture_dimension_2d, caps.max_buffer_size, caps.max_storage_buffer_binding_size), (16384, 1 << 30, 1 << 28)); + assert_eq!((caps.vendor_id, caps.software), (0x10de, false)); + let mut names = caps.features.clone(); + names.sort(); + assert_eq!(names, ["TEXTURE_FORMAT_NV12", "TIMESTAMP_QUERY"]); + // a device opened without features reports none + let bare = device_caps_of(&info("llvmpipe", 0x10005, DeviceType::Cpu), Features::empty(), &Limits::downlevel_defaults()); + assert!(bare.features.is_empty()); + assert_eq!(bare.max_texture_dimension_2d, 2048); + assert_eq!((bare.vendor_id, bare.software), (0x10005, true)); + } + + #[test] + fn caps_from_a_craft_gpu_context_read_as_capabilities() { + let caps = DeviceCaps { + backend_name: "Dx12".into(), + device_name: "Intel(R) Arc(TM) A770".into(), + features: vec!["TEXTURE_FORMAT_P010".into(), "SHADER_F16".into(), "TEXTURE_FORMAT_16BIT_NORM".into()], + vendor_id: 0x8086, + ..DeviceCaps::default() + }; + let c = Capabilities::from(caps.clone()); + assert!(c.p010() && c.shader_f16() && c.ten_bit() && !c.nv12() && !c.timestamps() && !c.software()); + assert_eq!(c.vendor(), Vendor::Intel); + assert_eq!(c.to_string(), "\"Intel(R) Arc(TM) A770\" (Intel, Dx12, P010, 16-bit norm, f16, textures up to 8192 px)"); + assert_eq!(DeviceCaps::from(c), caps); + // the caps of a backend with no device claim nothing + let none = Capabilities::from(DeviceCaps::default()); + assert!(!none.nv12() && !none.p010() && !none.norm16() && !none.shader_f16() && !none.timestamps() && !none.software()); + assert_eq!(none.vendor(), Vendor::Other(0)); + } +} diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs new file mode 100644 index 0000000000..9374175a6b --- /dev/null +++ b/crates/gpu-device/src/health.rs @@ -0,0 +1,764 @@ +//! Device health: notices a lost wgpu device or an uncaptured wgpu error, so callers stop issuing +//! GPU work and reopen a device or fall back, instead of panicking. +//! +//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device +//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the +//! fault and registers the device-lost callback, and the polls here run only while the device is +//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks +//! [`DeviceHealth::fault`] first. +//! +//! Builds for the web too: the callbacks only touch atomics and a mutex. + +use std::fmt; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; + +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; + +/// Outcome of a bounded wait for submitted GPU work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WaitOutcome { + /// The submitted work finished before the deadline, or just after it, when wgpu read the + /// fence again at the end of the last poll. + Finished, + /// The deadline passed (or the device faulted) before the work finished. + TimedOut, + /// The caller canceled the wait before the work finished. + Canceled, +} + +/// Why the GPU cannot be used any more. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// The device was lost (driver reset, the OS ended a submission, `Device::destroy`). + Lost(String), + /// An uncaptured wgpu error (out of memory, validation, internal): the GPU output cannot be + /// trusted, and on most drivers the device is about to be lost anyway. + Error(String), +} + +impl Fault { + /// Whether the device itself was lost (rather than an error reported). + pub fn is_lost(&self) -> bool { + matches!(self, Fault::Lost(_)) + } + + /// An out-of-memory error on a device that still works: freeing memory, calling + /// [`DeviceHealth::clear_out_of_memory`] with the count read from + /// [`DeviceHealth::out_of_memory_count`] and trying again can succeed, unlike after a loss or + /// a validation error. Polls and waits keep running meanwhile. Only wgpu's own out-of-memory + /// error is recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory + /// is not one. + pub fn is_out_of_memory(&self) -> bool { + matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY) + } + + /// The driver's or wgpu's message. + pub fn detail(&self) -> &str { + match self { + Fault::Lost(s) | Fault::Error(s) => s, + } + } +} + +impl fmt::Display for Fault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Fault::Lost(s) if s.is_empty() => f.write_str("GPU device lost"), + Fault::Lost(s) => write!(f, "GPU device lost: {s}"), + Fault::Error(s) => write!(f, "GPU error: {s}"), + } + } +} + +/// A loss becomes [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost), and any other +/// fault becomes [`GpuFault::Operation`](craft_gpu::GpuFault::Operation), each with the fault's +/// text. +impl From for craft_gpu::GpuFault { + fn from(fault: Fault) -> Self { + match fault { + Fault::Lost(s) => craft_gpu::GpuFault::DeviceLost(s), + Fault::Error(s) => craft_gpu::GpuFault::Operation(s), + } + } +} + +/// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`). +pub const OUT_OF_MEMORY: &str = "Out of Memory"; + +/// The state wgpu's callbacks write and callers read, without a lock: flags in atomics and each +/// fault's text in a [`OnceLock`], whose `get` does not wait. A `set` that races another `set` +/// of the same slot waits only for that one store. +#[derive(Default)] +struct Inner { + /// The first device loss. + lost: OnceLock, + /// Out-of-memory errors seen. + out_of_memory_seen: AtomicU64, + /// Out-of-memory errors the caller cleared ([`DeviceHealth::clear_out_of_memory`]). + out_of_memory_cleared: AtomicU64, + /// The first other error. + error: OnceLock, + errors: AtomicU64, + /// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]). + device_lost: AtomicBool, +} + +/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state. +#[derive(Clone, Default)] +pub struct DeviceHealth(Arc); + +impl fmt::Debug for DeviceHealth { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DeviceHealth").field("fault", &self.fault()).field("errors", &self.errors()).finish() + } +} + +impl DeviceHealth { + /// A healthy flag not attached to a device (tests, CPU-only callers). + pub fn new() -> Self { + Self::default() + } + + /// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag + /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). On the + /// browser backend, wgpu 30 panics on an uncaptured `GPUInternalError` before this handler + /// runs, so such an error is not recorded; validation and out-of-memory errors are. + pub fn watch(device: &wgpu::Device) -> Self { + let health = Self::new(); + let lost = health.clone(); + // Called by wgpu with its own locks held: only record, never call back into wgpu. + device.set_device_lost_callback(move |reason, message| { + let detail = match (reason, message.is_empty()) { + (wgpu::DeviceLostReason::Destroyed, true) => "device destroyed".to_string(), + (_, true) => "lost by the driver".to_string(), + (_, false) => message, + }; + log::error!("wgpu device lost ({reason:?}): {detail}"); + // The loss first: a caller that sees `device_lost` then also sees the fault. + lost.mark(Fault::Lost(detail)); + lost.0.device_lost.store(true, Ordering::Release); + }); + let errors = health.clone(); + device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e))); + health + } + + /// Record an uncaptured wgpu error. + fn uncaptured(&self, e: &wgpu::Error) { + self.0.errors.fetch_add(1, Ordering::Relaxed); + log::error!("uncaptured wgpu error: {e}"); + self.mark(fault_of(e)); + } + + /// Record an error an error scope caught. + /// + /// The uncaptured-error handler never sees a scoped error, so without this a watched device + /// would keep being handed work after it failed. Polls first: a lost device is a + /// [`Fault::Lost`], and its callback may not have run yet (it runs on a poll). The poll does + /// not block. + pub fn caught(&self, device: &wgpu::Device, error: &wgpu::Error) { + if self.lost() { + return; + } + #[cfg(not(target_arch = "wasm32"))] + self.poll(device); + #[cfg(target_arch = "wasm32")] + let _ = device; + if self.lost() { + return; + } + self.mark(fault_of(error)); + } + + fn lost(&self) -> bool { + self.fault().is_some_and(|f| f.is_lost()) + } + + /// Mark the device unusable. The first fault is kept; a later device loss replaces an error, + /// and a later out-of-memory error is reported over another error, so a caller still sees + /// that freeing memory may help after a validation error in the same frame. + pub fn mark(&self, fault: Fault) { + if fault.is_out_of_memory() { + self.0.out_of_memory_seen.fetch_add(1, Ordering::AcqRel); + return; + } + // A slot already set keeps its first text. + let _ = match fault { + Fault::Lost(text) => self.0.lost.set(text), + Fault::Error(text) => self.0.error.set(text), + }; + } + + /// Out-of-memory errors recorded so far. Read it when handling an out-of-memory fault, and + /// pass it to [`clear_out_of_memory`](Self::clear_out_of_memory) once memory was freed. + pub fn out_of_memory_count(&self) -> u64 { + self.0.out_of_memory_seen.load(Ordering::Acquire) + } + + /// Clear the out-of-memory errors up to `count` (from + /// [`out_of_memory_count`](Self::out_of_memory_count)) after the caller freed memory. One + /// recorded after `count` was read stays. The device counts as healthy again unless it was + /// lost or another error was recorded, which [`fault`](Self::fault) then reports. + pub fn clear_out_of_memory(&self, count: u64) { + let count = count.min(self.0.out_of_memory_seen.load(Ordering::Acquire)); + self.0.out_of_memory_cleared.fetch_max(count, Ordering::AcqRel); + } + + /// Whether an out-of-memory error is recorded and not cleared. + fn out_of_memory(&self) -> bool { + let cleared = self.0.out_of_memory_cleared.load(Ordering::Acquire); + self.0.out_of_memory_seen.load(Ordering::Acquire) > cleared + } + + /// Whether the device may still be used: no fault was recorded, or only out-of-memory errors + /// that [`clear_out_of_memory`](Self::clear_out_of_memory) cleared. + pub fn is_ok(&self) -> bool { + self.0.lost.get().is_none() && self.0.error.get().is_none() && !self.out_of_memory() + } + + /// Whether polls and waits still run: the device was not lost and reported no error other + /// than out of memory. A poll reclaims the staging memory that recovering from an + /// out-of-memory error needs. + fn pollable(&self) -> bool { + self.0.lost.get().is_none() && self.0.error.get().is_none() + } + + /// Why the device cannot be used, if it cannot. + pub fn fault(&self) -> Option { + if let Some(text) = self.0.lost.get() { + return Some(Fault::Lost(text.clone())); + } + if self.out_of_memory() { + return Some(Fault::Error(OUT_OF_MEMORY.into())); + } + self.0.error.get().map(|text| Fault::Error(text.clone())) + } + + /// The device loss in the form of `craft_gpu::GpuContext::device_status`: + /// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded, + /// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one + /// device-lost callback per device, so a `craft-gpu` context on a device that + /// [`watch`](Self::watch) watches reads the loss here instead of setting its own callback. + pub fn device_status(&self) -> Result<(), craft_gpu::GpuFault> { + match self.0.lost.get() { + Some(text) => Err(craft_gpu::GpuFault::DeviceLost(text.clone())), + None => Ok(()), + } + } + + /// Uncaptured wgpu errors seen so far. + pub fn errors(&self) -> u64 { + self.0.errors.load(Ordering::Relaxed) + } + + /// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it + /// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing + /// drawn with the device reaches the screen, the window's own frames included. + pub fn device_lost(&self) -> bool { + self.0.device_lost.load(Ordering::Acquire) + } + + /// Non-blocking poll that runs even after a fault was recorded, so a device that is lost + /// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next + /// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost). + pub fn probe(&self, device: &wgpu::Device) { + if self.device_lost() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// `Device::poll` panicked: wgpu found the device lost. + fn lost_by_poll(&self) { + self.mark(Fault::Lost("the device stopped responding".into())); + self.0.device_lost.store(true, Ordering::Release); + } + + /// Block until the work up to `index` finished, unless the device was lost or reported an + /// error other than out of memory. To wait for everything submitted so far, pass the index of + /// an empty submission (`queue.submit([])`); work submitted after it does not extend the + /// wait. Returns whether the work finished with the device still usable: `false` when it was + /// lost or reported such an error, before or during the wait, and when the poll itself + /// failed, so the work may still be running. After an out-of-memory error the wait still + /// runs. The wait has no deadline, but it polls in slices of at most 100 ms, so a loss or an + /// error other than out of memory that another clone records while the work has not finished + /// ends it after the current slice. A panic in `Device::poll` is caught and recorded as a + /// loss. Native only: the web has no blocking wait. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex) -> bool { + const SLICE: Duration = Duration::from_millis(100); + self.wait_unbounded(|| { + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(SLICE) }) + })); + match poll { + Ok(Ok(_)) => SlicePoll::Done, + Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }) + } + + /// [`Self::wait`]'s loop: `poll` runs one slice and reports what wgpu returned. The loop ends + /// when a slice finished or failed, and before the next slice once a clone of this flag + /// recorded a loss or an error other than out of memory. + #[cfg(not(target_arch = "wasm32"))] + fn wait_unbounded(&self, mut poll: impl FnMut() -> SlicePoll) -> bool { + loop { + if !self.pollable() { + return false; + } + match poll() { + SlicePoll::Done => return self.pollable(), + SlicePoll::Pending => {} + SlicePoll::Failed => return false, + } + } + } + + /// Non-blocking poll (reclaims staging memory), skipped once the device was lost or reported + /// an error other than out of memory. + pub fn poll(&self, device: &wgpu::Device) { + if !self.pollable() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// Like [`Self::wait`], but bounded: returns whether the work up to `index` finished within + /// `timeout`. To wait for everything submitted so far, pass the index of an empty submission + /// (`queue.submit([])`); work submitted after it does not extend the wait. A timeout marks the + /// device faulted, so later work stops going to a GPU that no longer answers. A submission + /// index the device never issued returns `false` and leaves the device healthy. A zero + /// `timeout`, or one that passes before the first poll, returns `false` and leaves the device + /// healthy. A device that was already lost, or that reported an error other than out of + /// memory, returns `false` unchanged. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex, timeout: Duration) -> bool { + self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished + } + + /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between + /// them, keeping the same overall deadline. Every slice waits for the same `index`. A slice + /// that times out means the work has not finished yet; only the overall deadline (or a poll + /// that panics) marks the device faulted. A loss or an error other than out of memory that + /// another clone records during the wait ends it after the current slice, with + /// [`WaitOutcome::TimedOut`]. wgpu reads the fence again after a slice's own timeout, so work + /// that finishes in that gap, just after the deadline, is [`WaitOutcome::Finished`]. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout_cancelable( + &self, + device: &wgpu::Device, + index: wgpu::SubmissionIndex, + timeout: Duration, + canceled: &(dyn Fn() -> bool + Sync), + ) -> WaitOutcome { + if !self.pollable() { + return WaitOutcome::TimedOut; + } + let mut wrong_index = false; + let mut polled = false; + let start = Instant::now(); + let elapsed = || start.elapsed(); + let outcome = wait_slices(timeout, canceled, elapsed, |slice| { + polled = true; + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) + })); + match poll { + Ok(Ok(_)) => self.after_slice(true), + Ok(Err(wgpu::PollError::Timeout)) => self.after_slice(false), + // A submission index the device never issued: the caller's mistake, not the GPU's. + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + wrong_index = true; + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }); + // A deadline that passed before the first poll says nothing about the device. + if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.pollable() { + self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64()))); + } + outcome + } + + /// What a slice that returned reports, `finished` or not: failed once a clone of this flag + /// recorded a loss or an error other than out of memory, so the next slice does not poll a + /// device that is not to be used. + #[cfg(not(target_arch = "wasm32"))] + fn after_slice(&self, finished: bool) -> SlicePoll { + if !self.pollable() { + SlicePoll::Failed + } else if finished { + SlicePoll::Done + } else { + SlicePoll::Pending + } + } +} + +/// What one bounded poll reported. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SlicePoll { + Done, + Pending, + Failed, +} + +/// Wait for `total`, polling in slices no longer than 100 ms and checking `canceled` between +/// them. `elapsed` gives the time since the wait started. A slice that times out is pending, not +/// a failure; only the overall deadline or a failed poll ends the wait early. +#[cfg(not(target_arch = "wasm32"))] +fn wait_slices( + total: Duration, + canceled: &(dyn Fn() -> bool + Sync), + mut elapsed: impl FnMut() -> Duration, + mut poll: impl FnMut(Duration) -> SlicePoll, +) -> WaitOutcome { + const SLICE: Duration = Duration::from_millis(100); + loop { + if canceled() { + return WaitOutcome::Canceled; + } + let remaining = total.saturating_sub(elapsed()); + if remaining.is_zero() { + return WaitOutcome::TimedOut; + } + match poll(remaining.min(SLICE)) { + SlicePoll::Done => return WaitOutcome::Finished, + SlicePoll::Pending => {} + SlicePoll::Failed => return WaitOutcome::TimedOut, + } + } +} + +/// The whole message of wgpu's `DeviceError::Lost`. +const LOST_CAUSE: &str = "Parent device is lost"; + +/// Whether one of the errors that caused `e` (its `source` chain) is wgpu's `DeviceError::Lost`: +/// an error whose whole message is [`LOST_CAUSE`]. A resource label is part of another error's +/// message, so a label never matches. +fn caused_by_loss(e: &wgpu::Error) -> bool { + let source: &(dyn std::error::Error + 'static) = match e { + wgpu::Error::Validation { source, .. } | wgpu::Error::Internal { source, .. } => source.as_ref(), + _ => return false, + }; + std::iter::successors(Some(source), |c| c.source()).any(|c| c.to_string().trim().eq_ignore_ascii_case(LOST_CAUSE)) +} + +/// The fault a wgpu error stands for. An error caused by a lost device ([`caused_by_loss`]) +/// follows a device loss whose callback may not have run yet (it runs on the next poll), so it +/// counts as a loss rather than as an error. An error about a destroyed buffer or texture is an +/// error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`]. The text keeps the causes +/// ([`one_line`]). +fn fault_of(e: &wgpu::Error) -> Fault { + let text = e.to_string(); + if matches!(e, wgpu::Error::OutOfMemory { .. }) { + Fault::Error(OUT_OF_MEMORY.into()) + } else if caused_by_loss(e) { + Fault::Lost(one_line(&text)) + } else { + Fault::Error(one_line(&text)) + } +} + +/// wgpu's multi-line error text on one line: the heading and each cause, joined with ": ", +/// without wgpu's "Caused by:" line, cut to 200 characters. +fn one_line(s: &str) -> String { + const MAX: usize = 200; + let mut out = String::new(); + let mut count = 0; + let lines = s.lines().map(str::trim).filter(|l| !l.is_empty() && !l.eq_ignore_ascii_case("Caused by:")); + for (i, line) in lines.enumerate() { + let separator = if i == 0 { "" } else { ": " }; + for c in separator.chars().chain(line.chars()) { + if count == MAX { + out.push('…'); + return out; + } + out.push(c); + count += 1; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_fault_wins_but_loss_replaces_an_error() { + let h = DeviceHealth::new(); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + h.mark(Fault::Error("out of memory".into())); + assert!(!h.is_ok()); + let c = h.clone(); + c.mark(Fault::Error("second".into())); + assert_eq!(h.fault(), Some(Fault::Error("out of memory".into()))); + c.mark(Fault::Lost("reset".into())); + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + c.mark(Fault::Lost("later".into())); + assert_eq!(h.fault().map(|f| f.to_string()).as_deref(), Some("GPU device lost: reset")); + // a recorded loss is not wgpu reporting the device lost + assert!(!h.device_lost()); + } + + #[test] + fn faults_in_the_craft_gpu_form() { + use craft_gpu::GpuFault; + let h = DeviceHealth::new(); + assert_eq!(h.device_status(), Ok(())); + // an error, out of memory included, is not a loss + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.mark(Fault::Error("Validation Error".into())); + assert_eq!(h.device_status(), Ok(())); + h.mark(Fault::Lost("reset".into())); + assert_eq!(h.device_status(), Err(GpuFault::DeviceLost("reset".into()))); + assert_eq!(GpuFault::from(Fault::Lost("reset".into())), GpuFault::DeviceLost("reset".into())); + assert_eq!(GpuFault::from(Fault::Error(OUT_OF_MEMORY.into())), GpuFault::Operation(OUT_OF_MEMORY.into())); + assert_eq!(h.fault().map(GpuFault::from), Some(GpuFault::DeviceLost("reset".into()))); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_cancel_timeout_and_completion() { + let never = || false; + // a clock that does not move: only the polls end these waits + let still = || Duration::ZERO; + assert_eq!(wait_slices(Duration::ZERO, &never, still, |_| SlicePoll::Done), WaitOutcome::TimedOut); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Done), WaitOutcome::Finished); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Failed), WaitOutcome::TimedOut); + + let mut polls = 0; + let outcome = wait_slices(Duration::from_secs(1), &never, still, |_| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + }); + assert_eq!(outcome, WaitOutcome::Finished); + assert_eq!(polls, 3, "a timed-out slice is retried, not treated as a failure"); + + let canceled = || true; + let mut called = false; + assert_eq!( + wait_slices(Duration::from_secs(1), &canceled, still, |_| { + called = true; + SlicePoll::Done + }), + WaitOutcome::Canceled + ); + assert!(!called, "cancellation is checked before polling"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_end_at_the_deadline_of_a_moving_clock() { + let never = || false; + let now = std::cell::Cell::new(Duration::ZERO); + let mut slices = Vec::new(); + let clock = || now.get(); + let outcome = wait_slices(Duration::from_millis(250), &never, clock, |slice| { + slices.push(slice); + now.set(now.get() + slice); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::TimedOut); + assert_eq!(slices, [Duration::from_millis(100), Duration::from_millis(100), Duration::from_millis(50)]); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_observes_cancel_while_pending() { + let flag = AtomicBool::new(false); + let canceled = || flag.load(Ordering::SeqCst); + let mut polls = 0; + let still = || Duration::ZERO; + let outcome = wait_slices(Duration::from_secs(1), &canceled, still, |_| { + polls += 1; + flag.store(true, Ordering::SeqCst); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::Canceled); + assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_a_wait_stops_the_next_slice() { + let h = DeviceHealth::new(); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + assert_eq!(h.after_slice(true), SlicePoll::Done); + // out of memory alone: polls keep reclaiming memory + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + // another clone records a validation error while a slice is pending + h.clone().mark(Fault::Error("Validation Error".into())); + assert_eq!(h.after_slice(false), SlicePoll::Failed, "the next slice must not poll"); + assert_eq!(h.after_slice(true), SlicePoll::Failed); + let lost = DeviceHealth::new(); + lost.clone().mark(Fault::Lost("reset".into())); + assert_eq!(lost.after_slice(false), SlicePoll::Failed); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_an_unbounded_wait_ends_it() { + let h = DeviceHealth::new(); + let other = h.clone(); + let mut polls = 0; + let finished = h.wait_unbounded(|| { + polls += 1; + if polls == 2 { + other.mark(Fault::Error("Validation Error".into())); + } + assert!(polls <= 2, "a slice ran after the fault"); + SlicePoll::Pending + }); + assert!(!finished); + assert_eq!(polls, 2); + // out of memory alone keeps the wait going until the work finishes + let oom = DeviceHealth::new(); + oom.mark(Fault::Error(OUT_OF_MEMORY.into())); + let mut polls = 0; + assert!(oom.wait_unbounded(|| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + })); + assert_eq!(polls, 3); + assert!(!DeviceHealth::new().wait_unbounded(|| SlicePoll::Failed)); + } + + #[test] + fn fault_text() { + assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); + assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x"); + assert_eq!(one_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid: more"); + assert_eq!(one_line(&"a".repeat(300)).chars().count(), 201); + assert_eq!(one_line(&"a".repeat(200)), "a".repeat(200)); + assert_eq!(one_line(&format!("{}\nb", "a".repeat(199))), format!("{}:…", "a".repeat(199))); + assert!(Fault::Error("Out of Memory".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory()); + let h = DeviceHealth::new(); + h.mark(Fault::Error("Validation Error".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.mark(Fault::Lost("reset".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_lost())); + assert!(!Fault::Lost("out of memory".into()).is_out_of_memory()); + } + + #[test] + fn out_of_memory_keeps_polls_running_until_cleared() { + let h = DeviceHealth::new(); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + assert!(h.pollable(), "polls reclaim the memory that recovery needs"); + let seen = h.out_of_memory_count(); + // one recorded while the caller freed memory is not cleared with the earlier ones + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.clear_out_of_memory(seen); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.clear_out_of_memory(h.out_of_memory_count()); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + // a count larger than the ones recorded does not hide later errors + h.clear_out_of_memory(u64::MAX); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + h.clear_out_of_memory(h.out_of_memory_count()); + // an earlier error is still there once the out-of-memory error is cleared + h.mark(Fault::Error("Validation Error".into())); + assert!(!h.pollable()); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.pollable(), "a later out-of-memory error does not undo the earlier error"); + h.clear_out_of_memory(h.out_of_memory_count()); + assert_eq!(h.fault(), Some(Fault::Error("Validation Error".into()))); + assert!(!h.is_ok() && !h.pollable()); + let lost = DeviceHealth::new(); + lost.mark(Fault::Error(OUT_OF_MEMORY.into())); + lost.mark(Fault::Lost("reset".into())); + assert!(!lost.pollable()); + } + + #[test] + fn marks_from_several_threads_keep_the_loss() { + let h = DeviceHealth::new(); + let threads: Vec<_> = (0..8) + .map(|i| { + let h = h.clone(); + std::thread::spawn(move || h.mark(if i == 5 { Fault::Lost("reset".into()) } else { Fault::Error(format!("e{i}")) })) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + } + + /// An error and the errors that caused it, outermost first, as wgpu-core chains them. + #[derive(Debug)] + struct Cause(&'static str, Option>); + + impl fmt::Display for Cause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } + } + + impl std::error::Error for Cause { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1.as_deref().map(|c| c as _) + } + } + + /// A validation error with the causes `chain` and wgpu's description of them. + fn validation(chain: &[&'static str]) -> wgpu::Error { + let source = chain.iter().rev().fold(None, |inner, text| Some(Box::new(Cause(text, inner)))); + let mut description = String::from("Validation Error\n\nCaused by:\n"); + for c in chain { + description.push_str(&format!(" {c}\n")); + } + wgpu::Error::Validation { source: source.unwrap_or_else(|| Box::new(Cause("", None))), description } + } + + #[test] + fn only_a_lost_device_counts_as_a_loss() { + let lost = validation(&["In Device::create_buffer", "Parent device is lost"]); + assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); + let destroyed = validation(&["In Queue::submit", "Buffer 'pc' has been destroyed"]); + // the stored text names what failed, not only wgpu's heading + assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error: In Queue::submit: Buffer 'pc' has been destroyed".into())); + assert_eq!(fault_of(&lost), Fault::Lost("Validation Error: In Device::create_buffer: Parent device is lost".into())); + let texture = validation(&["Texture with 'frame' label has been destroyed"]); + assert!(!fault_of(&texture).is_lost()); + // a label is the caller's text, not the cause, even on a line of its own + let labeled = validation(&["In Queue::submit", "Buffer 'device is lost' has been destroyed"]); + assert_eq!(fault_of(&labeled), Fault::Error("Validation Error: In Queue::submit: Buffer 'device is lost' has been destroyed".into())); + for label in ["Buffer 'Parent device is lost' has been destroyed", "Buffer 'a\nParent device is lost\nb' has been destroyed"] { + let labeled = validation(&["In Queue::submit", label]); + assert!(!fault_of(&labeled).is_lost(), "{label:?}"); + } + } +} diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs new file mode 100644 index 0000000000..a2988b90d2 --- /dev/null +++ b/crates/gpu-device/src/lib.rs @@ -0,0 +1,43 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Choosing and opening a wgpu device for a Craft app. +//! +//! - [`list`] gives every adapter as plain [`Candidate`] data for a settings page, and +//! [`AdapterKey`] identifies one across runs. +//! - [`select`] and [`ranked`] choose an adapter for a [`Preference`] (Auto, low power, a named +//! adapter, software) with wgpu's own rule and two corrections for drivers that crash +//! ([`choose`]); [`Notice`] says when the choice was not the one asked for. +//! - [`open`] opens a device, moving to the next adapter and last to a software one when a device +//! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` +//! block on wgpu's futures and are native only; [`list_async`] and [`open_async`] are the same +//! as futures, for a `wasm32` web worker as well as native. +//! - In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be +//! chosen, and wgpu 30 cannot ask for the browser's fallback (software) adapter. `open_async` +//! asks for the adapter with [`Preference::power`]. [`Capabilities`] and [`Recovery`] work +//! there as they do on native, and so does [`DeviceHealth`] apart from its blocking waits, +//! which are native only. +//! - [`Capabilities`] reads what the device can do (NV12 and P010 textures, 16-bit norm formats, +//! `f16`, timestamps, the vendor, a software adapter, sizes) from the `craft_gpu::DeviceCaps` +//! it holds, which [`device_caps`] and [`Opened::device_caps`] give for a `craft-gpu` context. +//! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and +//! [`Recovery`] says what to open after a loss. [`DeviceHealth::device_status`] reports a loss +//! as `craft_gpu::GpuFault::DeviceLost`, and a [`Fault`] converts to a `craft_gpu::GpuFault`. +//! +//! The selection functions are pure, so tests run without a GPU. + +mod adapter; +mod caps; +mod health; +mod open; +mod preference; +mod recovery; + +pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance}; +pub use caps::{Capabilities, Vendor, device_caps}; +pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome}; +pub use open::{OpenError, Opened, Request, list_async, open_async, pick}; +#[cfg(not(target_arch = "wasm32"))] +pub use open::{list, open}; +pub use preference::{AdapterKey, Notice, Preference, Selection, backend_name, ranked, select}; +pub use recovery::{Recovery, RecoveryPolicy, RecoveryStep}; diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs new file mode 100644 index 0000000000..cb55cdfcc3 --- /dev/null +++ b/crates/gpu-device/src/open.rs @@ -0,0 +1,474 @@ +//! Listing adapters and opening a device, trying the next adapter when one fails. + +use std::fmt; + +use wgpu::{Adapter, Features, Instance, Limits, Surface}; + +use crate::adapter::{Candidate, avoided, log_choice}; +use crate::caps::Capabilities; +use crate::health::DeviceHealth; +use crate::preference::{Notice, Preference, Selection, asked_for, ranked, select}; + +/// What the device is opened with. +#[derive(Clone, Debug, Default)] +pub struct Request<'a> { + pub label: Option<&'a str>, + /// Features the device must have. An adapter without them is skipped. + pub required_features: Features, + /// Features asked for when the adapter has them. Experimental features + /// (`Features::all_experimental_mask`) are left out here: the device descriptor does not + /// enable experimental features, and wgpu refuses a device that asks for one without that. + pub optional_features: Features, + /// The limits to ask for; `None` asks for the adapter's own limits. An adapter whose limits + /// are lower is skipped. + pub limits: Option, +} + +/// An opened device. +#[derive(Debug)] +pub struct Opened { + pub adapter: Adapter, + pub device: wgpu::Device, + pub queue: wgpu::Queue, + /// The adapter as plain data. + pub candidate: Candidate, + /// What the device was opened with, as the `craft_gpu::DeviceCaps` it reports. + pub caps: Capabilities, + /// Watches the device for a loss and for uncaptured errors. + pub health: DeviceHealth, + /// What to tell the user about the choice. + pub notices: Vec, +} + +impl Opened { + /// The device's [`DeviceCaps`](craft_gpu::DeviceCaps) for a `craft-gpu` context + /// ([`device_caps`](crate::device_caps)). + pub fn device_caps(&self) -> craft_gpu::DeviceCaps { + self.caps.device_caps().clone() + } +} + +/// Why no device could be opened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenError { + /// No adapter is listed that can draw (to the surface, when there is one). + NoAdapter, + /// Every adapter tried failed to open a device; each failure is a [`Notice::DeviceFailed`]. + NoDevice(Vec), + /// The only adapters that can draw are ones [`choose`](crate::choose) never draws with, + /// because their driver can end the process; these are their names. + UnsafeDriver(Vec), +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OpenError::NoAdapter => f.write_str("no graphics adapter is available"), + OpenError::NoDevice(notices) => { + f.write_str("no graphics adapter could be opened")?; + for n in notices { + if let Notice::DeviceFailed { adapter, error } = n { + write!(f, "; \"{adapter}\": {error}")?; + } + } + Ok(()) + } + OpenError::UnsafeDriver(names) => { + let names = names.iter().map(|n| format!("\"{n}\"")).collect::>().join(", "); + write!(f, "the only graphics adapters that can draw ({names}) use a driver that can crash; update the graphics driver") + } + } + } +} + +impl std::error::Error for OpenError {} + +/// Every adapter `instance` lists over its backends, as adapters and as plain data. `surface` +/// marks the adapters that cannot draw to it as unusable. Native only: it blocks on wgpu's +/// future, which on the web would wait on the thread that must resolve it. [`list_async`] works +/// on both. +#[cfg(not(target_arch = "wasm32"))] +pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + pollster::block_on(list_async(instance, surface)) +} + +/// [`list`] as a future, for a `wasm32` web worker as well as native. In a browser, WebGPU offers +/// one adapter for a power preference, and the list holds the high-performance one, which +/// [`open_async`] opens for `Auto` and for a named adapter. +pub async fn list_async(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await; + #[cfg(target_arch = "wasm32")] + let adapters = browser_adapter(instance, surface, wgpu::PowerPreference::HighPerformance).await; + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) +} + +/// The adapter a browser offers for `power`, if any. +#[cfg(target_arch = "wasm32")] +async fn browser_adapter(instance: &Instance, surface: Option<&Surface<'_>>, power: wgpu::PowerPreference) -> Vec { + let options = wgpu::RequestAdapterOptions { power_preference: power, compatible_surface: surface, ..Default::default() }; + instance.request_adapter(&options).await.into_iter().collect() +} + +/// The adapter to draw with for `preference`, from adapters already listed, with the choice in the +/// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device +/// itself; that selector takes a `String` error, so convert with `map_err(|e| e.to_string())`. +/// With no usable adapter the error is [`OpenError::UnsafeDriver`] when only adapters that +/// [`choose`](crate::choose) never draws with can draw, and [`OpenError::NoAdapter`] otherwise, +/// with the listed adapters in the log. +pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), OpenError> { + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + let Some(selection) = select(&candidates, preference) else { + return Err(unselected(&candidates)); + }; + log_choice(&candidates, selection.index, preference.power()); + for notice in &selection.notices { + log::warn!("{notice}"); + } + let adapter = adapters.get(selection.index).cloned().ok_or(OpenError::NoAdapter)?; + Ok((adapter, selection)) +} + +/// The error for `candidates` among which `select` found no adapter, with the list in the log +/// when it is not [`OpenError::UnsafeDriver`]. +fn unselected(candidates: &[Candidate]) -> OpenError { + let left_out = left_out(candidates); + if !left_out.is_empty() { + return OpenError::UnsafeDriver(left_out); + } + let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); + log::warn!("no usable graphics adapter among {}: {listed}", candidates.len()); + OpenError::NoAdapter +} + +/// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] +/// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter +/// without `request.required_features`, or whose device fails to open, adds a +/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`]; [`open_async`] +/// works on both. +#[cfg(not(target_arch = "wasm32"))] +pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result { + pollster::block_on(open_async(instance, surface, preference, request)) +} + +/// [`open`] as a future, for a `wasm32` web worker as well as native. On native it lists every +/// adapter, as `open` does. In a browser, WebGPU offers one adapter for a power preference, so +/// `open_async` asks for the adapter with [`Preference::power`]. A named adapter then gives the +/// automatic choice with [`Notice::AdapterMissing`]. wgpu 30 does not pass the fallback-adapter +/// option to the browser, so [`Preference::Software`] gives the browser's adapter with +/// [`Notice::NoSoftwareAdapter`] unless that adapter is itself a software one. +pub async fn open_async( + instance: &Instance, + surface: Option<&Surface<'_>>, + preference: &Preference, + request: &Request<'_>, +) -> Result { + let (adapters, candidates) = adapters_for(instance, surface, preference).await; + // Whether drawing is in software depends on the adapter that opens, which `finish` knows. + let mut notices: Vec = + select(&candidates, preference).map(|s| s.notices).unwrap_or_default().into_iter().filter(|n| *n != Notice::SoftwareOnly).collect(); + let order = ranked(&candidates, preference); + if let Some(first) = order.first() { + log_choice(&candidates, *first, preference.power()); + } + let mut tried: Vec<&Candidate> = Vec::new(); + for index in order { + let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else { + continue; + }; + tried.push(candidate); + match open_on(adapter, request).await { + Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)), + Err(error) => { + log::warn!("graphics adapter {candidate} could not be opened: {error}"); + notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }); + } + } + } + // wgpu's fallback adapter, unless the loop above already tried it. In a browser the request + // below would ask for the same adapter again. + if cfg!(not(target_arch = "wasm32")) { + let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() }; + let fallback = instance.request_adapter(&options).await.ok().map(|a| (Candidate::of(&a, surface), a)); + if let Some((candidate, adapter)) = fallback.filter(|(c, _)| !tried.contains(&c)) { + match open_on(&adapter, request).await { + Ok((device, queue)) => { + log::info!("graphics adapter chosen: {candidate}"); + return Ok(finish(adapter, device, queue, candidate, preference, notices)); + } + Err(error) => notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }), + } + } + } + if notices.iter().any(|n| matches!(n, Notice::DeviceFailed { .. })) { + return Err(OpenError::NoDevice(notices)); + } + let left_out = left_out(&candidates); + if left_out.is_empty() { Err(OpenError::NoAdapter) } else { Err(OpenError::UnsafeDriver(left_out)) } +} + +/// The names of the adapters that can draw but that [`choose`](crate::choose) never draws with. +fn left_out(candidates: &[Candidate]) -> Vec { + candidates.iter().enumerate().filter(|(i, c)| c.usable && avoided(candidates, *i)).map(|(_, c)| c.name.clone()).collect() +} + +/// The adapters `open_async` chooses among: every listed one on native, and in a browser the one +/// it offers for the preference's power. +async fn adapters_for(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + { + let _ = preference; + list_async(instance, surface).await + } + #[cfg(target_arch = "wasm32")] + { + let adapters = browser_adapter(instance, surface, preference.power()).await; + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) + } +} + +fn finish( + adapter: Adapter, + device: wgpu::Device, + queue: wgpu::Queue, + candidate: Candidate, + preference: &Preference, + mut notices: Vec, +) -> Opened { + let caps = Capabilities::of_device(&device); + // wgpu's fallback adapter can be a software one that the listing did not show. + if candidate.is_software() { + notices.retain(|n| *n != Notice::NoSoftwareAdapter); + } + if candidate.is_software() && !asked_for(preference, &candidate) { + notices.push(Notice::SoftwareOnly); + } + for notice in ¬ices { + log::warn!("{notice}"); + } + log::info!("graphics device opened: {caps}"); + let health = DeviceHealth::watch(&device); + Opened { adapter, device, queue, candidate, caps, health, notices } +} + +/// Open a device on `adapter`, or say why it cannot be. +async fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> { + let has = adapter.features(); + if !has.contains(request.required_features) { + return Err(format!("it lacks the features {:?}", request.required_features - has)); + } + let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits()); + let desc = wgpu::DeviceDescriptor { + label: request.label, + required_features: request.required_features | (request.optional_features & has & !Features::all_experimental_mask()), + required_limits, + ..Default::default() + }; + adapter.request_device(&desc).await.map_err(|e| e.to_string()) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::preference::AdapterKey; + + /// An instance whose only adapter is wgpu's noop one, which opens devices without a GPU. wgpu + /// 30 lists it as a software adapter whatever `NoopBackendOptions::device_type` says. + fn noop(features: Option) -> Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, features, ..Default::default() }; + Instance::new(desc) + } + + #[test] + fn a_device_opens_with_the_optional_features_the_adapter_has() { + let instance = noop(Some(Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.caps.shader_f16() && !opened.caps.timestamps(), "only the features asked for: {}", opened.caps); + assert!(opened.notices.is_empty(), "{:?}", opened.notices); + assert!(opened.health.is_ok()); + // the craft-gpu caps name only the features the device was opened with + let caps = opened.device_caps(); + assert_eq!(caps.features, ["TEXTURE_FORMAT_NV12"]); + assert_eq!(&caps, opened.caps.device_caps()); + assert_eq!(caps, crate::device_caps(&opened.device)); + assert_eq!(caps.max_texture_dimension_2d, opened.device.limits().max_texture_dimension_2d); + assert!(caps.software && caps.vendor_id == opened.candidate.vendor, "{caps:?}"); + assert_eq!(opened.health.device_status(), Ok(())); + } + + #[test] + fn open_async_opens_as_open_does() { + let instance = noop(Some(Features::TEXTURE_FORMAT_P010)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_P010 | Features::SHADER_F16, ..Default::default() }; + let opened = pollster::block_on(open_async(&instance, None, &Preference::Auto, &request)).unwrap(); + let blocking = open(&instance, None, &Preference::Auto, &request).unwrap(); + assert!(opened.caps.p010() && !opened.caps.shader_f16(), "{}", opened.caps); + assert_eq!(opened.caps, blocking.caps); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + assert_eq!(opened.notices, blocking.notices); + let (adapters, candidates) = pollster::block_on(list_async(&instance, None)); + assert_eq!((adapters.len(), candidates), (1, list(&instance, None).1)); + // the same errors + let missing = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = pollster::block_on(open_async(&instance, None, &Preference::Auto, &missing)).unwrap_err(); + assert!(matches!(&err, OpenError::NoDevice(n) if n.len() == 1), "{err}"); + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let none = Instance::new(desc); + assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn a_software_device_drops_the_no_software_notice() { + let instance = noop(None); + let opened = open(&instance, None, &Preference::Software, &Request::default()).unwrap(); + assert!(opened.candidate.is_software()); + // as when the listing showed no software adapter and wgpu's fallback adapter opened + let notices = vec![Notice::NoSoftwareAdapter]; + let again = finish(opened.adapter, opened.device, opened.queue, opened.candidate, &Preference::Software, notices); + assert!(again.notices.is_empty(), "{:?}", again.notices); + } + + #[test] + fn an_optional_experimental_feature_does_not_stop_the_device_opening() { + let instance = noop(Some(Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12)); + let request = Request { optional_features: Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.device.features().contains(Features::EXPERIMENTAL_RAY_QUERY)); + // a required one still fails as before + let required = Request { required_features: Features::EXPERIMENTAL_RAY_QUERY, ..Default::default() }; + assert!(matches!(open(&instance, None, &Preference::Software, &required), Err(OpenError::NoDevice(_)))); + } + + #[test] + fn an_adapter_without_a_required_feature_is_reported() { + let instance = noop(Some(Features::empty())); + let request = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = open(&instance, None, &Preference::Auto, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!(notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } if error.contains("SHADER_F16"))), "{notices:?}"); + assert!(err.to_string().starts_with("no graphics adapter could be opened"), "{err}"); + } + + #[test] + fn an_adapter_below_the_requested_limits_is_reported() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, limits: Some(Limits::default()), ..Default::default() }; + let instance = Instance::new(desc); + let over = Limits::default().max_texture_dimension_2d + 1; + let request = Request { limits: Some(Limits { max_texture_dimension_2d: over, ..Limits::default() }), ..Default::default() }; + let err = open(&instance, None, &Preference::Software, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!( + notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } + if error.contains("max_texture_dimension_2d"))), + "{notices:?}" + ); + // limits within the adapter's still open + let within = Request { limits: Some(Limits::downlevel_defaults()), ..Default::default() }; + assert!(open(&instance, None, &Preference::Software, &within).is_ok()); + } + + #[test] + fn a_software_adapter_is_reported_unless_it_was_asked_for() { + let cpu = noop(None); + let opened = open(&cpu, None, &Preference::Auto, &Request::default()).unwrap(); + assert!(opened.caps.software()); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + let asked = open(&cpu, None, &Preference::Software, &Request::default()).unwrap(); + assert!(asked.notices.is_empty(), "{:?}", asked.notices); + // the software adapter picked by name is what was asked for + let named = open(&cpu, None, &Preference::Adapter(AdapterKey::of(&asked.candidate)), &Request::default()).unwrap(); + assert!(named.notices.is_empty(), "{:?}", named.notices); + // a named adapter that is gone: the automatic choice, with both notices + let gone = + AdapterKey { name: "gone".into(), backend: "vulkan".into(), vendor: 0x10de, device: 1, pci_bus_id: String::new(), driver: String::new() }; + let opened = open(&cpu, None, &Preference::Adapter(gone.clone()), &Request::default()).unwrap(); + assert_eq!(opened.notices, vec![Notice::AdapterMissing(gone), Notice::SoftwareOnly]); + } + + #[test] + fn no_adapter_is_an_error() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let instance = Instance::new(desc); + assert_eq!(open(&instance, None, &Preference::Auto, &Request::default()).unwrap_err(), OpenError::NoAdapter); + assert_eq!(OpenError::NoAdapter.to_string(), "no graphics adapter is available"); + assert_eq!( + OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(), + "the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver" + ); + assert_eq!(pick(&[], None, &Preference::Auto).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn pick_says_when_only_a_driver_that_can_crash_can_draw() { + let vulkan_only: Vec = crate::adapter::tests::uhd_630().into_iter().take(1).collect(); + assert_eq!(select(&vulkan_only, &Preference::Auto), None); + assert_eq!(unselected(&vulkan_only), OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()])); + assert_eq!(unselected(&[]), OpenError::NoAdapter); + } + + #[test] + fn a_zero_timeout_leaves_a_healthy_device_healthy() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let everything = opened.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, everything.clone(), std::time::Duration::ZERO)); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + assert!(opened.health.wait_timeout(&opened.device, everything, std::time::Duration::from_secs(5))); + // an index from another device's queue is one this device never issued + let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + other.queue.submit([]); + let index = other.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, index, std::time::Duration::from_secs(5))); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + } + + #[test] + fn waits_run_after_an_out_of_memory_error() { + use crate::health::{Fault, OUT_OF_MEMORY}; + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + health.mark(Fault::Error(OUT_OF_MEMORY.into())); + let index = opened.queue.submit([]); + assert!(health.wait(&opened.device, index.clone()), "{health:?}"); + assert!(health.wait_timeout(&opened.device, index.clone(), std::time::Duration::from_secs(5)), "{health:?}"); + health.clear_out_of_memory(health.out_of_memory_count()); + assert!(health.is_ok(), "{health:?}"); + // any other error still stops them + health.mark(Fault::Error("Validation Error".into())); + assert!(!health.wait(&opened.device, index)); + } + + #[test] + fn a_lost_device_is_seen_by_its_health() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + let index = opened.queue.submit([]); + opened.device.destroy(); + health.probe(&opened.device); + assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}"); + assert!(!health.is_ok()); + assert!(matches!(health.device_status(), Err(craft_gpu::GpuFault::DeviceLost(_))), "{health:?}"); + // a later wait does not touch the lost device + assert!(!health.wait(&opened.device, index)); + } + + #[test] + fn pick_returns_the_selected_adapter() { + let instance = noop(None); + let (adapters, candidates) = list(&instance, None); + assert_eq!(candidates.len(), 1); + let (adapter, selection) = pick(&adapters, None, &Preference::Auto).unwrap(); + assert_eq!(selection.index, 0); + assert_eq!(Candidate::of(&adapter, None), candidates[0]); + } +} diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs new file mode 100644 index 0000000000..542bf66305 --- /dev/null +++ b/crates/gpu-device/src/preference.rs @@ -0,0 +1,422 @@ +//! The adapter the user asked for, and what was drawn with instead when it is not there. + +use std::fmt; + +use wgpu::{Backend, PowerPreference}; + +use crate::adapter::{Candidate, avoided, choose, intel_vulkan_crashes, settled, type_order}; + +/// Which adapter to draw with. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", tag = "kind"))] +pub enum Preference { + /// The fastest adapter: a discrete GPU before an integrated one, hardware before software. + #[default] + Auto, + /// An integrated GPU before a discrete one, for battery life. + LowPower, + /// One adapter the user picked from [`crate::list`]. + Adapter(AdapterKey), + /// A software adapter that draws on the CPU. + Software, +} + +impl Preference { + /// The power preference that orders the adapters for this preference: low power for + /// [`Preference::LowPower`], high performance otherwise. + pub fn power(&self) -> PowerPreference { + match self { + Preference::LowPower => PowerPreference::LowPower, + _ => PowerPreference::HighPerformance, + } + } +} + +/// What identifies an adapter across runs: the backend, the PCI ids and bus, the driver name, and +/// the name. The order in which the system lists adapters can change between runs, so an index +/// cannot be kept. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", default))] +pub struct AdapterKey { + pub name: String, + /// wgpu's lowercase backend name (`vulkan`, `dx12`, `metal`, `gl`). + pub backend: String, + pub vendor: u32, + pub device: u32, + /// Empty when the driver reports none. + pub pci_bus_id: String, + /// The Vulkan driver's name, which tells apart two Vulkan drivers for one GPU (such as two on + /// Linux) and stays the same across versions of a driver. Empty on the other backends, and + /// when the driver reports none. + pub driver: String, +} + +impl AdapterKey { + pub fn of(candidate: &Candidate) -> Self { + AdapterKey { + name: candidate.name.clone(), + backend: backend_name(candidate.backend).to_string(), + vendor: candidate.vendor, + device: candidate.device, + pci_bus_id: candidate.pci_bus_id.clone(), + // DirectX 12 reports the driver's version here, which changes with every update. + driver: if candidate.backend == Backend::Vulkan { candidate.driver.clone() } else { String::new() }, + } + } + + /// Whether `candidate` is this adapter: the same backend and PCI ids, the same bus and the + /// same driver when both report one, and the same name when the backend reports no PCI ids. + pub fn matches(&self, candidate: &Candidate) -> bool { + let identified = self.vendor != 0 || self.device != 0; + let same = |a: &str, b: &str| a.is_empty() || b.is_empty() || a == b; + self.backend == backend_name(candidate.backend) + && self.vendor == candidate.vendor + && self.device == candidate.device + && same(&self.pci_bus_id, &candidate.pci_bus_id) + && same(&self.driver, &candidate.driver) + && (identified || self.name == candidate.name) + } +} + +impl fmt::Display for AdapterKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({})", self.name, self.backend) + } +} + +/// wgpu's lowercase name of `backend`. +pub fn backend_name(backend: Backend) -> &'static str { + backend.to_str() +} + +/// Something the app tells the user about the adapter it draws with. The [`fmt::Display`] text is +/// English, for the log; an app shows its own translated text for each variant. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Notice { + /// The adapter the user picked is not listed (unplugged, disabled, or its driver removed). + /// The automatic choice draws instead. + AdapterMissing(AdapterKey), + /// Software was asked for and no software adapter is listed. The automatic choice draws + /// instead. + NoSoftwareAdapter, + /// The only adapter that can draw is a software one: drawing is slower and uses the CPU. + SoftwareOnly, + /// An adapter could not open a device, and the next one was tried. + DeviceFailed { adapter: String, error: String }, + /// The device was lost this many times in a short time, so drawing moved to software. + SoftwareAfterLosses(u32), +} + +impl fmt::Display for Notice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Notice::AdapterMissing(key) => write!(f, "the graphics adapter {key} is not available; using the automatic choice"), + Notice::NoSoftwareAdapter => f.write_str("no software graphics adapter is available; using the automatic choice"), + Notice::SoftwareOnly => f.write_str("no graphics hardware can be used; drawing in software, which is slower"), + Notice::DeviceFailed { adapter, error } => { + write!(f, "the graphics adapter \"{adapter}\" could not be opened ({error}); trying the next one") + } + Notice::SoftwareAfterLosses(n) => write!(f, "the graphics device stopped working {n} times; drawing in software"), + } + } +} + +/// The adapter chosen for a preference, and what the user should be told about it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Selection { + /// Index into the candidates. + pub index: usize, + pub notices: Vec, +} + +/// The adapter to draw with for `preference`, or `None` when no adapter is usable. +/// +/// - [`Preference::Auto`] and [`Preference::LowPower`] use [`choose`]. +/// - [`Preference::Adapter`] uses the usable entry that matches the key (the one exposing the most +/// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when +/// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and +/// [`Notice::AdapterMissing`]. +/// - [`Preference::Software`] uses the first usable software adapter, with [`choose`]'s +/// corrections; without one, the automatic choice and [`Notice::NoSoftwareAdapter`]. +/// +/// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`]. +pub fn select(candidates: &[Candidate], preference: &Preference) -> Option { + let mut notices = Vec::new(); + let wanted = match preference { + Preference::Auto | Preference::LowPower => None, + Preference::Adapter(key) => { + // An entry that reports no bus id matches any saved bus. When it is the same model on + // the same driver it cannot be told apart from an older version of that driver, and + // the correction draws with the entry exposing the most features. + let found = + candidates.iter().enumerate().filter(|(_, c)| c.usable && key.matches(c)).max_by_key(|(i, c)| (c.features, std::cmp::Reverse(*i))); + let found = found.and_then(|(index, _)| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::AdapterMissing(key.clone())); + } + found + } + Preference::Software => { + let found = candidates.iter().position(|c| c.usable && c.is_software()).and_then(|index| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::NoSoftwareAdapter); + } + found + } + }; + let index = match wanted { + Some(index) => index, + None => { + let index = choose(candidates, preference.power())?; + if candidates.get(index).is_some_and(Candidate::is_software) { + notices.push(Notice::SoftwareOnly); + } + index + } + }; + Some(Selection { index, notices }) +} + +/// The entry to draw with when the entry at `index` is asked for, with [`choose`]'s corrections: +/// the newest version of a driver that lists the GPU twice, or the DirectX 12 entry of an Intel +/// GPU whose Vulkan entry [`choose`] never draws with. `None` when that Intel Vulkan entry has no +/// usable DirectX 12 entry. +fn drawn_with(candidates: &[Candidate], index: usize) -> Option { + candidates.get(index)?; + let index = settled(candidates, index); + (!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index) +} + +/// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key +/// of this adapter. +pub(crate) fn asked_for(preference: &Preference, candidate: &Candidate) -> bool { + match preference { + Preference::Software => candidate.is_software(), + Preference::Adapter(key) => key.matches(candidate), + Preference::Auto | Preference::LowPower => false, + } +} + +/// The order in which to try opening a device for `preference`: [`select`]'s choice first, then +/// every other usable adapter by device type for the preference's power (software after +/// hardware), leaving out the entries [`choose`] never draws with: an older version of a driver +/// listed twice, and the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver. +/// Empty when no adapter is usable. +pub fn ranked(candidates: &[Candidate], preference: &Preference) -> Vec { + let Some(first) = select(candidates, preference).map(|s| s.index) else { + return Vec::new(); + }; + let power = preference.power(); + let mut rest: Vec = + (0..candidates.len()).filter(|&i| i != first && candidates.get(i).is_some_and(|c| c.usable) && !avoided(candidates, i)).collect(); + rest.sort_by_key(|&i| (candidates.get(i).map_or(u8::MAX, |c| type_order(c.device_type, power)), i)); + let mut order = vec![first]; + order.extend(rest); + order +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::adapter::tests::{gpu, two_amd_drivers, uhd_630}; + use wgpu::Backend::{Dx12, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu}; + + fn key_of(candidates: &[Candidate], index: usize) -> AdapterKey { + candidates.get(index).map(AdapterKey::of).unwrap_or_default() + } + + #[test] + fn auto_and_low_power_are_the_corrected_wgpu_choice() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Auto), Some(Selection { index: 1, notices: vec![] })); + assert_eq!(select(&adapters, &Preference::LowPower).map(|s| s.index), Some(2)); + assert_eq!(select(&[], &Preference::Auto), None); + assert_eq!(Preference::default(), Preference::Auto); + } + + #[test] + fn a_named_adapter_is_found_wherever_it_is_listed() { + let adapters = two_amd_drivers(); + // the integrated Radeon through DirectX 12, picked by the user + let key = key_of(&adapters, 4); + assert_eq!(select(&adapters, &Preference::Adapter(key.clone())).map(|s| s.index), Some(4)); + // listed in another order on the next run + let mut reordered = adapters.clone(); + reordered.reverse(); + assert_eq!(select(&reordered, &Preference::Adapter(key)).map(|s| s.index), Some(1)); + // the stale Vulkan entry of the RX 6800M stored as the choice: the newer version draws + let stale = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(stale)).map(|s| s.index), Some(1)); + } + + #[test] + fn a_named_intel_gen9_vulkan_entry_draws_through_directx_12() { + let adapters = uhd_630(); + let vulkan = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(vulkan.clone())).map(|s| s.index), Some(1)); + // without the DirectX 12 entry, the named Vulkan entry is not available + let mut dx12_unusable = adapters.clone(); + dx12_unusable[1].usable = false; + let s = select(&dx12_unusable, &Preference::Adapter(vulkan.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((2, vec![Notice::AdapterMissing(vulkan), Notice::SoftwareOnly]))); + } + + #[test] + fn a_missing_named_adapter_falls_back_to_auto_with_a_notice() { + let adapters = two_amd_drivers(); + let gone = AdapterKey { + name: "NVIDIA GeForce RTX 4090".into(), + backend: "vulkan".into(), + vendor: 0x10de, + device: 0x2684, + pci_bus_id: String::new(), + driver: "NVIDIA".into(), + }; + let s = select(&adapters, &Preference::Adapter(gone.clone())); + assert_eq!(s, Some(Selection { index: 1, notices: vec![Notice::AdapterMissing(gone.clone())] })); + // listed but unable to draw to the window counts as missing + let mut unusable = adapters.clone(); + for c in &mut unusable { + c.usable = c.backend != Vulkan; + } + let vulkan_key = key_of(&adapters, 1); + let s = select(&unusable, &Preference::Adapter(vulkan_key.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((3, vec![Notice::AdapterMissing(vulkan_key)]))); + // nothing usable at all + assert_eq!(select(&[], &Preference::Adapter(gone)), None); + } + + #[test] + fn keys_tell_apart_backends_buses_and_unidentified_names() { + let adapters = two_amd_drivers(); + let dx12 = key_of(&adapters, 3); + assert!(dx12.matches(&adapters[3])); + assert!(!dx12.matches(&adapters[1]), "same GPU, other backend"); + let other_bus = Candidate { pci_bus_id: "0000:04:00.0".into(), ..adapters[3].clone() }; + assert!(!dx12.matches(&other_bus)); + // a key stored without a bus id still matches an entry that reports one + let no_bus = AdapterKey { pci_bus_id: String::new(), ..dx12.clone() }; + assert!(no_bus.matches(&adapters[3])); + // two Vulkan drivers for one GPU are told apart by the driver name; a key saved without + // one matches either + let radv = gpu("AMD Radeon RX 6800M (RADV NAVI22)", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "radv", "Mesa 25.2.4", 70); + let amdvlk = gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "AMD open-source driver", "2025.Q2.1", 72); + let two = vec![radv.clone(), amdvlk.clone()]; + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&radv))).map(|s| s.index), Some(0)); + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&amdvlk))).map(|s| s.index), Some(1)); + let old = AdapterKey { driver: String::new(), ..AdapterKey::of(&radv) }; + assert!(old.matches(&radv) && old.matches(&amdvlk)); + // a DirectX 12 key keeps matching after a driver update changes the reported version + assert!(dx12.driver.is_empty()); + let updated = Candidate { driver: "32.0.21045.12000".into(), ..adapters[3].clone() }; + assert!(dx12.matches(&updated)); + // OpenGL reports no ids: the name decides + let angle = gpu("ANGLE (D3D11)", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let swiftshader = gpu("SwiftShader", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let key = AdapterKey::of(&angle); + assert!(key.matches(&angle) && !key.matches(&swiftshader)); + assert_eq!(dx12.to_string(), "\"AMD Radeon RX 6800M\" (dx12)"); + } + + #[test] + fn software_is_used_when_asked_and_reported_when_it_is_all_there_is() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 5, notices: vec![] })); + let hardware_only: Vec = adapters.iter().filter(|c| !c.is_software()).cloned().collect(); + assert_eq!(select(&hardware_only, &Preference::Software), Some(Selection { index: 1, notices: vec![Notice::NoSoftwareAdapter] })); + let llvmpipe = vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)]; + assert_eq!(select(&llvmpipe, &Preference::Auto), Some(Selection { index: 0, notices: vec![Notice::SoftwareOnly] })); + assert_eq!(select(&llvmpipe, &Preference::Software), Some(Selection { index: 0, notices: vec![] })); + // picked by name, it is what was asked for + let named = Preference::Adapter(AdapterKey::of(&llvmpipe[0])); + assert_eq!(select(&llvmpipe, &named), Some(Selection { index: 0, notices: vec![] })); + #[cfg(not(target_arch = "wasm32"))] + { + assert!(asked_for(&named, &llvmpipe[0]) && asked_for(&Preference::Software, &llvmpipe[0])); + assert!(!asked_for(&Preference::Auto, &llvmpipe[0]) && !asked_for(&Preference::Software, &adapters[1])); + } + } + + #[test] + fn software_draws_with_the_newer_version_of_a_driver_listed_twice() { + let stale = gpu("llvmpipe (LLVM 15.0.7, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 23.0.4", 40); + let newer = gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 25.2.4", 50); + let hardware = gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "32.0.21045.11001", "", 36); + let adapters = vec![stale, newer, hardware]; + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 1, notices: vec![] })); + // the stale entry is never tried, and the newer one is not left out + assert_eq!(ranked(&adapters, &Preference::Software), vec![1, 2]); + } + + #[test] + fn the_fallback_order_never_tries_entries_that_can_crash() { + let adapters = two_amd_drivers(); + // the newer RX 6800M, then the other hardware by type for high performance, then software; + // the stale RX 6800M entry is never tried + assert_eq!(ranked(&adapters, &Preference::Auto), vec![1, 3, 2, 4, 5]); + assert_eq!(ranked(&adapters, &Preference::LowPower), vec![2, 4, 1, 3, 5]); + assert_eq!(ranked(&adapters, &Preference::Software), vec![5, 1, 3, 2, 4]); + // two cards of one model on one driver, one without a Vulkan bus id: the second card's + // Vulkan entry looks like an older version, and the card is tried through DirectX 12 + let card = |bus: &str| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, 0x1002, 0x744c, bus, "AMD proprietary driver", "", 68); + let dx12 = |bus: &str| gpu("AMD Radeon RX 7900 XT", Dx12, DiscreteGpu, 0x1002, 0x744c, bus, "32.0.21045.11001", "", 36); + let twins = vec![card("0000:03:00.0"), card(""), dx12("0000:03:00.0"), dx12("0000:04:00.0")]; + assert_eq!(ranked(&twins, &Preference::Auto), vec![0, 2, 3]); + // the same bus id on both entries: one GPU, and the older version is never tried + let mut versions = vec![card("0000:03:00.0"), card("0000:03:00.0")]; + versions[1].features = 70; + assert_eq!(ranked(&versions, &Preference::Auto), vec![1]); + // a third entry without a bus id and with more features: both older entries are left out + versions.push(card("")); + versions[2].features = 80; + assert_eq!(ranked(&versions, &Preference::Auto), vec![2]); + // two GPUs on different buses are both tried + let cards = vec![card("0000:03:00.0"), card("0000:04:00.0")]; + assert_eq!(ranked(&cards, &Preference::Auto), vec![0, 1]); + // the Intel Gen 9 Vulkan entry is never tried, with or without a usable DirectX 12 entry + assert_eq!(ranked(&uhd_630(), &Preference::Auto), vec![1, 2]); + let mut dx12_unusable = uhd_630(); + dx12_unusable[1].usable = false; + assert_eq!(ranked(&dx12_unusable, &Preference::Auto), vec![2]); + assert!(ranked(&uhd_630()[..1], &Preference::Auto).is_empty()); + assert!(ranked(&[], &Preference::Auto).is_empty()); + let unusable: Vec = adapters.iter().map(|c| Candidate { usable: false, ..c.clone() }).collect(); + assert!(ranked(&unusable, &Preference::Auto).is_empty()); + } + + #[test] + fn a_laptop_with_two_vendors_keeps_the_named_gpu_across_reorders() { + let intel = gpu("Intel(R) UHD Graphics 770", Dx12, IntegratedGpu, 0x8086, 0x4680, "0000:00:02.0", "31.0.101.5186", "", 36); + let nvidia = gpu("NVIDIA GeForce RTX 4070 Laptop GPU", Dx12, DiscreteGpu, 0x10de, 0x2820, "0000:01:00.0", "32.0.15.6094", "", 36); + let a = vec![intel.clone(), nvidia.clone()]; + let b = vec![nvidia, intel]; + let picked = Preference::Adapter(key_of(&a, 0)); + assert_eq!(select(&a, &picked).map(|s| s.index), Some(0)); + assert_eq!(select(&b, &picked).map(|s| s.index), Some(1)); + assert_eq!(ranked(&b, &picked), vec![1, 0]); + } + + #[cfg(feature = "serde")] + #[test] + fn preferences_read_back_what_they_write() { + let key = AdapterKey { + name: "AMD Radeon RX 6800M".into(), + backend: "dx12".into(), + vendor: 0x1002, + device: 0x73df, + pci_bus_id: "0000:03:00.0".into(), + driver: String::new(), + }; + for p in [Preference::Auto, Preference::LowPower, Preference::Software, Preference::Adapter(key)] { + let text = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), p, "{text}"); + } + assert_eq!(serde_json::to_string(&Preference::Auto).unwrap(), r#"{"kind":"auto"}"#); + // a key written by an older version without some fields + let p: Preference = serde_json::from_str(r#"{"kind":"adapter","name":"x","backend":"vulkan"}"#).unwrap(); + assert_eq!(p, Preference::Adapter(AdapterKey { name: "x".into(), backend: "vulkan".into(), ..Default::default() })); + assert!(serde_json::from_str::(r#"{"kind":"fastest"}"#).is_err()); + } +} diff --git a/crates/gpu-device/src/recovery.rs b/crates/gpu-device/src/recovery.rs new file mode 100644 index 0000000000..2732d8c986 --- /dev/null +++ b/crates/gpu-device/src/recovery.rs @@ -0,0 +1,153 @@ +//! What to open after a device loss. +//! +//! A device is lost when the driver resets the GPU, the OS ends a long submission, the PC sleeps, +//! or the GPU is unplugged. The app drops everything it made with the device and opens a new one. +//! [`Recovery`] decides with what preference: the user's own, until the device has been lost +//! [`RecoveryPolicy::max_losses`] times within [`RecoveryPolicy::window`], and software after that, +//! so a GPU that keeps failing does not stop the app from drawing. + +use std::collections::VecDeque; +use std::time::Duration; + +use crate::preference::{Notice, Preference}; + +/// When repeated losses move drawing to software. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RecoveryPolicy { + /// Losses within [`window`](Self::window) after which the next device is a software one. + /// 0 never moves to software. + pub max_losses: u32, + pub window: Duration, +} + +impl Default for RecoveryPolicy { + fn default() -> Self { + RecoveryPolicy { max_losses: 3, window: Duration::from_secs(600) } + } +} + +/// The preference to open the next device with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecoveryStep { + pub preference: Preference, + /// [`Notice::SoftwareAfterLosses`] when this step moved drawing to software. + pub notice: Option, +} + +/// Device losses seen so far, against the user's preference. +#[derive(Clone, Debug)] +pub struct Recovery { + preference: Preference, + policy: RecoveryPolicy, + /// When each loss inside the window happened, oldest first. + losses: VecDeque, + software: bool, +} + +impl Recovery { + pub fn new(preference: Preference, policy: RecoveryPolicy) -> Self { + Recovery { preference, policy, losses: VecDeque::new(), software: false } + } + + /// The preference to open a device with now. + pub fn preference(&self) -> &Preference { + if self.software { &Preference::Software } else { &self.preference } + } + + /// The user changed the preference: losses counted so far no longer apply. + pub fn set_preference(&mut self, preference: Preference) { + self.preference = preference; + self.losses.clear(); + self.software = false; + } + + /// Record a loss at `at`, a monotonic time the caller keeps (since the app started), and + /// return what to open next. A time earlier than the last loss counts as the same time. + pub fn lost(&mut self, at: Duration) -> RecoveryStep { + let at = self.losses.back().map_or(at, |last| at.max(*last)); + self.losses.push_back(at); + // Only the last `max_losses` losses decide anything, so no more are kept. + let keep = usize::try_from(self.policy.max_losses.max(1)).unwrap_or(usize::MAX); + while self.losses.len() > keep || self.losses.front().is_some_and(|first| at.saturating_sub(*first) > self.policy.window) { + self.losses.pop_front(); + } + let count = u32::try_from(self.losses.len()).unwrap_or(u32::MAX); + let mut notice = None; + if !self.software && self.policy.max_losses > 0 && count >= self.policy.max_losses && self.preference != Preference::Software { + self.software = true; + notice = Some(Notice::SoftwareAfterLosses(count)); + } + RecoveryStep { preference: self.preference().clone(), notice } + } + + /// Losses inside the window, as of the last one, counting at most + /// [`RecoveryPolicy::max_losses`] (at least 1). + pub fn recent_losses(&self) -> usize { + self.losses.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(secs: u64) -> Duration { + Duration::from_secs(secs) + } + + #[test] + fn the_third_loss_in_ten_minutes_moves_to_software() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy::default()); + assert_eq!(r.lost(s(10)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(100)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(300)), RecoveryStep { preference: Preference::Software, notice: Some(Notice::SoftwareAfterLosses(3)) }); + // it stays on software, and says so once + assert_eq!(r.lost(s(400)), RecoveryStep { preference: Preference::Software, notice: None }); + assert_eq!(r.preference(), &Preference::Software); + } + + #[test] + fn losses_outside_the_window_are_forgotten() { + let mut r = Recovery::new(Preference::LowPower, RecoveryPolicy::default()); + r.lost(s(0)); + r.lost(s(500)); + // the first loss is more than 600 s before this one + assert_eq!(r.lost(s(601)).preference, Preference::LowPower); + assert_eq!(r.recent_losses(), 2); + // a clock that goes back counts as the last loss's time + assert_eq!(r.lost(s(1)).preference, Preference::Software); + } + + #[test] + fn changing_the_preference_starts_over() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 2, window: s(60) }); + r.lost(s(1)); + assert_eq!(r.lost(s(2)).preference, Preference::Software); + r.set_preference(Preference::LowPower); + assert_eq!(r.preference(), &Preference::LowPower); + assert_eq!(r.recent_losses(), 0); + assert_eq!(r.lost(s(3)).preference, Preference::LowPower); + } + + #[test] + fn software_and_a_zero_limit_never_add_a_notice() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy::default()); + for t in 0..5 { + assert_eq!(r.lost(s(t)), RecoveryStep { preference: Preference::Software, notice: None }); + } + let mut never = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 0, window: s(60) }); + for t in 0..10 { + assert_eq!(never.lost(s(t)).preference, Preference::Auto); + } + assert_eq!(never.recent_losses(), 1); + } + + #[test] + fn the_loss_history_stays_bounded() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy { max_losses: 3, window: Duration::MAX }); + for _ in 0..10_000 { + r.lost(s(5)); + } + assert_eq!(r.recent_losses(), 3); + } +} diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 60742bea84..3871c44891 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -46,6 +46,8 @@ fn probe_caps_native() -> DeviceCaps { max_buffer_size: limits.max_buffer_size, max_texture_dimension_2d: limits.max_texture_dimension_2d, features: Vec::new(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, } } @@ -144,6 +146,8 @@ mod native { max_buffer_size: device_limits.max_buffer_size, max_texture_dimension_2d: device_limits.max_texture_dimension_2d, features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, }; let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); Some((caps, backing)) diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs index 75dcf173d0..1ae87a0d30 100644 --- a/crates/gpu/src/caps.rs +++ b/crates/gpu/src/caps.rs @@ -20,6 +20,20 @@ pub struct DeviceCaps { /// never on what the adapter merely advertised. #[serde(default)] pub features: Vec, + /// The PCI vendor id of the device's adapter (or the Khronos vendor id some Vulkan drivers + /// report instead); 0 when unknown or on backends with no device. + #[serde(default)] + pub vendor_id: u32, + /// The device draws on the CPU (a software adapter such as WARP, llvmpipe or lavapipe). + #[serde(default)] + pub software: bool, +} + +impl DeviceCaps { + /// Whether the feature named `name` (as in [`features`](Self::features)) is enabled. + pub fn has_feature(&self, name: &str) -> bool { + self.features.iter().any(|f| f == name) + } } impl Default for DeviceCaps { @@ -31,6 +45,8 @@ impl Default for DeviceCaps { max_buffer_size: 256 * 1024 * 1024, max_texture_dimension_2d: 8192, features: Vec::new(), + vendor_id: 0, + software: false, } } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 528b2e587d..25ee131bc3 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -126,3 +126,15 @@ fn chunk_buffer_splits_on_storage_binding_limit() { let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer"); assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]); } + +#[test] +fn caps_without_vendor_or_software_read_as_unknown_hardware() { + let json = r#"{"backend_name":"Vulkan","device_name":"gpu","max_storage_buffer_binding_size":1,"max_buffer_size":2,"max_texture_dimension_2d":3,"features":["TEXTURE_FORMAT_NV12"]}"#; + let caps: DeviceCaps = serde_json::from_str(json).expect("caps"); + assert_eq!((caps.vendor_id, caps.software), (0, false)); + assert!(caps.has_feature("TEXTURE_FORMAT_NV12")); + assert!(!caps.has_feature("TEXTURE_FORMAT_P010") && !caps.has_feature("")); + let software = DeviceCaps { vendor_id: 0x10005, software: true, ..caps }; + let back: DeviceCaps = serde_json::from_str(&serde_json::to_string(&software).expect("json")).expect("caps"); + assert_eq!(back, software); +} diff --git a/crates/host/src/queue.rs b/crates/host/src/queue.rs index 8133d17e64..2dc1d34f60 100644 --- a/crates/host/src/queue.rs +++ b/crates/host/src/queue.rs @@ -47,9 +47,20 @@ impl Priority { /// The cancel flag a running job reads. The queue sets it when the job's key is dropped /// ([`JobQueue::reprioritize`] returning `None`, [`JobQueue::shutdown`], dropping the queue); a /// long job checks [`is_cancelled`](Cancel::is_cancelled) between steps and returns early. A -/// cancelled job's result is never delivered. Cloning shares the flag. +/// cancelled job's result is never delivered. A job that has nothing to do until it is cancelled +/// blocks in [`wait`](Cancel::wait) or [`wait_timeout`](Cancel::wait_timeout). Cloning shares the +/// flag. #[derive(Clone, Debug, Default)] -pub struct Cancel(Arc); +pub struct Cancel(Arc); + +/// The shared state behind a [`Cancel`]: the flag, and the lock and condition variable that wake +/// its waiters when it is set. +#[derive(Debug, Default)] +struct CancelFlag { + set: AtomicBool, + lock: Mutex<()>, + changed: Condvar, +} impl Cancel { /// A flag that is not set (tests call a decoder with it). @@ -59,12 +70,32 @@ impl Cancel { /// Whether the job should stop. pub fn is_cancelled(&self) -> bool { - self.0.load(Ordering::Relaxed) + self.0.set.load(Ordering::Relaxed) } - /// Sets the flag. + /// Sets the flag and wakes every thread blocked in [`wait`](Cancel::wait) or + /// [`wait_timeout`](Cancel::wait_timeout). pub fn cancel(&self) { - self.0.store(true, Ordering::Relaxed); + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + self.0.set.store(true, Ordering::Relaxed); + drop(guard); + self.0.changed.notify_all(); + } + + /// Blocks the calling thread until the flag is set, and returns at once when it already is. + /// Another thread must call [`cancel`](Cancel::cancel): on wasm32, where a job runs on the + /// thread that would cancel it, a call that has to wait never returns. + pub fn wait(&self) { + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + drop(self.0.changed.wait_while(guard, |_| !self.0.set.load(Ordering::Relaxed)).unwrap_or_else(|e| e.into_inner())); + } + + /// Blocks the calling thread until the flag is set or `timeout` has passed, and returns + /// whether the flag is set. A zero `timeout` reads the flag without waiting. + pub fn wait_timeout(&self, timeout: Duration) -> bool { + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + drop(self.0.changed.wait_timeout_while(guard, timeout, |_| !self.0.set.load(Ordering::Relaxed)).unwrap_or_else(|e| e.into_inner())); + self.is_cancelled() } } diff --git a/crates/host/src/queue_tests.rs b/crates/host/src/queue_tests.rs index 86565c9792..bbd4ca99a7 100644 --- a/crates/host/src/queue_tests.rs +++ b/crates/host/src/queue_tests.rs @@ -1,9 +1,12 @@ //! `JobQueue` and `ManualJobs`: order, replacement, one job per key, cancellation, wakes and //! inline runs. Every test drives lanes with `ManualJobs` (or `lanes: 0`), so nothing depends on -//! thread timing. +//! thread timing. The tests of `Cancel::wait` block a second thread and hand off over channels. use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, TryRecvError}; +use std::thread; +use std::time::Duration; use crate::queue::{Cancel, Finished, JobQueue, Priority, QueueOptions, QueueOrder}; use crate::{ManualJobs, Wake}; @@ -83,6 +86,62 @@ fn queue_dropped_keys_are_cancelled() { assert!(!queue.contains(&"waiting") && !queue.contains(&"running")); } +// `wait_timeout` reads the flag, a clone shares it, and `wait` returns at once on a set flag. +#[test] +fn cancel_wait_timeout_reports_the_flag() { + let cancel = Cancel::new(); + let shared = cancel.clone(); + assert!(!cancel.wait_timeout(Duration::ZERO)); + shared.cancel(); + assert!(cancel.is_cancelled()); + assert!(cancel.wait_timeout(Duration::ZERO)); + cancel.wait(); +} + +// A thread blocked in `wait` returns once another thread cancels. The 60-second bound only fails +// the test when the wake never comes. +#[test] +fn cancel_wait_returns_once_another_thread_cancels() { + let cancel = Cancel::new(); + let (started, has_started) = mpsc::channel(); + let (returned, has_returned) = mpsc::channel(); + let waiter = { + let cancel = cancel.clone(); + thread::spawn(move || { + let _ = started.send(()); + cancel.wait(); + let _ = returned.send(()); + }) + }; + has_started.recv().expect("the waiter starts"); + assert_eq!(has_returned.try_recv(), Err(TryRecvError::Empty), "wait returned before the cancel"); + cancel.cancel(); + has_returned.recv_timeout(Duration::from_secs(60)).expect("wait returns after the cancel"); + waiter.join().expect("the waiter ends"); +} + +// A running job blocked in `wait` ends when the queue drops its key, and its result never arrives. +#[test] +fn a_job_waiting_on_its_cancel_ends_when_its_key_is_dropped() { + let (queue, jobs, wakes) = queue(1); + let (started, has_started) = mpsc::channel(); + queue.submit("running", Priority::VISIBLE, move |cancel: &Cancel| { + let _ = started.send(()); + cancel.wait(); + "running" + }); + let (ran, has_run) = mpsc::channel(); + let lane = thread::spawn(move || { + let _ = ran.send(jobs.run_all()); + }); + has_started.recv().expect("the job starts"); + assert_eq!(queue.reprioritize(|_, _| None), ["running"]); + assert_eq!(has_run.recv_timeout(Duration::from_secs(60)), Ok(1), "the job ends after the cancel"); + lane.join().expect("the lane ends"); + assert!(drain(&queue).is_empty()); + assert_eq!(wakes.load(Ordering::Relaxed), 0); +} + // The wake is called once per finished job, never for a dropped or cancelled one. // With `lanes == 0` nothing runs on submit; `run_inline(1)` runs the best job and returns 1. diff --git a/crates/imaging/src/ui/fill/stories.rs b/crates/imaging/src/ui/fill/stories.rs index d1de28716a..e5fa8608f1 100644 --- a/crates/imaging/src/ui/fill/stories.rs +++ b/crates/imaging/src/ui/fill/stories.rs @@ -102,12 +102,7 @@ impl FillSource for StorySource { match self.preview { Preview::Loading => Job::new(|progress, cancel| { progress.report(LOADING_PROGRESS); - for _ in 0..LOADING_SECONDS { - if cancel.is_cancelled() { - break; - } - std::thread::sleep(Duration::from_secs(1)); - } + cancel.wait_timeout(Duration::from_secs(LOADING_SECONDS)); Ok(PreviewDone::new(Duration::ZERO)) }), Preview::Failed => Job::new(|_, _| Err("nothing to sample from: the sampling area has no pixels outside the fill area".to_owned())), diff --git a/crates/imaging/src/ui/filter_gallery/stories.rs b/crates/imaging/src/ui/filter_gallery/stories.rs index 900e7cb1da..cecc8033d0 100644 --- a/crates/imaging/src/ui/filter_gallery/stories.rs +++ b/crates/imaging/src/ui/filter_gallery/stories.rs @@ -27,8 +27,6 @@ use crate::ui::wide_angle::PreviewDone; const NOTE: Duration = Duration::from_millis(120); /// How far the loading render has come, as a fraction. const PROGRESS: f32 = 0.4; -/// How often the loading render looks for its cancellation. -const POLL: Duration = Duration::from_millis(20); // --- the fake app --- @@ -136,9 +134,7 @@ impl FilterGallerySource for MockSource { if self.rendering { Job::new(|progress, cancel| { progress.report(PROGRESS); - while !cancel.is_cancelled() { - std::thread::sleep(POLL); - } + cancel.wait(); Err(String::new()) }) } else { diff --git a/crates/imaging/src/ui/select_mask/stories.rs b/crates/imaging/src/ui/select_mask/stories.rs index 2bfd781a72..3ffb2d9bb6 100644 --- a/crates/imaging/src/ui/select_mask/stories.rs +++ b/crates/imaging/src/ui/select_mask/stories.rs @@ -27,9 +27,6 @@ use crate::ui::wide_angle::PreviewDone; /// The limits a story runs under: PhotoCraft's. const LIMITS: SelectMaskLimits = SelectMaskLimits { edits: 4096, edit_points: 100_000, strokes: 4096, stroke_points: 100_000 }; -/// How often a never-finishing preview job looks for its cancellation. -const POLL: Duration = Duration::from_millis(50); - /// The app's side over `MockImage`: the picture as the view, the house as the selection. struct StorySource { image: MockImage, @@ -54,9 +51,7 @@ impl SelectMaskSource for StorySource { fn preview_job(&self, _: &SelectMaskPreviewRequest) -> Job { if self.loading { Job::new(|_, cancel| { - while !cancel.is_cancelled() { - std::thread::sleep(POLL); - } + cancel.wait(); Err("cancelled".to_owned()) }) } else { diff --git a/crates/imaging/tests/it/filter_gallery.rs b/crates/imaging/tests/it/filter_gallery.rs index 6824f7586c..a58b4a783f 100644 --- a/crates/imaging/tests/it/filter_gallery.rs +++ b/crates/imaging/tests/it/filter_gallery.rs @@ -146,9 +146,7 @@ impl FilterGallerySource for Flat { Job::new(|_, _| Ok(PreviewDone::new(Duration::from_millis(12)))) } else { Job::new(|_, cancel| { - while !cancel.is_cancelled() { - std::thread::sleep(Duration::from_millis(10)); - } + cancel.wait(); Err(String::new()) }) } diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 8fd2b48ab0..21691ac881 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -305,6 +305,9 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File are applied in file order; the earlier key is listed in `skipped`), and an entry without keys can clear its command. It clears it only when no entry matched to the same command has keys, whatever the order of the entries. +- Conflicts removed from one command are saved as one final binding list. An intermediate + list that cannot be stored does not block an import whose final list fits. If that final + list cannot be saved, the entries taking those keys fail and keep their previous bindings. - Keys read approximately (a numeric keypad key bound as the main key) are listed in `approximated`. - With `ImportOptions.suggest`, unmatched entries get fuzzy candidates (`import::namematch`); diff --git a/crates/keymap/src/editor.rs b/crates/keymap/src/editor.rs index af8a2929f3..fbb2acafc9 100644 --- a/crates/keymap/src/editor.rs +++ b/crates/keymap/src/editor.rs @@ -104,8 +104,8 @@ impl EditSession { new: Binding, policy: Policy, ) -> Result { - let list: Vec = keymap.bindings(command).into_iter().map(|b| if b == *old { new.clone() } else { b }).collect(); - self.edit(keymap, |km| km.set_bindings(command, list, policy)) + let bindings = replacing(keymap, command, old, &new); + self.edit(keymap, |km| km.set_bindings(command, bindings, policy)) } /// Removes one binding of a command as one undo step. @@ -180,6 +180,16 @@ impl EditSession { } } +/// Checks whether the replacement that [`EditSession::replace`] would make can be saved under `policy`. +/// This leaves the keymap and its undo history untouched. +pub fn check_replace(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding, policy: Policy) -> Result<(), AssignError> { + keymap.check_set_bindings(command, replacing(keymap, command, old, new), policy) +} + +fn replacing(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding) -> Vec { + keymap.bindings(command).into_iter().map(|binding| if binding == *old { new.clone() } else { binding }).collect() +} + /// The other commands whose bindings clash with `binding` given to `command`: what /// [`Policy::Steal`] would take and [`Policy::Keep`] would leave clashing. Tools of the command's /// group and twins sharing a default key are not listed. A dialog shows these while the user diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 55347f4e5f..11eb1fcc96 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -745,6 +745,8 @@ impl ImportPlan { /// earlier entry stays with that entry. That includes taking a chord from another command, /// or from a command whose own change failed: both commands keep the bindings they had. With /// [`Start::Defaults`] that cannot happen. + /// All conflicts removed from one command are saved together, so only its final binding + /// list must fit in the overrides, rather than each intermediate list. pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); // Dropping every entry leaves room for all of them: each catalog command takes at most one @@ -802,7 +804,9 @@ impl ImportPlan { // A command that cannot take a chord from another command is dropped, so both keep // the bindings they had. That includes a command whose own change failed: freeing an // entry later must not take its chord away. - let mut unbind_failed = false; + let mut removals: Vec<(CommandRef, Vec, Vec)> = Vec::new(); + let mut removal_index = HashMap::new(); + let mut cleared = Vec::new(); for (c, (p, list)) in self.commands.iter().zip(&accepted).enumerate() { if list.is_empty() || !decided.contains(&p.command.key()) { continue; @@ -811,12 +815,27 @@ impl ImportPlan { if decided.contains(&h.command.key()) { continue; } - let home = home_of(keymap, &h.command); - let label = label_of(keymap, &h.command); - let shortcut = h.binding.text(&home); - if !failed_here.contains(&h.command.key()) && keymap.remove(&h.command, &h.binding) { - report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); - } else { + let index = *removal_index.entry(h.command.key()).or_insert_with(|| { + removals.push((h.command.clone(), Vec::new(), Vec::new())); + removals.len() - 1 + }); + let Some((_, bindings, claimants)) = removals.get_mut(index) else { continue }; + if !claimants.contains(&c) { + claimants.push(c); + } + if !bindings.contains(&h.binding) { + bindings.push(h.binding.clone()); + cleared.push(h); + } + } + } + let mut unbind_failed = false; + for (command, bindings, claimants) in removals { + let remaining = keymap.bindings(&command).into_iter().filter(|binding| !bindings.contains(binding)).collect(); + if failed_here.contains(&command.key()) || keymap.set_bindings(&command, remaining, Policy::Keep).is_err() { + for c in claimants { + let Some(p) = self.commands.get(c) else { continue }; + let Some(list) = accepted.get(c) else { continue }; let home = home_of(keymap, &p.command); let list = in_default_order(keymap, &p.command, list); let shortcuts = list.iter().map(|b| b.text(&home)).collect(); @@ -824,15 +843,21 @@ impl ImportPlan { c, Failed { command: p.command.clone(), label: label_of(keymap, &p.command), change: FailedChange::Bind, shortcuts }, ); - unbind_failed = true; - break; } + unbind_failed = true; + break; } } if unbind_failed { *keymap = start.clone(); continue 'attempt; } + for h in cleared { + let home = home_of(keymap, &h.command); + let label = label_of(keymap, &h.command); + let shortcut = h.binding.text(&home); + report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); + } for (p, from) in self.commands.iter().zip(&before) { if !decided.contains(&p.command.key()) { diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 31ed74a36d..2786108132 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -229,6 +229,8 @@ pub struct Conflict { /// A binding with its scope resolved. type Bound = (Trigger, Scope); +type BindingWrites = Vec<(usize, Vec)>; +type StoredBindingWrites = Vec<(usize, Vec, Option>)>; /// Whether `trigger` can start a command: any press can; a hold needs a chord that types a character, alone or with /// Shift, since the others are taken by the system and by text fields. @@ -592,11 +594,24 @@ impl Keymap { } let mut list = self.current[i].clone(); list.push(new.clone()); - self.apply(i, list, &[new], policy) + let (assigned, writes) = self.plan_writes(i, list, &[new], policy)?; + self.commit(writes)?; + Ok(assigned) } /// Replaces all bindings of a command. pub fn set_bindings(&mut self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result { + let (assigned, writes) = self.plan_set_bindings(command, bindings, policy)?; + self.commit(writes)?; + Ok(assigned) + } + + pub(crate) fn check_set_bindings(&self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result<(), AssignError> { + let (_, writes) = self.plan_set_bindings(command, bindings, policy)?; + self.prepare_writes(writes).map(|_| ()) + } + + fn plan_set_bindings(&self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> { let i = self.find(command).ok_or(AssignError::UnknownCommand)?; if bindings.len() > MAX_BINDINGS { return Err(AssignError::TooMany); @@ -606,7 +621,7 @@ impl Keymap { let kept: Vec = self.hidden(i).into_iter().filter(|h| !list.iter().any(|b| self.same(b, h))).collect(); list.extend(kept); let new: Vec = list.iter().filter(|b| !self.current[i].iter().any(|c| self.same(c, b))).cloned().collect(); - self.apply(i, list, &new, policy) + self.plan_writes(i, list, &new, policy) } /// Removes one binding (matched by effective trigger and scope). `false` when the command does @@ -898,7 +913,7 @@ impl Keymap { out.len() < MAX_CONFLICTS } - fn apply(&mut self, i: usize, list: Vec, new: &[Bound], policy: Policy) -> Result { + fn plan_writes(&self, i: usize, list: Vec, new: &[Bound], policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> { if list.len() > MAX_BINDINGS { return Err(AssignError::TooMany); } @@ -916,7 +931,7 @@ impl Keymap { let holders: Vec = clashes.iter().map(|(j, b)| Holder { command: self.catalog[*j].command.clone(), binding: self.public(*j, b) }).collect(); let mut done = Assigned::default(); - let mut writes: Vec<(usize, Vec)> = Vec::new(); + let mut writes = Vec::new(); match policy { Policy::Refuse if !holders.is_empty() => return Err(AssignError::Taken(holders)), Policy::Refuse => {} @@ -940,12 +955,11 @@ impl Keymap { } } writes.push((i, list)); - self.commit(writes)?; - Ok(done) + Ok((done, writes)) } /// Prepares all entries before replacing live or stored bindings, including commands whose bindings were taken. - fn commit(&mut self, writes: Vec<(usize, Vec)>) -> Result<(), AssignError> { + fn prepare_writes(&self, writes: BindingWrites) -> Result { let mut prepared = Vec::with_capacity(writes.len()); for (i, list) in writes { let texts = self.store_texts(i, &list)?; @@ -955,7 +969,11 @@ impl Keymap { if self.overrides.len() + needed > MAX_COMMANDS { return Err(AssignError::Full); } - for (i, list, texts) in prepared { + Ok(prepared) + } + + fn commit(&mut self, writes: BindingWrites) -> Result<(), AssignError> { + for (i, list, texts) in self.prepare_writes(writes)? { self.remove_entries(i); if let Some(texts) = texts { self.overrides.insert(self.keys[i].clone(), texts); diff --git a/crates/keymap/tests/editor.rs b/crates/keymap/tests/editor.rs index 3de26a98d5..4cda2cb526 100644 --- a/crates/keymap/tests/editor.rs +++ b/crates/keymap/tests/editor.rs @@ -1,6 +1,7 @@ //! Integration tests of craft-keymap: editor. -use craft_keymap::{Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes}; +use craft_keymap::editor::check_replace; +use craft_keymap::{AssignError, Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes}; fn b(text: &str) -> Binding { Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) @@ -20,6 +21,19 @@ fn keys(km: &Keymap, id: &str) -> Vec { km.bindings(&CommandRef::new(id)).iter().map(|b| b.to_string()).collect() } +#[test] +fn checking_a_replacement_does_not_take_the_other_commands_shortcut() { + let km = keymap(Platform::Mac); + let save = CommandRef::new("file.save"); + let old = b("Cmd+S"); + let new = b("Cmd+C"); + assert!(matches!(check_replace(&km, &save, &old, &new, Policy::Refuse), Err(AssignError::Taken(_)))); + assert!(check_replace(&km, &save, &old, &new, Policy::Steal).is_ok()); + assert_eq!(keys(&km, "file.save"), ["Cmd+S"]); + assert_eq!(keys(&km, "edit.copy"), ["Cmd+C"]); + assert!(km.overrides().is_empty()); +} + #[test] fn edits_undo_redo_and_cancel() { let mut km = keymap(Platform::Windows); diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index a48cd968c8..667385a3ba 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -203,6 +203,88 @@ fn a_failed_change_keeps_its_shortcut_when_a_later_change_frees_room() { assert_eq!(r.imported, 1); } +#[test] +fn an_import_removes_conflicts_using_each_commands_final_binding_list() { + let a = "A".repeat(64); + let b = "B".repeat(64); + let scopes = || Scopes::new().with_context(&a).with_context(&b); + let scope_a = Scope::new(&a).unwrap(); + let scope_b = Scope::new(&b).unwrap(); + let trigger = craft_keymap::Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let other = craft_keymap::Trigger::parse("Cmd+K").unwrap(); + let old = CommandRef::new("old.command"); + let first = CommandRef::new("new.first"); + let second = CommandRef::new("new.second"); + let catalog = || { + vec![ + CommandDef::new(old.clone(), "Old", Scope::app()) + .with_default(Binding::in_scope(trigger, scope_a.clone())) + .with_default(Binding::in_scope(other, scope_b.clone())), + CommandDef::new(first.clone(), "First", scope_a.clone()), + CommandDef::new(second.clone(), "Second", scope_b.clone()), + ] + }; + let mut km = Keymap::new(catalog(), scopes(), Platform::Mac); + assert_eq!(km.bindings(&old).len(), 2); + assert!(km.bindings(&old).iter().any(|binding| binding.text(&Scope::app()).len() > craft_keymap::MAX_BINDING_TEXT)); + // A reader can supply an already parsed sequence through the public import API. + let key = |trigger: craft_keymap::Trigger| ForeignKey { context: None, text: trigger.to_string(), trigger: Ok(trigger), notes: Vec::new() }; + let set = ForeignSet::new(vec![ + ForeignEntry::new(None, ["Second"]).with_id("new.second").with_key(key(other)), + ForeignEntry::new(None, ["First"]).with_id("new.first").with_key(key(trigger)), + ]); + let report = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + assert!(report.failed.is_empty(), "the final cleared list is savable: {report:?}"); + assert_eq!(report.imported, 2); + assert_eq!(report.conflicts_cleared.len(), 2); + assert!(km.bindings(&old).is_empty()); + assert_eq!(km.bindings(&first), [Binding::new(trigger)]); + assert_eq!(km.bindings(&second), [Binding::new(other)]); + let reopened = Keymap::new(catalog(), scopes(), Platform::Mac).with_overrides(km.overrides().clone()); + for command in [&old, &first, &second] { + assert_eq!(reopened.bindings(command), km.bindings(command), "the imported bindings persist in the same contexts"); + } +} + +#[test] +fn an_unsavable_final_conflict_list_keeps_all_claimants_and_applies_other_entries() { + let context = "A".repeat(64); + let scope = Scope::new(&context).unwrap(); + let long = craft_keymap::Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let old = CommandRef::new("old.command"); + let catalog = vec![ + CommandDef::new(old.clone(), "Old", Scope::app()) + .with_default(Binding::in_scope(long, scope.clone())) + .with_default(b("Cmd+K")) + .with_default(b("Cmd+L")), + command("new.first", "First", &[], &["Cmd+1"]), + command("new.second", "Second", &[], &["Cmd+2"]), + command("new.other", "Other", &[], &[]), + command("old.other", "Old Other", &[], &["Cmd+J"]), + ]; + let mut overrides = Overrides::new(); + for n in 0..MAX_COMMANDS - 3 { + overrides.insert(format!("junk.{n}"), vec!["Cmd+9".into()]); + } + let mut km = Keymap::new(catalog, Scopes::new().with_context(&context), Platform::Mac).with_overrides(overrides); + let before = km.bindings(&old); + let set = ForeignSet::new(vec![ + ForeignEntry::new(None, ["First"]).with_id("new.first").with_key(ForeignKey::read(None, "Cmd+K", Flavor::Mac)), + ForeignEntry::new(None, ["Second"]).with_id("new.second").with_key(ForeignKey::read(None, "Cmd+L", Flavor::Mac)), + ForeignEntry::new(None, ["Other"]).with_id("new.other").with_key(ForeignKey::read(None, "Cmd+J", Flavor::Mac)), + ]); + let report = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + assert_eq!(report.failed.iter().map(|failed| failed.command.id.as_str()).collect::>(), ["new.first", "new.second"]); + assert_eq!(report.imported, 1); + assert_eq!(report.conflicts_cleared.len(), 1); + assert_eq!(report.conflicts_cleared[0].command.id, "old.other"); + assert_eq!(km.bindings(&old), before); + has(&km, "new.first", &["Cmd+1"]); + has(&km, "new.second", &["Cmd+2"]); + has(&km, "new.other", &["Cmd+J"]); + has(&km, "old.other", &[]); +} + /// A Mac keymap of `catalog` with no reserved chords, for sets read with [`kys::read`]. fn mac_keymap(catalog: Vec) -> Keymap { Keymap::new(catalog, Scopes::new(), Platform::Mac) diff --git a/crates/mcp/README.md b/crates/mcp/README.md index 53e4c6550b..58c487edaa 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -1,6 +1,6 @@ # craft-mcp -Transport-independent MCP 2025-03-26 server initialization and tool result helpers. +Transport-independent MCP server initialization and tool result helpers. 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`. @@ -13,9 +13,18 @@ request IDs that MCP forbids. `process` does not check the message size. initialization, initialization can occur in a batch, and client information needs only to be an object. `Policy::Strict` requires initialization first (except ping), rejects batched or repeated initialization, and requires client name and version. -Both respond with the sole supported version, 2025-03-26, even if the client offered -a different version. Instructions set with `Session::set_instructions` are returned by -every initialize response, in either policy and with or without legacy initialization. +By default both respond with 2025-03-26, even if the client offered a different version. +`Session::with_versions` sets the accepted versions, in order of preference, from +`SUPPORTED_PROTOCOL_VERSIONS` (2025-06-18, 2025-03-26 and 2024-11-05). A client that +asks for one of them gets it back, and any other request gets the first. +`Session::negotiated_version` returns the version the session answered with, for +features that depend on it, such as the `MCP-Protocol-Version` HTTP header. Once +2025-06-18 is negotiated, `Policy::Strict` rejects every batched request and +`Session::accepts_batches` returns false. Reject a batch envelope with -32600 before +dispatching it when `accepts_batches` is false, because `Session::notification` cannot +tell a batched notification from a single one. Instructions set with +`Session::set_instructions` are returned by every initialize response, in either policy +and with or without legacy initialization. An initialized notification moves the session to `Ready`. This crate does not enforce every MCP lifecycle or capability rule; applications must validate any additional requirements they depend on. @@ -39,4 +48,5 @@ roots without both kinds. A path is checked before it is opened, so another program that replaces a folder with a link between the two steps can still reach outside the roots. -See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle). +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). diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 43685c9b56..d5e1a8b10d 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -1,6 +1,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! MCP 2025-03-26 server initialization and tool envelopes, independent of transport and tools. +//! 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`. //! 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. @@ -10,8 +11,15 @@ use serde_json::{Value, json}; pub mod roots; +/// The version a session answers with unless `Session::with_versions` sets others. pub const PROTOCOL_VERSION: &str = "2025-03-26"; +/// Protocol versions whose initialization this crate implements, newest first. +pub const SUPPORTED_PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"]; + +/// Versions that removed JSON-RPC batching. +const BATCHLESS_VERSIONS: [&str; 1] = ["2025-06-18"]; + /// JSON-RPC limits for an MCP connection. MCP requires a string or integer request ID, so /// `craft_jsonrpc::process` answers a null or fractional ID with an invalid-request error and does /// not call the request handler. The size bounds are `Limits::default()`'s; override them with @@ -48,6 +56,7 @@ pub struct Session { permissive_initialize: bool, server_info: Option, instructions: Option, + negotiated: Option, initialized: bool, } @@ -63,10 +72,30 @@ impl Session { permissive_initialize: false, server_info: None, instructions: None, + negotiated: None, initialized: false, } } + /// Set the protocol versions the session accepts, in order of preference. A client that asks + /// for one of them gets it back; any other request gets the first. Each version must be in + /// `SUPPORTED_PROTOCOL_VERSIONS`, and the list must be non-empty and free of repeats. + pub fn with_versions(mut self, versions: &[&str]) -> Result { + if versions.is_empty() { + return Err(RpcError::new(-32602, "Protocol versions must not be empty")); + } + for (i, version) in versions.iter().enumerate() { + if !SUPPORTED_PROTOCOL_VERSIONS.contains(version) { + return Err(RpcError::new(-32602, format!("Unsupported protocol version {version}"))); + } + if versions[..i].contains(version) { + return Err(RpcError::new(-32602, format!("Repeated protocol version {version}"))); + } + } + self.versions = versions.iter().map(|v| (*v).to_owned()).collect(); + Ok(self) + } + /// Set the server capabilities returned at initialization. The value must be an object. pub fn with_capabilities(mut self, capabilities: Value) -> Result { if !capabilities.is_object() { @@ -101,9 +130,32 @@ impl Session { self.state } + /// The protocol version the last successful initialize answered with. + pub fn negotiated_version(&self) -> Option<&str> { + self.negotiated.as_deref() + } + + fn answer_version(&self, asked: Option<&str>) -> String { + asked + .filter(|v| self.versions.iter().any(|supported| supported == v)) + .unwrap_or_else(|| self.versions.first().map(String::as_str).unwrap_or(PROTOCOL_VERSION)) + .to_owned() + } + + /// Whether the caller may dispatch a JSON-RPC batch. False in strict mode once a version + /// without batching (2025-06-18) is negotiated; reject such a batch envelope with + /// -32600 before dispatching it, since `notification` cannot tell a batched notification apart. + pub fn accepts_batches(&self) -> bool { + self.policy != Policy::Strict || !self.negotiated.as_deref().is_some_and(|v| BATCHLESS_VERSIONS.contains(&v)) + } + /// Handles `initialize` and `ping`. Returns `None` for a request the app should route. - /// `in_batch` must describe the outer JSON-RPC envelope. + /// `in_batch` must describe the outer JSON-RPC envelope. A batched request is rejected + /// when `accepts_batches` is false. pub fn request(&mut self, request: Request<'_>, in_batch: bool) -> Option> { + if in_batch && !self.accepts_batches() { + return Some(Err(RpcError::new(-32600, "Invalid Request"))); + } if request.method == "ping" { return Some(Ok(json!({}))); } @@ -113,27 +165,29 @@ impl Session { } if self.permissive_initialize { let asked = request.params.and_then(|p| p.get("protocolVersion")).and_then(Value::as_str); - let version = asked - .filter(|v| self.versions.iter().any(|supported| supported == v)) - .unwrap_or_else(|| self.versions.first().map(String::as_str).unwrap_or(PROTOCOL_VERSION)); + let version = self.answer_version(asked); let result = json!({"protocolVersion": version, "capabilities": self.capabilities, "serverInfo": self.server_info}); self.state = State::AwaitingInitialized; + self.negotiated = Some(version); return Some(Ok(self.with_instructions(result))); } let Some(params) = request.params.and_then(Value::as_object) else { return Some(Err(invalid_initialize())); }; - let valid = params.get("protocolVersion").and_then(Value::as_str).is_some() - && params.get("capabilities").is_some_and(Value::is_object) - && params.get("clientInfo").is_some_and(Value::is_object); + let asked = params.get("protocolVersion").and_then(Value::as_str); + let valid = + asked.is_some() && params.get("capabilities").is_some_and(Value::is_object) && params.get("clientInfo").is_some_and(Value::is_object); let identity = params.get("clientInfo").and_then(Value::as_object); let strict_identity = identity .is_some_and(|info| info.get("name").and_then(Value::as_str).is_some() && info.get("version").and_then(Value::as_str).is_some()); if !valid || (self.policy == Policy::Strict && !strict_identity) { return Some(Err(invalid_initialize())); } + let version = self.answer_version(asked); + let result = + json!({"protocolVersion": version, "capabilities": self.capabilities, "serverInfo": {"name": self.name, "version": self.version}}); self.state = State::AwaitingInitialized; - let result = json!({"protocolVersion": PROTOCOL_VERSION, "capabilities": self.capabilities, "serverInfo": {"name": self.name, "version": self.version}}); + self.negotiated = Some(version); return Some(Ok(self.with_instructions(result))); } if self.policy == Policy::Strict && self.state == State::New { @@ -205,6 +259,7 @@ mod tests { assert_eq!(result["protocolVersion"], expected); assert_eq!(result["serverInfo"]["title"], "Title"); assert_eq!(result["instructions"], "help"); + assert_eq!(s.negotiated_version(), Some(expected)); } } @@ -266,6 +321,54 @@ mod tests { } } + #[test] + fn validated_initialize_negotiates_configured_versions() { + let mut s = Session::new("test", "1", Policy::Compatible).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert_eq!(s.negotiated_version(), None); + for (asked, expected) in [("2024-11-05", "2024-11-05"), ("2025-03-26", "2025-03-26"), ("2025-06-18", "2025-06-18"), ("1.0.0", "2025-06-18")] { + let p = json!({"protocolVersion": asked, "capabilities": {}, "clientInfo": {}}); + let r = s.request(call("initialize", Some(&p)), false).unwrap().unwrap(); + assert_eq!(r["protocolVersion"], expected); + assert_eq!(s.negotiated_version(), Some(expected)); + } + let mut old_first = Session::new("test", "1", Policy::Compatible).with_versions(&["2025-03-26", "2025-06-18"]).unwrap(); + let p = json!({"protocolVersion": "2099-01-01", "capabilities": {}, "clientInfo": {}}); + assert_eq!(old_first.request(call("initialize", Some(&p)), false).unwrap().unwrap()["protocolVersion"], "2025-03-26"); + } + + #[test] + fn version_lists_reject_empty_unknown_and_repeated_entries() { + let new = || Session::new("test", "1", Policy::Compatible); + assert!(new().with_versions(&[]).is_err()); + assert!(new().with_versions(&["2099-01-01"]).is_err()); + assert!(new().with_versions(&["2025-06-18", "2025-06-18"]).is_err()); + let mut s = new(); + let p = json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {}}); + assert!(s.request(call("initialize", Some(&json!({}))), false).unwrap().is_err()); + assert_eq!(s.negotiated_version(), None); + assert_eq!(s.request(call("initialize", Some(&p)), false).unwrap().unwrap()["protocolVersion"], PROTOCOL_VERSION); + } + + #[test] + fn strict_rejects_batches_after_negotiating_a_version_without_them() { + let p = |v: &str| json!({"protocolVersion": v, "capabilities": {}, "clientInfo": {"name": "client", "version": "1"}}); + let mut s = Session::new("test", "1", Policy::Strict).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(s.accepts_batches()); + assert!(s.request(call("initialize", Some(&p("2025-06-18"))), false).unwrap().is_ok()); + assert!(!s.accepts_batches()); + assert_eq!(s.request(call("ping", None), true).unwrap().unwrap_err().code, -32600); + assert_eq!(s.request(call("tools/list", None), true).unwrap().unwrap_err().code, -32600); + assert!(s.request(call("tools/list", None), false).is_none()); + let mut older = Session::new("test", "1", Policy::Strict).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(older.request(call("initialize", Some(&p("2025-03-26"))), false).unwrap().is_ok()); + assert!(older.accepts_batches()); + assert!(older.request(call("tools/list", None), true).is_none()); + let mut compatible = Session::new("test", "1", Policy::Compatible).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(compatible.request(call("initialize", Some(&p("2025-06-18"))), false).unwrap().is_ok()); + assert!(compatible.accepts_batches()); + assert!(compatible.request(call("tools/list", None), true).is_none()); + } + #[test] fn tool_envelopes_validate_arguments_and_preserve_results() { let p = json!({"name":"open"}); diff --git a/crates/media/README.md b/crates/media/README.md index 38c0ced3f7..bbbe121a5a 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -467,6 +467,10 @@ not apply to it; damage is skipped with the same budget and warnings as `open`. in `streams()`, where a later link of a chained file appears as a new stream when its pages are reached. `OggFile::read_packet_into` reads a packet into a reused buffer. `OpusTiming` gives each Opus packet's start, the pre-skip and the end trimming of the final page. +`VorbisTiming` gives each Vorbis packet's start and duration (from the block sizes of the modes that +`VorbisModes` reads from the setup header), the samples to discard before a negative starting +position, the offset of a stream that starts after 0, and the end trimming of the final page +(Vorbis I §4.3.8 and §A.2). The muxer side is `PageWriter`, from FilmCraft's `filmcraft-oggmux` by @JordyUSA (storytold/filmcraft#4481): it laces the packets of one logical stream into pages (continued @@ -625,9 +629,10 @@ let au: Vec = file.read_unit(&bytes, v, 0)?; // the first access unit - **Program streams**: MPEG-2 and MPEG-1 packs, system headers, the program stream map (stream types for elementary stream ids), padding, private stream 2 (DVD navigation) skipped, private stream 1 split by sub-stream id. Garbage resynchronises on the next pack or PES start code. -- **Streams**: MPEG-1/2 video, H.264, HEVC, MPEG audio, AAC (ADTS, LATM/LOAS), AC-3, E-AC-3, - DTS, TrueHD, Blu-ray LPCM, DVD LPCM (format from the sub-stream header), PGS / DVB / teletext - subtitles; ISO 639 language from the PMT. +- **Streams**: MPEG-1/2 video, H.264, HEVC, MPEG-4 Part 2 (stream type 0x10), AV1 and Opus + (stream type 0x06 with the `AV01` or `Opus` registration descriptor), MPEG audio, AAC (ADTS, + LATM/LOAS), AC-3, E-AC-3, DTS, TrueHD, Blu-ray LPCM, DVD LPCM (format from the sub-stream + header), PGS / DVB / teletext subtitles; ISO 639 language from the PMT. - **Access units**, found while the file is scanned (one pass, streaming; only a few bytes of each stream are buffered): - MPEG-1/2 video: a coded frame — a frame picture, or two field pictures (paired by @@ -639,6 +644,17 @@ let au: Vec = file.read_unit(&bytes, v, 0)?; // the first access unit - Audio: one frame per unit from the frame headers (sync re-hunted after garbage; a header found while hunting is confirmed by the next one); a PTS belongs to the first frame starting in the PES. + - MPEG-4 Part 2: PES packets with a timestamp, as for H.264; the first VOP's coding type + gives the key (I-VOP) and disposable (B-VOP) flags. + - Opus: one access unit per unit, cut by its control header's payload size; `read_unit` + returns the Opus packet without the header, and the start and end trims are in + `Stream::opus` (`OpusConfig::trims`). An access unit without a control header runs to the + end of its PES packet; one whose size runs past its PES packet is dropped and counted in + `skipped_bytes`. + - AV1: one PES packet per unit, a key unit when the TS packet that starts it sets the random + access indicator. `read_unit` returns the OBUs in the low overhead bitstream format (start + codes, emulation prevention bytes and temporal delimiters removed, `obu_size` added where it + is missing), as Matroska and ISOBMFF store them. - LPCM and everything else: one PES packet per unit. - **Timestamps**: 33-bit PTS/DTS unwrapped across the wrap (and back, for B pictures shown before a wrap that came earlier); PCR / SCR range. @@ -652,8 +668,12 @@ MPEG audio or AC-3 frames in chunks that do not follow them (AVI) find the frame `Codec::codec_id()` and `Stream::codec_params()` give the crate-wide `CodecId` / `CodecParams`. MPEG-1 video reports `Mpeg2Video`; MPEG audio reports `Mp2` whatever its layer (the layer is in each frame header: `frame_info(..).variant`); ADTS and LATM AAC both report `Aac`; DTS, TrueHD and -subtitles have no identifier (`Unknown`). The streams carry their configuration in band, so -`extradata` is empty; DVD LPCM fills `sample_rate`, `channels` and `pcm`. +subtitles have no identifier (`Unknown`). Opus fills `sample_rate` (48 kHz), `channels` and an +`OpusHead` header in `extradata`, built from the PMT's Opus audio descriptor (`Stream::opus`) with +the start trims of the units that open the stream as its pre-skip. AV1 puts the first four bytes of an `av1C` record, +from the PMT's AV1 video descriptor (`Stream::av1c`), in `extradata`. The other streams carry +their configuration in band, so `extradata` is empty; DVD LPCM fills `sample_rate`, `channels` +and `pcm`. Limits, each with a test: 2²³ access units per stream (the rest are not indexed, with a warning), 128 MiB per unit read (`MAX_UNIT_BYTES`), a PES header given up after 1024 bytes, 16 stuffing bytes @@ -670,6 +690,9 @@ at least 8 bytes. | DVD-Video private stream 1 sub-stream layout (AC-3 / DTS 0x80-0x8F with a 3-byte header, LPCM 0xA0-0xAF with a 6-byte header, sub-pictures 0x20-0x3F) | public descriptions | `.vob` | | ETSI EN 300 468 (descriptors 0x56, 0x59, 0x6A, 0x7A, 0x7B), ATSC A/52 Annex A (AC-3 in TS) | — | identifying private PES streams | | ISO/IEC 11172-3, 13818-3 (frame headers), ISO/IEC 13818-7 (ADTS), 14496-3 (LOAS), ATSC A/52 (syncinfo, E-AC-3 frmsiz) | — | audio frame lengths for splitting | +| ISO/IEC 14496-2 | any edition | MPEG-4 Part 2 VOP coding types | +| Opus Interactive Audio Codec Transport Multiplexing Standard | draft TS V0.1.3 (2015-10) | Opus control headers, the Opus audio descriptor and its channel configurations; RFC 7845 for the `OpusHead` header and the channel mapping families | +| Carriage of AV1 in MPEG-2 TS (Alliance for Open Media) | working draft | the AV1 video descriptor, start codes and emulation prevention; the AV1 Bitstream & Decoding Process Specification for OBU headers and `obu_size` | ### Gaps @@ -688,9 +711,10 @@ Differences from `filmcraft-mpegts`: `ByteSource` is `craft_media::ByteSource`; Tests: a small TS muxer and PS writer (every access unit reads back byte-identical with its PTS, key and disposable flags), 33-bit unwrap, truncation and mutation, streams of every codec filled with random start codes and sync words, damaged PSI sections with valid CRCs, and the frame-header -helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made files (MPEG-2, H.264 -and HEVC video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Blu-ray and DVD LPCM; TS, M2TS, VOB and -MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, timestamps and key flags. +helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares eleven ffmpeg-made files (MPEG-2, +H.264, HEVC and MPEG-4 Part 2 video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Opus, Blu-ray and DVD +LPCM; TS, M2TS, VOB and MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, +timestamps and key flags. ### Transport stream writer @@ -783,9 +807,7 @@ the first stream) every 40 ms and 700 ms behind the DTS, the PAT and PMT every 1 keyframes, and writes of 7 packets. Gaps: one program per stream; no null packets (no constant bit rate); not written: LPCM (H.222.0 -defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. The -demuxer reads Opus and AV1 streams as `Unknown(6)` and MPEG-4 Part 2 as `Unknown(0x10)`, one unit -per PES packet. +defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. Specifications: the ones above, and Opus Interactive Audio Codec Transport Multiplexing Standard, draft TS V0.1.3 (2015-10), for the Opus control header and descriptors; RFC 6716 for Opus packet @@ -796,7 +818,8 @@ descriptors. Tests: `tests/mpegts_mux_readback.rs` reads the output back with the demuxer: streams, codecs, languages, every frame's bytes, PTS and DTS, keyframes and the PCR range, with no continuity or -CRC warnings, including AV1 units, Opus with an explicit mapping and a start trim, both sides of a +CRC warnings, including AV1 units as OBUs with their `av1C` fields, Opus packets with fixed +and explicit channel configurations and their start and end trims, MPEG-4 Part 2, both sides of a discontinuity, and the output that follows an I/O error. `tests/mpegts_mux_fuzz.rs` muxes random programs and timelines with idle gaps and output swaps and reads them back, and feeds random bytes to every codec. Unit tests check every PES header's fixed bits, the sections' CRC, and that every diff --git a/crates/media/src/mpegts/es.rs b/crates/media/src/mpegts/es.rs index 8568c7cba2..c17f086484 100644 --- a/crates/media/src/mpegts/es.rs +++ b/crates/media/src/mpegts/es.rs @@ -7,7 +7,7 @@ use std::collections::VecDeque; -use super::{Codec, PictureInfo, Unit}; +use super::{Codec, OpusTrim, PictureInfo, Unit}; /// How a stream is cut into units. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -19,6 +19,16 @@ enum Mode { Nal { hevc: bool }, /// Framed audio with self-describing frame headers. Audio(AudioSync), + /// Opus: one access unit per unit, cut by its control header's payload size and starting + /// after the header; an access unit without a control header runs to the end of its PES + /// packet (Opus transport draft §6). + Opus, + /// MPEG-4 Part 2 video: a PES packet with a timestamp starts a unit; the first VOP's coding + /// type gives the flags. + Mpeg4, + /// AV1: one PES packet per unit (Carriage of AV1 in MPEG-2 TS §3.4), a key unit where the + /// packet that starts it sets the random access indicator. + Av1, /// One PES packet per unit. Pes, } @@ -41,6 +51,9 @@ impl Mode { Codec::AacAdts => Mode::Audio(AudioSync::Adts), Codec::AacLatm => Mode::Audio(AudioSync::Loas), Codec::Ac3 | Codec::Eac3 => Mode::Audio(AudioSync::Ac3), + Codec::Opus => Mode::Opus, + Codec::Mpeg4Part2 => Mode::Mpeg4, + Codec::Av1 => Mode::Av1, _ => Mode::Pes, } } @@ -101,8 +114,16 @@ pub(crate) struct Splitter { gop: Option<(bool, bool)>, pending: Option, open_field: Option, - // audio state + // audio state; for Opus, where the next access unit's control header starts (None: the + // rest of the PES packet belongs to the open unit) or, once one is read, where its payload + // ends next_frame: Option, + /// Opus: how far the payload size of a control header cut off by the end of a chunk was read. + opus_scan: OpusSizeScan, + /// Opus: the open unit's start and end trims. + open_trim: (u16, u16), + /// Opus: the trims of the units so far. + pub trims: Vec, } /// AC-3 frame sizes in 16-bit words for 48 / 44.1 / 32 kHz (A/52 Table 5.18), by @@ -331,6 +352,158 @@ pub(crate) const MAX_UNITS: usize = 1 << 23; /// Full-bandwidth channels per AC-3 audio coding mode (A/52 Table 5.8). const AC3_CHANNELS: [u32; 8] = [2, 1, 2, 3, 3, 4, 4, 5]; +/// What starts an Opus access unit. +#[derive(Debug, PartialEq, Eq)] +enum OpusHeader { + /// More bytes are needed to tell. + Incomplete, + /// No control header: the access unit is the rest of the PES packet. + Absent, + /// A control header whose payload size is past [`super::MAX_UNIT_BYTES`]. + Invalid, + /// A control header of `len` bytes, then `size` bytes of payload with these start and end + /// trims. + Found { len: usize, size: u64, trim: (u16, u16) }, +} + +/// How far the payload size of the control header at ES offset `at` was read: `next` is the +/// header index of the next size byte to read, and `size` is the sum of the bytes before it. +#[derive(Debug, Default)] +struct OpusSizeScan { + at: u64, + next: usize, + size: u64, + /// Size bytes read, by every header. + #[cfg(test)] + reads: u64, +} + +/// The opus_control_header at the start of `b`, which is ES offset `at` (Opus transport draft +/// §6.2): the 11-bit prefix 0x3FF, the start trim, end trim and extension flags, the payload size +/// as bytes of 0xFF and a last byte, then the 13-bit trims and the extension. When `b` ends +/// before the header does, `scan` keeps the size read so far, and a call with more bytes of the +/// same header goes on from there, so each size byte is read once. +fn opus_control_header(b: &[u8], at: u64, scan: &mut OpusSizeScan) -> OpusHeader { + match b { + [] => return OpusHeader::Incomplete, + [0x7F] => return OpusHeader::Incomplete, + [0x7F, b1, ..] if b1 & 0xE0 == 0xE0 => {} + _ => return OpusHeader::Absent, + } + let flags = b[1]; + if scan.at != at || scan.next < 2 { + scan.at = at; + scan.next = 2; + scan.size = 0; + } + let mut i = scan.next; + let mut size = scan.size; + loop { + let Some(&x) = b.get(i) else { + scan.next = i; + scan.size = size; + return OpusHeader::Incomplete; + }; + #[cfg(test)] + { + scan.reads += 1; + } + if size + u64::from(x) > u64::from(super::MAX_UNIT_BYTES) { + return OpusHeader::Invalid; + } + if x != 0xFF { + // the trims or the extension may still be cut off: a later call reads this last + // size byte again + scan.next = i; + scan.size = size; + size += u64::from(x); + i += 1; + break; + } + size += u64::from(x); + i += 1; + } + let mut trim = [0u16; 2]; + for (k, bit) in [0x10u8, 0x08].into_iter().enumerate() { + if flags & bit != 0 { + let Some(v) = b.get(i..i + 2) else { return OpusHeader::Incomplete }; + trim[k] = u16::from_be_bytes([v[0], v[1]]) & 0x1FFF; + i += 2; + } + } + if flags & 0x04 != 0 { + let Some(&n) = b.get(i) else { return OpusHeader::Incomplete }; + i += 1 + usize::from(n); + if i > b.len() { + return OpusHeader::Incomplete; + } + } + OpusHeader::Found { len: i, size, trim: (trim[0], trim[1]) } +} + +/// Rewrites an AV1 access unit from the start code form of Carriage of AV1 in MPEG-2 TS §3.2 to +/// the low overhead bitstream format: each OBU follows a start code 0x000001, and the 0x03 of +/// every 0x000003 in it is an emulation prevention byte. Temporal delimiters and bytes before the +/// first start code are left out, as Matroska and ISOBMFF store AV1. An OBU that carries +/// obu_size ends there; one without gets an obu_size for the bytes up to the next start code. +pub(crate) fn av1_obus(es: &mut Vec) { + let mut out = Vec::with_capacity(es.len() + 16); + let mut obu = Vec::new(); + let start_code = |i: usize| es.get(i..i + 3) == Some(&[0, 0, 1][..]); + let mut i = (0..es.len()).find(|&i| start_code(i)).unwrap_or(es.len()); + while i < es.len() { + // `i` is at a start code + i += 3; + obu.clear(); + let mut zeros = 0; + while i < es.len() && !start_code(i) { + let b = es[i]; + i += 1; + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + obu.push(b); + } + let Some(&h) = obu.first() else { continue }; + let header = 1 + usize::from(h & 0x04 != 0); + if obu.len() < header || (h >> 3) & 0x0F == 2 { + continue; + } + if h & 0x02 != 0 { + // obu_size, leb128 (AV1 §4.10.5) + let mut size = 0u64; + let mut at = header; + for k in 0..8 { + let Some(&b) = obu.get(at) else { break }; + at += 1; + size |= u64::from(b & 0x7F) << (7 * k); + if b & 0x80 == 0 { + break; + } + } + let end = usize::try_from(size).ok().and_then(|s| at.checked_add(s)).filter(|&e| e <= obu.len()).unwrap_or(obu.len()); + out.extend_from_slice(&obu[..end]); + } else { + out.push(h | 0x02); + out.extend_from_slice(&obu[1..header]); + let mut size = obu.len() - header; + loop { + let b = (size & 0x7F) as u8; + size >>= 7; + if size == 0 { + out.push(b); + break; + } + out.push(b | 0x80); + } + out.extend_from_slice(&obu[header..]); + } + } + *es = out; +} + /// Frame length at the start of `b` for the given sync type (`None`: no valid header; `Some(0)` /// is never returned). fn frame_len(sync: AudioSync, b: &[u8]) -> Option { @@ -388,6 +561,9 @@ impl Splitter { pending: None, open_field: None, next_frame: None, + opus_scan: OpusSizeScan::default(), + open_trim: (0, 0), + trims: Vec::new(), } } @@ -398,12 +574,48 @@ impl Splitter { self.pes.pop_front(); } match self.mode { - Mode::Pes => self.begin_pes_unit(true), - Mode::Nal { .. } => self.begin_pes_unit(pts.is_some() || dts.is_some()), + Mode::Pes | Mode::Av1 => self.begin_pes_unit(true), + Mode::Nal { .. } | Mode::Mpeg4 => self.begin_pes_unit(pts.is_some() || dts.is_some()), + Mode::Opus => { + // a PES packet holds whole access units: the next one starts here + self.close_opus(self.es_pos); + self.next_frame = Some(self.es_pos); + } _ => {} } } + /// The packet that started the PES packet set the random access indicator: an AV1 unit + /// that the packet starts is a key unit. + pub fn random_access(&mut self) { + if self.mode == Mode::Av1 + && let Some(o) = self.open.as_mut() + && o.start == self.es_pos + { + o.key = true; + } + } + + /// Opus: end the open unit before ES byte `limit` (the end of its PES packet). A unit whose + /// payload size runs past `limit` is dropped, and so are the bytes of a control header that + /// the PES packet cuts off. + fn close_opus(&mut self, limit: u64) { + match self.next_frame { + Some(end) if end > limit => { + if let Some(o) = self.open.take() { + self.skipped += limit.saturating_sub(o.start); + } + self.open_trim = (0, 0); + } + Some(end) => { + self.close(end); + self.skipped += limit - end; + } + None => self.close(limit), + } + self.next_frame = None; + } + /// PES-delimited units: a packet with a timestamp (or any packet in plain PES mode) starts a /// new unit; one without continues the previous unit. fn begin_pes_unit(&mut self, new: bool) { @@ -443,6 +655,7 @@ impl Splitter { /// End the open unit at `end`. fn close(&mut self, end: u64) { let Some(o) = self.open.take() else { return }; + let (start_trim, end_trim) = std::mem::take(&mut self.open_trim); if end <= o.start || o.pos == u64::MAX { return; } @@ -450,6 +663,9 @@ impl Splitter { self.truncated = true; return; } + if (start_trim, end_trim) != (0, 0) { + self.trims.push(OpusTrim { unit: self.units.len(), start: start_trim, end: end_trim }); + } let size = (end - o.start).min(u32::MAX as u64) as u32; self.units.push(Unit { pts: o.pts, @@ -469,9 +685,9 @@ impl Splitter { return; } // PES-delimited modes resolve a unit's position from `pos` right here and never look a - // chunk up again, so remembering chunks there would only grow without bound (NAL streams - // keep theirs: an access unit can start inside a PES; `keep_from` prunes them) - if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. }) { + // chunk up again, so remembering chunks there would only grow without bound (NAL and Opus + // streams keep theirs: an access unit can start inside a PES; `keep_from` prunes them) + if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. } | Mode::Opus) { self.chunks.push_back((pos, self.es_pos)); } if let Some(o) = self.open.as_mut() @@ -484,10 +700,12 @@ impl Splitter { let start = self.es_pos; self.es_pos += data.len() as u64; match self.mode { - Mode::Pes => {} + Mode::Pes | Mode::Av1 => {} Mode::Nal { hevc } => self.scan_nal(start, data, hevc), Mode::MpegVideo => self.scan_mpeg(start, data), + Mode::Mpeg4 => self.scan_mpeg4(start, data), Mode::Audio(sync) => self.scan_audio(start, data, sync), + Mode::Opus => self.scan_opus(start, data), } // forget chunks no pending position can refer to let keep_from = self.buf_start.min(self.pending.map_or(u64::MAX, |p| p.unit_start.min(p.at))).min(self.header_start.unwrap_or(u64::MAX)); @@ -789,8 +1007,115 @@ impl Splitter { frame_len(sync, &self.buf[j..]).is_some() } + /// Opus access units: each control header gives the payload size, so the unit starts after + /// the header and ends where the next header starts. + fn scan_opus(&mut self, start: u64, data: &[u8]) { + let end = start + data.len() as u64; + let Some(next) = self.next_frame else { + // the rest of the PES packet belongs to the open unit, or is not Opus at all + if self.open.is_none() { + self.skipped += data.len() as u64; + } + // no later header can refer back to these bytes: `feed` may forget their chunks + self.buf.clear(); + self.buf_start = end; + return; + }; + if next >= end { + // inside the open unit's payload + self.buf.clear(); + self.buf_start = end; + return; + } + self.window(start, data); + while let Some(at) = self.next_frame { + if at < self.buf_start { + self.next_frame = None; + break; + } + let i = (at - self.buf_start) as usize; + if i >= self.buf.len() { + break; + } + match opus_control_header(&self.buf[i..], at, &mut self.opus_scan) { + OpusHeader::Incomplete => { + self.trim(self.buf.len() - i); + return; + } + OpusHeader::Absent => { + // no control header: the access unit runs to the end of the PES packet + self.close(at); + self.open_opus(at, at, (0, 0)); + self.next_frame = None; + } + OpusHeader::Invalid => { + self.close(at); + self.skipped += end - at; + self.next_frame = None; + } + OpusHeader::Found { len, size, trim } => { + self.close(at); + let payload = at + len as u64; + self.open_opus(at, payload, trim); + self.next_frame = Some(payload + size); + } + } + } + self.buf.clear(); + self.buf_start = end; + } + + /// Open an Opus unit at `start` for the access unit whose header (if any) starts at `at`. + fn open_opus(&mut self, at: u64, start: u64, trim: (u16, u16)) { + // a payload that starts with the next chunk is placed when that chunk arrives + let (pos, offset) = if start < self.es_pos { self.locate(start).unwrap_or((u64::MAX, 0)) } else { (u64::MAX, 0) }; + let mut o = Open { start, pos, offset, pts: None, dts: None, key: true, disposable: false, vcl: false, picture: None }; + if let Some((pts, dts)) = self.timestamps_at(at) { + o.pts = pts; + o.dts = dts; + } + self.open = Some(o); + self.open_trim = trim; + } + + /// MPEG-4 Part 2 video: the unit's first VOP header gives its coding type (ISO/IEC 14496-2 + /// §6.2.5: 0 I, 1 P, 2 B, 3 S). + fn scan_mpeg4(&mut self, start: u64, data: &[u8]) { + self.window(start, data); + if self.open.is_some_and(|o| o.vcl) { + // the unit's flags are known: keep only where a start code may begin + self.trim(3); + return; + } + let mut i = 0; + let mut blocked = None; + while let Some(k) = self.next_start_code(i) { + if k + 5 > self.buf.len() { + blocked = Some(k); + break; + } + let at = self.buf_start + k as u64; + if self.buf[k + 3] == 0xB6 + && let Some(o) = self.open.as_mut() + && !o.vcl + && at >= o.start + { + let coding_type = self.buf[k + 4] >> 6; + o.key = coding_type == 0; + o.disposable = coding_type == 2; + o.vcl = true; + } + i = k + 3; + } + self.keep_tail(i, blocked); + } + /// End of stream: close the open unit. pub fn finish(&mut self) { + if self.mode == Mode::Opus { + self.close_opus(self.es_pos); + return; + } self.settle_pending(); let end = match (self.mode, self.next_frame) { (Mode::Audio(_), Some(n)) => n.min(self.es_pos), @@ -884,6 +1209,48 @@ mod tests { } } + #[test] + fn a_long_opus_control_header_is_read_once() { + // a payload size of 100,000 bytes of 0xFF, cut into transport stream payloads + let mut s = Splitter::new(&Codec::Opus); + s.pes_start(Some(0), None); + let mut es = vec![0x7F, 0xE0]; + es.extend(std::iter::repeat_n(0xFF, 100_000)); + es.push(0); + for (k, c) in es.chunks(184).enumerate() { + s.feed(k as u64 * 188, c); + } + assert!(s.opus_scan.reads <= es.len() as u64, "{} size bytes read for a {}-byte header", s.opus_scan.reads, es.len()); + assert_eq!(s.next_frame, Some(es.len() as u64 + 255 * 100_000)); + } + + #[test] + fn opus_chunks_are_forgotten_inside_a_unit_and_after_a_headerless_one() { + // an access unit whose payload spans 500 chunks, then a PES packet without a control + // header + let mut s = Splitter::new(&Codec::Opus); + s.pes_start(Some(0), None); + let size = 184 * 500; + let mut es = vec![0x7F, 0xE0]; + es.extend(std::iter::repeat_n(0xFF, size / 255)); + es.push((size % 255) as u8); + es.resize(es.len() + size, 0x11); + let mut pos = 0; + for (k, c) in es.chunks(184).enumerate() { + s.feed(pos, c); + pos += 188; + assert!(k < 3 || s.chunks.len() <= 2, "chunk {k}: {} chunks retained", s.chunks.len()); + } + s.pes_start(Some(1800), None); + for k in 0..500 { + s.feed(pos, &[0xFC; 184]); + pos += 188; + assert!(s.chunks.len() <= 2, "headerless chunk {k}: {} chunks retained", s.chunks.len()); + } + s.finish(); + assert_eq!(s.units.iter().map(|u| u.size as usize).collect::>(), [size, 184 * 500]); + } + #[test] fn unit_table_is_capped() { let frame = |k: u8| { diff --git a/crates/media/src/mpegts/mod.rs b/crates/media/src/mpegts/mod.rs index 32356be02d..3e0570fa29 100644 --- a/crates/media/src/mpegts/mod.rs +++ b/crates/media/src/mpegts/mod.rs @@ -9,10 +9,11 @@ //! LPCM). //! - **Elementary streams** are split into access units on open — coded frames for MPEG-1/2 //! video (picture start codes, field pairs), H.264 and HEVC (access unit delimiters / first -//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, PES -//! packets for LPCM — each with its PTS/DTS (a PES timestamp belongs to the first access unit -//! that starts in the packet), random-access flag and, for MPEG video, picture type, temporal -//! reference and field structure. That index is the seeking table. +//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, Opus +//! access units (by their control headers), PES packets for LPCM, AV1 and MPEG-4 Part 2 video. +//! Each unit has its PTS/DTS (a PES timestamp belongs to the first access unit that starts in +//! the packet), random-access flag and, for MPEG video, picture type, temporal reference and field +//! structure. That index is the seeking table. //! - Units are read back on demand by re-reading the file from the unit's first packet, so the //! index costs a few dozen bytes per access unit. //! - [`mux`] writes one program as a transport stream to any `io::Write`, frame by frame. @@ -162,6 +163,13 @@ pub enum Codec { H264, /// H.265 / HEVC, Annex B. Hevc, + /// MPEG-4 Part 2 visual (ISO/IEC 14496-2), stream type 0x10. + Mpeg4Part2, + /// AV1 (stream type 0x06 with the registration descriptor "AV01"). [`File::read_unit`] + /// returns each access unit in the low overhead bitstream format, without start codes, + /// emulation prevention bytes or temporal delimiters; the AV1 video descriptor is in + /// [`Stream::av1c`]. + Av1, /// MPEG-1/2 audio (layers I-III; the layer is in each frame header). MpegAudio, /// AAC in ADTS frames. @@ -174,6 +182,10 @@ pub enum Codec { Eac3, /// DTS. Dts, + /// Opus (stream type 0x06 with the registration descriptor "Opus"). Each unit is one Opus + /// access unit without its control header; the channel configuration and the trims are in + /// [`Stream::opus`]. + Opus, /// Dolby TrueHD. TrueHd, /// Blu-ray / AVCHD LPCM (a 4-byte header per PES packet, big-endian samples). @@ -194,12 +206,15 @@ impl Codec { Codec::Mpeg2Video => "MPEG-2 Video".into(), Codec::H264 => "H.264".into(), Codec::Hevc => "HEVC".into(), + Codec::Mpeg4Part2 => "MPEG-4 Part 2".into(), + Codec::Av1 => "AV1".into(), Codec::MpegAudio => "MPEG Audio".into(), Codec::AacAdts => "AAC (ADTS)".into(), Codec::AacLatm => "AAC (LATM)".into(), Codec::Ac3 => "AC-3".into(), Codec::Eac3 => "E-AC-3".into(), Codec::Dts => "DTS".into(), + Codec::Opus => "Opus".into(), Codec::TrueHd => "Dolby TrueHD".into(), Codec::LpcmBluray => "LPCM (Blu-ray)".into(), Codec::LpcmDvd => "LPCM (DVD)".into(), @@ -220,10 +235,13 @@ impl Codec { Codec::Mpeg1Video | Codec::Mpeg2Video => Id::Mpeg2Video, Codec::H264 => Id::H264, Codec::Hevc => Id::Hevc, + Codec::Mpeg4Part2 => Id::Mpeg4Video, + Codec::Av1 => Id::Av1, Codec::MpegAudio => Id::Mp2, Codec::AacAdts | Codec::AacLatm => Id::Aac, Codec::Ac3 => Id::Ac3, Codec::Eac3 => Id::Eac3, + Codec::Opus => Id::Opus, Codec::LpcmBluray | Codec::LpcmDvd => Id::Pcm, Codec::Dts | Codec::TrueHd | Codec::Subtitle(_) | Codec::Unknown(_) => Id::Unknown, } @@ -232,13 +250,14 @@ impl Codec { /// The kind of media. pub fn kind(&self) -> Kind { match self { - Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc => Kind::Video, + Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc | Codec::Mpeg4Part2 | Codec::Av1 => Kind::Video, Codec::MpegAudio | Codec::AacAdts | Codec::AacLatm | Codec::Ac3 | Codec::Eac3 | Codec::Dts + | Codec::Opus | Codec::TrueHd | Codec::LpcmBluray | Codec::LpcmDvd => Kind::Audio, @@ -280,11 +299,14 @@ pub struct Unit { pub pts: Option, /// See `pts`. pub dts: Option, - /// Decoding can start here (I / IDR / IRAP pictures; every audio frame). + /// Decoding can start here (I / IDR / IRAP pictures, MPEG-4 Part 2 I-VOPs, AV1 units whose + /// packet sets the random access indicator; every audio frame). pub key: bool, - /// No other unit depends on it (B pictures of MPEG-1/2 video, non-reference H.264/HEVC). + /// No other unit depends on it (B pictures of MPEG-1/2 video, MPEG-4 Part 2 B-VOPs, + /// non-reference H.264/HEVC). pub disposable: bool, - /// Bytes of elementary stream. + /// Bytes of elementary stream (for AV1, with its start codes and emulation prevention + /// bytes). pub size: u32, /// TS: byte offset of the packet holding the first byte; PS: byte offset of its PES packet. pub(crate) pos: u64, @@ -305,6 +327,59 @@ pub struct LpcmFormat { pub bits: u32, } +/// An Opus stream's channel configuration (the Opus audio descriptor of the Opus transport +/// draft, with the fixed configurations of its table 4-3 written out) and its trims. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OpusConfig { + /// Output channels. + pub channels: u8, + /// Channel mapping family (RFC 7845 §5.1.1): 0, 1 or 255. + pub family: u8, + /// Opus streams in each access unit. + pub streams: u8, + /// Streams that decode to two channels. + pub coupled: u8, + /// For each output channel, the coded channel it is taken from, or 255 for silence. + pub mapping: Vec, + /// The units whose control header carries a start or end trim, in unit order. + pub trims: Vec, +} + +/// Samples at 48 kHz that a unit's control header says to discard. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OpusTrim { + /// Index of the unit in [`Stream::units`]. + pub unit: usize, + /// Samples to discard from the start of the unit. + pub start: u16, + /// Samples to discard from the end of the unit. + pub end: u16, +} + +impl OpusConfig { + /// The `OpusHead` identification header (RFC 7845 §5.1) for this configuration. Its pre-skip + /// is the sum of the start trims of the units that open the stream (units 0, 1, 2 and so on, + /// as long as each one has a start trim), at most 65 535; a start trim later in the stream, + /// after a discontinuity, stays in [`OpusConfig::trims`] only. Its input sample rate is 48 kHz + /// and its output gain 0. + pub fn opus_head(&self) -> Vec { + let pre_skip = + self.trims.iter().enumerate().take_while(|&(k, t)| t.unit == k && t.start > 0).fold(0u16, |a, (_, t)| a.saturating_add(t.start)); + let mut v = b"OpusHead".to_vec(); + v.push(1); + v.push(self.channels); + v.extend_from_slice(&pre_skip.to_le_bytes()); + v.extend_from_slice(&48_000u32.to_le_bytes()); + v.extend_from_slice(&0i16.to_le_bytes()); + v.push(self.family); + if self.family != 0 { + v.extend_from_slice(&[self.streams, self.coupled]); + v.extend_from_slice(&self.mapping); + } + v + } +} + /// Where a stream's PES packets come from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StreamId { @@ -334,6 +409,13 @@ pub struct Stream { pub units: Vec, /// DVD LPCM: the sample format. pub lpcm: Option, + /// Opus: the channel configuration from the PMT's Opus audio descriptor, and the trims of the + /// units' control headers. `None` when the descriptor is missing or not valid. + pub opus: Option, + /// AV1: the first four bytes of an ISOBMFF `av1C` record, from the PMT's AV1 video + /// descriptor (marker and version, profile and level, tier and color format, initial + /// presentation delay). `None` without a valid descriptor. + pub av1c: Option<[u8; 4]>, /// PES packets seen. pub pes_packets: u64, /// Bytes of payload ignored because the stream could not be split (e.g. before the first @@ -347,16 +429,24 @@ impl Stream { self.codec.kind() } /// What a decoder needs for this stream, in the container-neutral form the codec crates take: - /// the codec ([`Codec::codec_id`]) and, for DVD LPCM, the sample format (big-endian). These - /// streams carry their configuration in band, so `extradata` is empty: H.264 and HEVC are - /// Annex B with their parameter sets, AAC is ADTS or LATM frames, and a Blu-ray LPCM packet - /// starts with its own 4-byte format header. + /// the codec ([`Codec::codec_id`]) and, for DVD LPCM, the sample format (big-endian). Opus + /// gets its `OpusHead` header ([`OpusConfig::opus_head`]), 48 kHz and its channel count, and + /// AV1 the four bytes of [`Stream::av1c`]. The other streams carry their configuration in + /// band, so `extradata` is empty: H.264 and HEVC are Annex B with their parameter sets, + /// MPEG-4 Part 2 has its configuration headers before its keyframes, AAC is ADTS or LATM + /// frames, and a Blu-ray LPCM packet starts with its own 4-byte format header. pub fn codec_params(&self) -> crate::CodecParams { let mut p = crate::CodecParams::new(self.codec.codec_id()); if let Some(f) = self.lpcm { let n = |v: u32| u16::try_from(v).unwrap_or(0); p = p.with_sample_rate(f.sample_rate).with_channels(n(f.channels)).with_pcm(crate::PcmFormat::int(n(f.bits), true, true)); } + if let (Codec::Opus, Some(o)) = (&self.codec, &self.opus) { + p = p.with_sample_rate(48_000).with_channels(u16::from(o.channels)).with_extradata(o.opus_head()); + } + if let (Codec::Av1, Some(c)) = (&self.codec, self.av1c) { + p = p.with_extradata(c.to_vec()); + } p } /// First and last presentation timestamps (90 kHz) of the stream's units. @@ -397,7 +487,8 @@ impl File { self.streams.iter().position(|s| s.kind() == kind && !s.units.is_empty() && f(&s.codec)) } - /// Read access unit `i` of stream `s`. + /// Read access unit `i` of stream `s`. An AV1 unit comes back in the low overhead bitstream + /// format ([`Codec::Av1`]), so it can be shorter than [`Unit::size`]. pub fn read_unit(&self, src: &S, s: usize, i: usize) -> Result> { let st = self.streams.get(s).ok_or_else(|| Error::Invalid("no such stream".into()))?; let u = st.units.get(i).ok_or_else(|| Error::Invalid("no such unit".into()))?; @@ -413,6 +504,9 @@ impl File { if out.len() < u.size as usize { return Err(Error::Invalid(format!("unit {i} truncated ({} of {} bytes)", out.len(), u.size))); } + if st.codec == Codec::Av1 { + es::av1_obus(&mut out); + } Ok(out) } } diff --git a/crates/media/src/mpegts/mux/mod.rs b/crates/media/src/mpegts/mux/mod.rs index 7e7ced7918..89f5ba8fd8 100644 --- a/crates/media/src/mpegts/mux/mod.rs +++ b/crates/media/src/mpegts/mux/mod.rs @@ -51,6 +51,8 @@ mod av1; mod pes; mod psi; +pub(crate) use psi::OPUS_DESCRIPTOR_EXTENSION; + use std::fmt; use std::io::{self, Write}; diff --git a/crates/media/src/mpegts/ps.rs b/crates/media/src/mpegts/ps.rs index d044c01f45..effc7b92c0 100644 --- a/crates/media/src/mpegts/ps.rs +++ b/crates/media/src/mpegts/ps.rs @@ -247,6 +247,8 @@ pub(crate) fn scan(src: &S, mpeg1: bool) -> Result language: None, units: Vec::new(), lpcm, + opus: None, + av1c: None, pes_packets: 0, skipped_bytes: 0, }; diff --git a/crates/media/src/mpegts/tests.rs b/crates/media/src/mpegts/tests.rs index b9cb1af3b7..842dc43625 100644 --- a/crates/media/src/mpegts/tests.rs +++ b/crates/media/src/mpegts/tests.rs @@ -5,6 +5,7 @@ use super::*; mod hostile; +mod opus_av1_mpeg4; fn ts_bytes(prefix: u8, v: i64) -> [u8; 5] { let v = v & ((1 << 33) - 1); @@ -1035,6 +1036,8 @@ fn oversized_unit_is_refused_without_reserving_it() { language: None, units: vec![Unit { pts: None, dts: None, key: true, disposable: false, size: u32::MAX, pos: 0, offset: 0, picture: None }], lpcm: None, + opus: None, + av1c: None, pes_packets: 0, skipped_bytes: 0, }], diff --git a/crates/media/src/mpegts/tests/hostile.rs b/crates/media/src/mpegts/tests/hostile.rs index a0503fc0c1..5f4d09b4b5 100644 --- a/crates/media/src/mpegts/tests/hostile.rs +++ b/crates/media/src/mpegts/tests/hostile.rs @@ -57,13 +57,13 @@ fn ps_seed() -> Vec { #[test] fn hostile_input_never_panics() { - let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed()]; + let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed(), super::opus_av1_mpeg4::seed()]; seeds.push(work_tests::big_program_stream(false, 8).0); seeds.push(work_tests::big_program_stream(true, 8).0); // fewer rounds than FilmCraft's 40 000: tests here build without optimisation, and the two // large program streams cost a megabyte of window refill per unit read for (i, s) in seeds.iter().enumerate() { - craft_media_testkit::hostile::hammer(&format!("mpegts seed {i}"), s, if i < 3 { 4_000 } else { 150 }, exercise); + craft_media_testkit::hostile::hammer(&format!("mpegts seed {i}"), s, if i < 4 { 4_000 } else { 150 }, exercise); } } @@ -83,6 +83,9 @@ fn elementary_stream_frame_parsers_never_panic() { Codec::TrueHd, Codec::LpcmBluray, Codec::LpcmDvd, + Codec::Mpeg4Part2, + Codec::Av1, + Codec::Opus, Codec::Unknown(0x55), ]; let mut ac3 = vec![0x0B, 0x77, 0, 0, 30, 0x40]; diff --git a/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs b/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs new file mode 100644 index 0000000000..6375fb3981 --- /dev/null +++ b/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs @@ -0,0 +1,279 @@ +//! Opus, AV1 and MPEG-4 Part 2 streams built by hand from the carriage rules: the Opus transport +//! draft (control headers, the Opus audio descriptor), Carriage of AV1 in MPEG-2 TS (start codes, +//! emulation prevention, the AV1 video descriptor) and stream type 0x10. + +use super::super::ts::opus_config; +use super::*; + +const OPUS_PID: u16 = 0x1100; +const AV1_PID: u16 = 0x1200; +const MPEG4_PID: u16 = 0x1300; + +/// The registration descriptor "Opus" and an Opus audio descriptor with this channel_config_code +/// and the bytes after it. +fn opus_desc(code: &[u8]) -> Vec { + let mut d = vec![0x05, 4, b'O', b'p', b'u', b's', 0x7F, 1 + code.len() as u8, 0x80]; + d.extend_from_slice(code); + d +} + +/// An opus_control_header for `size` payload bytes. +fn control(size: usize, start: Option, end: Option, ext: Option<&[u8]>) -> Vec { + let flags = 0xE0 | if start.is_some() { 0x10 } else { 0 } | if end.is_some() { 0x08 } else { 0 } | if ext.is_some() { 0x04 } else { 0 }; + let mut v = vec![0x7F, flags]; + v.extend(std::iter::repeat_n(0xFF, size / 255)); + v.push((size % 255) as u8); + for t in [start, end].into_iter().flatten() { + v.extend_from_slice(&t.to_be_bytes()); + } + if let Some(e) = ext { + v.push(e.len() as u8); + v.extend_from_slice(e); + } + v +} + +/// `n` bytes of an Opus packet: a TOC byte, then filler. +fn opus_packet(n: usize, seed: u8) -> Vec { + let mut v = vec![0xFC]; + v.extend((1..n).map(|i| (i as u8).wrapping_mul(7) ^ seed)); + v +} + +fn opus_mux(code: &[u8]) -> TsMux { + let mut mux = TsMux::new(false); + mux.psi_full(&[(0x06, OPUS_PID, opus_desc(code))], OPUS_PID); + mux +} + +/// A transport stream packet on `pid` that starts a PES packet and sets the random access +/// indicator; `payload` is at most 182 bytes. +fn random_access_packet(mux: &mut TsMux, pid: u16, payload: &[u8]) { + let cc = mux.cc.entry(pid).or_insert(0); + let al = 183 - payload.len(); + let mut p = vec![0x47, 0x40 | (pid >> 8) as u8, pid as u8, 0x30 | *cc, al as u8, 0x40]; + p.extend(std::iter::repeat_n(0xFF, al - 1)); + p.extend_from_slice(payload); + *cc = (*cc + 1) & 15; + mux.out.extend(p); +} + +/// A transport stream packet on `pid` that sets the unit start indicator and carries only an +/// adaptation field, with the random access indicator set when `random_access` is. +fn adaptation_only_start(mux: &mut TsMux, pid: u16, random_access: bool) { + let cc = *mux.cc.entry(pid).or_insert(0); + let mut p = vec![0x47, 0x40 | (pid >> 8) as u8, pid as u8, 0x20 | cc, 183, if random_access { 0x40 } else { 0 }]; + p.extend(std::iter::repeat_n(0xFF, 182)); + mux.out.extend(p); +} + +/// Opus, AV1 and MPEG-4 Part 2 streams in one program, for the hostile-input sweep. +pub(super) fn seed() -> Vec { + let mut mux = TsMux::new(false); + let av1 = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0xC0]; + mux.psi_full(&[(0x06, OPUS_PID, opus_desc(&[0x02])), (0x06, AV1_PID, av1), (0x10, MPEG4_PID, Vec::new())], OPUS_PID); + for k in 0..6i64 { + let mut au = control(40, (k == 0).then_some(312), None, Some(&[1, 2])); + au.extend(opus_packet(40, k as u8)); + au.extend(control(3, None, None, None)); + au.extend(opus_packet(3, k as u8)); + mux.pes(OPUS_PID, &pes(0xBD, Some(1800 * k), None, &au, true)); + let tu = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x0A, 0x04, 0, 0, 3, 0, 0x7F, 0, 0, 1, 0x30, 0x10, 0x20]; + mux.pes(AV1_PID, &pes(0xBD, Some(3600 * k), None, &tu, true)); + let vop = [0, 0, 1, 0xB6, if k == 0 { 0x10 } else { 0x50 }, 1, 2, 3]; + mux.pes(MPEG4_PID, &pes(0xE0, Some(3600 * k), None, &vop, true)); + } + mux.out +} + +#[test] +fn opus_access_units_are_cut_by_their_control_headers() { + let mut mux = opus_mux(&[0x02]); + let (a, b, c, d) = (opus_packet(600, 1), opus_packet(5, 2), opus_packet(7, 3), opus_packet(10, 4)); + // one PES packet: an access unit with a start trim and a control extension, a plain one, and + // one without a control header that runs to the end of the packet + let mut first = control(a.len(), Some(312), None, Some(&[9, 9, 9])); + first.extend(&a); + first.extend(control(b.len(), None, None, None)); + first.extend(&b); + first.extend(&c); + mux.pes(OPUS_PID, &pes(0xBD, Some(90_000), None, &first, true)); + let mut second = control(d.len(), None, Some(100), None); + second.extend(&d); + mux.pes(OPUS_PID, &pes(0xBD, Some(91_800), None, &second, true)); + let f = open(&mux.out).unwrap(); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.skipped_bytes), (Codec::Opus, Kind::Audio, 0)); + let units: Vec> = (0..s.units.len()).map(|n| f.read_unit(&mux.out, 0, n).unwrap()).collect(); + assert_eq!(units, [a, b, c, d]); + // the PES timestamps belong to the first access unit of each packet + assert_eq!(s.units.iter().map(|u| u.pts).collect::>(), [Some(90_000), None, None, Some(91_800)]); + assert!(s.units.iter().all(|u| u.key)); + let o = s.opus.as_ref().unwrap(); + assert_eq!(o.trims, [OpusTrim { unit: 0, start: 312, end: 0 }, OpusTrim { unit: 3, start: 0, end: 100 }]); +} + +#[test] +fn an_opus_control_header_may_cross_packet_boundaries() { + // the second header starts at every offset around the end of the first TS packet's payload + for len in 150..200 { + let mut mux = opus_mux(&[0x01]); + let (a, b) = (opus_packet(len, 5), opus_packet(300, 6)); + let mut au = control(a.len(), None, None, None); + au.extend(&a); + au.extend(control(b.len(), Some(80), Some(20), None)); + au.extend(&b); + mux.pes(OPUS_PID, &pes(0xBD, Some(1000), None, &au, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 2, "len {len}"); + assert_eq!((f.read_unit(&mux.out, 0, 0).unwrap(), f.read_unit(&mux.out, 0, 1).unwrap()), (a, b), "len {len}"); + assert_eq!(s.opus.as_ref().unwrap().trims, [OpusTrim { unit: 1, start: 80, end: 20 }], "len {len}"); + } +} + +#[test] +fn opus_access_units_past_their_packet_are_dropped() { + let mut mux = opus_mux(&[0x02]); + // a payload size of 1000 in a packet that holds 50 bytes of it + let mut cut = control(1000, None, None, None); + cut.extend(opus_packet(50, 1)); + mux.pes(OPUS_PID, &pes(0xBD, Some(0), None, &cut, true)); + // a payload size past the largest unit: 0xFF bytes for 130 MiB, then the packet ends + let mut huge = vec![0x7F, 0xE0]; + huge.extend(std::iter::repeat_n(0xFF, 535_000)); + mux.pes(OPUS_PID, &pes(0xBD, Some(1800), None, &huge, false)); + let good = opus_packet(20, 2); + let mut au = control(good.len(), None, None, None); + au.extend(&good); + mux.pes(OPUS_PID, &pes(0xBD, Some(3600), None, &au, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 1); + assert_eq!(s.units[0].pts, Some(3600)); + assert_eq!(f.read_unit(&mux.out, 0, 0).unwrap(), good); + assert!(s.skipped_bytes >= 50 + 535_000, "{} bytes skipped", s.skipped_bytes); +} + +#[test] +fn opus_channel_configurations_follow_the_draft_table() { + let config = |code: &[u8]| opus_config(&opus_desc(code)).map(|o| (o.channels, o.family, o.streams, o.coupled, o.mapping)); + // dual mono as one coupled stream and as two mono streams + assert_eq!(config(&[0x00]), Some((2, 255, 1, 1, vec![0, 1]))); + assert_eq!(config(&[0x80]), Some((2, 255, 2, 0, vec![0, 1]))); + assert_eq!(config(&[0x03]), Some((3, 1, 2, 1, vec![0, 2, 1]))); + assert_eq!(config(&[0x07]), Some((7, 1, 4, 3, vec![0, 4, 1, 2, 3, 5, 6]))); + // the same orders with a mono stream per channel + assert_eq!(config(&[0x82]), Some((2, 1, 2, 0, vec![0, 1]))); + assert_eq!(config(&[0x88]), Some((8, 1, 8, 0, vec![0, 1, 2, 3, 4, 5, 6, 7]))); + for reserved in [0x09, 0x7F, 0x89, 0xFF] { + assert_eq!(config(&[reserved]), None, "{reserved:#x}"); + } + // explicit: 3 channels, family 1, 2 streams (01), 1 coupled (01), mapping 0 2 1 (00 10 01) + assert_eq!(config(&[0x81, 3, 1, 0b0101_0010, 0b0100_0000]), Some((3, 1, 2, 1, vec![0, 2, 1]))); + // a silent channel is the all-ones mapping value: 2 streams (1), none coupled (00), mapping + // silence 0 (11 00) + assert_eq!(config(&[0x81, 2, 255, 0b1001_1000]), Some((2, 255, 2, 0, vec![255, 0]))); + // no channels, a reserved family, more streams than channels, a mapping past the coded + // channels, too few bytes + assert_eq!(config(&[0x81, 0, 0]), None); + assert_eq!(config(&[0x81, 2, 2, 0]), None); + assert_eq!(config(&[0x81, 3, 1, 0xFF, 0xFF]), None); + // two streams, none coupled: mapping values take 2 bits, and 2 names no coded channel + // (1, 00, then 10 00) + assert_eq!(config(&[0x81, 2, 255, 0b1001_0000]), None); + assert_eq!(config(&[0x81, 3, 1]), None); + // family 1 stops at 8 channels; family 0 at 2 + assert_eq!(config(&[0x81, 9, 1, 0, 0, 0, 0, 0]), None); + assert_eq!(config(&[0x81, 3, 0]), None); +} + +#[test] +fn the_pre_skip_counts_only_the_start_trims_that_open_the_stream() { + let pre_skip = |trims: &[(usize, u16, u16)]| { + let mut o = opus_config(&opus_desc(&[0x02])).unwrap(); + o.trims = trims.iter().map(|&(unit, start, end)| OpusTrim { unit, start, end }).collect(); + let head = o.opus_head(); + u16::from_le_bytes([head[10], head[11]]) + }; + assert_eq!(pre_skip(&[]), 0); + // a lead-in longer than one access unit, then a start trim after a discontinuity + assert_eq!(pre_skip(&[(0, 960, 0), (1, 960, 0), (2, 312, 0), (40, 500, 0)]), 2232); + // an end trim on the first unit stops the lead-in + assert_eq!(pre_skip(&[(0, 0, 100), (1, 312, 0)]), 0); + assert_eq!(pre_skip(&[(3, 312, 0)]), 0); + assert_eq!(pre_skip(&[(0, 60_000, 0), (1, 60_000, 0)]), u16::MAX); +} + +#[test] +fn av1_units_come_back_as_obus() { + let mut mux = TsMux::new(false); + // hdr_wcg_idc 3 (11), a reserved bit (0), initial_presentation_delay_present (1), delay 3 + // (0011) + let desc = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0b1101_0011]; + mux.psi_full(&[(0x06, AV1_PID, desc)], AV1_PID); + // a temporal delimiter; a sequence header with obu_size 4 whose payload 00 00 00 7F carries + // an emulation prevention byte, and a stray byte after it; a frame OBU without obu_size + let key = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x0A, 0x04, 0, 0, 3, 0, 0x7F, 0x55, 0, 0, 1, 0x30, 0x10, 0x20, 0x30]; + random_access_packet(&mut mux, AV1_PID, &pes(0xBD, Some(3600), None, &key, true)); + let next = [0, 0, 1, 0x32, 0x02, 0xAA, 0xBB]; + mux.pes(AV1_PID, &pes(0xBD, Some(7200), None, &next, true)); + // null packets, so the file holds the five packets the probe looks for + mux.pes(0x1FFF, &[0xFF; 184 * 2]); + let f = open(&mux.out).unwrap(); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.codec.codec_id()), (Codec::Av1, Kind::Video, crate::CodecId::Av1)); + assert_eq!(s.av1c, Some([0x81, 0x08, 0x0C, 0b0001_0011])); + assert_eq!(s.codec_params().extradata, [0x81, 0x08, 0x0C, 0b0001_0011]); + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [true, false]); + assert_eq!(f.read_unit(&mux.out, 0, 0).unwrap(), [0x0A, 0x04, 0, 0, 0, 0x7F, 0x32, 0x03, 0x10, 0x20, 0x30]); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), [0x32, 0x02, 0xAA, 0xBB]); +} + +#[test] +fn an_adaptation_field_only_unit_start_keeps_the_random_access_indicator_of_the_pes_packet() { + let tu = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x32, 0x02, 0xAA, 0xBB]; + for first_is_key in [true, false] { + let mut mux = TsMux::new(false); + let desc = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0xC0]; + mux.psi_full(&[(0x06, AV1_PID, desc)], AV1_PID); + // the PES header ends in the next packet; an adaptation-field-only unit start with the + // other indicator comes between the two + let first = pes(0xBD, Some(3600), None, &tu, true); + if first_is_key { + random_access_packet(&mut mux, AV1_PID, &first[..5]); + } else { + mux.packet(AV1_PID, true, &first[..5]); + } + adaptation_only_start(&mut mux, AV1_PID, !first_is_key); + mux.packet(AV1_PID, false, &first[5..]); + mux.pes(AV1_PID, &pes(0xBD, Some(7200), None, &tu, true)); + mux.pes(0x1FFF, &[0xFF; 184 * 2]); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [first_is_key, false], "first is key: {first_is_key}"); + } +} + +#[test] +fn mpeg4_part2_units_take_their_flags_from_the_first_vop() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x10, MPEG4_PID)]); + // visual object sequence and VOL headers, then an I-VOP; a P-VOP whose data goes on in a PES + // packet without a timestamp; a B-VOP + let i_vop = [0, 0, 1, 0xB0, 0x01, 0, 0, 1, 0x00, 0, 0, 1, 0x20, 0x00, 0x84, 0, 0, 1, 0xB6, 0x10, 1, 2]; + let p_vop = [0, 0, 1, 0xB6, 0x50, 3, 4]; + let more = [5u8; 300]; + let b_vop = [0, 0, 1, 0xB6, 0x90, 6, 7]; + mux.pes(MPEG4_PID, &pes(0xE0, Some(3600), None, &i_vop, true)); + mux.pes(MPEG4_PID, &pes(0xE0, Some(7200), None, &p_vop, true)); + mux.pes(MPEG4_PID, &pes(0xE0, None, None, &more, true)); + mux.pes(MPEG4_PID, &pes(0xE0, Some(10_800), None, &b_vop, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.codec.codec_id()), (Codec::Mpeg4Part2, Kind::Video, crate::CodecId::Mpeg4Video)); + assert_eq!(s.units.iter().map(|u| (u.key, u.disposable)).collect::>(), [(true, false), (false, false), (false, true)]); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), [&p_vop[..], &more].concat()); +} diff --git a/crates/media/src/mpegts/ts.rs b/crates/media/src/mpegts/ts.rs index 1d28bb736a..7c9ea716ef 100644 --- a/crates/media/src/mpegts/ts.rs +++ b/crates/media/src/mpegts/ts.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use super::es::Splitter; use super::pes::{self, PesHeader}; -use super::{ByteSource, ClockRange, Codec, Error, File, Format, Result, Stream, StreamId, Unit, Unwrap, read_some}; +use super::{ByteSource, ClockRange, Codec, Error, File, Format, OpusConfig, Result, Stream, StreamId, Unit, Unwrap, read_some}; /// Byte-wise table for the MSB-first CRC-32 (polynomial 0x04C11DB7): entry `i` is the CRC register /// after shifting the byte `i` through eight bit steps. @@ -40,6 +40,8 @@ struct Packet<'a> { cc: u8, has_payload: bool, discontinuity: bool, + /// random_access_indicator of the adaptation field. + random_access: bool, pcr: Option, payload: &'a [u8], } @@ -65,6 +67,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { let mut start = 4; let mut pcr = None; let mut discontinuity = false; + let mut random_access = false; if afc & 2 != 0 { let al = p[4] as usize; start = 5 + al; @@ -74,6 +77,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { if al > 0 { let flags = p[5]; discontinuity = flags & 0x80 != 0; + random_access = flags & 0x40 != 0; if flags & 0x10 != 0 && al >= 7 { let base = ((p[6] as i64) << 25) | ((p[7] as i64) << 17) | ((p[8] as i64) << 9) | ((p[9] as i64) << 1) | (p[10] as i64 >> 7); let ext = (((p[10] & 1) as i64) << 8) | p[11] as i64; @@ -82,7 +86,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { } } let has_payload = afc & 1 != 0; - Ok(Packet { pusi, pid, cc, has_payload, discontinuity, pcr, payload: if has_payload { &p[start..188] } else { &[] } }) + Ok(Packet { pusi, pid, cc, has_payload, discontinuity, random_access, pcr, payload: if has_payload { &p[start..188] } else { &[] } }) } /// `(transport_error_indicator, scrambled)` of a packet whose first byte is the sync byte (H.222.0 @@ -230,6 +234,31 @@ struct EsState { asm: PesAsm, cc: Option, dup: DupGuard, + /// The packet that started the PES packet being assembled set random_access_indicator. + random_access: bool, +} + +impl EsState { + /// Reassemble PES packets from packet `pk` (at file offset `pos`) and pass their payload to + /// the splitter. + fn feed(&mut self, pk: &Packet<'_>, pos: u64, unwrap: &mut Unwrap) { + // `PesAsm` passes over an adaptation-field-only unit start, so its indicator does not + // belong to the PES packet being assembled + if pk.pusi && !pk.payload.is_empty() { + self.random_access = pk.random_access; + } + let (hdr, bytes) = self.asm.packet(pk.pusi, pk.payload); + if let Some(h) = hdr { + self.stream.pes_packets += 1; + let pts = h.pts.map(|t| unwrap.unwrap(t)); + let dts = h.dts.map(|t| unwrap.unwrap(t)); + self.split.pes_start(pts, dts); + if std::mem::take(&mut self.random_access) { + self.split.random_access(); + } + } + self.split.feed(pos, bytes); + } } /// Map a PMT stream_type (and the ES descriptors) to a codec. `hdmv`: a Blu-ray / AVCHD stream @@ -253,6 +282,7 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { 0x03 | 0x04 => Codec::MpegAudio, 0x0F => Codec::AacAdts, 0x11 => Codec::AacLatm, + 0x10 => Codec::Mpeg4Part2, 0x1B => Codec::H264, 0x24 => Codec::Hevc, 0x80 if hdmv => Codec::LpcmBluray, @@ -264,6 +294,10 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { 0x87 => Codec::Eac3, 0x90 if hdmv => Codec::Subtitle("PGS subtitles"), 0x92 if hdmv => Codec::Subtitle("Text subtitles"), + // the registration descriptors of the Opus transport draft (§4.3) and of Carriage of + // AV1 in MPEG-2 TS (§2.1) + 0x06 if reg == Some(*b"Opus") => Codec::Opus, + 0x06 if reg == Some(*b"AV01") => Codec::Av1, 0x06 => { if tags.contains(&0x6A) || reg == Some(*b"AC-3") { Codec::Ac3 @@ -283,6 +317,131 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { } } +/// The body of the first descriptor with this tag (and, for tag 0x7F, this extension tag, which +/// the returned body leaves out). +fn descriptor(desc: &[u8], tag: u8, extension: Option) -> Option<&[u8]> { + let mut i = 0; + while i + 2 <= desc.len() { + let (t, len) = (desc[i], desc[i + 1] as usize); + let body = desc.get(i + 2..i + 2 + len)?; + match extension { + None if t == tag => return Some(body), + Some(e) if t == tag && body.first() == Some(&e) => return Some(&body[1..]), + _ => {} + } + i += 2 + len; + } + None +} + +/// Bits needed for the values 0 to `n - 1`: ceil(log2(n)). +fn bits_for(n: u32) -> u32 { + if n <= 1 { 0 } else { 32 - (n - 1).leading_zeros() } +} + +/// The channel configuration of the Opus audio descriptor (Opus transport draft §5.3: tag 0x7F, +/// extension tag 0x80, the value the writer uses): a fixed configuration of table 4-3, or one +/// coded in full (channel_config_code 0x81). `None` for a reserved code or fields out of range. +pub(crate) fn opus_config(desc: &[u8]) -> Option { + let body = descriptor(desc, 0x7F, Some(super::mux::OPUS_DESCRIPTOR_EXTENSION))?; + let code = *body.first()?; + let fixed = |channels: u8, family: u8, streams: u8, coupled: u8, mapping: &[u8]| OpusConfig { + channels, + family, + streams, + coupled, + mapping: mapping.to_vec(), + trims: Vec::new(), + }; + let c = match code { + // two channels as one coupled stream, or as two mono streams, in no speaker order + 0x00 => fixed(2, 255, 1, 1, &[0, 1]), + 0x80 => fixed(2, 255, 2, 0, &[0, 1]), + 0x01 => fixed(1, 0, 1, 0, &[0]), + 0x02 => fixed(2, 0, 1, 1, &[0, 1]), + // the RFC 7845 §5.1.1.2 surround orders, with as many coupled streams as fit + 0x03 => fixed(3, 1, 2, 1, &[0, 2, 1]), + 0x04 => fixed(4, 1, 2, 2, &[0, 1, 2, 3]), + 0x05 => fixed(5, 1, 3, 2, &[0, 4, 1, 2, 3]), + 0x06 => fixed(6, 1, 4, 2, &[0, 4, 1, 2, 3, 5]), + 0x07 => fixed(7, 1, 4, 3, &[0, 4, 1, 2, 3, 5, 6]), + 0x08 => fixed(8, 1, 5, 3, &[0, 6, 1, 2, 3, 4, 5, 7]), + // the same orders with every channel in a mono stream + 0x82..=0x88 => { + let ch = code - 0x80; + fixed(ch, 1, ch, 0, &(0..ch).collect::>()) + } + 0x81 => opus_explicit(body.get(1..)?)?, + _ => return None, + }; + Some(c) +} + +/// An explicit Opus channel configuration: channel_count, mapping_family and, for a family above +/// 0, stream_count_minus_one, coupled_stream_count and the channel mapping in as few bits as the +/// draft gives each. +fn opus_explicit(b: &[u8]) -> Option { + let (&channels, &family) = (b.first()?, b.get(1)?); + if channels == 0 { + return None; + } + if family == 0 { + // one mono or stereo stream in coded order + return (channels <= 2).then(|| OpusConfig { + channels, + family, + streams: 1, + coupled: channels - 1, + mapping: (0..channels).collect(), + trims: Vec::new(), + }); + } + // family 1 is defined for 1 to 8 channels (RFC 7845 §5.1.1.2) + if !(family == 255 || family == 1 && channels <= 8) { + return None; + } + let bits = &b[2..]; + let mut at = 0u32; + let mut take = |n: u32| -> Option { + let mut v = 0u32; + for _ in 0..n { + let byte = *bits.get((at / 8) as usize)?; + v = v << 1 | u32::from(byte >> (7 - at % 8) & 1); + at += 1; + } + Some(v) + }; + let ch = u32::from(channels); + let streams = take(bits_for(ch))? + 1; + let coupled = take(bits_for(streams + 1))?; + // a mapping entry is one byte, 255 meaning silence (RFC 7845 §5.1.1) + if streams > ch || coupled > streams || streams + coupled > 255 { + return None; + } + let width = bits_for(streams + coupled + 1); + let silence = (1u32 << width) - 1; + let mut mapping = Vec::with_capacity(usize::from(channels)); + for _ in 0..channels { + let m = take(width)?; + match m { + m if m == silence => mapping.push(255), + m if m < streams + coupled => mapping.push(m as u8), + _ => return None, + } + } + Some(OpusConfig { channels, family, streams: streams as u8, coupled: coupled as u8, mapping, trims: Vec::new() }) +} + +/// The AV1 video descriptor (Carriage of AV1 in MPEG-2 TS §2.2: tag 0x80, marker and version 1) +/// as the first four bytes of an `av1C` record: the descriptor's fourth byte holds hdr_wcg_idc +/// and a reserved bit where `av1C` has reserved zeros. +pub(crate) fn av1c(desc: &[u8]) -> Option<[u8; 4]> { + match descriptor(desc, 0x80, None)? { + &[0x81, b1, b2, b3, ..] => Some([0x81, b1, b2, b3 & 0x1F]), + _ => None, + } +} + fn language(desc: &[u8]) -> Option { let mut i = 0; while i + 2 <= desc.len() { @@ -369,10 +528,15 @@ fn add_pmt_streams(sec: &[u8], packet_size: usize, later: bool, es: &mut HashMap language: language(desc), units: Vec::new(), lpcm: None, + opus: if codec == Codec::Opus { opus_config(desc) } else { None }, + av1c: if codec == Codec::Av1 { av1c(desc) } else { None }, pes_packets: 0, skipped_bytes: 0, }; - es.insert(pid, EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None, dup: DupGuard::default() }); + es.insert( + pid, + EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None, dup: DupGuard::default(), random_access: false }, + ); order.push(pid); } changed || (later && es.keys().any(|p| !listed.contains(p))) @@ -595,14 +759,7 @@ pub(crate) fn scan(src: &S, packet_size: usize, sync_off } e.cc = Some(pk.cc); } - let (hdr, bytes) = e.asm.packet(pk.pusi, pk.payload); - if let Some(h) = hdr { - e.stream.pes_packets += 1; - let pts = h.pts.map(|t| unwrap.unwrap(t)); - let dts = h.dts.map(|t| unwrap.unwrap(t)); - e.split.pes_start(pts, dts); - } - e.split.feed(pos, bytes); + e.feed(&pk, pos, &mut unwrap); } // `p >= 1` here (the loop ran at least once or `resync` moved past the failed packet) off += p.max(1) as u64; @@ -640,6 +797,9 @@ pub(crate) fn scan(src: &S, packet_size: usize, sync_off e.split.finish(); e.stream.units = std::mem::take(&mut e.split.units); e.stream.skipped_bytes = e.split.skipped; + if let Some(o) = e.stream.opus.as_mut() { + o.trims = std::mem::take(&mut e.split.trims); + } if e.split.truncated { warnings.push(format!("PID {pid}: more than {} access units, the rest are not indexed", super::es::MAX_UNITS)); } @@ -729,7 +889,16 @@ mod dup_tests { #[test] fn a_discontinuity_packet_is_never_a_duplicate() { let payload = [7u8; 20]; - let pk = |discontinuity| Packet { pusi: true, pid: 0x100, cc: 3, has_payload: true, discontinuity, pcr: None, payload: &payload }; + let pk = |discontinuity| Packet { + pusi: true, + pid: 0x100, + cc: 3, + has_payload: true, + discontinuity, + random_access: false, + pcr: None, + payload: &payload, + }; let mut g = DupGuard::default(); assert!(!g.is_dup(&pk(false))); assert!(!g.is_dup(&pk(true)), "same counter and payload, but the stream restarts here"); @@ -745,6 +914,7 @@ mod dup_tests { cc: 3, has_payload, discontinuity, + random_access: false, pcr: None, payload: if has_payload { &payload } else { &[] }, }; diff --git a/crates/media/src/ogg/mod.rs b/crates/media/src/ogg/mod.rs index 850240f453..54ffc045eb 100644 --- a/crates/media/src/ogg/mod.rs +++ b/crates/media/src/ogg/mod.rs @@ -16,6 +16,10 @@ //! TOC-derived durations, the pre-skip, and end trimming of the final page, so a player can seek //! to any 48 kHz sample. //! +//! [`VorbisTiming`] does the same for Vorbis (Vorbis I §4.3.8 and §A.2): packet durations from the +//! block sizes of the modes in the setup header ([`VorbisModes`]), a nonzero starting position, +//! and end trimming of the final page. +//! //! [`PageWriter`] writes the pages of a logical bitstream, and [`opus_tags`] and //! [`vorbis_comment`] build the comment headers of Ogg Opus and Ogg Vorbis. //! @@ -32,8 +36,10 @@ use std::fmt; use std::io; pub use crate::source::{ByteSource, ReadSeekSource}; +pub use vorbis::{VorbisModes, VorbisTiming}; pub use write::{PAGE_TARGET_BYTES, PAGE_TARGET_PACKETS, PageWriter, opus_tags, vorbis_comment}; +mod vorbis; mod write; /// Errors from reading an Ogg file. @@ -1046,4 +1052,6 @@ pub use timing::{MAX_OPUS_GRANULE, OpusTiming, VorbisInfo, opus_packet_samples}; #[cfg(test)] mod tests; #[cfg(test)] +mod vorbis_tests; +#[cfg(test)] mod write_tests; diff --git a/crates/media/src/ogg/timing.rs b/crates/media/src/ogg/timing.rs index e01f39b4c3..e5485f507b 100644 --- a/crates/media/src/ogg/timing.rs +++ b/crates/media/src/ogg/timing.rs @@ -126,6 +126,10 @@ pub struct VorbisInfo { pub sample_rate: u32, /// Nominal bit rate in bits per second (0 or negative when not set). pub bitrate_nominal: i32, + /// The short block size in samples, as the header states it (Vorbis I allows 64 to 8192). + pub blocksize_0: u32, + /// The long block size in samples, as the header states it. + pub blocksize_1: u32, } impl VorbisInfo { @@ -138,6 +142,9 @@ impl VorbisInfo { channels: h[11], sample_rate: u32::from_le_bytes([h[12], h[13], h[14], h[15]]), bitrate_nominal: i32::from_le_bytes([h[20], h[21], h[22], h[23]]), + // two 4-bit exponents, the short block's in the low bits + blocksize_0: 1 << (h[28] & 0x0F), + blocksize_1: 1 << (h[28] >> 4), }) } } diff --git a/crates/media/src/ogg/vorbis.rs b/crates/media/src/ogg/vorbis.rs new file mode 100644 index 0000000000..c80d4ceb56 --- /dev/null +++ b/crates/media/src/ogg/vorbis.rs @@ -0,0 +1,447 @@ +//! Vorbis packet durations and stream timing, from the Vorbis I specification: the block sizes of +//! the identification header (§4.2.2), the modes at the end of the setup header (§4.2.4), the +//! samples a packet returns (§4.3.8) and the Ogg granule positions (§A.2). + +use super::{MAX_OPUS_GRANULE, Stream, VorbisInfo}; + +/// The most modes a setup header can declare (a 6-bit count plus one). +const MAX_MODES: usize = 64; + +/// What a Vorbis stream's packets need for their durations: the two block sizes and the block flag +/// of each mode. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VorbisModes { + /// The short and the long block size, in samples. + pub blocksizes: [u32; 2], + /// The block flag of each mode: `true` for the long block. + pub long: Vec, +} + +impl VorbisModes { + /// Reads the block sizes from the identification header and the modes from the setup header; + /// `None` when either is not a valid Vorbis I header. + /// + /// The setup header is walked from its start (codebooks, time-domain transforms, floors, + /// residues and mappings) to reach the modes, without building any decoder tables, so the cost + /// is one pass over the header's bits. + pub fn parse(identification: &[u8], setup: &[u8]) -> Option { + let info = VorbisInfo::parse(identification)?; + let [b0, b1] = [info.blocksize_0, info.blocksize_1]; + // Vorbis I is version 0, with channels and a sample rate (§4.2.2) + let version = u32::from_le_bytes([identification[7], identification[8], identification[9], identification[10]]); + if version != 0 + || info.channels == 0 + || info.sample_rate == 0 + || !(64..=8192).contains(&b0) + || !(64..=8192).contains(&b1) + || b0 > b1 + || identification[29] & 1 == 0 + { + return None; + } + let long = setup_modes(setup, info.channels)?; + Some(VorbisModes { blocksizes: [b0, b1], long }) + } + + /// The block size of an audio packet from its first byte (§4.3.1: a packet-type bit of 0, then + /// the mode number in `ilog(modes - 1)` bits); `None` for a packet that is not audio or names a + /// mode the setup header does not have. + pub fn blocksize(&self, first: u8) -> Option { + self.mode(first).map(|(_, long)| self.blocksizes[usize::from(long)]) + } + + /// The block size of an audio packet of `size` bytes starting with `prefix`; `None` also when + /// the packet ends inside its header, whose long blocks carry the previous and next window + /// flags after the mode number (§4.3.1), since a decoder drops such a packet. + fn packet_blocksize(&self, prefix: [u8; 2], size: u32) -> Option { + let (bits, long) = self.mode(prefix[0])?; + let header = 1 + bits + if long { 2 } else { 0 }; + (u64::from(size) * 8 >= u64::from(header)).then(|| self.blocksizes[usize::from(long)]) + } + + /// The width of the mode number and the block flag of the mode an audio packet's first byte + /// names. + fn mode(&self, first: u8) -> Option<(u32, bool)> { + if first & 1 != 0 { + return None; + } + let bits = ilog(self.long.len().saturating_sub(1) as u32); + let mode = usize::from(first >> 1) & ((1usize << bits) - 1); + self.long.get(mode).map(|&l| (bits, l)) + } +} + +/// Vorbis I §A.2 timing of a Vorbis stream, in samples at the stream's sample rate. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VorbisTiming { + /// Granule position of the first sample each packet returns. A packet's samples run from its + /// start for its duration; positions before 0 are samples to discard. + pub starts: Vec, + /// Samples each packet returns (§4.3.8): 0 for the first audio packet, which only primes the + /// decoder, and for packets that are not audio; otherwise a quarter of the previous audio + /// packet's block size plus a quarter of its own. + pub durations: Vec, + /// Samples to discard at the start: the first page's granule position states fewer samples + /// than its packets return (a negative starting position, at most the first two audio + /// packets' overlap). + pub skip: u32, + /// Granule position of the first sample to play: 0, or the positive start offset of a stream + /// that does not begin at time zero. + pub first: i64, + /// Playable samples from `first`, with the final page's end trimming applied. + pub total: i64, +} + +impl VorbisTiming { + /// Timing of the Vorbis stream `stream`, from its identification and setup headers and the + /// granule positions of its pages; `None` when the stream has no valid Vorbis headers. + /// + /// A granule position outside `0..=MAX_OPUS_GRANULE` is treated like a missing one, as + /// [`OpusTiming::of`](super::OpusTiming::of) does. + pub fn of(stream: &Stream) -> Option { + let modes = VorbisModes::parse(stream.headers.first()?, stream.headers.get(2)?)?; + Some(VorbisTiming::with_modes(stream, &modes)) + } + + /// Timing of `stream` with modes already read, for example from a stream whose headers came + /// from elsewhere. + pub fn with_modes(stream: &Stream, modes: &VorbisModes) -> VorbisTiming { + // Granule positions come straight from the file, so the arithmetic saturates. + let mut previous: Option = None; + // samples the first two audio packets return, the most a negative start can discard + let mut overlap = 0i64; + let mut audio = 0u8; + let durations: Vec = stream + .packets + .iter() + .map(|p| { + let Some(size) = modes.packet_blocksize(p.prefix, p.size) else { return 0 }; + let n = previous.map_or(0, |prev| prev / 4 + size / 4); + previous = Some(size); + if audio < 2 { + audio += 1; + overlap = overlap.saturating_add(i64::from(n)); + } + n + }) + .collect(); + let n = durations.len(); + let granule_of = |k: usize| stream.packets.get(k).and_then(|p| p.granule).filter(|g| (0..=MAX_OPUS_GRANULE).contains(g)); + let mut ends: Vec = vec![0; n]; + let mut cursor: Option = None; + let mut trimmed_end: Option = None; + let mut start: Option = None; + let mut i = 0; + while i < n { + // packets completing on the same page: i..=j, the last carries the page's granule + let mut j = i; + while j < n && granule_of(j).is_none() { + j += 1; + } + let sum = durations[i..j.min(n - 1) + 1].iter().fold(0i64, |a, &d| a.saturating_add(i64::from(d))); + let end = match (granule_of(j), cursor) { + // trailing packets without a granule (a truncated file): continue from the cursor + (None, c) => c.unwrap_or(0).saturating_add(sum), + // end trimming on the final page: keep the positions the packets would have + (Some(g), Some(c)) if stream.packets[j].eos && g < c.saturating_add(sum) => { + trimmed_end = Some(g); + c.saturating_add(sum) + } + // a page that returns no samples (only the priming packet) does not place the stream + (Some(g), None) if sum == 0 && !stream.packets[j].eos => { + ends[i..=j].fill(g); + i = j + 1; + continue; + } + // the first page with audio: its granule places the stream, which may start before + // or after 0 (§A.2) + (Some(g), None) => { + let s = g.saturating_sub(sum); + start = Some(s); + if stream.packets[j].eos && s < 0 { + // one page holds the whole stream: a granule below the samples it returns + // trims the end, not the start + trimmed_end = Some(g); + start = Some(0); + sum + } else { + g + } + } + // a discontinuity: trust the granule + (Some(g), Some(_)) => g, + }; + let mut e = end; + for k in (i..=j.min(n - 1)).rev() { + ends[k] = e; + e = e.saturating_sub(i64::from(durations[k])); + } + cursor = Some(end); + i = j + 1; + } + let starts: Vec = ends.iter().zip(&durations).map(|(e, &d)| e.saturating_sub(i64::from(d))).collect(); + let origin = start.unwrap_or(0); + // a negative start discards samples, never more than the first two audio packets overlap + let skip = origin.saturating_neg().clamp(0, overlap); + let first = origin.saturating_add(skip).max(0); + let end = trimmed_end.or(cursor).unwrap_or(0); + let total = end.saturating_sub(first).max(0); + VorbisTiming { starts, durations, skip: u32::try_from(skip).unwrap_or(u32::MAX), first, total } + } +} + +/// Number of bits needed to hold `x` (§9.2.1). +fn ilog(x: u32) -> u32 { + 32 - x.leading_zeros() +} + +/// Bits read least significant first (§2.1.4). +struct Bits<'a> { + data: &'a [u8], + pos: u64, +} + +impl Bits<'_> { + fn left(&self) -> u64 { + (self.data.len() as u64 * 8).saturating_sub(self.pos) + } + fn read(&mut self, n: u32) -> Option { + if u64::from(n) > self.left() { + return None; + } + let mut v = 0u32; + for k in 0..n { + let at = self.pos + u64::from(k); + let bit = (self.data[(at / 8) as usize] >> (at % 8)) & 1; + v |= u32::from(bit) << k; + } + self.pos += u64::from(n); + Some(v) + } + fn skip(&mut self, n: u64) -> Option<()> { + (n <= self.left()).then(|| self.pos += n) + } + fn zero(&mut self, n: u32) -> Option<()> { + (self.read(n)? == 0).then_some(()) + } +} + +/// The largest `r` with `r^dims <= entries` (§9.2.3). +pub(super) fn lookup1_values(entries: u32, dims: u32) -> u64 { + let fits = |r: u64| { + let mut p = 1u64; + for _ in 0..dims { + p = p.saturating_mul(r); + if p > u64::from(entries) { + return false; + } + } + true + }; + let (mut lo, mut hi) = (0u64, u64::from(entries)); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + if fits(mid) { lo = mid } else { hi = mid - 1 } + } + lo +} + +/// The block flag of each mode of a setup header (§4.2.4), passing over everything before them. +fn setup_modes(h: &[u8], channels: u8) -> Option> { + if !h.starts_with(b"\x05vorbis") { + return None; + } + let mut b = Bits { data: &h[7..], pos: 0 }; + let codebooks = b.read(8)? + 1; + for _ in 0..codebooks { + codebook(&mut b)?; + } + for _ in 0..b.read(6)? + 1 { + b.zero(16)?; + } + let floors = b.read(6)? + 1; + for _ in 0..floors { + floor(&mut b, codebooks)?; + } + let residues = b.read(6)? + 1; + for _ in 0..residues { + residue(&mut b, codebooks)?; + } + let mappings = b.read(6)? + 1; + for _ in 0..mappings { + mapping(&mut b, channels, floors, residues)?; + } + let count = b.read(6)? as usize + 1; + let mut long = Vec::with_capacity(count.min(MAX_MODES)); + for _ in 0..count { + let flag = b.read(1)? == 1; + b.zero(16)?; + b.zero(16)?; + if b.read(8)? >= mappings { + return None; + } + long.push(flag); + } + (b.read(1)? == 1).then_some(long) +} + +/// Passes over one codebook (§3.2.1). +fn codebook(b: &mut Bits<'_>) -> Option<()> { + if b.read(24)? != 0x56_4342 { + return None; + } + // a codebook of no dimensions is allowed and has no lookup values, as in the reference decoder + let dims = b.read(16)?; + let entries = b.read(24)?; + if b.read(1)? == 1 { + // ordered: runs of entries per length, each count in ilog(entries left) bits + let mut length = b.read(5)? + 1; + let mut entry = 0u32; + while entry < entries { + if length > 32 { + return None; + } + entry = entry.checked_add(b.read(ilog(entries - entry))?).filter(|&e| e <= entries)?; + length += 1; + } + } else { + let sparse = b.read(1)? == 1; + for _ in 0..entries { + if !sparse || b.read(1)? == 1 { + b.skip(5)?; + } + } + } + match b.read(4)? { + 0 => {} + kind @ (1 | 2) => { + // minimum value and delta, then the value width and the sequence flag + b.skip(32 + 32)?; + let width = u64::from(b.read(4)? + 1); + b.skip(1)?; + let values = match (kind, dims) { + (_, 0) => 0, + (1, _) => lookup1_values(entries, dims), + _ => u64::from(entries) * u64::from(dims), + }; + b.skip(values.checked_mul(width)?)?; + } + _ => return None, + } + Some(()) +} + +/// Passes over one floor configuration (§6.2.1, §7.2.2), whose books are among `codebooks`. +fn floor(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + match b.read(16)? { + 0 => { + // order, rate, bark map size, amplitude bits, amplitude offset, then the books + b.skip(8 + 16 + 16 + 6 + 8)?; + let books = b.read(4)? + 1; + for _ in 0..books { + if b.read(8)? >= codebooks { + return None; + } + } + Some(()) + } + 1 => floor1(b, codebooks), + _ => None, + } +} + +/// Passes over one residue configuration (§8.6.1), whose books are among `codebooks`. +fn residue(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + if b.read(16)? > 2 { + return None; + } + // begin, end, partition size, then the classifications and the classbook + b.skip(24 + 24 + 24)?; + let classifications = b.read(6)? + 1; + if b.read(8)? >= codebooks { + return None; + } + let mut books = 0u64; + for _ in 0..classifications { + let low = b.read(3)?; + let high = if b.read(1)? == 1 { b.read(5)? } else { 0 }; + books += u64::from((high << 3 | low).count_ones()); + } + for _ in 0..books { + if b.read(8)? >= codebooks { + return None; + } + } + Some(()) +} + +/// Passes over one mapping configuration (§4.2.4, mappings), whose submaps name one of `floors` +/// floors and one of `residues` residues. +fn mapping(b: &mut Bits<'_>, channels: u8, floors: u32, residues: u32) -> Option<()> { + b.zero(16)?; + let submaps = if b.read(1)? == 1 { b.read(4)? + 1 } else { 1 }; + if b.read(1)? == 1 { + let channel_bits = ilog(u32::from(channels) - 1); + for _ in 0..b.read(8)? + 1 { + let (magnitude, angle) = (b.read(channel_bits)?, b.read(channel_bits)?); + if magnitude == angle || magnitude >= u32::from(channels) || angle >= u32::from(channels) { + return None; + } + } + } + b.zero(2)?; + if submaps > 1 { + for _ in 0..channels { + if b.read(4)? >= submaps { + return None; + } + } + } + // per submap: an unused time configuration, the floor and the residue + for _ in 0..submaps { + b.skip(8)?; + if b.read(8)? >= floors || b.read(8)? >= residues { + return None; + } + } + Some(()) +} + +/// Passes over a floor 1 configuration (§7.2.2), whose books are among `codebooks`. The X list, +/// with its two implicit end points, holds at most 65 distinct values. +fn floor1(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + let partitions = b.read(5)?; + let mut classes = Vec::with_capacity(partitions as usize); + for _ in 0..partitions { + classes.push(b.read(4)? as usize); + } + let count = classes.iter().max().map_or(0, |&m| m + 1); + let mut dims = [0u32; 16]; + for d in dims.iter_mut().take(count) { + *d = b.read(3)? + 1; + let subclasses = b.read(2)?; + if subclasses != 0 && b.read(8)? >= codebooks { + return None; + } + // a subclass book is its number plus one, and 0 means none + for _ in 0..1u32 << subclasses { + if b.read(8)? > codebooks { + return None; + } + } + } + b.skip(2)?; + let range = b.read(4)?; + let points: u64 = classes.iter().map(|&c| u64::from(dims[c])).sum(); + if points + 2 > 65 { + return None; + } + let mut xs = vec![0u32, 1u32 << range]; + for _ in 0..points { + xs.push(b.read(range)?); + } + xs.sort_unstable(); + xs.windows(2).all(|w| w[0] != w[1]).then_some(()) +} diff --git a/crates/media/src/ogg/vorbis_tests.rs b/crates/media/src/ogg/vorbis_tests.rs new file mode 100644 index 0000000000..e84322099e --- /dev/null +++ b/crates/media/src/ogg/vorbis_tests.rs @@ -0,0 +1,359 @@ +//! Vorbis modes and timing on synthetic headers and packets. + +use super::vorbis::*; +use super::*; + +/// Bits written least significant first, as Vorbis reads them. +#[derive(Default)] +struct BitWriter { + bytes: Vec, + bits: u64, +} + +impl BitWriter { + fn put(&mut self, value: u32, n: u32) -> &mut Self { + for k in 0..n { + if self.bits.is_multiple_of(8) { + self.bytes.push(0); + } + let bit = ((value >> k) & 1) as u8; + let last = self.bytes.len() - 1; + self.bytes[last] |= bit << (self.bits % 8); + self.bits += 1; + } + self + } +} + +/// An identification header: one channel at 44.1 kHz, blocks of 256 and 2048 samples. +fn identification() -> Vec { + let mut h = b"\x01vorbis".to_vec(); + h.extend_from_slice(&0u32.to_le_bytes()); + h.push(1); + h.extend_from_slice(&44_100u32.to_le_bytes()); + h.extend_from_slice(&[0; 12]); + h.push(0xB8); + h.push(1); + h +} + +/// The smallest setup header: one codebook, floor 1, residue 0 and mapping, then `modes` with the +/// given block flags. +fn setup(modes: &[bool]) -> Vec { + setup_with(modes, Codebook { dims: 1, lookup: 0 }, 0, 0) +} + +/// The codebook of [`setup_with`]: 2 entries of length 1 with `dims` dimensions and lookup type +/// `lookup` (0, or 1 with 1-bit values). +#[derive(Clone, Copy)] +struct Codebook { + dims: u32, + lookup: u32, +} + +/// [`setup`] with the given codebook and the floor and residue its one mapping's submap names. +fn setup_with(modes: &[bool], book: Codebook, floor: u32, residue: u32) -> Vec { + let plain_floor = |w: &mut BitWriter| { + // one floor 1 with no partitions: multiplier and range bits + w.put(0, 6).put(1, 16).put(0, 5).put(0, 2).put(0, 4); + }; + let plain_residue = |w: &mut BitWriter| { + // one residue 0 with one classification, classbook 0 and no books + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + setup_parts(modes, book, floor, residue, &plain_floor, &plain_residue) +} + +/// [`setup_with`] with the floor and residue configurations written by the given closures, each +/// starting with its count of 0 (one entry). +fn setup_parts( + modes: &[bool], + book: Codebook, + floor: u32, + residue: u32, + write_floor: &dyn Fn(&mut BitWriter), + write_residue: &dyn Fn(&mut BitWriter), +) -> Vec { + let mut w = BitWriter::default(); + // one codebook: 2 entries of length 1 + w.put(0, 8).put(0x56_4342, 24).put(book.dims, 16).put(2, 24).put(0, 1).put(0, 1).put(0, 5).put(0, 5).put(book.lookup, 4); + if book.lookup == 1 { + // minimum value, delta, 1-bit values, no sequence flag, then the values themselves + w.put(0, 32).put(0, 32).put(0, 4).put(0, 1); + let values = if book.dims == 0 { 0 } else { lookup1_values(2, book.dims) }; + for _ in 0..values { + w.put(0, 1); + } + } + // one time-domain transform + w.put(0, 6).put(0, 16); + write_floor(&mut w); + write_residue(&mut w); + // one mapping: one submap, no coupling, reserved bits, the submap's time, floor and residue + w.put(0, 6).put(0, 16).put(0, 1).put(0, 1).put(0, 2).put(0, 8).put(floor, 8).put(residue, 8); + w.put(modes.len() as u32 - 1, 6); + for &long in modes { + w.put(u32::from(long), 1).put(0, 16).put(0, 16).put(0, 8); + } + w.put(1, 1); + let mut h = b"\x05vorbis".to_vec(); + h.extend_from_slice(&w.bytes); + h +} + +const SHORT: u8 = 0b00; +const LONG: u8 = 0b10; + +/// A Vorbis stream whose packets are laid out in `pages`: each page is its packets' first bytes and +/// the page's granule position; the last page is the end of the stream. +fn stream(pages: &[(&[u8], i64)]) -> Stream { + let mut packets = Vec::new(); + for (k, &(firsts, granule)) in pages.iter().enumerate() { + for (i, &first) in firsts.iter().enumerate() { + let last = i + 1 == firsts.len(); + packets.push(Packet { + parts: Vec::new(), + size: 10, + granule: last.then_some(granule), + page: k as u32, + eos: k + 1 == pages.len(), + prefix: [first, 0], + }); + } + } + Stream { + serial: 1, + codec: Codec::Vorbis, + // three modes, so mode 3 is one the header does not have + headers: vec![identification(), b"\x03vorbis".to_vec(), setup(&[false, true, true])], + packets, + pages: pages.len() as u32, + last_granule: pages.last().map(|p| p.1), + saw_eos: true, + header_count: 3, + header_bytes: 0, + next_seq: None, + started: true, + } +} + +#[test] +fn modes_come_from_the_end_of_the_setup_header() { + let modes = VorbisModes::parse(&identification(), &setup(&[false, true, true])).unwrap(); + assert_eq!(modes.blocksizes, [256, 2048]); + assert_eq!(modes.long, [false, true, true]); + // two bits of mode number after the packet-type bit + assert_eq!(modes.blocksize(0b000), Some(256)); + assert_eq!(modes.blocksize(0b100), Some(2048)); + assert_eq!(modes.blocksize(0b110), None, "a mode the header does not have"); + assert_eq!(modes.blocksize(0b001), None, "not an audio packet"); +} + +#[test] +fn damaged_headers_give_no_modes() { + let id = identification(); + let full = setup(&[false, true]); + for cut in 7..full.len() { + assert_eq!(VorbisModes::parse(&id, &full[..cut]), None, "setup cut to {cut} bytes"); + } + let mut no_framing = full.clone(); + *no_framing.last_mut().unwrap() = 0; + assert_eq!(VorbisModes::parse(&id, &no_framing), None); + let mut long_first = id.clone(); + long_first[28] = 0x8B; + assert_eq!(VorbisModes::parse(&long_first, &full), None, "short block larger than the long one"); + let mut version_1 = id.clone(); + version_1[7] = 1; + assert_eq!(VorbisModes::parse(&version_1, &full), None, "not Vorbis I"); +} + +#[test] +fn a_zero_sample_rate_gives_no_modes() { + let full = setup(&[false, true]); + assert!(VorbisModes::parse(&identification(), &full).is_some()); + let mut no_rate = identification(); + no_rate[12..16].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(VorbisModes::parse(&no_rate, &full), None); +} + +#[test] +fn a_mapping_names_only_configured_floors_and_residues() { + let id = identification(); + let plain = Codebook { dims: 1, lookup: 0 }; + assert!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 0, 0)).is_some()); + assert_eq!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 1, 0)), None, "floor 1 of one floor"); + assert_eq!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 0, 1)), None, "residue 1 of one residue"); +} + +/// The setup of [`setup_with`] with one floor 1 (partition list, then classes) and one residue. +fn books_setup(floor: &dyn Fn(&mut BitWriter), residue: &dyn Fn(&mut BitWriter)) -> Option { + let plain = Codebook { dims: 1, lookup: 0 }; + VorbisModes::parse(&identification(), &setup_parts(&[false, true], plain, 0, 0, floor, residue)) +} + +#[test] +fn residue_books_name_configured_codebooks() { + let residue = |classbook: u32, book: u32| { + move |w: &mut BitWriter| { + // one classification with the first cascade bit set, which names one book + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(classbook, 8).put(1, 3).put(0, 1); + w.put(book, 8); + } + }; + let floor = |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(0, 5).put(0, 2).put(0, 4); + }; + assert!(books_setup(&floor, &residue(0, 0)).is_some()); + assert_eq!(books_setup(&floor, &residue(1, 0)), None, "classbook 1 of one codebook"); + assert_eq!(books_setup(&floor, &residue(0, 1)), None, "book 1 of one codebook"); +} + +#[test] +fn floor_books_name_configured_codebooks() { + let residue = |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + // floor 0: order, rate, bark map size, amplitude bits and offset, one book + let floor0 = |book: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 8).put(0, 16).put(0, 16).put(0, 6).put(0, 8).put(0, 4).put(book, 8); + } + }; + assert!(books_setup(&floor0(0), &residue).is_some()); + assert_eq!(books_setup(&floor0(1), &residue), None); + // floor 1: one partition of class 0 with one dimension and 1 subclass bit, a master book and + // two subclass books (number plus one), then 2 range bits and one X value + let floor1 = |master: u32, sub: u32, x: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(1, 5).put(0, 4).put(0, 3).put(1, 2).put(master, 8).put(sub, 8).put(0, 8); + w.put(0, 2).put(2, 4).put(x, 2); + } + }; + assert!(books_setup(&floor1(0, 1, 1), &residue).is_some()); + assert!(books_setup(&floor1(0, 0, 1), &residue).is_some(), "no subclass book"); + assert_eq!(books_setup(&floor1(1, 1, 1), &residue), None, "master book 1"); + assert_eq!(books_setup(&floor1(0, 2, 1), &residue), None, "subclass book 1"); + assert_eq!(books_setup(&floor1(0, 1, 0), &residue), None, "X value equal to the implicit 0"); + assert_eq!(books_setup(&floor1(0, 1, 1), &residue).map(|m| m.long), Some(vec![false, true])); +} + +#[test] +fn floor_one_x_values_are_distinct() { + let residue = |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + // one partition of class 0 with two dimensions and no subclasses, 3 range bits, two X values + let floor1 = |a: u32, b: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(1, 5).put(0, 4).put(1, 3).put(0, 2).put(0, 8); + w.put(0, 2).put(3, 4).put(a, 3).put(b, 3); + } + }; + assert!(books_setup(&floor1(3, 5), &residue).is_some()); + assert_eq!(books_setup(&floor1(3, 3), &residue), None, "repeated X value"); + assert_eq!(books_setup(&floor1(0, 5), &residue), None, "X value equal to the implicit 0"); +} + +#[test] +fn a_codebook_of_no_dimensions_has_no_lookup_values() { + let id = identification(); + for lookup in [0, 1] { + let modes = VorbisModes::parse(&id, &setup_with(&[false, true], Codebook { dims: 0, lookup }, 0, 0)); + assert_eq!(modes.map(|m| m.long), Some(vec![false, true]), "lookup type {lookup}"); + let one = VorbisModes::parse(&id, &setup_with(&[false, true], Codebook { dims: 1, lookup }, 0, 0)); + assert_eq!(one.map(|m| m.long), Some(vec![false, true]), "lookup type {lookup}, one dimension"); + } +} + +#[test] +fn the_first_packet_primes_and_the_rest_overlap_by_quarter_blocks() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, LONG, SHORT], 3200)])).unwrap(); + assert_eq!(t.durations, [0, 64 + 512, 1024, 1024, 512 + 64]); + assert_eq!(t.starts, [0, 0, 576, 1600, 2624]); + assert_eq!((t.skip, t.first, t.total), (0, 0, 3200)); +} + +#[test] +fn a_negative_start_discards_leading_samples() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(t.starts[1], -100); + assert_eq!((t.skip, t.first), (100, 0)); + assert_eq!(t.total, 2076); +} + +#[test] +fn packets_that_are_not_audio_do_not_shrink_the_leading_discard() { + let t = VorbisTiming::of(&stream(&[(&[0xFF, SHORT, LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(&t.durations[..3], [0, 0, 576]); + assert_eq!(t.starts[2], -100); + assert_eq!((t.skip, t.first, t.total), (100, 0, 2076)); +} + +#[test] +fn a_packet_too_short_for_its_window_flags_returns_nothing() { + // 64 modes: six bits of mode number, so a long block's two window flags reach the second byte + let mut modes = vec![false; 64]; + modes[1] = true; + let mut s = stream(&[(&[SHORT, LONG, SHORT], 1000)]); + s.headers[2] = setup(&modes); + s.packets[1].size = 1; + let t = VorbisTiming::of(&s).unwrap(); + assert_eq!(t.durations, [0, 0, 128], "the cut long packet is skipped and the next one follows the first"); + s.packets[1].size = 2; + let t = VorbisTiming::of(&s).unwrap(); + assert_eq!(t.durations, [0, 64 + 512, 512 + 64]); +} + +#[test] +fn a_positive_start_is_a_time_offset() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 44_676), (&[LONG, SHORT], 46_276)])).unwrap(); + assert_eq!((t.skip, t.first), (0, 44_100)); + assert_eq!(t.starts[1], 44_100); + assert_eq!(t.total, 46_276 - 44_100); +} + +#[test] +fn a_page_with_only_the_priming_packet_does_not_place_the_stream() { + let negative = VorbisTiming::of(&stream(&[(&[SHORT], 0), (&[LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(negative.starts[1], -100); + assert_eq!((negative.skip, negative.first, negative.total), (100, 0, 2076)); + let offset = VorbisTiming::of(&stream(&[(&[SHORT], 0), (&[LONG], 44_676), (&[LONG, SHORT], 46_276)])).unwrap(); + assert_eq!(offset.starts[1], 44_100); + assert_eq!((offset.skip, offset.first, offset.total), (0, 44_100, 2176)); +} + +#[test] +fn the_final_page_trims_the_end() { + let full = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, SHORT], 2176)])).unwrap(); + let trimmed = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, SHORT], 2000)])).unwrap(); + assert_eq!(trimmed.starts, full.starts, "trimming moves no packet"); + assert_eq!(trimmed.total, full.total - 176); +} + +#[test] +fn one_page_shorter_than_its_packets_trims_the_end() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG, SHORT], 1000)])).unwrap(); + assert_eq!((t.skip, t.first, t.total), (0, 0, 1000)); + assert_eq!(t.starts[1], 0); +} + +#[test] +fn hostile_granules_and_packets_do_not_overflow() { + for g in [i64::MIN, -2, i64::MAX, MAX_OPUS_GRANULE] { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], g), (&[0xFF, 0b110, LONG], g)])).unwrap(); + assert_eq!(t.starts.len(), 5); + assert_eq!(&t.durations[2..4], [0, 0], "a non-audio packet and an unknown mode return nothing"); + assert!(t.total >= 0); + } + let mut no_setup = stream(&[(&[SHORT], 0)]); + no_setup.headers.truncate(2); + assert_eq!(VorbisTiming::of(&no_setup), None); +} + +#[test] +fn lookup_values_are_the_integer_root_of_the_entries() { + assert_eq!(lookup1_values(81, 4), 3); + assert_eq!(lookup1_values(80, 4), 2); + assert_eq!(lookup1_values(1 << 24, 1), 1 << 24); + assert_eq!(lookup1_values(1 << 24, 65_535), 1); +} diff --git a/crates/media/tests/mpegts_mux/mod.rs b/crates/media/tests/mpegts_mux/mod.rs index 4a3e6f2d11..0287a8ce9c 100644 --- a/crates/media/tests/mpegts_mux/mod.rs +++ b/crates/media/tests/mpegts_mux/mod.rs @@ -195,13 +195,24 @@ pub fn av1_unescape(es: &[u8]) -> Vec { out } -/// The Opus control header and packet the demuxer gives back for an Opus frame. -pub fn opus_unit(packet: &[u8]) -> Vec { - let mut v = vec![0x7F, 0xE0]; - v.extend(std::iter::repeat_n(0xFF, packet.len() / 255)); - v.push((packet.len() % 255) as u8); - v.extend_from_slice(packet); - v +/// The payload of every PES packet on `pid`, as the muxer wrote it (the PES header left out). +pub fn pes_payloads(ts: &[u8], pid: u16) -> Vec> { + let mut out: Vec> = Vec::new(); + for p in ts.chunks(PACKET_SIZE) { + if ((p[1] & 0x1F) as u16) << 8 | p[2] as u16 != pid || p[3] & 0x10 == 0 { + continue; + } + let start = if p[3] & 0x20 != 0 { 5 + p[4] as usize } else { 4 }; + let mut payload = &p[start..]; + if p[1] & 0x40 != 0 { + payload = &payload[9 + payload[8] as usize..]; + out.push(Vec::new()); + } + if let Some(last) = out.last_mut() { + last.extend_from_slice(payload); + } + } + out } /// What the demuxer gives back for a video frame: an access unit delimiter first. diff --git a/crates/media/tests/mpegts_mux_fuzz.rs b/crates/media/tests/mpegts_mux_fuzz.rs index 0067e5a17c..662105ae8e 100644 --- a/crates/media/tests/mpegts_mux_fuzz.rs +++ b/crates/media/tests/mpegts_mux_fuzz.rs @@ -66,8 +66,7 @@ fn frame(s: usize, size: usize, key: bool, n: usize) -> (Vec, Vec) { 1 => { let mut d = vec![0xFC]; fill(&mut d, size.min(1500), seed); - let e = opus_unit(&d); - (d, e) + (d.clone(), d) } 2 => { let mut d = Vec::new(); diff --git a/crates/media/tests/mpegts_mux_readback.rs b/crates/media/tests/mpegts_mux_readback.rs index 7d8471525c..733a6f2d75 100644 --- a/crates/media/tests/mpegts_mux_readback.rs +++ b/crates/media/tests/mpegts_mux_readback.rs @@ -90,7 +90,7 @@ fn every_codec_in_one_program() { for k in 0..150i64 { let mut p = vec![0xFC]; fill(&mut p, 1 + (k as usize * 41) % 700, k as u8); - items.push(Item { stream: 2, expect: opus_unit(&p), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); + items.push(Item { stream: 2, expect: p.clone(), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); } for k in 0..90i64 { let f = ac3(k as u8); @@ -100,7 +100,7 @@ fn every_codec_in_one_program() { let f = mp3(false, k as u8); items.push(Item { stream: 4, expect: f.clone(), data: f, pts: t0 + k * 2160, dts: t0 + k * 2160, key: true }); } - let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Unknown(6), Demuxed::Ac3, Demuxed::MpegAudio]; + let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Opus, Demuxed::Ac3, Demuxed::MpegAudio]; let (ts, pcrs) = round_trip(Config::default(), &streams, &mut items, &want); let file = mpegts::open(&ts).unwrap(); assert_eq!(file.pcr_range, Some((pcrs[0], *pcrs.last().unwrap()))); @@ -108,6 +108,10 @@ fn every_codec_in_one_program() { // the frames' own headers read back with the demuxer's frame parser let aac = file.read_unit(&ts, 1, 0).unwrap(); assert_eq!(mpegts::frame_info(&Demuxed::AacAdts, &aac).map(|i| (i.sample_rate, i.channels)), Some((48_000, 2))); + // a stereo Opus stream (channel_config_code 2): one coupled stream, no start trim + let opus = file.streams[2].codec_params(); + assert_eq!((opus.codec, opus.sample_rate, opus.channels), (craft_media::CodecId::Opus, Some(48_000), Some(2))); + assert_eq!(opus.extradata, [b"OpusHead".as_slice(), &[1, 2, 0, 0, 0x80, 0xBB, 0, 0, 0, 0, 0]].concat()); } #[test] @@ -162,9 +166,9 @@ fn timestamps_run_past_the_33_bit_wrap() { for k in 0..140i64 { let p = vec![0x08, k as u8 | 1, 0x55]; let t = start + k * 1800; - items.push(Item { stream: 1, expect: opus_unit(&p), data: p, pts: t, dts: t, key: true }); + items.push(Item { stream: 1, expect: p.clone(), data: p, pts: t, dts: t, key: true }); } - round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Unknown(6)]); + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Opus]); } #[test] @@ -185,7 +189,7 @@ fn eac3_mpeg1_video_and_mpeg4_part2() { let t = 100_000 + k * 2880; items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); } - round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Unknown(0x10)]); + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Mpeg4Part2]); } #[test] @@ -200,20 +204,61 @@ fn av1_reads_back_as_its_obus() { let t = 90_000 + k * 3000; m.write_frame(0, &Frame { data: &tu, pts: t, dts: None, key }).unwrap(); m.write_frame(1, &Frame { data: &[0xFC, k as u8 | 1], pts: t, dts: None, key: true }).unwrap(); - tus.push((tu, t)); + tus.push((tu, t, key)); } let ts = m.finish().unwrap(); check_packets(&ts, 0x100, 3600 * 300); let file = mpegts::open(&ts).unwrap(); assert!(file.warnings.is_empty(), "{:?}", file.warnings); - assert_eq!(file.streams[0].codec, Demuxed::Unknown(6)); + assert_eq!(file.streams[0].codec, Demuxed::Av1); assert_eq!(file.streams[0].stream_type, 0x06); + assert_eq!(file.streams[1].codec, Demuxed::Opus); + // the descriptor's fields come back as the av1C record they were taken from + let params = file.streams[0].codec_params(); + assert_eq!(params.codec, craft_media::CodecId::Av1); + assert_eq!(Av1Config::from_av1c(¶ms.extradata).unwrap(), config); let units = &file.streams[0].units; assert_eq!(units.len(), tus.len()); - for (n, (u, (tu, t))) in units.iter().zip(&tus).enumerate() { + let written = pes_payloads(&ts, 0x100); + assert_eq!(written.len(), tus.len()); + for (n, (u, (tu, t, key))) in units.iter().zip(&tus).enumerate() { assert_eq!(u.pts, Some(*t)); - let es = file.read_unit(&ts, 0, n).unwrap(); - assert_eq!(av1_unescape(&es), av1_without_delimiters(tu), "unit {n}"); + assert_eq!(u.key, *key, "unit {n}"); + // the writer's start code form, and the demuxer's OBUs + assert_eq!(av1_unescape(&written[n]), av1_without_delimiters(tu), "unit {n}"); + assert_eq!(file.read_unit(&ts, 0, n).unwrap(), av1_without_delimiters(tu), "unit {n}"); + } +} + +#[test] +fn opus_channel_configurations_read_back() { + let opened = |codec: Codec| { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, codec)]).unwrap(); + for k in 0..10i64 { + m.write_frame(0, &Frame { data: &[0xFC, 1, 0x55], pts: 90_000 + k * 1800, dts: None, key: true }).unwrap(); + } + let ts = m.finish().unwrap(); + let s = mpegts::open(&ts).unwrap().streams.remove(0); + assert_eq!(s.codec, Demuxed::Opus); + let o = s.opus.unwrap(); + (o.channels, o.family, o.streams, o.coupled, o.mapping) + }; + // the fixed configurations: family 0 for one or two channels, the RFC 7845 surround orders + // for more + assert_eq!(opened(Codec::Opus { channels: 1 }), (1, 0, 1, 0, vec![0])); + assert_eq!(opened(Codec::Opus { channels: 2 }), (2, 0, 1, 1, vec![0, 1])); + assert_eq!(opened(Codec::Opus { channels: 6 }), (6, 1, 4, 2, vec![0, 4, 1, 2, 3, 5])); + assert_eq!(opened(Codec::Opus { channels: 8 }), (8, 1, 5, 3, vec![0, 6, 1, 2, 3, 4, 5, 7])); + // explicit configurations come back field for field, silent channels included + for m in [ + OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }, + OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [2, 255, 0, 0, 0, 0, 0, 0] }, + OpusMapping { channels: 8, family: 255, streams: 8, coupled: 0, mapping: [7, 6, 5, 4, 3, 2, 1, 0] }, + OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }, + OpusMapping { channels: 1, family: 1, streams: 1, coupled: 0, mapping: [0, 0, 0, 0, 0, 0, 0, 0] }, + ] { + let ch = usize::from(m.channels); + assert_eq!(opened(Codec::OpusMapped(m)), (m.channels, m.family, m.streams, m.coupled, m.mapping[..ch].to_vec()), "{m:?}"); } } @@ -226,23 +271,32 @@ fn opus_with_an_explicit_mapping_and_trims() { for k in 0..20i64 { // three streams of 20 ms: two self-delimited packets, then the last one let au = [0xFC, 1, 0x55, 0xFC, 1, 0x66, 0xFC, 0x77]; - let trim = if k == 0 { craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 } } else { Default::default() }; + let trim = match k { + 0 => craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 }, + 19 => craft_media::mpegts::mux::OpusTrim { start: 0, end: 100 }, + _ => Default::default(), + }; let t = 90_000 + k * 1800; m.write_frame_with_trim(0, &Frame { data: &au, pts: t, dts: None, key: true }, trim).unwrap(); - let mut unit = if k == 0 { vec![0x7F, 0xF0, 8] } else { vec![0x7F, 0xE0, 8] }; - if k == 0 { - unit.extend_from_slice(&312u16.to_be_bytes()); - } - unit.extend_from_slice(&au); - want.push(unit); + want.push(au.to_vec()); } let ts = m.finish().unwrap(); let file = mpegts::open(&ts).unwrap(); assert!(file.warnings.is_empty(), "{:?}", file.warnings); - assert_eq!(file.streams[0].units.len(), want.len()); + let s = &file.streams[0]; + assert_eq!(s.codec, Demuxed::Opus); + assert_eq!(s.units.len(), want.len()); for (n, w) in want.iter().enumerate() { assert_eq!(&file.read_unit(&ts, 0, n).unwrap(), w); } + let opus = s.opus.as_ref().unwrap(); + assert_eq!((opus.channels, opus.family, opus.streams, opus.coupled, &opus.mapping[..]), (3, 255, 3, 0, &[0, 1, 2][..])); + assert_eq!(opus.trims, [mpegts::OpusTrim { unit: 0, start: 312, end: 0 }, mpegts::OpusTrim { unit: 19, start: 0, end: 100 }]); + // the OpusHead header (RFC 7845 §5.1) carries the start trim as its pre-skip + let head = s.codec_params().extradata; + assert_eq!(&head[..8], b"OpusHead"); + assert_eq!(u16::from_le_bytes([head[10], head[11]]), 312); + assert_eq!(&head[18..], &[255, 3, 0, 0, 1, 2]); } #[test] diff --git a/crates/media/tests/oracle_mpegts.rs b/crates/media/tests/oracle_mpegts.rs index d395c09ff1..28e5904fdb 100644 --- a/crates/media/tests/oracle_mpegts.rs +++ b/crates/media/tests/oracle_mpegts.rs @@ -22,6 +22,7 @@ const ALL: &[&str] = &[ "m2ts_h264_ac3.mts", "ts_hevc_latm.ts", "ts_h264_eac3.ts", + "ts_mpeg4_opus.ts", "ps_mpeg2_mp2.vob", "ps_mpeg2_lpcm.vob", "ps_mpeg2_ac3.vob", @@ -72,6 +73,10 @@ fn spec(name: &str) -> Vec<&'static str> { &["-c:a", "aac", "-b:a", "96k", "-f", "mpegts", "-mpegts_flags", "latm"], ]), "ts_h264_eac3.ts" => cat(&[PIC, NOISE, &["-t", "1"], x264, &["-c:a", "eac3", "-b:a", "192k", "-f", "mpegts"]]), + // stream type 0x10, and Opus with its registration and audio descriptors and control headers + "ts_mpeg4_opus.ts" => { + cat(&[PIC, NOISE, &["-t", "1.2", "-c:v", "mpeg4", "-bf", "2", "-g", "12", "-c:a", "libopus", "-b:a", "96k", "-f", "mpegts"]]) + } // DVD-style program streams "ps_mpeg2_mp2.vob" => cat(&[ &["-f", "lavfi", "-i", "testsrc2=size=720x480:rate=30000/1001"], @@ -112,7 +117,9 @@ fn expected_codec(name: &str, format: Format) -> Codec { "mpeg2video" => Codec::Mpeg2Video, "h264" => Codec::H264, "hevc" => Codec::Hevc, + "mpeg4" => Codec::Mpeg4Part2, "mp2" | "mp3" => Codec::MpegAudio, + "opus" => Codec::Opus, "aac" => Codec::AacAdts, "aac_latm" => Codec::AacLatm, "ac3" => Codec::Ac3, @@ -184,7 +191,7 @@ fn check(name: &str) -> Option { #[test] fn transport_streams_match_ffprobe() { - for name in ["ts_mpeg2_mp2.ts", "ts_h264_aac.ts", "ts_hevc_latm.ts", "ts_h264_eac3.ts"] { + for name in ["ts_mpeg2_mp2.ts", "ts_h264_aac.ts", "ts_hevc_latm.ts", "ts_h264_eac3.ts", "ts_mpeg4_opus.ts"] { let Some(f) = check(name) else { return }; assert_eq!(f.format, Format::Ts { packet_size: 188, sync_offset: 0 }, "{name}"); assert_eq!(f.program, Some(1), "{name}"); @@ -195,9 +202,17 @@ fn transport_streams_match_ffprobe() { "ts_mpeg2_mp2.ts" => [CodecId::Mpeg2Video, CodecId::Mp2], "ts_h264_aac.ts" => [CodecId::H264, CodecId::Aac], "ts_hevc_latm.ts" => [CodecId::Hevc, CodecId::Aac], + "ts_mpeg4_opus.ts" => [CodecId::Mpeg4Video, CodecId::Opus], _ => [CodecId::H264, CodecId::Eac3], }; assert_eq!(ids, want, "{name}"); + if name == "ts_mpeg4_opus.ts" { + // stereo from the Opus audio descriptor, and libopus's 312-sample start trim as the + // pre-skip + let p = f.streams[1].codec_params(); + assert_eq!((p.sample_rate, p.channels), (Some(48_000), Some(2))); + assert_eq!(&p.extradata[..12], &[b"OpusHead".as_slice(), &[1, 2], &312u16.to_le_bytes()].concat()[..]); + } } } diff --git a/crates/media/tests/oracle_ogg.rs b/crates/media/tests/oracle_ogg.rs index 4e14a651e0..d81dba1f35 100644 --- a/crates/media/tests/oracle_ogg.rs +++ b/crates/media/tests/oracle_ogg.rs @@ -1,9 +1,9 @@ -//! Oracle tests: compare the Ogg demuxer's streams, packet bytes and Opus timing with ffprobe on -//! ffmpeg-generated fixtures (skipped when ffmpeg/ffprobe are not installed). +//! Oracle tests: compare the Ogg demuxer's streams, packet bytes and Opus and Vorbis timing with +//! ffprobe on ffmpeg-generated fixtures (skipped when ffmpeg/ffprobe are not installed). use super::common; -use craft_media::ogg::{self, Codec, OggFile, OpusTiming}; +use craft_media::ogg::{self, Codec, OggFile, OpusTiming, VorbisTiming}; use serde_json::Value; use std::path::{Path, PathBuf}; use std::process::Command; @@ -184,6 +184,27 @@ fn assert_opus_timing_matches(name: &str, file: &OggFile, s: usize, json: &Value eprintln!("{context}: timing of {} packets matches, {} samples", theirs.len(), timing.total); } +/// `VorbisTiming` against ffmpeg: from the second packet on, the starts are its pts and the +/// durations its packet durations (the last one trimmed by the discard padding), and the total is +/// the sum of those durations. ffmpeg gives the first packet, which returns no samples, a pts and +/// duration of its own, so it is compared only for returning nothing. +fn assert_vorbis_timing_matches(name: &str, file: &OggFile, s: usize, json: &Value, ff: usize) { + let timing = VorbisTiming::of(&file.streams[s]).unwrap_or_else(|| panic!("{name}: Vorbis headers")); + let theirs = ff_packets(json, ff); + let context = format!("{name}: Vorbis stream {ff}"); + assert_eq!(timing.starts.len(), theirs.len(), "{context}: packet count"); + assert_eq!(timing.durations[0], 0, "{context}: the first packet returns nothing"); + let last = theirs.len() - 1; + for (k, p) in theirs.iter().enumerate().skip(1) { + assert_eq!(p.pts, Some(timing.starts[k]), "{context}: start of packet {k}"); + let duration = p.duration.unwrap() + if k == last { p.discard } else { 0 }; + assert_eq!(duration, i64::from(timing.durations[k]), "{context}: duration of packet {k}"); + } + let playable: i64 = theirs.iter().skip(1).map(|p| p.duration.unwrap()).sum(); + assert_eq!((timing.skip, timing.first, timing.total), (0, 0, playable), "{context}: skip, first, total"); + eprintln!("{context}: timing of {} packets matches, {} samples", theirs.len(), timing.total); +} + /// Multiplexed streams: each is read on its own, in ffmpeg's order. #[test] fn grouped_streams() { @@ -197,6 +218,7 @@ fn grouped_streams() { for s in 0..2 { assert_opus_timing_matches("grouped.ogg", &file, s, &json, s); } + assert_vorbis_timing_matches("grouped.ogg", &file, 2, &json, 2); } /// A chained file: two links, each its own stream with its own headers. ffmpeg joins the links of diff --git a/crates/menu/README.md b/crates/menu/README.md index a9de1bfded..69947e7bae 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -135,6 +135,14 @@ The module documentation lists every `Outcome`, `Options` and the words (`Shortc app translates. The dialog never opens a file dialog or touches the file system. Enable `screen-testing` for the stories and the `it` trials. +Automation can select a command and set `replace` to `{"old":"Text: Cmd+B","new":"Cmd+K"}` +through `ShortcutsDialog::set_json_field`. The old text must identify exactly one current binding; +the new trigger keeps its scope and regular or Hold column. An equivalent trigger changes nothing, +and a changed replacement has one Undo step. Ask mode leaves the original binding until the user +answers the conflict bar; Steal and Keep follow the host's configured policy. A stale confirmation +cannot replace bindings that changed after its prompt opened. Unavailable edits and replacements +that cannot be stored return a refusal. + ## Windows, Linux and web: the in-window bar `MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by diff --git a/crates/menu/src/shortcuts/mod.rs b/crates/menu/src/shortcuts/mod.rs index 7a2bb5b536..2b2165d4f9 100644 --- a/crates/menu/src/shortcuts/mod.rs +++ b/crates/menu/src/shortcuts/mod.rs @@ -444,10 +444,14 @@ impl<'a> ShortcutsDialog<'a> { self } - /// Sets the value `field` names in `state`, as the user editing that control would - /// (`search`, `area`, `command`, `pressed`; `assign` true presses Assign; `remove` takes the text - /// of one of the command's keys, as [`DialogSnapshot::keys`] reports it), for automation. It builds the words `Env` that `DialogState::set_field` needs. `Err` says why - /// the field was refused. + /// Sets a dialog field for automation, as the user editing `search`, `area`, `command` or `pressed` would. + /// `assign` true presses Assign. + /// `remove` takes one of the selected command's keys as reported by [`DialogSnapshot::keys`]. `replace` takes + /// an object with `old` in the same form and `new` as [`Trigger`] text. It preserves the old scope and keeps + /// hold shortcuts in the Hold column. In [`ConflictMode::Ask`], a conflict leaves the old binding in place + /// until the user confirms. Hosts can use [`ConflictMode::Steal`] or [`ConflictMode::Keep`] for immediate + /// handling. Replacing a shortcut with an equivalent trigger leaves it alone. A replacement that changes + /// the shortcut can be undone in one step. `Err` says why the field was refused. pub fn set_json_field(self, ui: &Ui, state: &mut DialogState, field: &str, value: &serde_json::Value) -> Result<(), String> { use craft_ui::dialog::FieldRefusal; let rejects = || FieldRefusal::Rejects(value).message(field); @@ -490,6 +494,31 @@ impl<'a> ShortcutsDialog<'a> { state.remove(env, &command, &wanted); state.edit_result()?; } + "replace" => { + if !env.options.editable || !state.is_showing() || state.modal() || state.is_recording() || env.has_app_tab(state.tab) { + return Err(inactive()); + } + let command = state.selected.clone().ok_or_else(inactive)?; + let text = |key: &str| value.get(key).and_then(serde_json::Value::as_str).ok_or_else(rejects); + let old_text = text("old")?; + let bindings = env.keymap.bindings(&command); + let mut matches = bindings.iter().filter(|binding| binding.to_string() == old_text); + let old = matches.next().ok_or_else(rejects)?; + let trigger = Trigger::parse(text("new")?).map_err(|_| rejects())?; + if matches.next().is_some() || trigger.is_hold() != old.trigger.is_hold() { + return Err(rejects()); + } + let platform = env.keymap.platform(); + let effective = trigger.effective(platform); + if effective == old.trigger.effective(platform) { + return Ok(()); + } + if bindings.iter().any(|binding| binding.scope == old.scope && binding.trigger.effective(platform) == effective) { + return Err(rejects()); + } + let new = Binding { trigger, scope: old.scope.clone() }; + state.replace_for_automation(env, &command, old, new)?; + } _ => return Err(FieldRefusal::Unknown.message(field)), } Ok(()) diff --git a/crates/menu/src/shortcuts/pages.rs b/crates/menu/src/shortcuts/pages.rs index dee3c9589d..134cd86763 100644 --- a/crates/menu/src/shortcuts/pages.rs +++ b/crates/menu/src/shortcuts/pages.rs @@ -120,7 +120,7 @@ pub struct DialogSnapshot { pub selected: Option, /// Commands whose bindings differ from the defaults, with their binding texts. pub overrides: Vec<(CommandRef, Vec)>, - /// The conflict bar's chord and the commands holding it, while it shows. + /// The pending conflict's chord and the commands holding it. Another prompt or app tab can hide the conflict bar. pub conflict: Option<(String, Vec)>, /// Whether a chord is being recorded, and the command it is for. pub recording: Option, diff --git a/crates/menu/src/shortcuts/state.rs b/crates/menu/src/shortcuts/state.rs index eb9bc606c8..9f67d256b8 100644 --- a/crates/menu/src/shortcuts/state.rs +++ b/crates/menu/src/shortcuts/state.rs @@ -7,13 +7,15 @@ use craft_keymap::editor::{self, DOUBLE_PRESS, EditSession, Recorded, Recorder}; use craft_keymap::import::{self, ForeignEntry, ForeignSet, ImportOptions, ImportPlan, ImportReport, Start}; use craft_keymap::profiles::{Builtins, ProfileError, Profiles, set_name}; use craft_keymap::{ - AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Policy, Scope, Trigger, + AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Platform, Policy, + Scope, Trigger, }; +use craft_ui::primitives::ChordText; use super::keyboard::KeyboardState; use super::pages::TabSet; use super::rows::{self, AreaEntry, AreaId, Built, Filter, RowCache, View}; -use super::words::Say; +use super::words::{Say, around_chord}; use super::{ConflictMode, HoldSetting, JSON_FORMAT, Layout, Options, Outcome, summary}; /// What the dialog edits this frame. @@ -28,6 +30,10 @@ pub(crate) struct Env<'e> { } impl Env<'_> { + pub(crate) fn has_app_tab(&self, id: Option<&str>) -> bool { + id.is_some_and(|id| self.tabs.as_ref().is_some_and(|tabs| (0..tabs.len()).any(|i| tabs.describe(i).is_some_and(|(tab, _)| tab == id)))) + } + fn chord_text(&self, t: &Trigger) -> String { self.text.trigger(t, self.keymap.platform()) } @@ -129,14 +135,43 @@ pub(crate) struct FieldChord { /// The conflict bar, for one pending chord. #[derive(Clone, Debug, PartialEq)] pub(crate) struct ConflictBar { + pub revision: u64, pub command: CommandRef, pub old: Option, pub binding: Binding, pub holders: Vec, + pub can_steal: bool, + pub can_keep: bool, + before: Option, /// "{chord} is used by {label}". pub text: String, } +impl ConflictBar { + pub(crate) fn notice_text(&self, env: &Env) -> String { + if self.before.is_some() { self.text.clone() } else { around_chord(env.text.rtl(), &self.text, &env.chord_text(&self.binding.trigger)) } + } +} + +/// The existing bindings and home scopes that an automation conflict was opened against. +#[derive(Clone, Debug, PartialEq)] +struct ConflictBasis { + bindings: Vec>, + scopes: Vec>, + platform: Platform, +} + +impl ConflictBasis { + fn of(keymap: &Keymap, command: &CommandRef, holders: &[Holder]) -> Self { + let scopes = std::iter::once(command) + .chain(holders.iter().map(|holder| &holder.command)) + .map(|command| keymap.bindable(command).map(|entry| entry.scope.clone())) + .collect(); + let bindings = std::iter::once(command).chain(holders.iter().map(|holder| &holder.command)).map(|command| keymap.bindings(command)).collect(); + Self { bindings, scopes, platform: keymap.platform() } + } +} + /// A line under the table after an action. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Message { @@ -269,6 +304,7 @@ pub struct DialogState { pub(crate) recording: Option, pub(crate) field: Option, pub(crate) conflict: Option, + conflict_revision: u64, pub(crate) prompt: Option, pub(crate) message: Option, pub(crate) review: Option, @@ -320,6 +356,7 @@ impl DialogState { recording: None, field: None, conflict: None, + conflict_revision: 0, prompt: None, message: None, review: None, @@ -679,6 +716,49 @@ impl DialogState { self.commit_with(env, command, old, binding, mode); } + /// Checks that a replacement can be saved before offering conflict confirmation to an automation caller. + pub(crate) fn replace_for_automation(&mut self, env: &mut Env, command: &CommandRef, old: &Binding, binding: Binding) -> Result<(), String> { + let mut actions = None; + if env.options.conflicts == ConflictMode::Ask && !editor::holders(env.keymap, command, &binding).is_empty() { + let preview = |policy| editor::check_replace(env.keymap, command, old, &binding, policy); + let steal = preview(Policy::Steal); + let keep = preview(Policy::Keep).is_ok(); + if let Err(error) = &steal + && (!keep || !env.options.allow_keep) + { + let text = assign_error(env, error); + self.conflict = None; + self.refuse(text.clone()); + return Err(text); + } + actions = Some((steal.is_ok(), keep)); + } + self.commit(env, command, Some(old.clone()), binding); + if let (Some(conflict), Some((steal, keep))) = (&mut self.conflict, actions) { + conflict.can_steal = steal; + conflict.can_keep = keep; + conflict.before = Some(ConflictBasis::of(env.keymap, command, &conflict.holders)); + let chord = |trigger| { + let text = env.chord_text(trigger); + if env.text.rtl() { ChordText::new(text).isolated() } else { text } + }; + let label = env.label(command); + let target = match env.keymap.bindable(command) { + Some(entry) => fill!(env, label_scope, ("label", &label), ("scope", &env.text.scope_name(old.scope_or(&entry.scope)))), + None => label, + }; + conflict.text = fill!( + env, + replace_old_for_command_with_chord_used_by_label, + ("old", &chord(&old.trigger)), + ("command", &target), + ("chord", &chord(&conflict.binding.trigger)), + ("label", &env.holder_labels(&conflict.holders)) + ); + } + self.edit_result() + } + fn commit_with(&mut self, env: &mut Env, command: &CommandRef, old: Option, binding: Binding, mode: ConflictMode) { self.conflict = None; self.message = None; @@ -701,7 +781,18 @@ impl DialogState { match mode { ConflictMode::Ask => { let text = fill!(env, chord_is_used_by_label, ("chord", &chord), ("label", &env.holder_labels(&holders))); - self.conflict = Some(ConflictBar { command: command.clone(), old, binding, holders, text }); + self.conflict_revision = self.conflict_revision.wrapping_add(1); + self.conflict = Some(ConflictBar { + revision: self.conflict_revision, + command: command.clone(), + old, + binding, + holders, + can_steal: true, + can_keep: true, + before: None, + text, + }); } ConflictMode::Steal => { self.apply_and_say(env, command, old, binding, Policy::Steal); @@ -771,14 +862,14 @@ impl DialogState { /// Take It. pub(crate) fn take_it(&mut self, env: &mut Env) { - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal); } } /// Accept and Go to Conflict. pub(crate) fn take_it_and_go(&mut self, env: &mut Env) { - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { let first = c.holders.first().map(|h| h.command.clone()); if self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal) && let Some(holder) = first @@ -793,11 +884,37 @@ impl DialogState { if !env.options.allow_keep { return; } - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Keep); } } + /// The pending conflict the user can currently answer. + pub(crate) fn visible_conflict(&self, env: &Env) -> Option<&ConflictBar> { + self.conflict.as_ref().filter(|conflict| { + conflict.before.is_none() || (env.options.editable && !self.modal() && !self.is_recording() && !env.has_app_tab(self.tab)) + }) + } + + fn accept_conflict(&mut self, env: &Env) -> Option { + self.visible_conflict(env)?; + let conflict = self.conflict.take()?; + if let Some(before) = &conflict.before { + let holders = editor::holders(env.keymap, &conflict.command, &conflict.binding); + if holders != conflict.holders || ConflictBasis::of(env.keymap, &conflict.command, &holders) != *before { + self.refuse(word!(env, the_shortcuts_changed_try_replacing_again)); + return None; + } + if let (Some(accept), Some(command)) = (&env.options.accept, env.keymap.bindable(&conflict.command)) + && let Err(text) = accept(command, &conflict.binding) + { + self.refuse(text); + return None; + } + } + Some(conflict) + } + /// ✕ on the conflict bar: nothing was applied, so nothing changes. pub(crate) fn dismiss_conflict(&mut self) { self.conflict = None; @@ -982,7 +1099,7 @@ impl DialogState { pub(crate) fn escape(&mut self, env: &mut Env) { if self.recording.is_some() { self.stop_recording(); - } else if self.conflict.is_some() { + } else if self.visible_conflict(env).is_some() { self.conflict = None; } else if self.prompt.is_some() { self.prompt = None; diff --git a/crates/menu/src/shortcuts/view/bars.rs b/crates/menu/src/shortcuts/view/bars.rs index 22326b7f55..10c0ca6e75 100644 --- a/crates/menu/src/shortcuts/view/bars.rs +++ b/crates/menu/src/shortcuts/view/bars.rs @@ -49,30 +49,40 @@ fn prompt(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) { } fn conflict_bar(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) { - let Some(conflict) = state.conflict.clone() else { return }; + enum Action { + Take, + TakeAndGo, + Keep, + Dismiss, + } + + let Some(conflict) = state.visible_conflict(env).cloned() else { return }; let words = env.text.words(); - let chord = env.text.trigger(&conflict.binding.trigger, env.keymap.platform()); - let text = around_chord(env.text.rtl(), &conflict.text, &chord); + let text = conflict.notice_text(env); + let keep = conflict.can_keep && env.options.allow_keep; let mut notice = Notice::new(Tone::Warn, text) - .id_salt("shortcuts.conflict") + .id_salt(("shortcuts.conflict", conflict.revision, keep)) .layout(NoticeLayout::Inline) - .announce(Politeness::Polite) - .action(NoticeAction::new(words.take_it.clone())) - .action(NoticeAction::new(words.accept_and_go_to_conflict.clone())); - let keep = env.options.allow_keep; - if keep { - notice = notice.action(NoticeAction::new(words.keep_both.clone())); + .announce(Politeness::Polite); + let mut actions = Vec::new(); + for (available, label, action) in [ + (conflict.can_steal, &words.take_it, Action::Take), + (conflict.can_steal, &words.accept_and_go_to_conflict, Action::TakeAndGo), + (keep, &words.keep_both, Action::Keep), + (true, &words.undo_changes, Action::Dismiss), + ] { + if available { + notice = notice.action(NoticeAction::new(label.clone())); + actions.push(action); + } } - // Photoshop's wording for turning the new shortcut down is "Undo Changes", the notice's last action. - let undo_at = if keep { 3 } else { 2 }; - notice = notice.action(NoticeAction::new(words.undo_changes.clone())); let out = notice.show(ui); - match out.action { - Some(0) => state.take_it(env), - Some(1) => state.take_it_and_go(env), - Some(2) if keep => state.keep_both(env), - Some(at) if at == undo_at => state.dismiss_conflict(), - _ => {} + match out.action.and_then(|at| actions.get(at)) { + Some(Action::Take) => state.take_it(env), + Some(Action::TakeAndGo) => state.take_it_and_go(env), + Some(Action::Keep) => state.keep_both(env), + Some(Action::Dismiss) => state.dismiss_conflict(), + None => {} } } diff --git a/crates/menu/src/shortcuts/words.rs b/crates/menu/src/shortcuts/words.rs index 77c054e118..886b2a3df5 100644 --- a/crates/menu/src/shortcuts/words.rs +++ b/crates/menu/src/shortcuts/words.rs @@ -123,6 +123,8 @@ craft_ui::words! { keep_both: "keyboardShortcuts.keepBoth" = "Keep Both"; go_to_conflict: "keyboardShortcuts.goToConflict" = "Go to Conflict"; undo_changes: "keyboardShortcuts.undoChanges" = "Undo Changes"; + replace_old_for_command_with_chord_used_by_label: template "keyboardShortcuts.replaceOldForCommandWithChordUsedByLabel" = "Replace {old} for {command} with {chord}, which is used by {label}"; + the_shortcuts_changed_try_replacing_again: "keyboardShortcuts.theShortcutsChangedTryReplacingAgain" = "The shortcuts changed. Try the replacement again."; dismiss: "keyboardShortcuts.dismiss" = "Dismiss"; // Saved shortcuts that could not be used. key_no_command_has_this_name: template "keyboardShortcuts.keyNoCommandHasThisName" = "{key}: no command has this name"; diff --git a/crates/menu/tests/it/shortcuts/fixture.rs b/crates/menu/tests/it/shortcuts/fixture.rs index 1bc858139d..fbafc48bf1 100644 --- a/crates/menu/tests/it/shortcuts/fixture.rs +++ b/crates/menu/tests/it/shortcuts/fixture.rs @@ -258,6 +258,16 @@ impl Rig { self.shared.borrow().sets.as_ref().map(|(p, _)| p.active().to_string()) } + /// Sets an automation field in the next dialog pass. + pub(crate) fn set_json_field(&mut self, field: &'static str, value: serde_json::Value) -> Result<(), String> { + let result = Rc::new(RefCell::new(None)); + let out = result.clone(); + let job: Job = Box::new(move |dialog, ui, state| *out.borrow_mut() = Some(dialog.set_json_field(ui, state, field, &value))); + self.shared.borrow_mut().jobs.push(job); + self.fixture.idle(2); + result.take().expect("the automation job ran") + } + /// Runs `job` with the dialog in the next pass and returns what it returns. pub(crate) fn import_json(&mut self, json: &str) -> Result { let result = Rc::new(RefCell::new(None)); diff --git a/crates/menu/tests/it/shortcuts/mod.rs b/crates/menu/tests/it/shortcuts/mod.rs index fc1ff547c8..b59b5b7f59 100644 --- a/crates/menu/tests/it/shortcuts/mod.rs +++ b/crates/menu/tests/it/shortcuts/mod.rs @@ -9,11 +9,307 @@ pub(crate) mod rows; pub(crate) mod sets; pub(crate) mod tabs; -use craft_keymap::Platform; +use std::cell::Cell; +use std::rc::Rc; + +use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Policy, Scope, Scopes, Trigger}; +use craft_menu::shortcuts::HoldSetting; +use craft_ui::contract::Role; use craft_ui::testing::trial; +use egui::{Key, Modifiers}; +use serde_json::json; use fixture::Rig; +#[trial] +fn automation_replaces_a_shortcut_in_its_scope_as_one_undo_step() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("type.bold")).unwrap(); + let original = rig.bindings("type.bold"); + let old = &original[0]; + + assert!(rig.set_json_field("replace", json!({"old": old, "new": "not a trigger"})).is_err()); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+B", "new": "Cmd+K"})).is_err()); + assert!(rig.set_json_field("replace", json!({"old": old, "new": "Hold K"})).is_err()); + assert_eq!(rig.bindings("type.bold"), original); + + rig.set_json_field("replace", json!({"old": old, "new": "Cmd+K"})).unwrap(); + assert_eq!(rig.bindings("type.bold"), ["Text: Cmd+K"]); + rig.click("Undo"); + assert_eq!(rig.bindings("type.bold"), original); + let shared = rig.shared.borrow(); + assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo); +} + +#[trial] +fn an_automation_replacement_waits_for_conflict_confirmation() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + assert!([Role::STATUS, Role::ALERT].into_iter().any(|role| !rig.names_with(role, "for Save (Application) with").is_empty())); + + rig.click("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+E"]); + assert!(rig.bindings("file.export").is_empty()); + rig.click("Undo"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); +} + +#[trial] +fn confirming_an_automation_replacement_preserves_shortcuts_that_changed_after_the_prompt() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let third = CommandRef::from("object.front"); + rig.shared.borrow_mut().km.assign(&third, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap(); + rig.pass(); + rig.answer("Take It"); + + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + assert_eq!(rig.bindings("object.front"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn confirming_an_automation_replacement_cannot_change_shortcuts_in_a_new_scope() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let mut catalog = rig.shared.borrow().km.catalog().to_vec(); + for command in &mut catalog { + if matches!(command.command.key().as_str(), "file.save" | "file.export") { + command.scope = Scope::new("Text").unwrap(); + } + } + rig.shared.borrow_mut().km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac); + rig.pass(); + rig.answer("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_holder_binding_change_retires_its_pending_replacement_confirmation() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + rig.shared.borrow_mut().km.assign(&CommandRef::from("file.export"), Binding::parse("Cmd+K").unwrap(), Policy::Keep).unwrap(); + rig.pass(); + rig.answer("Take It"); + + assert_eq!(rig.bindings("file.save"), ["Cmd+S"], "a stale confirmation cannot replace the original shortcut"); + assert_eq!(rig.bindings("file.export"), ["Cmd+E", "Cmd+K"], "the changed holder keeps all its current shortcuts"); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_superseding_replacement_has_its_own_confirmation_actions() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let old_action = rig.find("Take It").node; + rig.shared.borrow_mut().options.allow_keep = false; + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+Shift+S"})).unwrap(); + assert_ne!(rig.find("Take It").node, old_action); + assert!(!rig.has("Keep Both")); + let dismiss = rig.find("Undo Changes").node; + rig.shared.borrow_mut().options.allow_keep = true; + rig.pass(); + assert_ne!(rig.find("Keep Both").node, dismiss); +} + +#[trial] +fn escape_dismisses_a_visible_prompt_before_a_hidden_replacement() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+E"})).unwrap(); + assert!(rig.has("Take It")); + rig.click("Reset All…"); + assert!(rig.has("Reset All")); + assert!(!rig.has("Take It")); + + rig.press(Modifiers::NONE, Key::Escape); + assert!(!rig.has("Reset All")); + assert!(rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), ["Cmd+K"]); +} + +#[trial] +fn automation_offers_only_keep_both_when_taking_the_shortcut_cannot_be_saved() { + let scope = "Text".repeat(16); + let trigger = Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let retained = Binding::in_scope(trigger, Scope::new(&scope).unwrap()); + let save = CommandDef::new("file.save", "Save", Scope::app()).with_default(Binding::parse("Cmd+S").unwrap()); + let export = CommandDef::new("file.export", "Export", Scope::app()).with_default(retained.clone()).with_default(Binding::parse("Cmd+E").unwrap()); + let keymap = Keymap::new(vec![save, export], Scopes::new().with_context(&scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert!(!rig.has("Take It")); + assert!(!rig.has("Accept and Go to Conflict")); + rig.click("Keep Both"); + assert_eq!(rig.bindings("file.save"), ["Cmd+E"]); + assert_eq!(rig.bindings("file.export"), [retained.to_string(), "Cmd+E".into()]); +} + +#[trial] +fn automation_replacement_preserves_the_shortcut_when_the_app_rejects_it() { + let mut rig = Rig::tuned(Platform::Mac, |options| options.accept = Some(Box::new(|_, _| Err("That shortcut is unavailable".into())))); + rig.set_json_field("command", json!("file.save")).unwrap(); + let result = rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})); + assert_eq!(result, Err("That shortcut is unavailable".into())); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); +} + +#[trial] +fn confirming_an_automation_replacement_checks_the_current_app_rule() { + let accepted = Rc::new(Cell::new(true)); + let rule = accepted.clone(); + let mut rig = Rig::tuned(Platform::Mac, |options| { + options.accept = Some(Box::new(move |_, _| if rule.get() { Ok(()) } else { Err("That shortcut is unavailable".into()) })); + }); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + accepted.set(false); + rig.answer("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_pending_automation_conflict_cannot_be_applied_from_a_read_only_dialog() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert!(rig.has("Take It")); + + rig.shared.borrow_mut().options.editable = false; + rig.pass(); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + rig.press(Modifiers::NONE, Key::Escape); + assert!(!rig.is_open()); +} + +#[trial] +fn automation_cannot_replace_a_shortcut_while_reset_confirmation_is_open() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap(); + rig.click("Reset All…"); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+B"})).is_err()); + assert_eq!(rig.bindings("file.save"), ["Cmd+K"]); +} + +#[trial] +fn an_automation_hold_replacement_is_dismissed_when_holds_are_disabled() { + let mut keymap = fixture::keymap(Platform::Mac); + keymap.set_holds(true); + for (command, binding) in [("file.save", "Hold K"), ("file.export", "Hold L")] { + keymap.assign(&CommandRef::from(command), Binding::parse(binding).unwrap(), Policy::Keep).unwrap(); + } + let mut rig = Rig::with_holds(keymap, fixture::options(), HoldSetting::new(true, 0.5, 0.2..=2.0)); + rig.set_json_field("command", json!("file.save")).unwrap(); + let original = rig.bindings("file.save"); + assert!(rig.set_json_field("replace", json!({"old": "Hold K", "new": "Cmd+E"})).is_err()); + rig.set_json_field("replace", json!({"old": "Hold K", "new": "Hold L"})).unwrap(); + assert!(rig.has("Take It")); + + rig.click("Hold Shortcuts"); + assert!(!rig.has("Take It")); + rig.click("Hold Shortcuts"); + assert_eq!(rig.bindings("file.save"), original); +} + +#[trial] +fn automation_does_not_replace_a_binding_while_the_recorder_owns_it() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.click("Save: ⌘S"); + assert!(rig.shared.borrow().state.is_recording()); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).is_err()); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + rig.press(Modifiers::COMMAND, Key::L); + assert_eq!(rig.bindings("file.save"), ["Cmd+L"]); + assert!(!rig.shared.borrow().state.is_recording()); +} + +#[trial] +fn automation_rejects_oversize_replacements_but_can_replace_an_oversize_default() { + let scope = "Text".repeat(16); + let original = Binding::in_scope(Trigger::parse("Cmd+S").unwrap(), Scope::new(&scope).unwrap()); + let trigger = "Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash"; + let oversize = Binding::in_scope(Trigger::parse(trigger).unwrap(), Scope::new(&scope).unwrap()); + let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone()); + let repair = CommandDef::new("text.fix", "Fix Text", Scope::app()).with_default(oversize.clone()).with_default(Binding::parse("Cmd+K").unwrap()); + let export = CommandDef::new("text.export", "Export Text", Scope::app()).with_default(Binding::parse("Cmd+L").unwrap()); + let keymap = Keymap::new(vec![command, repair, export], Scopes::new().with_context(&scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("text.save")).unwrap(); + + assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": trigger})).is_err()); + assert_eq!(rig.bindings("text.save"), [original.to_string()]); + rig.set_json_field("command", json!("text.fix")).unwrap(); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+L"})).is_err()); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]); + let adjusted = format!("{scope}: Cmd+J"); + rig.set_json_field("replace", json!({"old": oversize.to_string(), "new": "Cmd+J"})).unwrap(); + assert_eq!(rig.bindings("text.fix"), [adjusted.clone(), "Cmd+K".into()]); + rig.set_json_field("replace", json!({"old": adjusted, "new": trigger})).unwrap(); + assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]); + assert!(rig.shared.borrow().km.overrides().is_empty()); +} + +#[trial] +fn automation_rejects_a_shortcut_that_would_reload_in_a_different_scope() { + let scope = "Cmd+"; + let original = Binding::in_scope(Trigger::parse("K").unwrap(), Scope::new(scope).unwrap()); + let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone()); + let keymap = Keymap::new(vec![command], Scopes::new().with_context(scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("text.save")).unwrap(); + assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": "Cmd+:"})).is_err()); + assert_eq!(rig.bindings("text.save"), [original.to_string()]); +} + +#[trial] +fn an_automation_replacement_with_the_same_effective_shortcut_is_a_noop() { + let mut rig = Rig::tuned(Platform::Windows, |_| {}); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Ctrl+S"})).unwrap(); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + let shared = rig.shared.borrow(); + assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo); +} + +#[trial] +fn an_automation_replacement_does_not_offer_to_take_a_shortcut_the_command_already_has() { + let mut keymap = fixture::keymap(Platform::Mac); + let save = CommandRef::from("file.save"); + keymap.assign(&save, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap(); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("file.save")).unwrap(); + let original = rig.bindings("file.save"); + + assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).is_err()); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), original); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); +} + /// A read-only shortcuts reference does not stretch to the window's height: it opens at a moderate, fixed height and /// scrolls inside it. #[trial] diff --git a/crates/menu/tests/it/shortcuts/tabs.rs b/crates/menu/tests/it/shortcuts/tabs.rs index a1d8022351..2f3dcea838 100644 --- a/crates/menu/tests/it/shortcuts/tabs.rs +++ b/crates/menu/tests/it/shortcuts/tabs.rs @@ -1,5 +1,8 @@ //! The app's pages share the Keyboard Shortcuts dialog's width and navigation. +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + use craft_host::target::Os; use craft_keymap::{Platform, Profiles}; use craft_menu::shortcuts::{Area, DialogState, DialogTab, ShortcutsDialog}; @@ -8,9 +11,42 @@ use craft_ui::contract::Role; use craft_ui::runtime::egui::access::AccessTree; use craft_ui::runtime::env::RootEnv; use craft_ui::testing::{Fixture, Frames, pointer, trial}; +use serde_json::json; use super::fixture; +#[trial] +fn shortcut_replacement_is_unavailable_on_an_app_tab() { + for (tab, app_tab) in [("menus", true), ("unknown", false)] { + let result = Rc::new(RefCell::new(None)); + let observed = result.clone(); + let drawn = Rc::new(Cell::new(false)); + let app_page_drawn = drawn.clone(); + let mut keys = fixture::keymap(Platform::Mac); + let mut state = DialogState::new().with_tab(tab); + let mut fixture = Fixture::new(move |ui| { + let mut tabs = [DialogTab::new("menus", "Menus", |_| { + app_page_drawn.set(true); + false + })]; + if observed.borrow().is_none() { + ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, "command", &json!("file.save")).unwrap(); + let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field( + ui, + &mut state, + "replace", + &json!({"old": "Cmd+S", "new": "Cmd+E"}), + ); + *observed.borrow_mut() = Some(answer); + } + ShortcutsDialog::new(&mut keys).tabs(&mut tabs).show(ui, &mut state); + }); + fixture.settle(); + assert_eq!(drawn.get(), app_tab); + assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab); + } +} + fn dialog_at_125_percent(toolbar_label: &str) -> (Frames, impl FnMut(&mut egui::Ui) + '_) { // Use the Windows test context and a 1600 × 1000 physical-pixel window at 125%. let mut os = Fixture::new(|_| {}); diff --git a/crates/pbr/Cargo.toml b/crates/pbr/Cargo.toml index 654a7c93b8..31790c372f 100644 --- a/crates/pbr/Cargo.toml +++ b/crates/pbr/Cargo.toml @@ -20,7 +20,6 @@ rayon = { workspace = true, optional = true } thiserror = { workspace = true } [dev-dependencies] -craft-pbr = { path = ".", features = ["parallel"] } # 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 6a531206d0..9d3e836538 100644 --- a/crates/pbr/README.md +++ b/crates/pbr/README.md @@ -107,6 +107,8 @@ It has no UI, does no file or network I/O and has no `unsafe` code. (`PbrError::OutOfMemory`). Options out of range give `PbrError::BadOption`, and directions that are not finite or have zero length give `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. @@ -190,9 +192,12 @@ text with naga, alone and with app bindings and `vs` and `fs` entry points, and ## Origin The algorithms come from the `crates/render/src/ibl.rs` files of TextureCraft and MaterialCraft, -which held the same filtering code. With a firefly cap of 64, which both apps applied, the -prefiltered levels match theirs for sources with even sides that are at least twice as wide as -they are tall. Changes from those files: +which held the same filtering code. With a firefly cap of 64, 128 samples and a level bias of 1, +the differential tests measure differences in prefiltered levels at most `1e-5` relative to +`max(1, |a|, |b|)` for procedural sources of 64 × 32, 128 × 64 and 256 × 128 and synthetic sources +of 128 × 64. An odd intermediate side +retains its last column or row when halved, so initially even sources can also differ. +Changes from those files: - Halving an odd side keeps its last column or row instead of dropping it. - The firefly cap is an option, off by default, and the source level bias is an option. @@ -201,7 +206,7 @@ they are tall. Changes from those files: - Level sizes never grow past the level before, so a source smaller than 4 × 2 is accepted. - The source pyramid halves a source while it is wider than 8 or taller than 4, so a source 8 or fewer pixels wide and more than 4 tall also gets coarser levels. A source at least twice as wide - as it is tall gets the same pyramid as in those files. + as it is tall stops at the same pyramid dimensions as in those files. - The SH projection reads every pixel of the source instead of a source halved to 128 wide by plain averaging, which gave rows near the poles too much weight (a lit top row of a 256 × 128 source counted twice). It integrates each basis function over the area of each pixel instead of diff --git a/crates/pbr/src/prefilter.rs b/crates/pbr/src/prefilter.rs index 31122f80b4..66d76dfe27 100644 --- a/crates/pbr/src/prefilter.rs +++ b/crates/pbr/src/prefilter.rs @@ -49,9 +49,12 @@ impl PrefilterOptions { } /// Point `i` of `n` of the Hammersley set: `(i / n, radical inverse of i in base 2)`. Returns -/// `None` when `i` is not below `n`. +/// coordinates in `0..1`, or `None` when `i` is not below `n`. pub fn hammersley(i: u32, n: u32) -> Option<[f32; 2]> { - (i < n).then(|| [i as f32 / n as f32, i.reverse_bits() as f32 * 2.328_306_4e-10]) + (i < n).then(|| { + let upper = f32::from_bits(1.0_f32.to_bits() - 1); + [i as f32 / n as f32, i.reverse_bits() as f32 * 2.328_306_4e-10].map(|v| v.min(upper)) + }) } /// The GGX normal distribution `D` at `n_dot_h` for perceptual `roughness`, with @@ -180,7 +183,8 @@ fn check_budget(env: &EnvImage, options: &PrefilterOptions, pyramid: &[(u32, u32 let lists = u64::from(options.levels) * (size_of::<(u32, u32)>() + size_of::()) as u64 + pyramid_lists; let bytes = pixels.and_then(|p| p.checked_mul(PIXEL_BYTES)?.checked_add(table)?.checked_add(lists)); limits.check_total_bytes(bytes, w, h)?; - let needed = levels.and_then(|l| l.checked_mul(u64::from(options.samples))).unwrap_or(u64::MAX); + let needed = + levels.and_then(|l| l.checked_mul(u64::from(options.samples))).ok_or(PbrError::BadOption("the filtering work count exceeds u64::MAX"))?; if needed > limits.max_work { return Err(PbrError::TooMuchWork { needed, limit: limits.max_work }); } @@ -258,7 +262,8 @@ fn filter_level(w: u32, h: u32, table: &[Sample<'_>]) -> Result Result, PbrError> { options.validate(limits)?; let (w, h) = (env.width(), env.height()); @@ -300,3 +305,18 @@ pub fn try_prefilter(env: &EnvImage, options: &PrefilterOptions, limits: &Limits } Ok(out) } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + #[test] + fn overflowing_sample_work_is_refused_with_unlimited_work() { + let limits = Limits { max_levels: u32::MAX, max_samples: u32::MAX, max_bytes: u64::MAX, max_work: u64::MAX, ..Limits::default() }; + let env = EnvImage::try_from_linear(4, 2, vec![[1.0; 3]; 8], &limits).unwrap(); + let options = PrefilterOptions { levels: 536_870_914, samples: u32::MAX, ..PrefilterOptions::default() }; + assert!(check_budget(&env, &options, &[], &limits).is_err()); + } +} diff --git a/crates/pbr/tests/it/bench.rs b/crates/pbr/tests/it/bench.rs index 3abfbe9265..caecedfb18 100644 --- a/crates/pbr/tests/it/bench.rs +++ b/crates/pbr/tests/it/bench.rs @@ -1,7 +1,6 @@ //! Elapsed (wall-clock) time of the default filtering: -//! `cargo test -p craft-pbr --release --test it -- --ignored --nocapture bench`. -//! The `parallel` feature is on in this test target even without `--features parallel`, since -//! the crate's dev-dependency on itself enables it, so the times are not a serial baseline. +//! `cargo test -p craft-pbr --release --features parallel --test it -- --ignored --nocapture bench`. +//! The command measures the parallel build. Omitting `--features parallel` measures the serial build. use std::time::Instant; diff --git a/crates/pbr/tests/it/bounds.rs b/crates/pbr/tests/it/bounds.rs index ee5ea4fd20..0b7f5e7be5 100644 --- a/crates/pbr/tests/it/bounds.rs +++ b/crates/pbr/tests/it/bounds.rs @@ -28,6 +28,15 @@ fn zero_sizes_are_refused() { assert_eq!(Environment::Night.try_render(0, &limits), Err(PbrError::BadSize(0, 0))); } +#[test] +fn hammersley_points_stay_below_one_after_rounding() { + for (i, n) in [(0x03ff_ffff, 0x0400_0000), (u32::MAX - 1, u32::MAX)] { + let point = hammersley(i, n).unwrap(); + assert!(point.into_iter().all(|v| (0.0..1.0).contains(&v)), "{i}/{n}: {point:?}"); + } + assert_eq!(hammersley(u32::MAX, u32::MAX), None); +} + #[test] fn huge_sizes_are_refused_before_allocating() { let default = Limits::default(); diff --git a/crates/pbr/tests/it/brdf.rs b/crates/pbr/tests/it/brdf.rs index d150803e79..79f4dc98f6 100644 --- a/crates/pbr/tests/it/brdf.rs +++ b/crates/pbr/tests/it/brdf.rs @@ -5,8 +5,7 @@ use std::f32::consts::PI; use craft_pbr::{ - EnvImage, MIN_DIRECT_ROUGHNESS, Material, PbrError, Visibility, default_environment, ggx_distribution, ggx_distribution_between, hammersley, - try_environment_brdf, + EnvImage, MIN_DIRECT_ROUGHNESS, Material, PbrError, Visibility, default_environment, ggx_distribution, hammersley, try_environment_brdf, }; const VISIBILITIES: [Visibility; 3] = [Visibility::SmithSchlick, Visibility::SmithSeparable, Visibility::SmithHeightCorrelated]; @@ -338,15 +337,6 @@ fn the_default_visibility_is_effectcrafts_smith_schlick() { assert!(at(Visibility::SmithHeightCorrelated) > at(Visibility::SmithSeparable)); } -/// A unit vector along `d`, computed in the same steps and order as the crate normalizes -/// directions: divided by its largest component, then multiplied by the reciprocal length. -fn crate_unit(d: [f32; 3]) -> [f32; 3] { - let big = d[0].abs().max(d[1].abs()).max(d[2].abs()); - let s = [d[0] / big, d[1] / big, d[2] / big]; - let r = 1.0 / ((s[0] * s[0]) + (s[1] * s[1]) + (s[2] * s[2])).sqrt(); - [s[0] * r, s[1] * r, s[2] * r] -} - /// The light a material reflects from a uniform white sky onto a surface seen at `theta`: the /// specular lobe by GGX importance sampling of the half vector, and the diffuse lobe by cosine /// sampling of the light. @@ -354,34 +344,36 @@ fn albedo(m: &Material, theta: f32, steps: u32) -> f64 { let n = [0.0, 0.0, 1.0]; let v = [theta.sin(), 0.0, theta.cos()]; let spec_only = m.try_with_weights(m.specular(), 0.0).unwrap(); - let a = m.roughness().max(MIN_DIRECT_ROUGHNESS).powi(2); + let a = f64::from(m.roughness().max(MIN_DIRECT_ROUGHNESS).powi(2)); + let view = v.map(f64::from); + let view_length = view.into_iter().map(|c| c * c).sum::().sqrt(); + let view = view.map(|c| c / view_length); let (mut spec, mut diff) = (0.0f64, 0.0f64); for i in 0..steps { - let xi = (i as f32 + 0.5) / steps as f32; + let xi = (f64::from(i) + 0.5) / f64::from(steps); for j in 0..steps { - let phi = 2.0 * PI * (j as f32 + 0.5) / steps as f32; + let phi = 2.0 * std::f64::consts::PI * (f64::from(j) + 0.5) / f64::from(steps); // Specular: a half vector drawn from D (n·h), a light reflected about it. let ct = ((1.0 - xi) / (1.0 + (a * a - 1.0) * xi)).sqrt(); let st = (1.0 - ct * ct).max(0.0).sqrt(); let hv = [st * phi.cos(), st * phi.sin(), ct]; - let vh = dot(v, hv); + let vh = view.into_iter().zip(hv).map(|(v, h)| v * h).sum::(); if vh > 0.0 { - let l = [2.0 * vh * hv[0] - v[0], 2.0 * vh * hv[1] - v[1], 2.0 * vh * hv[2] - v[2]]; + let l = [2.0 * vh * hv[0] - view[0], 2.0 * vh * hv[1] - view[1], 2.0 * vh * hv[2] - view[2]]; if l[2] > 0.0 { - // The density at the half vector `try_direct` finds again from `v` and `l`, - // rounded the same way and with `D` taken from the same vectors. - let (uv, ul) = (crate_unit(v), crate_unit(l)); - let h = crate_unit([uv[0] + ul[0], uv[1] + ul[1], uv[2] + ul[2]]); - let d = ggx_distribution_between(n, h, m.roughness().max(MIN_DIRECT_ROUGHNESS)).unwrap(); - let pdf = d * h[2] / (4.0 * dot(uv, h)); - spec += f64::from(spec_only.try_direct(n, v, l).unwrap()[0] / PI / pdf); + // The sampled half vector has density D(h) * h.z, and reflection divides it by 4(v.h). + let a2 = a * a; + let denominator = hv[0] * hv[0] + hv[1] * hv[1] + a2 * hv[2] * hv[2]; + let d = a2 / (std::f64::consts::PI * denominator.powi(2)); + let pdf = d * hv[2] / (4.0 * vh); + spec += f64::from(spec_only.try_direct(n, v, l.map(|c| c as f32)).unwrap()[0]) / std::f64::consts::PI / pdf; } } // Diffuse: a light drawn from n·l / π. let (cl, sl) = ((1.0 - xi).sqrt(), xi.sqrt()); - let l = [sl * phi.cos(), sl * phi.sin(), cl]; + let l = [sl * phi.cos(), sl * phi.sin(), cl].map(|c| c as f32); let d = m.try_direct(n, v, l).unwrap()[0] - spec_only.try_direct(n, v, l).unwrap()[0]; - diff += f64::from(d / cl); + diff += f64::from(d) / cl; } } (spec + diff) / f64::from(steps * steps) diff --git a/crates/pbr/tests/it/differential.rs b/crates/pbr/tests/it/differential.rs index 787544f329..fa912eac8d 100644 --- a/crates/pbr/tests/it/differential.rs +++ b/crates/pbr/tests/it/differential.rs @@ -1,10 +1,10 @@ -//! This crate against the apps' previous code (`crate::reference`), on the same generated -//! environments. With the apps' settings (a firefly cap of 64, 128 samples, a level bias of 1), -//! every level matches within `TOLERANCE` for sources with even sides. The intended differences: -//! halving an odd side keeps the last column or row, which the previous code dropped, so levels -//! read from the pyramid of an odd-sized source differ; and the SH projection integrates the -//! basis over each pixel of the full source and sums in `f64`, so the irradiance differs within -//! `SH_TOLERANCE`. +//! These tests compare this crate with `crate::reference` on generated environments. +//! With a firefly cap of 64, 128 samples and a level bias of 1, +//! every level matches within `TOLERANCE` for the 64 × 32, 128 × 64 and 256 × 128 procedural +//! sources and the 128 × 64 synthetic sources tested here. Halving an odd side keeps its last +//! column or row, so its source pyramid can differ from the reference. The SH projection +//! integrates the basis over each pixel of the full source and sums in `f64`. +//! The irradiance comparison uses `SH_TOLERANCE`. use craft_pbr::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, Limits, PrefilterOptions, irradiance, try_prefilter, try_sh9}; diff --git a/crates/prepress/src/flatten/geom.rs b/crates/prepress/src/flatten/geom.rs index 433484be4f..72fedeb079 100644 --- a/crates/prepress/src/flatten/geom.rs +++ b/crates/prepress/src/flatten/geom.rs @@ -12,6 +12,7 @@ //! a boolean per clipped shape, and a clip edge is then the same edge in every region it bounds. use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape as _, Vec2}; use linesweeper::topology::{ContourIdx, Contours, Topology, WindingNumber}; @@ -212,8 +213,12 @@ pub fn transparent_groups(bounds: &[Rect], transparent: &[bool]) -> Vec); +struct Multi(Arc>); impl Multi { fn get(&self, tag: usize) -> i32 { @@ -233,17 +238,21 @@ impl std::ops::AddAssign for Multi { fn add_assign(&mut self, rhs: Self) { // The sweep mostly adds one input's ±1 to a short list: add in place, insert in tag order, // drop a winding that reaches zero. - for (t, k) in rhs.0 { - match self.0.binary_search_by_key(&t, |e| e.0) { + if rhs.0.iter().all(|e| e.1 == 0) { + return; + } + let list = Arc::make_mut(&mut self.0); + for &(t, k) in rhs.0.iter() { + match list.binary_search_by_key(&t, |e| e.0) { Ok(i) => { - if let Some(e) = self.0.get_mut(i) { + if let Some(e) = list.get_mut(i) { e.1 += k; if e.1 == 0 { - self.0.remove(i); + list.remove(i); } } } - Err(i) if k != 0 => self.0.insert(i, (t, k)), + Err(i) if k != 0 => list.insert(i, (t, k)), Err(_) => {} } } @@ -253,11 +262,11 @@ impl std::ops::AddAssign for Multi { impl WindingNumber for Multi { type Tag = usize; fn single(tag: usize, positive: bool) -> Self { - Multi(vec![(tag, if positive { 1 } else { -1 })]) + Multi(Arc::new(vec![(tag, if positive { 1 } else { -1 })])) } fn of_tag(&self, tag: usize) -> Self { let w = self.get(tag); - Multi(if w == 0 { vec![] } else { vec![(tag, w)] }) + Multi(Arc::new(if w == 0 { vec![] } else { vec![(tag, w)] })) } } @@ -1034,6 +1043,33 @@ mod tests { assert_eq!(overlap_groups(&stack(4_000)).len(), 1, "8 million comparisons: folded"); } + /// A segment's clockwise side holds the same winding as the previous segment's + /// counter-clockwise side, and the two sides share one stored list instead of two copies. + #[test] + fn neighboring_sides_share_one_winding_list() { + // Eight squares that all cross each other. + let shapes: Vec = (0..8) + .map(|i| { + let i = i as f64; + fill(rect(i, i + 0.25, i + 8.0, i + 8.25)) + }) + .collect(); + let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER).unwrap(); + let mut sides = 0; + let mut lists = std::collections::HashSet::new(); + for s in a.top.segment_indices() { + let h = s.first_half(); + for w in [a.top.winding_clockwise(h), a.top.winding_counter_clockwise(h)] { + if !w.0.is_empty() { + sides += 1; + lists.insert(w.0.as_ptr().addr()); + } + } + } + assert!(sides > 100, "{sides} sides"); + assert!(lists.len() * 3 <= sides * 2, "{} lists for {sides} sides", lists.len()); + } + /// One open cubic per path, from `p0` to `p3` through the two handles. fn cubic(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64)) -> BezPath { let mut bp = BezPath::new(); diff --git a/crates/print/src/cups/mod.rs b/crates/print/src/cups/mod.rs index 970745d5aa..c6a1646fc3 100644 --- a/crates/print/src/cups/mod.rs +++ b/crates/print/src/cups/mod.rs @@ -212,7 +212,19 @@ enum Stream { Tcp(TcpStream), } -impl Stream { +/// A connection a [`DeadlineReader`] drives: before each read and write it is given the time +/// left as its timeout. +trait Connection: Read + Write { + fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()>; + + /// One read after [`Self::set_timeouts`] failed with `error`: by default that error. + fn read_without_timeout(&mut self, error: std::io::Error, buf: &mut [u8]) -> std::io::Result { + let _ = buf; + Err(error) + } +} + +impl Connection for Stream { fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()> { let (read, write) = match self { #[cfg(unix)] @@ -221,6 +233,23 @@ impl Stream { }; read.and(write) } + + #[cfg(target_os = "macos")] + fn read_without_timeout(&mut self, error: std::io::Error, buf: &mut [u8]) -> std::io::Result { + // Darwin rejects timeout updates on a disconnected Unix socket even + // when a complete reply is still buffered. Never fall back to a + // blocking read: drain at most this buffer, or fail on WouldBlock. + // Every subsequent read rechecks the same absolute deadline. + if error.raw_os_error() == Some(22) + && let Stream::Unix(stream) = self + { + stream.set_nonblocking(true)?; + let result = stream.read(buf); + let restored = stream.set_nonblocking(false); + return result.and_then(|count| restored.map(|()| count)); + } + Err(error) + } } impl Read for Stream { @@ -511,7 +540,7 @@ pub(crate) fn post(endpoints: &[Server], path: &str, body: &[u8], timeout: Durat /// Send one IPP request and read the reply's body. fn exchange(stream: &mut Stream, authority: &str, path: &str, body: &[u8], timeout: Duration) -> Result, Error> { - let mut stream = DeadlineReader { stream, end: Instant::now() + timeout }; + let mut stream = DeadlineReader { stream, end: Instant::now() + timeout, now: &Instant::now }; let head = format!( "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() @@ -526,16 +555,18 @@ fn exchange(stream: &mut Stream, authority: &str, path: &str, body: &[u8], timeo Ok(reply) } -/// One absolute deadline shared by request writes and reply reads after connection. -struct DeadlineReader<'a> { - stream: &'a mut Stream, +/// One absolute deadline shared by request writes and reply reads after connection, kept +/// against the time `now` reads. +struct DeadlineReader<'a, S = Stream> { + stream: &'a mut S, end: Instant, + now: &'a dyn Fn() -> Instant, } -impl Write for DeadlineReader<'_> { +impl Write for DeadlineReader<'_, S> { fn write(&mut self, buf: &[u8]) -> std::io::Result { let left = self .end - .checked_duration_since(Instant::now()) + .checked_duration_since((self.now)()) .filter(|d| !d.is_zero()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS exchange deadline exceeded"))?; self.stream.set_timeouts(left)?; @@ -553,30 +584,15 @@ fn validate_reply_identity(request: &[u8], reply: &[u8]) -> Result<(), Error> { Ok(()) } -impl Read for DeadlineReader<'_> { +impl Read for DeadlineReader<'_, S> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let left = self .end - .checked_duration_since(Instant::now()) + .checked_duration_since((self.now)()) .filter(|d| !d.is_zero()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS reply deadline exceeded"))?; - #[cfg(not(target_os = "macos"))] - self.stream.set_timeouts(left)?; - #[cfg(target_os = "macos")] if let Err(error) = self.stream.set_timeouts(left) { - // Darwin rejects timeout updates on a disconnected Unix socket even - // when a complete reply is still buffered. Never fall back to a - // blocking read: drain at most this buffer, or fail on WouldBlock. - // Every subsequent read rechecks the same absolute deadline above. - if error.raw_os_error() == Some(22) - && let Stream::Unix(stream) = self.stream - { - stream.set_nonblocking(true)?; - let result = stream.read(buf); - let restored = stream.set_nonblocking(false); - return result.and_then(|count| restored.map(|()| count)); - } - return Err(error); + return self.stream.read_without_timeout(error, buf); } self.stream.read(buf) } diff --git a/crates/print/src/cups/tests.rs b/crates/print/src/cups/tests.rs index e7df135bf3..3fceca3ded 100644 --- a/crates/print/src/cups/tests.rs +++ b/crates/print/src/cups/tests.rs @@ -5,11 +5,14 @@ use super::*; use crate as spool; use crate::cups::{self as ipp, Server}; use craft_ui::testing::trial; +use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::io::{Read, Write}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver}; -use std::time::Duration; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; const TIMEOUT: Duration = Duration::from_secs(2); @@ -19,6 +22,8 @@ const TIMEOUT: Duration = Duration::from_secs(2); struct FakeCups { server: Server, requests: Receiver>, + stopping: Arc, + listener: JoinHandle<()>, } impl FakeCups { @@ -28,15 +33,17 @@ impl FakeCups { let listener = std::os::unix::net::UnixListener::bind(&path)?; // The socket must outlive this function; the folder is left for the process to reap. std::mem::forget(dir); - let requests = listen_unix(listener, replies); - Ok(FakeCups { server: Server::Unix(path), requests }) + let stopping = Arc::new(AtomicBool::new(false)); + let (requests, listener) = listen_unix(listener, replies, stopping.clone()); + Ok(FakeCups { server: Server::Unix(path), requests, stopping, listener }) } fn on_tcp(replies: Vec>) -> std::io::Result { let listener = std::net::TcpListener::bind("127.0.0.1:0")?; let server = Server::Tcp(listener.local_addr()?); - let requests = listen_tcp(listener, replies); - Ok(FakeCups { server, requests }) + let stopping = Arc::new(AtomicBool::new(false)); + let (requests, listener) = listen_tcp(listener, replies, stopping.clone()); + Ok(FakeCups { server, requests, stopping, listener }) } fn request(&self) -> Result, mpsc::RecvTimeoutError> { @@ -47,28 +54,44 @@ impl FakeCups { fn endpoint(&self) -> &[Server] { std::slice::from_ref(&self.server) } + + /// Stops the server once it has served every connection made before this call, and returns + /// the requests it recorded: the channel is closed after the last of them. + fn stop(self) -> Receiver> { + self.stopping.store(true, Ordering::SeqCst); + // A connection of its own wakes the listener; it carries no request. + let _ = super::connect(&self.server); + self.listener.join().unwrap(); + self.requests + } } -fn listen_unix(listener: std::os::unix::net::UnixListener, replies: Vec>) -> Receiver> { +fn listen_unix(listener: std::os::unix::net::UnixListener, replies: Vec>, stopping: Arc) -> (Receiver>, JoinHandle<()>) { let (tx, rx) = mpsc::channel(); let replies = Mutex::new(VecDeque::from(replies)); - std::thread::spawn(move || { + let listening = std::thread::spawn(move || { for stream in listener.incoming().flatten() { serve(stream, &replies, &tx); + if stopping.load(Ordering::SeqCst) { + break; + } } }); - rx + (rx, listening) } -fn listen_tcp(listener: std::net::TcpListener, replies: Vec>) -> Receiver> { +fn listen_tcp(listener: std::net::TcpListener, replies: Vec>, stopping: Arc) -> (Receiver>, JoinHandle<()>) { let (tx, rx) = mpsc::channel(); let replies = Mutex::new(VecDeque::from(replies)); - std::thread::spawn(move || { + let listening = std::thread::spawn(move || { for stream in listener.incoming().flatten() { serve(stream, &replies, &tx); + if stopping.load(Ordering::SeqCst) { + break; + } } }); - rx + (rx, listening) } fn serve(mut stream: impl Read + Write, replies: &Mutex>>, requests: &mpsc::Sender>) { @@ -399,7 +422,8 @@ fn uncertain_submission_never_tries_the_second_endpoint() { let destination = super::Destination { name: "Studio".into(), is_class: false }; assert!(super::submit_at(&[first.server.clone(), second.server.clone()], &destination, b"pdf", &Job::default()).is_err()); let _ = first.request().unwrap(); - assert!(second.requests.recv_timeout(Duration::from_millis(100)).is_err()); + // Every connection the client made has been served once the second server stops. + assert!(matches!(second.stop().try_recv(), Err(mpsc::TryRecvError::Disconnected)), "the second endpoint got no request"); } #[trial] @@ -440,34 +464,62 @@ fn reply_identity_and_metadata_request_are_checked() { assert!(super::validate_reply_identity(&request, &reply).is_err()); } +/// A peer that trickles: each read gives one byte and each write takes one, and each takes 20 ms +/// on the clock `now` holds. It records every timeout it is given. +struct Trickle<'a> { + now: &'a Cell, + timeouts: RefCell>, +} + +impl Trickle<'_> { + fn step(&self) -> usize { + self.now.set(self.now.get() + Duration::from_millis(20)); + 1 + } +} + +impl Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let Some(first) = buf.first_mut() else { return Ok(0) }; + *first = b'x'; + Ok(self.step()) + } +} + +impl Write for Trickle<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if buf.is_empty() { Ok(0) } else { Ok(self.step()) } + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl super::Connection for Trickle<'_> { + fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()> { + self.timeouts.borrow_mut().push(timeout); + Ok(()) + } +} + #[trial] fn slow_reply_cannot_reset_the_absolute_deadline() { - let (client, mut peer) = std::os::unix::net::UnixStream::pair().unwrap(); - let producer = std::thread::spawn(move || { - // Finite work and a joined handle: no abandoned timeout worker. - for _ in 0..20 { - if peer.write_all(b"x").is_err() { - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - }); - let start = std::time::Instant::now(); - let mut stream = super::Stream::Unix(client); - let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let start = Instant::now(); + let now = Cell::new(start); + let mut peer = Trickle { now: &now, timeouts: RefCell::default() }; + let mut reader = super::DeadlineReader { stream: &mut peer, end: start + Duration::from_millis(80), now: &|| now.get() }; let mut bytes = [0; 20]; - assert!(reader.read_exact(&mut bytes).is_err(), "trickle reads must not extend the absolute deadline"); - drop(stream); - producer.join().unwrap(); - assert!(start.elapsed() < Duration::from_secs(3)); + let error = reader.read_exact(&mut bytes).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::TimedOut, "trickle reads must not extend the absolute deadline"); + assert_eq!(*peer.timeouts.borrow(), [80, 60, 40, 20].map(Duration::from_millis), "each read gets only the time left"); } #[trial] fn blocked_upload_obeys_the_same_absolute_deadline() { - let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); - let start = std::time::Instant::now(); - let mut stream = super::Stream::Unix(client); - let mut writer = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let start = Instant::now(); + let now = Cell::new(start); + let mut peer = Trickle { now: &now, timeouts: RefCell::default() }; + let mut writer = super::DeadlineReader { stream: &mut peer, end: start + Duration::from_millis(80), now: &|| now.get() }; let chunk = [0u8; 64 * 1024]; let mut timed_out = false; // A peer that never drains cannot turn each partial write into a fresh timeout budget. @@ -478,7 +530,7 @@ fn blocked_upload_obeys_the_same_absolute_deadline() { } } assert!(timed_out, "blocked upload must terminate without a reader"); - assert!(start.elapsed() < Duration::from_secs(3)); + assert_eq!(*peer.timeouts.borrow(), [80, 60, 40, 20].map(Duration::from_millis), "each partial write gets only the time left"); } #[trial] @@ -573,24 +625,28 @@ fn closed_unix_peer_keeps_its_buffered_reply_readable_with_a_deadline() { peer.write_all(&http_reply(&body)).unwrap(); drop(peer); let mut stream = super::Stream::Unix(client); - let mut reader = super::DeadlineReader { stream: &mut stream, end: std::time::Instant::now() + Duration::from_secs(1) }; + let start = Instant::now(); + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_secs(1), now: &|| start }; assert_eq!(super::read_reply(&mut reader).unwrap(), body); let mut byte = [0]; assert_eq!(reader.read(&mut byte).unwrap(), 0); - reader.end = std::time::Instant::now(); + reader.end = start; assert_eq!(reader.read(&mut byte).unwrap_err().kind(), std::io::ErrorKind::TimedOut); } +/// The read waits on the socket for the time left, then fails: the deadline is the socket's +/// timeout, never a blocking read. #[trial] fn stalled_unix_peer_still_fails_within_the_absolute_read_deadline() { let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); - let start = std::time::Instant::now(); + let start = Instant::now(); let mut stream = super::Stream::Unix(client); - let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80), now: &|| start }; let mut byte = [0]; let error = reader.read(&mut byte).unwrap_err(); assert!(matches!(error.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)); - assert!(start.elapsed() < Duration::from_secs(3)); + let super::Stream::Unix(client) = &stream else { panic!("the stream is the unix socket") }; + assert_eq!(client.read_timeout().unwrap(), Some(Duration::from_millis(80)), "the socket waits only for the time left"); } #[test] diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs index c2e2765d76..52ab060cb5 100644 --- a/crates/print/src/lib.rs +++ b/crates/print/src/lib.rs @@ -625,7 +625,7 @@ const DISCOVERY_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); pub fn printers() -> Vec { #[cfg(all(unix, not(target_arch = "wasm32")))] { - printers_via(&mut lpstat_command(), QUEUES_LIMIT, &mut lpstat_e_command(), DISCOVERY_LIMIT) + printers_via(&mut lpstat_command(), QUEUES_LIMIT, &mut lpstat_e_command(), DISCOVERY_LIMIT, &Clock::REAL) } #[cfg(windows)] { @@ -637,18 +637,19 @@ pub fn printers() -> Vec { } } -/// [`printers`] with the two `lpstat` commands and their limits supplied, so tests can stand in a -/// command that hangs. +/// [`printers`] with the two `lpstat` commands, their limits and the clock the limits are kept +/// against supplied, so tests can stand in a command that hangs. #[cfg(all(unix, not(target_arch = "wasm32")))] fn printers_via( queues: &mut std::process::Command, queues_limit: std::time::Duration, available: &mut std::process::Command, available_limit: std::time::Duration, + clock: &Clock<'_>, ) -> Vec { // Exits 1 with only driverless printers ("No destinations added"); `-e` still finds them, so // the exit status isn't checked. - let queues = match output_within(queues, queues_limit) { + let queues = match output_within(queues, queues_limit, clock) { Ok(out) => String::from_utf8_lossy(&out).into_owned(), Err(e) if e.kind() == std::io::ErrorKind::NotFound => { // A Flatpak needs lpstat/lp bundled plus the CUPS socket and Avahi (see README). @@ -662,7 +663,7 @@ fn printers_via( }; // A spooler without `-e`, or one whose discovery doesn't answer in time, only loses the // driverless names. - let available = match output_within(available, available_limit) { + let available = match output_within(available, available_limit, clock) { Ok(out) => Some(String::from_utf8_lossy(&out).into_owned()), Err(e) => { log::info!("lpstat -e gave no driverless printers ({e})"); @@ -676,18 +677,32 @@ fn printers_via( /// output capped, and given `limit` to answer (none when it doesn't). #[cfg(all(unix, not(target_arch = "wasm32")))] fn queue_defaults(command: &mut std::process::Command, limit: std::time::Duration) -> Vec<(String, String)> { - output_within(command, limit).map(|out| parse_lpoptions(&String::from_utf8_lossy(&out))).unwrap_or_default() + output_within(command, limit, &Clock::REAL).map(|out| parse_lpoptions(&String::from_utf8_lossy(&out))).unwrap_or_default() } /// The most of a command's output that is read: far more than any `lpstat` listing. #[cfg(all(unix, not(target_arch = "wasm32")))] const OUTPUT_CAP: u64 = 4 << 20; -/// Run `command` and collect its standard output, giving it `limit`: a command still running -/// then is killed and reaped, and the error is `TimedOut`. Standard input and error are not -/// connected. The exit status is not checked, as `Command::output` leaves it to the caller. +/// The time [`output_within`] keeps a command's limit against (`now`), and how it waits before +/// it checks on the command again (`pause`). #[cfg(all(unix, not(target_arch = "wasm32")))] -fn output_within(command: &mut std::process::Command, limit: std::time::Duration) -> std::io::Result> { +struct Clock<'a> { + now: &'a dyn Fn() -> std::time::Instant, + pause: &'a dyn Fn(), +} + +#[cfg(all(unix, not(target_arch = "wasm32")))] +impl Clock<'static> { + /// The real clock, checking on the command every 10 ms. + const REAL: Clock<'static> = Clock { now: &std::time::Instant::now, pause: &|| std::thread::sleep(std::time::Duration::from_millis(10)) }; +} + +/// Run `command` and collect its standard output, giving it `limit` on `clock`: a command still +/// running then is killed and reaped, and the error is `TimedOut`. Standard input and error are +/// not connected. The exit status is not checked, as `Command::output` leaves it to the caller. +#[cfg(all(unix, not(target_arch = "wasm32")))] +fn output_within(command: &mut std::process::Command, limit: std::time::Duration, clock: &Clock<'_>) -> std::io::Result> { use std::io::Read as _; use std::process::Stdio; let mut child = command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?; @@ -717,23 +732,23 @@ fn output_within(command: &mut std::process::Command, limit: std::time::Duration return Err(e); } let timed_out = || std::io::Error::new(std::io::ErrorKind::TimedOut, format!("the command did not answer within {limit:?}")); - let deadline = std::time::Instant::now() + limit; + let deadline = (clock.now)() + limit; loop { match child.try_wait() { Ok(Some(_)) => { // A moment's grace, so output written just before an exit at the deadline counts. - let left = deadline.saturating_duration_since(std::time::Instant::now()).max(std::time::Duration::from_millis(100)); + let left = deadline.saturating_duration_since((clock.now)()).max(std::time::Duration::from_millis(100)); return match rx.recv_timeout(left) { Ok(read) => read, Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(timed_out()), Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(std::io::Error::other("the command's output was lost")), }; } - Ok(None) if std::time::Instant::now() >= deadline => { + Ok(None) if (clock.now)() >= deadline => { stop(&mut child); return Err(timed_out()); } - Ok(None) => std::thread::sleep(std::time::Duration::from_millis(10)), + Ok(None) => (clock.pause)(), Err(e) => { stop(&mut child); return Err(e); diff --git a/crates/print/src/spool_tests.rs b/crates/print/src/spool_tests.rs index 4627f3bc24..9fe23d9b46 100644 --- a/crates/print/src/spool_tests.rs +++ b/crates/print/src/spool_tests.rs @@ -3,12 +3,13 @@ //! process cleanup are the production ones, with no printer. use std::collections::VecDeque; -use std::io::Write; +use std::io::{BufRead, BufReader, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use craft_host::ManualJobs; use craft_ui::testing::trial; @@ -26,6 +27,8 @@ const PRINT_MODE: &str = "CRAFT_TEST_PRINT_MODE"; /// Set on the child: where it marks the stages it reached, apart from the input folder, which /// the parent removes. const PRINT_MARKS: &str = "CRAFT_TEST_PRINT_MARKS"; +/// Set on the child: the loopback address of the [`Stages`] it reports each stage to. +const PRINT_STAGES: &str = "CRAFT_TEST_PRINT_STAGES"; const PDF: &[u8] = b"synthetic PDF"; /// One prepared job of [`Fake`]: its cancel's answer, whether it answers after a cancel, and the @@ -161,8 +164,16 @@ fn stand_in_print_helper() { let directory = PathBuf::from(directory); let marks = PathBuf::from(std::env::var_os(PRINT_MARKS).unwrap()); let mode = std::env::var(PRINT_MODE).unwrap_or_default(); + let stages = std::env::var(PRINT_STAGES).ok().map(|address| TcpStream::connect(address).unwrap()); + // Each stage is marked in the folder and reported to the parent. + let reached = |stage: &str| { + std::fs::write(marks.join(stage), stage).unwrap(); + if let Some(mut stages) = stages.as_ref() { + writeln!(stages, "{stage}").and_then(|()| stages.flush()).unwrap(); + } + }; if mode == "waking" { - std::fs::write(marks.join("waking"), b"starting").unwrap(); + reached("waking"); loop { std::thread::park(); } @@ -174,7 +185,7 @@ fn stand_in_print_helper() { |pdf, job, _token| { assert_eq!(pdf, PDF); assert_eq!(job.printer.as_deref(), Some("test queue")); - std::fs::write(marks.join("driver"), b"driver entered").unwrap(); + reached("driver"); match mode.as_str() { "held" => { let provider = Mutex::new(()); @@ -185,10 +196,11 @@ fn stand_in_print_helper() { } "crash" => std::process::exit(7), "sending" => { - std::fs::write(marks.join("sending"), b"sending").unwrap(); - while !marks.join("release").exists() { - std::thread::sleep(Duration::from_millis(5)); - } + reached("sending"); + // Sends until the parent releases it. + let mut release = String::new(); + BufReader::new(stages.as_ref().unwrap()).read_line(&mut release).unwrap(); + assert_eq!(release.trim_end(), "release"); Ok("spooled synthetic job".into()) } _ => Ok("spooled synthetic job".into()), @@ -198,14 +210,18 @@ fn stand_in_print_helper() { std::process::exit(i32::from(result.is_err())); } -/// Launches [`stand_in_print_helper`] over `directory` in `mode`, marking its stages in `marks`. -fn helper_command(directory: &Path, marks: &Path, mode: &str, may_be_killed: bool) -> std::io::Result { +/// Launches [`stand_in_print_helper`] over `directory` in `mode`, marking its stages in `marks` +/// and reporting them to `stages` when there is one. +fn helper_command(directory: &Path, marks: &Path, stages: Option, mode: &str, may_be_killed: bool) -> std::io::Result { let mut command = Command::new(std::env::current_exe()?); command .args(["--exact", "spool_tests::stand_in_print_helper", "--nocapture", "--"]) .env(PRINT_DIR, directory) .env(PRINT_MARKS, marks) .env(PRINT_MODE, mode); + if let Some(stages) = stages { + command.env(PRINT_STAGES, stages.to_string()); + } // A force-killed child can leave a partial LLVM profile; keep it in this trial's // temporary directory while normally exiting children retain their coverage. if may_be_killed && std::env::var_os("LLVM_PROFILE_FILE").is_some() { @@ -219,29 +235,69 @@ fn job() -> Job { Job { printer: Some("test queue".into()), ..Job::default() } } -/// Waits until the child has marked `path`, failing after [`LIMIT`]. -fn wait_for(path: &Path) { - let deadline = Instant::now() + LIMIT; - while !path.exists() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(5)); +/// The parent's end of one child's stage reports: the child connects once and sends a line for +/// each stage it reaches, and a child in `sending` waits for a line back. +struct Stages { + address: SocketAddr, + reached: Receiver, + connection: Receiver, +} + +impl Stages { + fn new() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let (report, reached) = channel(); + let (accepted, connection) = channel(); + std::thread::spawn(move || { + let Ok((stream, _)) = listener.accept() else { return }; + if let Ok(writer) = stream.try_clone() { + let _ = accepted.send(writer); + } + for line in BufReader::new(stream).lines() { + let Ok(line) = line else { break }; + if report.send(line).is_err() { + break; + } + } + }); + Stages { address, reached, connection } + } + + /// Waits until the child reports `stage`; [`LIMIT`] only guards against a hang. + fn wait_for(&self, stage: &str) { + loop { + match self.reached.recv_timeout(LIMIT) { + Ok(line) if line == stage => return, + Ok(_) => {} + Err(error) => panic!("the child never reached {stage}: {error}"), + } + } + } + + /// Lets a child in `sending` finish. + fn release(&self) { + let mut connection = self.connection.recv_timeout(LIMIT).unwrap(); + connection.write_all(b"release\n").and_then(|()| connection.flush()).unwrap(); } - assert!(path.exists(), "the child never reached {path:?}"); } /// Runs `submission` on a thread with the child in `mode`; the receiver gets its input folder. fn submit_in( submission: &Submission, marks: &Path, + stages: &Stages, mode: &'static str, may_be_killed: bool, ) -> (std::thread::JoinHandle>, Receiver) { let worker = submission.clone(); let marks = marks.to_path_buf(); + let stages = stages.address; let (folder, folders) = channel(); let running = std::thread::spawn(move || { worker.submit_with(PDF, &job(), |directory| { folder.send(directory.to_path_buf()).unwrap(); - helper_command(directory, &marks, mode, may_be_killed) + helper_command(directory, &marks, Some(stages), mode, may_be_killed) }) }); (running, folders) @@ -271,7 +327,7 @@ fn a_cancel_during_startup_never_starts_the_driver() { worker.submit_with(PDF, &job(), |directory| { started.send(directory.to_path_buf()).unwrap(); wait.recv().unwrap(); - helper_command(directory, &held, "held", true) + helper_command(directory, &held, None, "held", true) }) }); let directory = starting.recv_timeout(LIMIT).unwrap(); @@ -282,9 +338,10 @@ fn a_cancel_during_startup_never_starts_the_driver() { // Cancelled while the child is waking and has not acknowledged anything. let submission = Submission::new(); - let (running, folders) = submit_in(&submission, marks.path(), "waking", true); + let stages = Stages::new(); + let (running, folders) = submit_in(&submission, marks.path(), &stages, "waking", true); let directory = folders.recv_timeout(LIMIT).unwrap(); - wait_for(&marks.path().join("waking")); + stages.wait_for("waking"); assert!(submission.cancel(), "a process without a start grant cannot send anything"); assert_eq!(running.join().unwrap(), Err(CANCELLED.into())); assert!(!directory.exists()); @@ -296,13 +353,14 @@ fn a_cancel_during_startup_never_starts_the_driver() { fn a_refusal_while_sending_keeps_the_job() { let marks = tempfile::tempdir().unwrap(); let submission = Submission::new(); - let (running, folders) = submit_in(&submission, marks.path(), "sending", false); + let stages = Stages::new(); + let (running, folders) = submit_in(&submission, marks.path(), &stages, "sending", false); let directory = folders.recv_timeout(LIMIT).unwrap(); - wait_for(&marks.path().join("sending")); + stages.wait_for("sending"); assert!(!submission.cancel(), "a sending job refuses cancellation"); assert!(!submission.cancel(), "and keeps refusing it"); assert!(!running.is_finished(), "the child is retained until it finishes sending"); - std::fs::write(marks.path().join("release"), b"continue").unwrap(); + stages.release(); assert_eq!(running.join().unwrap(), Ok("spooled synthetic job".into())); assert!(!directory.exists()); } @@ -313,15 +371,16 @@ fn a_refusal_while_sending_keeps_the_job() { fn a_cancelled_driver_does_not_block_the_next_job() { let marks = tempfile::tempdir().unwrap(); let submission = Submission::new(); - let (running, folders) = submit_in(&submission, marks.path(), "held", true); + let stages = Stages::new(); + let (running, folders) = submit_in(&submission, marks.path(), &stages, "held", true); let directory = folders.recv_timeout(LIMIT).unwrap(); - wait_for(&marks.path().join("driver")); + stages.wait_for("driver"); assert!(!directory.join("input.pdf").exists(), "the stalled driver retains no plaintext PDF"); assert!(!directory.join("job.json").exists(), "loaded settings were erased before driver work"); assert!(submission.cancel(), "a stalled driver still acknowledges cancellation"); let next_marks = tempfile::tempdir().unwrap(); let next = Submission::new(); - assert_eq!(next.submit_with(PDF, &job(), |dir| helper_command(dir, next_marks.path(), "ready", false)), Ok("spooled synthetic job".into())); + assert_eq!(next.submit_with(PDF, &job(), |dir| helper_command(dir, next_marks.path(), None, "ready", false)), Ok("spooled synthetic job".into())); assert_eq!(running.join().unwrap(), Err(CANCELLED.into())); assert!(!directory.exists(), "the reaped helper's PDF and settings were removed"); assert!(!next.cancel(), "a completed job keeps its receipt"); @@ -338,7 +397,7 @@ fn helper_crashes_are_errors_and_inputs_are_bounded() { Submission::new() .submit_with(PDF, &job(), |dir| { inputs = Some(dir.to_path_buf()); - helper_command(dir, marks.path(), "crash", false) + helper_command(dir, marks.path(), None, "crash", false) }) .is_err() ); @@ -363,7 +422,8 @@ fn helper_crashes_are_errors_and_inputs_are_bounded() { let folder = tempfile::tempdir().unwrap(); std::fs::write(folder.path().join("job.json"), serde_json::to_vec(&Request::from_job(&job())).unwrap()).unwrap(); std::fs::write(folder.path().join("input.pdf"), PDF).unwrap(); - let mut child = helper_command(folder.path(), marks.path(), "held", false) + let stages = Stages::new(); + let mut child = helper_command(folder.path(), marks.path(), Some(stages.address), "held", false) .unwrap() .stdin(Stdio::piped()) .stdout(Stdio::null()) @@ -372,7 +432,7 @@ fn helper_crashes_are_errors_and_inputs_are_bounded() { .unwrap(); let mut input = child.stdin.take().unwrap(); input.write_all(b"start\n").and_then(|_| input.flush()).unwrap(); - wait_for(&marks.path().join("driver")); + stages.wait_for("driver"); drop(input); assert!(child.wait().unwrap().success(), "a vanished parent ends the waiting child"); assert!(!folder.path().join("input.pdf").exists()); diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs index cc86e6da61..3a735cd972 100644 --- a/crates/print/src/tests.rs +++ b/crates/print/src/tests.rs @@ -213,6 +213,7 @@ fn macos_offers_auto_select_where_the_driver_would_pick_its_default_tray() { pub(crate) mod lpstat_limits { use super::*; use craft_ui::testing::trial; + use std::cell::Cell; use std::process::Command; use std::time::{Duration, Instant}; @@ -222,16 +223,25 @@ pub(crate) mod lpstat_limits { c } - /// Discovery that hangs only loses the driverless printers; the queues are listed. + /// Discovery that hangs only loses the driverless printers; the queues are listed. The limits + /// are kept on a clock that moves 10 ms at each check on a command, so the hanging discovery + /// is stopped at its 30th check however slowly the checks run, and its late answer is never + /// read. #[trial] fn discovery_that_hangs_keeps_the_queues() { let mut queues = sh("printf 'printer Office_Laser is idle. enabled since Mon\\n\\tDescription: Office\\nsystem default destination: Office_Laser\\n'"); - let started = Instant::now(); - let found = printers_via(&mut queues, Duration::from_secs(5), &mut sh("sleep 30"), Duration::from_millis(300)); - assert_eq!(found.iter().map(|p| p.name.as_str()).collect::>(), ["Office_Laser"]); + let now = Cell::new(Instant::now()); + let pause = || { + // The queue listing needs real time to finish between checks. + std::thread::sleep(Duration::from_millis(10)); + now.set(now.get() + Duration::from_millis(10)); + }; + let clock = Clock { now: &|| now.get(), pause: &pause }; + let mut hangs = sh("sleep 30; echo Late_Printer"); + let found = printers_via(&mut queues, Duration::from_secs(5), &mut hangs, Duration::from_millis(300), &clock); + assert_eq!(found.iter().map(|p| p.name.as_str()).collect::>(), ["Office_Laser"], "the late answer is not waited for"); assert!(found[0].default); - assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); } } /// Driver settings `len` bytes long whose header says `size` + `extra`, filled with `fill`. diff --git a/crates/scopes/Cargo.toml b/crates/scopes/Cargo.toml new file mode 100644 index 0000000000..dbdd448b29 --- /dev/null +++ b/crates/scopes/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-scopes" +description = "Video scope math: waveform, parade, histogram and vectorscopes from RGBA8 or NV12 frames, with numeric summaries and trace images" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-color = { workspace = true } +serde = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/scopes/NOTICE b/crates/scopes/NOTICE new file mode 100644 index 0000000000..fe894b8f0f --- /dev/null +++ b/crates/scopes/NOTICE @@ -0,0 +1,9 @@ +craft-scopes +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The scope math, summaries and trace painting come from FilmCraft's `crates/scopes` +(https://github.com/storytold/filmcraft, commit 3f137a7ed420cac79b32145f5243b7f98b31f71c), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. +The HDR histogram bins come from LightCraft's `crates/raster/src/histogram.rs` +(https://github.com/storytold/lightcraft, commit aa08a77060c0cca737dcc29b5db814cbc07ae611), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. diff --git a/crates/scopes/README.md b/crates/scopes/README.md new file mode 100644 index 0000000000..bd21c86e89 --- /dev/null +++ b/crates/scopes/README.md @@ -0,0 +1,74 @@ +# craft-scopes + +Video scope math for a Craft app's scopes panel: the waveform, parade, histogram and the YUV and +HLS vectorscopes of a frame, as count grids, with numeric summaries and trace images. The crate +depends only on `craft-color` and `serde`, has no UI, and builds for `wasm32-unknown-unknown`. + +The `scopes` feature of `craft` re-exports this crate as `craft::scopes`. + +| Item | What | +|---|---| +| `Frame` | a borrowed frame: `Rgba8` with a row stride, or `Nv12` (Y' plane and interleaved Cb Cr plane, each with its own stride, plus the matrix and range) | +| `Signal` | a frame's R'G'B' code values, decimated by nearest-sample picking to at most 480 × 270 (`fill`, `fill_max`, `from_rgba8`, `from_rgba_f32_with` with `linear_to_pq` for HDR, `from_fn`) | +| `waveform`, `waveform_into` | RGB, luma, luma and chroma, or luma and chroma with the chroma hidden: one count grid per trace (columns = signal width, `rows` levels) | +| `parade`, `parade_into` | RGB, YUV, or RGB and luma traces, drawn side by side | +| `histogram`, `histogram_into` | 256 bins of R', G', B', Y'; samples below 0 and above 1 are counted separately | +| `histogram_hdr_into`, `HdrBins` | 256 bins of linear values: black to SDR white sRGB-encoded in the first half, then equal stops above SDR white | +| `vectorscope_yuv`, `vectorscope_yuv_into` | Cb right, Cr up, ±0.6; `targets(matrix, amplitude)` gives the six color-bar targets, `SKIN_TONE_DEG` is 123° | +| `vectorscope_hls`, `vectorscope_hls_into` | hue as the angle (red at the matrix's YUV red angle, then yellow, green, cyan, blue, magenta counter-clockwise), HLS saturation as the radius | +| `compute`, `compute_into` | one scope by `ScopeKind`, with the waveform and parade traces from `Params::waveform` and `Params::parade` | +| `summary` | levels (min, max and mean in percent) per channel and per column range, the densest vectorscope cells with angle and magnitude, a coarse vectorscope | +| `paint` | count grids to premultiplied RGBA8 (log intensity, additive traces, Brightness gain; vectorscope points spread over 3 × 3), with `*_into` forms that take a `Scratch` | + +Settings types (all serde, camelCase): `ScopeKind`, `WaveformType`, `ParadeType`, `ColorSpace` +(Automatic, Rec. 601, Rec. 709 and Rec. 2100 for the BT.601, BT.709 and BT.2020 NCL matrices), +`Scale` (8-bit, Float, HDR), `Brightness` and `Targets` (75 %, 100 %). Their `label` strings are +English; an app translates them before showing them. `ScopeKind`, `Computed`, `Frame` and +`FrameError` are `#[non_exhaustive]`, so a later scope or frame format is not a breaking change. + +## Reusing buffers + +Each `*_into` function writes into a value the caller keeps between frames. After the first frame +of a size, `Signal::fill`, the `*_into` scopes and the `paint::*_into` painters do not allocate. +`summary` allocates its results. + +## Input checks + +`Frame::validate` (called by `Signal::fill`) returns a `FrameError` for a stride shorter than a +row, a plane shorter than its rows, or a size that overflows; the signal is then empty. A signal +holds at most 1920 × 1080 samples whatever size `fill_max` is asked for, and a grid at most 1920 +columns. `Params` clamps `rows` to 2..=4096 and `vector_size` to 3..=1023, rounding an even size up to the next odd one. Grid and vectorscope +lookups outside the grid return 0. `Signal::from_fn` cuts a larger size to 1920 × 1080, and the +painters paint nothing for a hand-built grid wider than 1920 columns or taller than 4096 rows, or a +vectorscope larger than 1023. Summaries leave NaN and infinite samples out. + +## Definitions + +- Y'CbCr from R'G'B' with the matrix's Kr and Kb (ITU-R BT.601-7, BT.709-6, BT.2020-2 NCL), Cb and + Cr in −0.5…0.5. YC chroma amplitude is √(Cb² + Cr²), plotted at Y' ± C. +- NV12 code values are normalized with the frame's range (limited: Y' 16–235, Cb and Cr 16–240; + full: 0–255) and turned into R'G'B' with its matrix. Each Cb Cr pair covers 2 × 2 pixels. +- Waveform rows span 0…1 with clamping (values clamped first) or −0.1…1.1 without (values + outside are dropped). With 256 rows an 8-bit code value `c` lands on row `c`. +- HDR: linear working values (1.0 = 203 cd/m², ITU-R BT.2408) to SMPTE ST 2084 PQ code values; the + axis is 0…10 000 cd/m². SDR frames on the HDR scale use BT.1886 (γ 2.4, 100 cd/m² white). + +## Tests + +`src/tests.rs` uses generated frames with known values: a flat color lands in exact histogram bins; +a 256-step ramp fills every bin and puts column `x` on row `x`; 75 % color bars put each parade +column on its code value and each bar on its vectorscope target cell (BT.601, BT.709, BT.2020); the +8-bit limited-range BT.709 code values of the 100 % color bars in SMPTE RP 219-1 decode from NV12 +to their R'G'B' within 1.5 codes; strided and packed RGBA read the same samples; bad strides, short +planes and overflowing sizes give errors; the `*_into` functions match the allocating ones and keep +their buffers across frames; hostile parameters and inconsistent signals stay bounded; HDR bins +split SDR and stops for any split. + +## Speed + +`cargo test --release -p craft-scopes perf -- --ignored --nocapture` decimates a 1920 × 1080 frame +and times each scope on the 480 × 270 signal. + +## License + +MIT OR Apache-2.0. `NOTICE` names the code this crate started from. diff --git a/crates/scopes/src/frame.rs b/crates/scopes/src/frame.rs new file mode 100644 index 0000000000..4725f18d6e --- /dev/null +++ b/crates/scopes/src/frame.rs @@ -0,0 +1,93 @@ +//! Borrowed frames the scopes read: 8-bit R'G'B'A, or 8-bit NV12 (a Y' plane and an interleaved +//! Cb Cr plane at half width and half height), each with its own row stride. + +use std::fmt; + +use craft_color::{Matrix, Range}; + +/// A frame borrowed from its owner (a readback buffer, a decoder, a capture). Strides are in bytes. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub enum Frame<'a> { + /// R'G'B'A, 4 bytes per pixel, `stride` bytes per row (at least `width * 4`). Alpha is ignored. + Rgba8 { width: usize, height: usize, stride: usize, data: &'a [u8] }, + /// Y' at full size and Cb Cr pairs at half width and half height (rounded up). `matrix` and + /// `range` say how the code values turn back into R'G'B'. + Nv12 { width: usize, height: usize, y: &'a [u8], y_stride: usize, uv: &'a [u8], uv_stride: usize, matrix: Matrix, range: Range }, +} + +/// Why a [`Frame`] cannot be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum FrameError { + /// A row stride shorter than one row of samples. + Stride { plane: &'static str, stride: usize, needed: usize }, + /// A plane shorter than its rows. + Short { plane: &'static str, len: usize, needed: usize }, + /// The frame's size in bytes overflows `usize`. + TooLarge, +} + +impl fmt::Display for FrameError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FrameError::Stride { plane, stride, needed } => write!(f, "{plane} plane stride {stride} is shorter than a row ({needed} bytes)"), + FrameError::Short { plane, len, needed } => write!(f, "{plane} plane holds {len} bytes; the frame needs {needed}"), + FrameError::TooLarge => write!(f, "the frame is too large to address"), + } + } +} + +impl std::error::Error for FrameError {} + +/// Bytes a plane of `rows` rows needs: every row but the last at `stride`, the last one `row_bytes`. +fn plane_len(rows: usize, stride: usize, row_bytes: usize) -> Option { + if rows == 0 { Some(0) } else { stride.checked_mul(rows - 1)?.checked_add(row_bytes) } +} + +fn check_plane(plane: &'static str, len: usize, rows: usize, stride: usize, row_bytes: usize) -> Result<(), FrameError> { + if rows == 0 || row_bytes == 0 { + return Ok(()); + } + if stride < row_bytes { + return Err(FrameError::Stride { plane, stride, needed: row_bytes }); + } + let needed = plane_len(rows, stride, row_bytes).ok_or(FrameError::TooLarge)?; + if len < needed { + return Err(FrameError::Short { plane, len, needed }); + } + Ok(()) +} + +impl Frame<'_> { + pub fn width(&self) -> usize { + match *self { + Frame::Rgba8 { width, .. } | Frame::Nv12 { width, .. } => width, + } + } + + pub fn height(&self) -> usize { + match *self { + Frame::Rgba8 { height, .. } | Frame::Nv12 { height, .. } => height, + } + } + + /// Checks that every row of every plane lies inside its slice. A frame with no width or no + /// height is valid and has no samples. + pub fn validate(&self) -> Result<(), FrameError> { + if self.width() == 0 || self.height() == 0 { + return Ok(()); + } + match *self { + Frame::Rgba8 { width, height, stride, data } => { + let row = width.checked_mul(4).ok_or(FrameError::TooLarge)?; + check_plane("RGBA", data.len(), height, stride, row) + } + Frame::Nv12 { width, height, y, y_stride, uv, uv_stride, .. } => { + check_plane("Y", y.len(), height, y_stride, width)?; + let uv_row = width.div_ceil(2).checked_mul(2).ok_or(FrameError::TooLarge)?; + check_plane("UV", uv.len(), height.div_ceil(2), uv_stride, uv_row) + } + } + } +} diff --git a/crates/scopes/src/lib.rs b/crates/scopes/src/lib.rs new file mode 100644 index 0000000000..0e83ccc9b4 --- /dev/null +++ b/crates/scopes/src/lib.rs @@ -0,0 +1,1074 @@ +//! Video scope math (no UI): the waveform, parade, histogram and the YUV and HLS vectorscopes of +//! a frame, as count grids ("how many samples land on this cell"), plus numeric summaries +//! ([`summary`]) and the density-to-pixels mapping a UI draws ([`paint`]). +//! +//! The input is a [`Signal`]: the frame's R'G'B' code values (display-encoded, 0..1 nominal; +//! values outside it are super-whites and sub-blacks of float or HDR frames), decimated to at most +//! [`MAX_W`] × [`MAX_H`] samples by nearest-sample picking (no averaging, so flat colors and test +//! patterns land on exact cells). [`Signal::fill`] reads a borrowed RGBA8 or NV12 [`Frame`] with +//! any row stride. Y'CbCr comes from the scope's matrix (BT.601, BT.709 or BT.2020 NCL; +//! `craft_color::rgb_to_ycbcr`). +//! +//! | Scope | Grid | Columns × rows | +//! |---|---|---| +//! | Waveform RGB / luma / luma and chroma / luma and chroma with the chroma hidden | per trace: R, G, B / Y / Y and C (Y ± \|CbCr\|) / Y | signal width × `rows` | +//! | Parade RGB / YUV / RGB and luma | per trace: R, G, B / Y, Cb + ½, Cr + ½ / R, G, B, Y | signal width × `rows` (drawn side by side) | +//! | Histogram | 256 bins per channel R, G, B, Y | — | +//! | YUV vectorscope | Cb horizontal, Cr up, ±[`VECTOR_EXTENT`] | `vector_size`² | +//! | HLS vectorscope | hue as the angle (red at the YUV red angle), HLS saturation as the radius (1 = 0.5) | `vector_size`² | +//! +//! [`compute`] picks the waveform and parade traces from [`Params::waveform`] and +//! [`Params::parade`]. +//! +//! Waveform rows cover `[lo, hi]` = `[0, 1]` with clamping on (values clamped first) and +//! `[-0.1, 1.1]` without (values outside are dropped). With 256 rows over `[0, 1]`, an 8-bit code +//! value `c` lands exactly on row `c`. +//! +//! Every `*_into` function writes into a value the caller keeps between frames. Once that value +//! and the [`Signal`] have grown to the frame's size, the call does not allocate. + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +pub mod frame; +pub mod paint; +pub mod summary; +#[cfg(test)] +mod tests; + +pub use craft_color::{Matrix, Range}; +use craft_color::{normalize_c, normalize_y, rgb_to_ycbcr, ycbcr_to_rgb}; +pub use frame::{Frame, FrameError}; +use serde::{Deserialize, Serialize}; + +/// Largest decimated signal (a 1080p frame is sampled every 4th pixel both ways). +pub const MAX_W: usize = 480; +pub const MAX_H: usize = 270; + +/// Largest signal [`Signal::fill_max`] and [`Signal::fill_rgba_f32_with`] make, whatever size they +/// are asked for, and the most columns a [`Grid`] holds. +pub const MAX_SIGNAL_W: usize = 1920; +pub const MAX_SIGNAL_H: usize = 1080; + +/// Most waveform and parade levels a [`Params`] or a [`Grid`] can hold; larger values are clamped. +pub const MAX_ROWS: usize = 4096; +/// Largest vectorscope grid a [`Params`] can ask for; larger values are clamped. +pub const MAX_VECTOR_SIZE: usize = 1023; + +/// Half-width of the vectorscope plane in Cb/Cr units (the 100 % targets of every matrix fit). +pub const VECTOR_EXTENT: f32 = 0.6; + +/// The skin-tone line (the "I" axis of NTSC): 123° counter-clockwise from +Cb. +pub const SKIN_TONE_DEG: f32 = 123.0; + +// ------------------------------------------------------------------------------------ settings + +/// A scope. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum ScopeKind { + VectorscopeYuv, + VectorscopeHls, + Histogram, + Parade, + #[default] + Waveform, +} + +impl ScopeKind { + pub const ALL: [ScopeKind; 5] = + [ScopeKind::VectorscopeYuv, ScopeKind::VectorscopeHls, ScopeKind::Histogram, ScopeKind::Parade, ScopeKind::Waveform]; + /// Stable id (`"vectorscopeYuv"`…), as in JSON. + pub fn name(self) -> &'static str { + match self { + ScopeKind::VectorscopeYuv => "vectorscopeYuv", + ScopeKind::VectorscopeHls => "vectorscopeHls", + ScopeKind::Histogram => "histogram", + ScopeKind::Parade => "parade", + ScopeKind::Waveform => "waveform", + } + } + /// English label; an app translates it before showing it. + pub fn label(self) -> &'static str { + match self { + ScopeKind::VectorscopeYuv => "YUV vectorscope", + ScopeKind::VectorscopeHls => "HLS vectorscope", + ScopeKind::Histogram => "Histogram", + ScopeKind::Parade => "Parade", + ScopeKind::Waveform => "Waveform", + } + } + /// By id or label, ignoring case, spaces and dashes (`"vectorscope"` = the YUV one). + pub fn from_name(s: &str) -> Option { + let n = norm(s); + if n == "vectorscope" || n == "yuv" { + return Some(ScopeKind::VectorscopeYuv); + } + if n == "hls" { + return Some(ScopeKind::VectorscopeHls); + } + Self::ALL.into_iter().find(|k| norm(k.name()) == n || norm(k.label()) == n) + } +} + +fn norm(s: &str) -> String { + s.chars().filter(|c| c.is_alphanumeric()).collect::().to_ascii_lowercase() +} + +/// Waveform type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WaveformType { + #[default] + Rgb, + Luma, + Yc, + YcNoChroma, +} + +impl WaveformType { + pub const ALL: [WaveformType; 4] = [WaveformType::Rgb, WaveformType::Luma, WaveformType::Yc, WaveformType::YcNoChroma]; + pub fn label(self) -> &'static str { + match self { + WaveformType::Rgb => "RGB", + WaveformType::Luma => "Luma", + WaveformType::Yc => "Luma and chroma", + WaveformType::YcNoChroma => "Luma and chroma, chroma hidden", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// Parade type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ParadeType { + #[default] + Rgb, + Yuv, + RgbWhite, +} + +impl ParadeType { + pub const ALL: [ParadeType; 3] = [ParadeType::Rgb, ParadeType::Yuv, ParadeType::RgbWhite]; + pub fn label(self) -> &'static str { + match self { + ParadeType::Rgb => "RGB", + ParadeType::Yuv => "YUV", + ParadeType::RgbWhite => "RGB and luma", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// The scopes' color space (the Y'CbCr matrix; Rec. 2100 also means an HDR signal). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ColorSpace { + /// Follow the source: Rec. 2100 for an HDR working space, else Rec. 709. + #[default] + Auto, + Rec601, + Rec709, + Rec2100, +} + +impl ColorSpace { + pub const ALL: [ColorSpace; 4] = [ColorSpace::Auto, ColorSpace::Rec601, ColorSpace::Rec709, ColorSpace::Rec2100]; + pub fn label(self) -> &'static str { + match self { + ColorSpace::Auto => "Automatic", + ColorSpace::Rec601 => "Rec. 601", + ColorSpace::Rec709 => "Rec. 709", + ColorSpace::Rec2100 => "Rec. 2100", + } + } + /// `Auto` resolved for a source (`hdr`: its working space is PQ or HLG). + pub fn resolve(self, hdr: bool) -> ColorSpace { + match self { + ColorSpace::Auto if hdr => ColorSpace::Rec2100, + ColorSpace::Auto => ColorSpace::Rec709, + c => c, + } + } + pub fn matrix(self) -> Matrix { + match self { + ColorSpace::Rec601 => Matrix::Bt601, + ColorSpace::Rec2100 => Matrix::Bt2020Ncl, + _ => Matrix::Bt709, + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n || norm(k.label()).trim_start_matches("rec") == n) + } +} + +/// Signal scale (the bit-depth choice): the labels of the levels axis. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Scale { + /// 0–255 code values. + #[default] + Bits8, + /// 0.0–1.0. + Float, + /// cd/m² on a PQ axis (0–10 000). + Hdr, +} + +impl Scale { + pub const ALL: [Scale; 3] = [Scale::Bits8, Scale::Float, Scale::Hdr]; + pub fn label(self) -> &'static str { + match self { + Scale::Bits8 => "8-bit", + Scale::Float => "Float", + Scale::Hdr => "HDR", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// Trace brightness. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Brightness { + Dimmed, + #[default] + Normal, + Bright, +} + +impl Brightness { + pub const ALL: [Brightness; 3] = [Brightness::Dimmed, Brightness::Normal, Brightness::Bright]; + pub fn label(self) -> &'static str { + match self { + Brightness::Dimmed => "Dimmed", + Brightness::Normal => "Normal", + Brightness::Bright => "Bright", + } + } + /// Multiplier of the trace intensity. + pub fn gain(self) -> f32 { + match self { + Brightness::Dimmed => 0.55, + Brightness::Normal => 1.0, + Brightness::Bright => 1.6, + } + } +} + +/// Which color-bar targets the YUV vectorscope draws. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Targets { + #[default] + #[serde(rename = "75")] + Percent75, + #[serde(rename = "100")] + Percent100, +} + +impl Targets { + pub fn amplitude(self) -> f32 { + match self { + Targets::Percent75 => 0.75, + Targets::Percent100 => 1.0, + } + } + pub fn label(self) -> &'static str { + match self { + Targets::Percent75 => "75%", + Targets::Percent100 => "100%", + } + } +} + +/// How scopes are computed. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Params { + pub matrix: Matrix, + /// Clamping: values are clamped to 0..1 before they are plotted. + pub clamp: bool, + /// Waveform and parade levels (2..=[`MAX_ROWS`]). + pub rows: usize, + /// Vectorscope grid size (square; 3..=[`MAX_VECTOR_SIZE`]). An even size is rounded up to the + /// next odd one, so the center is a cell. + pub vector_size: usize, + /// The traces [`compute`] draws for [`ScopeKind::Waveform`]. + pub waveform: WaveformType, + /// The traces [`compute`] draws for [`ScopeKind::Parade`]. + pub parade: ParadeType, +} + +impl Default for Params { + fn default() -> Self { + Params { matrix: Matrix::Bt709, clamp: true, rows: 256, vector_size: 255, waveform: WaveformType::Rgb, parade: ParadeType::Rgb } + } +} + +impl Params { + /// The plotted value range of waveform rows. + pub fn range(&self) -> (f32, f32) { + if self.clamp { (0.0, 1.0) } else { (-0.1, 1.1) } + } + fn rows(&self) -> usize { + self.rows.clamp(2, MAX_ROWS) + } + fn vector_size(&self) -> usize { + (self.vector_size.clamp(3, MAX_VECTOR_SIZE) | 1).min(MAX_VECTOR_SIZE) + } +} + +// ------------------------------------------------------------------------------------ signal + +/// A frame's R'G'B' samples (decimated), row-major: `rgb[y * w + x]`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Signal { + pub w: usize, + pub h: usize, + pub rgb: Vec<[f32; 3]>, +} + +/// Decimation steps for a `w × h` frame read into at most `max_w × max_h` samples (each capped to +/// [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]). +fn steps(w: usize, h: usize, max_w: usize, max_h: usize) -> (usize, usize) { + let (max_w, max_h) = (max_w.clamp(1, MAX_SIGNAL_W), max_h.clamp(1, MAX_SIGNAL_H)); + (w.div_ceil(max_w).max(1), h.div_ceil(max_h).max(1)) +} + +impl Signal { + /// From tightly packed RGBA8 (code / 255), decimated to [`MAX_W`] × [`MAX_H`]. A buffer + /// shorter than `w * h * 4` gives an empty signal. + pub fn from_rgba8(w: usize, h: usize, px: &[u8]) -> Signal { + Self::from_rgba8_max(w, h, px, MAX_W, MAX_H) + } + + pub fn from_rgba8_max(w: usize, h: usize, px: &[u8], max_w: usize, max_h: usize) -> Signal { + let mut s = Signal::default(); + let Some(stride) = w.checked_mul(4) else { return s }; + if s.fill_max(&Frame::Rgba8 { width: w, height: h, stride, data: px }, max_w, max_h).is_err() { + s.clear(); + } + s + } + + /// Reads `frame` into this signal, decimated to [`MAX_W`] × [`MAX_H`], reusing its buffer. + pub fn fill(&mut self, frame: &Frame<'_>) -> Result<(), FrameError> { + self.fill_max(frame, MAX_W, MAX_H) + } + + /// Reads `frame` into this signal, decimated to at most `max_w` × `max_h` samples (never more + /// than [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]). The buffer is reused, so the call does not + /// allocate once it has held a frame this size. On an error the signal is left empty. + pub fn fill_max(&mut self, frame: &Frame<'_>, max_w: usize, max_h: usize) -> Result<(), FrameError> { + self.clear(); + frame.validate()?; + let (w, h) = (frame.width(), frame.height()); + if w == 0 || h == 0 { + return Ok(()); + } + let (sx, sy) = steps(w, h, max_w, max_h); + let (ow, oh) = (w.div_ceil(sx), h.div_ceil(sy)); + self.rgb.reserve(ow.saturating_mul(oh)); + match *frame { + Frame::Rgba8 { stride, data, .. } => { + let lut: [f32; 256] = std::array::from_fn(|i| i as f32 / 255.0); + for y in (0..h).step_by(sy) { + let row = data.get(y * stride..).unwrap_or(&[]); + for x in (0..w).step_by(sx) { + let c = match row.get(x * 4..x * 4 + 3) { + Some(&[r, g, b]) => [lut[r as usize], lut[g as usize], lut[b as usize]], + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + } + Frame::Nv12 { y: yp, y_stride, uv, uv_stride, matrix, range, .. } => { + let ylut: [f32; 256] = std::array::from_fn(|i| normalize_y(i as u32, 8, range).unwrap_or(0.0)); + let clut: [f32; 256] = std::array::from_fn(|i| normalize_c(i as u32, 8, range).unwrap_or(0.0)); + for y in (0..h).step_by(sy) { + let yrow = yp.get(y * y_stride..).unwrap_or(&[]); + let crow = uv.get((y / 2) * uv_stride..).unwrap_or(&[]); + for x in (0..w).step_by(sx) { + let c = match (yrow.get(x), crow.get((x / 2) * 2..(x / 2) * 2 + 2)) { + (Some(&l), Some(&[cb, cr])) => ycbcr_to_rgb(ylut[l as usize], clut[cb as usize], clut[cr as usize], matrix), + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + } + } + self.w = ow; + self.h = oh; + Ok(()) + } + + /// From tightly packed RGBA f32 pixels through `map` (for example linear light to PQ code + /// values), decimated. A buffer shorter than `w * h * 4` gives an empty signal. + pub fn from_rgba_f32_with(w: usize, h: usize, px: &[f32], max_w: usize, max_h: usize, map: impl Fn([f32; 4]) -> [f32; 3]) -> Signal { + let mut s = Signal::default(); + s.fill_rgba_f32_with(w, h, px, max_w, max_h, map); + s + } + + /// [`Signal::from_rgba_f32_with`] into this signal, reusing its buffer. + pub fn fill_rgba_f32_with(&mut self, w: usize, h: usize, px: &[f32], max_w: usize, max_h: usize, map: impl Fn([f32; 4]) -> [f32; 3]) { + self.clear(); + let needed = w.checked_mul(h).and_then(|n| n.checked_mul(4)); + if w == 0 || h == 0 || needed.is_none_or(|n| px.len() < n) { + return; + } + let (sx, sy) = steps(w, h, max_w, max_h); + let (ow, oh) = (w.div_ceil(sx), h.div_ceil(sy)); + self.rgb.reserve(ow.saturating_mul(oh)); + for y in (0..h).step_by(sy) { + for x in (0..w).step_by(sx) { + let i = (y * w + x) * 4; + let c = match px.get(i..i + 4) { + Some(&[r, g, b, a]) => map([r, g, b, a]), + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + self.w = ow; + self.h = oh; + } + + /// A synthetic signal (tests, generated patterns), at most [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]: + /// a larger size is cut to that. + pub fn from_fn(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 3]) -> Signal { + let (w, h) = (w.min(MAX_SIGNAL_W), h.min(MAX_SIGNAL_H)); + let mut rgb = Vec::with_capacity(w * h); + for y in 0..h { + for x in 0..w { + rgb.push(f(x, y)); + } + } + Signal { w, h, rgb } + } + + /// Every sample through `f` (for example SDR code values to PQ for the HDR scale). + pub fn map(&self, f: impl Fn([f32; 3]) -> [f32; 3]) -> Signal { + Signal { w: self.w, h: self.h, rgb: self.rgb.iter().map(|c| f(*c)).collect() } + } + + /// Empties the signal and keeps its buffer. + pub fn clear(&mut self) { + self.w = 0; + self.h = 0; + self.rgb.clear(); + } + + pub fn len(&self) -> usize { + self.rgb.len() + } + pub fn is_empty(&self) -> bool { + self.rgb.is_empty() + } + + /// The rows of samples, each `w` long. A signal whose `w` and `rgb` disagree yields only + /// whole rows. + fn rows(&self) -> std::slice::ChunksExact<'_, [f32; 3]> { + self.rgb.chunks_exact(self.w.max(1)) + } + + /// Columns the grids of this signal have: `w`, or 0 when there are no samples. + fn cols(&self) -> usize { + if self.rgb.is_empty() { 0 } else { self.w.min(self.rgb.len()) } + } +} + +/// Linear light (1.0 = reference white = 203 cd/m², premultiplied RGBA) to PQ code values, for +/// HDR scopes: 0..1 on the axis is 0..10 000 cd/m². +pub fn linear_to_pq([r, g, b, a]: [f32; 4]) -> [f32; 3] { + let a = if a > 1e-6 { a } else { 1.0 }; + let white = craft_color::REFERENCE_WHITE_NITS as f32; + let f = |v: f32| craft_color::pq_inverse_eotf(((v / a).max(0.0) * white / 10_000.0).clamp(0.0, 1.0)); + [f(r), f(g), f(b)] +} + +/// An SDR code value (BT.1886, 100 cd/m² white) on the PQ axis (the HDR scale of an SDR frame). +pub fn sdr_to_pq(v: f32) -> f32 { + craft_color::pq_inverse_eotf((v.clamp(0.0, 1.0).powf(2.4) * 100.0 / 10_000.0).clamp(0.0, 1.0)) +} + +/// cd/m² to height on the PQ axis (0..1). +pub fn nits_to_pq(nits: f32) -> f32 { + craft_color::pq_inverse_eotf((nits / 10_000.0).clamp(0.0, 1.0)) +} + +// ------------------------------------------------------------------------------------ grids + +/// A count grid: `data[row * cols + col]`, row 0 = the lowest level. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Grid { + pub name: &'static str, + pub cols: usize, + pub rows: usize, + pub data: Vec, +} + +impl Grid { + pub fn new(name: &'static str, cols: usize, rows: usize) -> Grid { + let mut g = Grid::default(); + g.reset(name, cols, rows); + g + } + /// Zeroes the grid at a new size (at most [`MAX_SIGNAL_W`] columns and [`MAX_ROWS`] rows), + /// reusing its buffer. + pub fn reset(&mut self, name: &'static str, cols: usize, rows: usize) { + self.name = name; + self.cols = cols.min(MAX_SIGNAL_W); + self.rows = rows.min(MAX_ROWS); + self.data.clear(); + self.data.resize(self.cols * self.rows, 0); + } + /// The count of a cell (0 outside the grid). + pub fn at(&self, col: usize, row: usize) -> u32 { + if col >= self.cols || row >= self.rows { + return 0; + } + row.checked_mul(self.cols).and_then(|i| i.checked_add(col)).and_then(|i| self.data.get(i)).copied().unwrap_or(0) + } + pub fn total(&self) -> u64 { + self.data.iter().map(|&c| c as u64).sum() + } + pub fn max(&self) -> u32 { + self.data.iter().copied().max().unwrap_or(0) + } + /// The rows hit in a column, lowest first. + pub fn rows_in(&self, col: usize) -> Vec { + (0..self.rows).filter(|&r| self.at(col, r) > 0).collect() + } + #[inline] + fn hit(&mut self, col: usize, row: usize) { + if col >= self.cols || row >= self.rows { + return; + } + if let Some(c) = self.data.get_mut(row * self.cols + col) { + *c = c.saturating_add(1); + } + } +} + +/// Waveform or parade: one grid per trace, columns = the signal's width. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Waveform { + pub lo: f32, + pub hi: f32, + /// Levels of every trace. + pub rows: usize, + /// Samples per column (the signal's height). + pub per_column: usize, + pub traces: Vec, +} + +impl Waveform { + pub fn trace(&self, name: &str) -> Option<&Grid> { + self.traces.iter().find(|t| t.name == name) + } + /// The value at the center of a row. + pub fn level(&self, row: usize) -> f32 { + self.lo + (self.hi - self.lo) * row as f32 / (self.rows.max(2) - 1) as f32 + } +} + +/// Row of value `v` in `[lo, hi]` over `rows` levels (None outside, for NaN, or with fewer than +/// two rows or an empty range). +#[inline] +pub fn row_of(v: f32, lo: f32, hi: f32, rows: usize) -> Option { + if rows < 2 || hi <= lo { + return None; + } + let t = (v - lo) / (hi - lo); + if !(0.0..=1.0).contains(&t) { + return None; + } + Some(((t * (rows - 1) as f32).round() as usize).min(rows - 1)) +} + +/// Up to 4 (trace, value) pairs per sample. +type Hits = ([(u8, f32); 4], usize); + +fn build_into(s: &Signal, p: &Params, names: &[&'static str], out: &mut Waveform, sample: impl Fn([f32; 3]) -> Hits) { + let (lo, hi) = p.range(); + let rows = p.rows(); + let cols = s.cols(); + out.traces.truncate(names.len()); + while out.traces.len() < names.len() { + out.traces.push(Grid::default()); + } + for (g, &name) in out.traces.iter_mut().zip(names) { + g.reset(name, cols, rows); + } + let mut per_column = 0; + if cols > 0 { + for row in s.rows() { + per_column += 1; + for (x, &c) in row.iter().enumerate() { + let c = if p.clamp { c.map(|v| v.clamp(0.0, 1.0)) } else { c }; + let (hits, n) = sample(c); + for &(t, v) in hits.get(..n).unwrap_or(&[]) { + let v = if p.clamp { v.clamp(0.0, 1.0) } else { v }; + if let (Some(r), Some(g)) = (row_of(v, lo, hi, rows), out.traces.get_mut(t as usize)) { + g.hit(x, r); + } + } + } + } + } + out.lo = lo; + out.hi = hi; + out.rows = rows; + out.per_column = per_column; +} + +/// The waveform of a signal. +pub fn waveform(s: &Signal, kind: WaveformType, p: &Params) -> Waveform { + let mut w = Waveform::default(); + waveform_into(s, kind, p, &mut w); + w +} + +/// [`waveform`] into `out`, reusing its grids. +pub fn waveform_into(s: &Signal, kind: WaveformType, p: &Params, out: &mut Waveform) { + let m = p.matrix; + let z = (0u8, 0.0f32); + match kind { + WaveformType::Rgb => build_into(s, p, &["R", "G", "B"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), z], 3)), + WaveformType::Luma | WaveformType::YcNoChroma => build_into(s, p, &["Y"], out, |[r, g, b]| ([(0, rgb_to_ycbcr(r, g, b, m)[0]), z, z, z], 1)), + WaveformType::Yc => build_into(s, p, &["Y", "C"], out, |[r, g, b]| { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + let c = (cb * cb + cr * cr).sqrt(); + ([(0, y), (1, y + c), (1, y - c), z], if c > 1e-6 { 3 } else { 2 }) + }), + } +} + +/// The parade of a signal (the traces are drawn side by side). +pub fn parade(s: &Signal, kind: ParadeType, p: &Params) -> Waveform { + let mut w = Waveform::default(); + parade_into(s, kind, p, &mut w); + w +} + +/// [`parade`] into `out`, reusing its grids. +pub fn parade_into(s: &Signal, kind: ParadeType, p: &Params, out: &mut Waveform) { + let m = p.matrix; + let z = (0u8, 0.0f32); + match kind { + ParadeType::Rgb => build_into(s, p, &["R", "G", "B"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), z], 3)), + ParadeType::RgbWhite => { + build_into(s, p, &["R", "G", "B", "Y"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), (3, rgb_to_ycbcr(r, g, b, m)[0])], 4)) + } + ParadeType::Yuv => build_into(s, p, &["Y", "Cb", "Cr"], out, |[r, g, b]| { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + ([(0, y), (1, cb + 0.5), (2, cr + 0.5), z], 3) + }), + } +} + +// ------------------------------------------------------------------------------------ histogram + +/// 256-bin histograms of R', G', B' and Y'. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Histogram { + pub r: Vec, + pub g: Vec, + pub b: Vec, + pub y: Vec, + pub samples: u32, + /// Samples below 0 or above the top bin per channel (R, G, B, Y). With clamping they are + /// also counted in the first or last bin of an SDR histogram. + pub below: [u32; 4], + pub above: [u32; 4], + /// How an HDR histogram splits its bins; `None` for an SDR histogram. + #[serde(skip_serializing_if = "Option::is_none")] + pub hdr: Option, + /// HDR histograms: samples with any of R, G and B above SDR white (0 for SDR histograms). + pub above_sdr_samples: u32, +} + +pub const BINS: usize = 256; + +impl Histogram { + fn reset(&mut self, hdr: Option) { + for v in [&mut self.r, &mut self.g, &mut self.b, &mut self.y] { + v.clear(); + v.resize(BINS, 0); + } + self.samples = 0; + self.below = [0; 4]; + self.above = [0; 4]; + self.hdr = hdr; + self.above_sdr_samples = 0; + } + fn channel(&mut self, i: usize) -> &mut Vec { + match i { + 0 => &mut self.r, + 1 => &mut self.g, + 2 => &mut self.b, + _ => &mut self.y, + } + } + fn count(&mut self, i: usize, bin: usize) { + if let Some(c) = self.channel(i).get_mut(bin) { + *c = c.saturating_add(1); + } + } +} + +/// Bin of a value (None when outside 0..1). +#[inline] +pub fn bin_of(v: f32) -> Option { + if (0.0..=1.0 + 1e-6).contains(&v) { Some(((v * 255.0).round() as usize).min(BINS - 1)) } else { None } +} + +pub fn histogram(s: &Signal, p: &Params) -> Histogram { + let mut h = Histogram::default(); + histogram_into(s, p, &mut h); + h +} + +/// [`histogram`] into `out`, reusing its bins. +pub fn histogram_into(s: &Signal, p: &Params, out: &mut Histogram) { + out.reset(None); + out.samples = u32::try_from(s.len()).unwrap_or(u32::MAX); + for &[r, g, b] in &s.rgb { + let y = rgb_to_ycbcr(r, g, b, p.matrix)[0]; + // With clamping, the luma bin comes from the clamped R'G'B', as on the waveform; `below` + // and `above` count the luma of the sample as it is. + let y_bin = if p.clamp { + let [cr, cg, cb] = [r, g, b].map(|v| v.clamp(0.0, 1.0)); + rgb_to_ycbcr(cr, cg, cb, p.matrix)[0] + } else { + y + }; + for (i, (v, at)) in [(r, r), (g, g), (b, b), (y, y_bin)].into_iter().enumerate() { + if !v.is_nan() && bin_of(v).is_none() { + let side = if v < 0.0 { &mut out.below[i] } else { &mut out.above[i] }; + *side = side.saturating_add(1); + } + match bin_of(at) { + Some(k) => out.count(i, k), + None if at.is_nan() || !p.clamp => {} + None => out.count(i, if at < 0.0 { 0 } else { BINS - 1 }), + } + } + } +} + +/// The split of an HDR histogram: bins below `from` cover black to SDR white (sRGB-encoded, as an +/// SDR histogram), and bins `from..256` cover `0..stops` stops above SDR white in equal steps. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HdrBins { + pub from: usize, + pub stops: f32, +} + +impl HdrBins { + /// SDR takes the left half of the bins. + pub const DEFAULT_FROM: usize = BINS / 2; + + /// The default split reaching `stops` stops above SDR white. + pub fn new(stops: f32) -> HdrBins { + HdrBins { from: Self::DEFAULT_FROM, stops } + } + + /// The bin of a linear value (1 = SDR white; NaN and negatives count as black). Any `from` + /// and any `stops` give a bin inside the histogram. + pub fn bin(self, v: f32) -> usize { + let last = BINS - 1; + let from = self.from.clamp(2, last); + if v.is_nan() || v <= 0.0 { + return 0; + } + if v <= 1.0 { + let e = craft_color::linear_to_srgb(v); + return ((e * (from - 1) as f32 + 0.5) as usize).min(from - 1); + } + let t = (v.log2() / self.stops()).clamp(0.0, 1.0); + (from + (t * (last - from) as f32 + 0.5) as usize).min(last) + } + + fn stops(self) -> f32 { + if self.stops.is_finite() { self.stops.max(1e-3) } else { 1e-3 } + } + + /// The linear value the last bin reaches. + pub fn top(self) -> f32 { + self.stops().exp2() + } +} + +/// The HDR histogram of a signal of linear values (1 = SDR white): R, G, B and the luma of +/// `matrix`, split by `bins`. Negative values count in `below`, values past [`HdrBins::top`] in +/// `above`; both also land in the first or last bin. +pub fn histogram_hdr_into(linear: &Signal, matrix: Matrix, bins: HdrBins, out: &mut Histogram) { + out.reset(Some(bins)); + out.samples = u32::try_from(linear.len()).unwrap_or(u32::MAX); + let (kr, kb) = matrix.kr_kb(); + let top = bins.top(); + for &[r, g, b] in &linear.rgb { + if r > 1.0 || g > 1.0 || b > 1.0 { + out.above_sdr_samples = out.above_sdr_samples.saturating_add(1); + } + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + for (i, v) in [r, g, b, y].into_iter().enumerate() { + out.count(i, bins.bin(v)); + if v < 0.0 { + out.below[i] = out.below[i].saturating_add(1); + } else if v > top { + out.above[i] = out.above[i].saturating_add(1); + } + } + } +} + +/// Fraction of samples with any of R, G and B above SDR white (0 for SDR histograms). +pub fn above_sdr(h: &Histogram) -> f32 { + if h.hdr.is_none() || h.samples == 0 { + return 0.0; + } + (h.above_sdr_samples as f32 / h.samples as f32).min(1.0) +} + +// ------------------------------------------------------------------------------------ vectorscopes + +/// A vectorscope: `data[y * size + x]`, x = Cb (right = +), y = Cr (row 0 = top = +Cr). +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Vectorscope { + pub size: usize, + pub extent: f32, + pub data: Vec, + pub samples: u32, + /// Mean (Cb, Cr) of the plotted points. + pub mean: [f32; 2], + /// The matrix the points were plotted with; [`paint::vectorscope`] colors them with it. + pub matrix: Matrix, + /// Whether the points are HLS (hue as the angle from the matrix's red, saturation as the + /// radius) instead of (Cb, Cr). + pub hls: bool, +} + +/// Cell of a (Cb, Cr) point on a `size`² plane spanning ±`extent` (None outside, for NaN, or for a +/// plane under 2 cells or with no extent). +#[inline] +pub fn cell_of(cb: f32, cr: f32, size: usize, extent: f32) -> Option<(usize, usize)> { + if size < 2 || extent.is_nan() || extent <= 0.0 { + return None; + } + let n = (size - 1) as f32; + let fx = (cb / extent * 0.5 + 0.5) * n; + let fy = (0.5 - cr / extent * 0.5) * n; + if !(0.0..=n).contains(&fx) || !(0.0..=n).contains(&fy) { + return None; + } + Some((fx.round() as usize, fy.round() as usize)) +} + +impl Vectorscope { + fn reset(&mut self, size: usize, matrix: Matrix, hls: bool) { + self.size = size; + self.matrix = matrix; + self.hls = hls; + self.extent = VECTOR_EXTENT; + self.data.clear(); + self.data.resize(size.saturating_mul(size), 0); + self.samples = 0; + self.mean = [0.0; 2]; + } + /// The count of a cell (0 outside the plane). + pub fn at(&self, x: usize, y: usize) -> u32 { + if x >= self.size || y >= self.size { + return 0; + } + y.checked_mul(self.size).and_then(|i| i.checked_add(x)).and_then(|i| self.data.get(i)).copied().unwrap_or(0) + } + pub fn cell(&self, cb: f32, cr: f32) -> Option<(usize, usize)> { + cell_of(cb, cr, self.size, self.extent) + } + /// (Cb, Cr) at the center of a cell. + pub fn point(&self, x: usize, y: usize) -> [f32; 2] { + let n = self.size.saturating_sub(1).max(1) as f32; + [(x as f32 / n - 0.5) * 2.0 * self.extent, (0.5 - y as f32 / n) * 2.0 * self.extent] + } + #[inline] + fn plot(&mut self, cb: f32, cr: f32, sum: &mut [f64; 2]) { + if let Some((x, y)) = self.cell(cb, cr) + && let Some(c) = self.data.get_mut(y * self.size + x) + { + *c = c.saturating_add(1); + self.samples = self.samples.saturating_add(1); + sum[0] += cb as f64; + sum[1] += cr as f64; + } + } + fn finish(&mut self, sum: [f64; 2]) { + if self.samples > 0 { + self.mean = [(sum[0] / self.samples as f64) as f32, (sum[1] / self.samples as f64) as f32]; + } + } +} + +/// The YUV vectorscope (Cb, Cr of each sample). +pub fn vectorscope_yuv(s: &Signal, p: &Params) -> Vectorscope { + let mut v = Vectorscope::default(); + vectorscope_yuv_into(s, p, &mut v); + v +} + +/// [`vectorscope_yuv`] into `out`, reusing its plane. +pub fn vectorscope_yuv_into(s: &Signal, p: &Params, out: &mut Vectorscope) { + out.reset(p.vector_size(), p.matrix, false); + let mut sum = [0f64; 2]; + for &c in &s.rgb { + let [r, g, b] = if p.clamp { c.map(|x| x.clamp(0.0, 1.0)) } else { c }; + let [_, cb, cr] = rgb_to_ycbcr(r, g, b, p.matrix); + out.plot(cb, cr, &mut sum); + } + out.finish(sum); +} + +/// Angle (degrees, counter-clockwise from +Cb, 0..360) of a chroma point. +pub fn angle_deg(cb: f32, cr: f32) -> f32 { + cr.atan2(cb).to_degrees().rem_euclid(360.0) +} + +/// The angle of pure red on a matrix's vectorscope (BT.709 ≈ 103°): the HLS scope puts hue 0 there. +pub fn red_angle(m: Matrix) -> f32 { + let [_, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, m); + angle_deg(cb, cr) +} + +/// A sample's point on the HLS vectorscope: hue as the angle from red (counter-clockwise, red, +/// yellow, green, cyan, blue, magenta), HLS saturation as the radius (1 = 0.5). +pub fn hls_point([r, g, b]: [f32; 3], m: Matrix) -> [f32; 2] { + let [h, s, _] = craft_color::rgb_to_hsl(r, g, b); + let a = (red_angle(m) + h * 360.0).to_radians(); + let rad = s.clamp(0.0, 1.0) * 0.5; + [rad * a.cos(), rad * a.sin()] +} + +/// Hue steps of the HLS vectorscope's direction table (0.1°). +const HUE_STEPS: usize = 3600; + +/// The HLS vectorscope. +pub fn vectorscope_hls(s: &Signal, p: &Params) -> Vectorscope { + let mut v = Vectorscope::default(); + vectorscope_hls_into(s, p, &mut v); + v +} + +/// [`vectorscope_hls`] into `out`, reusing its plane. +pub fn vectorscope_hls_into(s: &Signal, p: &Params, out: &mut Vectorscope) { + out.reset(p.vector_size(), p.matrix, true); + let mut sum = [0f64; 2]; + // hue to unit direction, tabulated at 0.1° on the stack (trigonometry per sample is the slow part) + let red = red_angle(p.matrix); + let dirs: [[f32; 2]; HUE_STEPS + 1] = std::array::from_fn(|i| { + let a = (red + i as f32 / 10.0).to_radians(); + [a.cos(), a.sin()] + }); + for &c in &s.rgb { + let [r, g, b] = if p.clamp { c.map(|x| x.clamp(0.0, 1.0)) } else { c }; + let [h, sat, _] = craft_color::rgb_to_hsl(r, g, b); + let [dx, dy] = dirs.get(((h * HUE_STEPS as f32).round() as usize).min(HUE_STEPS)).copied().unwrap_or([1.0, 0.0]); + let rad = sat.clamp(0.0, 1.0) * 0.5; + out.plot(rad * dx, rad * dy, &mut sum); + } + out.finish(sum); +} + +/// A color-bar target of the YUV vectorscope. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct Target { + pub name: &'static str, + pub rgb: [f32; 3], + pub cb: f32, + pub cr: f32, +} + +/// The six color-bar targets (R, Mg, B, Cy, G, Yl) at `amplitude` (0.75 or 1.0). +pub fn targets(m: Matrix, amplitude: f32) -> [Target; 6] { + let a = amplitude; + let t = |name, rgb: [f32; 3]| { + let [_, cb, cr] = rgb_to_ycbcr(rgb[0], rgb[1], rgb[2], m); + Target { name, rgb, cb, cr } + }; + [t("R", [a, 0.0, 0.0]), t("Mg", [a, 0.0, a]), t("B", [0.0, 0.0, a]), t("Cy", [0.0, a, a]), t("G", [0.0, a, 0.0]), t("Yl", [a, a, 0.0])] +} + +/// Hue labels of the HLS vectorscope at radius 0.5: (name, Cb, Cr). +pub fn hls_targets(m: Matrix) -> [(&'static str, f32, f32); 6] { + let red = red_angle(m); + let at = |name, h: f32| { + let a = (red + h).to_radians(); + (name, 0.5 * a.cos(), 0.5 * a.sin()) + }; + [at("R", 0.0), at("Yl", 60.0), at("G", 120.0), at("Cy", 180.0), at("B", 240.0), at("Mg", 300.0)] +} + +// ------------------------------------------------------------------------------------ all scopes + +/// One computed scope. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum Computed { + Waveform(Waveform), + Parade(Waveform), + Histogram(Histogram), + Vectorscope(Vectorscope), +} + +impl Default for Computed { + fn default() -> Self { + Computed::Waveform(Waveform::default()) + } +} + +/// Compute one scope. +pub fn compute(kind: ScopeKind, s: &Signal, p: &Params) -> Computed { + let mut c = Computed::default(); + compute_into(kind, s, p, &mut c); + c +} + +/// [`compute`] into `out`. While `kind` stays the same, the buffers of the previous result are +/// reused. +pub fn compute_into(kind: ScopeKind, s: &Signal, p: &Params, out: &mut Computed) { + match (kind, &mut *out) { + (ScopeKind::Waveform, Computed::Waveform(w)) => waveform_into(s, p.waveform, p, w), + (ScopeKind::Parade, Computed::Parade(w)) => parade_into(s, p.parade, p, w), + (ScopeKind::Histogram, Computed::Histogram(h)) => histogram_into(s, p, h), + (ScopeKind::VectorscopeYuv, Computed::Vectorscope(v)) => vectorscope_yuv_into(s, p, v), + (ScopeKind::VectorscopeHls, Computed::Vectorscope(v)) => vectorscope_hls_into(s, p, v), + _ => { + // a different kind: move the old grids over where the shapes match + let old = std::mem::take(out); + *out = match (kind, old) { + (ScopeKind::Waveform, Computed::Parade(w)) => Computed::Waveform(w), + (ScopeKind::Parade, Computed::Waveform(w)) => Computed::Parade(w), + (ScopeKind::Waveform, _) => Computed::Waveform(Waveform::default()), + (ScopeKind::Parade, _) => Computed::Parade(Waveform::default()), + (ScopeKind::Histogram, _) => Computed::Histogram(Histogram::default()), + (ScopeKind::VectorscopeYuv | ScopeKind::VectorscopeHls, Computed::Vectorscope(v)) => Computed::Vectorscope(v), + (ScopeKind::VectorscopeYuv | ScopeKind::VectorscopeHls, _) => Computed::Vectorscope(Vectorscope::default()), + }; + compute_into(kind, s, p, out); + } + } +} diff --git a/crates/scopes/src/paint.rs b/crates/scopes/src/paint.rs new file mode 100644 index 0000000000..fff26ea9a2 --- /dev/null +++ b/crates/scopes/src/paint.rs @@ -0,0 +1,166 @@ +//! Count grids to pixels: the trace images a UI uploads as textures. +//! +//! A cell's intensity grows with the logarithm of its count relative to a reference count (a +//! "full" cell: a flat color puts a whole column of samples on one waveform cell), so sparse +//! detail stays visible next to flat areas, like a phosphor trace. Traces of several grids add +//! up (R + G + B traces that coincide read white). +//! +//! The `*_into` functions write into buffers the caller keeps ([`Scratch`] and the output `Vec`), +//! so painting the same size again does not allocate. + +use crate::{Grid, MAX_ROWS, MAX_SIGNAL_W, MAX_VECTOR_SIZE, Vectorscope}; + +/// Intensity 0..1 of a cell holding `count` samples (`reference` = a full cell, `gain` = the +/// Brightness setting). +#[inline] +pub fn intensity(count: u32, reference: f32, gain: f32) -> f32 { + if count == 0 { + return 0.0; + } + let r = (1.0 + reference.max(1.0)).ln(); + (gain * (0.12 + 0.88 * (1.0 + count as f32).ln() / r)).clamp(0.0, 1.0) +} + +/// Working buffers of the painters, kept between frames. +#[derive(Clone, Debug, Default)] +pub struct Scratch { + acc: Vec<[f32; 3]>, + level: Vec, + tint: Vec<[f32; 3]>, +} + +fn reset(v: &mut Vec, n: usize, value: T) { + v.clear(); + v.resize(n, value); +} + +/// Paint grids of equal size with colors (0..1 RGB), additively, into premultiplied RGBA8 with the +/// highest row at the top. Empty cells are transparent. Grids of another size than the first are +/// skipped. +pub fn grids(layers: &[(&Grid, [f32; 3])], reference: f32, gain: f32) -> (usize, usize, Vec) { + let mut out = Vec::new(); + let (w, h) = grids_into(layers, reference, gain, &mut Scratch::default(), &mut out); + (w, h, out) +} + +/// [`grids`] into `out` (resized to `w * h * 4`), returning `(w, h)`. A first grid wider than +/// [`MAX_SIGNAL_W`] or taller than [`MAX_ROWS`] paints nothing and gives `(0, 0)`. +pub fn grids_into(layers: &[(&Grid, [f32; 3])], reference: f32, gain: f32, scratch: &mut Scratch, out: &mut Vec) -> (usize, usize) { + let Some((first, _)) = layers.first().filter(|(g, _)| g.cols <= MAX_SIGNAL_W && g.rows <= MAX_ROWS) else { + out.clear(); + return (0, 0); + }; + let (w, h) = (first.cols, first.rows); + let n = w.saturating_mul(h); + reset(out, n.saturating_mul(4), 0u8); + reset(&mut scratch.acc, n, [0f32; 3]); + for (g, col) in layers { + if g.cols != w || g.rows != h || g.data.len() < n { + continue; + } + for (row, counts) in g.data.chunks_exact(w.max(1)).take(h).enumerate() { + let dst = (h - 1 - row) * w; + let Some(acc) = scratch.acc.get_mut(dst..dst + w) else { continue }; + for (a, &c) in acc.iter_mut().zip(counts) { + if c > 0 { + let i = intensity(c, reference, gain); + for k in 0..3 { + a[k] += col[k] * i; + } + } + } + } + } + for (o, a) in out.as_chunks_mut::<4>().0.iter_mut().zip(&scratch.acc) { + let m = a[0].max(a[1]).max(a[2]); + if m <= 0.0 { + continue; + } + o[0] = (a[0].min(1.0) * 255.0).round() as u8; + o[1] = (a[1].min(1.0) * 255.0).round() as u8; + o[2] = (a[2].min(1.0) * 255.0).round() as u8; + o[3] = (m.min(1.0) * 255.0).round() as u8; + } + (w, h) +} + +/// The reference count of a waveform cell: half a column. +pub fn waveform_reference(per_column: usize) -> f32 { + (per_column as f32 / 2.0).max(1.0) +} + +/// The 3 × 3 spread of a vectorscope point: (dy, dx, weight). +const SPREAD: [(i64, i64, f32); 9] = + [(0, 0, 1.0), (-1, 0, 0.6), (1, 0, 0.6), (0, -1, 0.6), (0, 1, 0.6), (-1, -1, 0.35), (-1, 1, 0.35), (1, -1, 0.35), (1, 1, 0.35)]; + +/// Paint a vectorscope: each point takes the color of its own position (hue = angle) when +/// `colorize`, else `col`, and spreads over its 3 × 3 neighborhood (falling off), so isolated +/// points stay visible when the scope is drawn smaller than its grid. Premultiplied RGBA8, row +/// 0 = +Cr. +pub fn vectorscope(v: &Vectorscope, col: [f32; 3], gain: f32, colorize: bool) -> (usize, usize, Vec) { + let mut out = Vec::new(); + let (w, h) = vectorscope_into(v, col, gain, colorize, &mut Scratch::default(), &mut out); + (w, h, out) +} + +/// [`vectorscope`] into `out` (resized to `size² * 4`), returning `(size, size)`. A vectorscope +/// larger than [`MAX_VECTOR_SIZE`] paints nothing and gives `(0, 0)`. +pub fn vectorscope_into(v: &Vectorscope, col: [f32; 3], gain: f32, colorize: bool, scratch: &mut Scratch, out: &mut Vec) -> (usize, usize) { + if v.size > MAX_VECTOR_SIZE { + out.clear(); + return (0, 0); + } + let n = v.size; + let cells = n.saturating_mul(n); + let reference = (v.samples as f32 / 64.0).max(1.0); + reset(&mut scratch.level, cells, 0f32); + reset(&mut scratch.tint, cells, [0f32; 3]); + for y in 0..n { + for x in 0..n { + let c = v.at(x, y); + if c == 0 { + continue; + } + let i = intensity(c, reference, gain); + let t = if colorize { + let [px, py] = v.point(x, y); + // the color at this point with mid lightness, desaturated towards white + let [r, g, b] = if v.hls { + let hue = ((crate::angle_deg(px, py) - crate::red_angle(v.matrix)) / 360.0).rem_euclid(1.0); + let sat = (px.hypot(py) / 0.5).clamp(0.0, 1.0); + craft_color::hsl_to_rgb(hue, sat * 0.8, 0.5) + } else { + craft_color::ycbcr_to_rgb(0.6, px * 0.8, py * 0.8, v.matrix) + }; + [0.55 + 0.45 * r.clamp(0.0, 1.0), 0.55 + 0.45 * g.clamp(0.0, 1.0), 0.55 + 0.45 * b.clamp(0.0, 1.0)] + } else { + col + }; + for (dy, dx, w) in SPREAD { + let (yy, xx) = (y as i64 + dy, x as i64 + dx); + if yy < 0 || xx < 0 || yy >= n as i64 || xx >= n as i64 { + continue; + } + let k = yy as usize * n + xx as usize; + if let (Some(l), Some(tk)) = (scratch.level.get_mut(k), scratch.tint.get_mut(k)) + && i * w > *l + { + *l = i * w; + *tk = t; + } + } + } + } + reset(out, cells.saturating_mul(4), 0u8); + for ((o, l), t) in out.as_chunks_mut::<4>().0.iter_mut().zip(&scratch.level).zip(&scratch.tint) { + if *l > 0.0 { + o.copy_from_slice(&[ + (t[0] * l * 255.0).round() as u8, + (t[1] * l * 255.0).round() as u8, + (t[2] * l * 255.0).round() as u8, + (l * 255.0).round() as u8, + ]); + } + } + (n, n) +} diff --git a/crates/scopes/src/summary.rs b/crates/scopes/src/summary.rs new file mode 100644 index 0000000000..a8c73d00a4 --- /dev/null +++ b/crates/scopes/src/summary.rs @@ -0,0 +1,199 @@ +//! Numeric summaries of scopes, for agents and control clients checking color without looking. +//! Levels are in percent of full scale (IRE-like: code value / 255 × 100 for 8-bit signals). + +use craft_color::rgb_to_ycbcr; +use serde::Serialize; + +use crate::{Grid, MAX_ROWS, MAX_SIGNAL_W, MAX_VECTOR_SIZE, Matrix, Signal, Vectorscope, Waveform, angle_deg, red_angle}; + +/// Minimum, maximum and mean of a set of levels (percent). +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct Level { + pub min: f64, + pub max: f64, + pub mean: f64, +} + +#[derive(Default)] +struct Acc { + min: f32, + max: f32, + sum: f64, + n: u64, +} + +impl Acc { + /// Adds `count` samples at `v`; NaN and infinite values are left out. + fn add(&mut self, v: f32, count: u64) { + if !v.is_finite() { + return; + } + if self.n == 0 { + self.min = v; + self.max = v; + } else { + self.min = self.min.min(v); + self.max = self.max.max(v); + } + self.sum += v as f64 * count as f64; + self.n += count; + } + fn level(&self) -> Option { + (self.n > 0).then(|| Level { min: round2(self.min), max: round2(self.max), mean: round2(self.sum / self.n as f64) }) + } +} + +/// Rounded to 0.01 (as f64, so JSON shows `78.43`, not the f32's `78.43000030517578`). +fn round2(v: impl Into) -> f64 { + (v.into() * 100.0).round() / 100.0 +} + +/// Per-channel levels of the signal itself (R', G', B', Y'), exact (not from grid cells). NaN and +/// infinite values are left out of every level and of the chroma mean. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelStats { + pub r: Level, + pub g: Level, + pub b: Level, + pub y: Level, + /// Mean chroma (Cb, Cr) in −50..50 and its angle and magnitude (percent of 0.5). + pub chroma_mean: [f64; 2], + pub hue_deg: f64, + pub saturation: f64, +} + +pub fn channel_stats(s: &Signal, m: Matrix) -> Option { + if s.is_empty() { + return None; + } + let mut acc: [Acc; 4] = Default::default(); + let (mut cb_sum, mut cr_sum, mut chroma_n) = (0f64, 0f64, 0u64); + for &[r, g, b] in &s.rgb { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + for (a, v) in acc.iter_mut().zip([r, g, b, y]) { + a.add(v * 100.0, 1); + } + if cb.is_finite() && cr.is_finite() { + cb_sum += cb as f64; + cr_sum += cr as f64; + chroma_n += 1; + } + } + let n = chroma_n.max(1) as f64; + let (cb, cr) = ((cb_sum / n) as f32, (cr_sum / n) as f32); + let [r, g, b, y] = &acc; + Some(ChannelStats { + r: r.level()?, + g: g.level()?, + b: b.level()?, + y: y.level()?, + chroma_mean: [round2(cb * 100.0), round2(cr * 100.0)], + hue_deg: round2(angle_deg(cb, cr)), + saturation: round2((cb * cb + cr * cr).sqrt() / 0.5 * 100.0), + }) +} + +/// A trace split into `buckets` column ranges, each with the levels its cells hold (None when a +/// range holds no samples). A grid wider than [`MAX_SIGNAL_W`] or taller than [`MAX_ROWS`] gives +/// no ranges. +pub fn trace_columns(w: &Waveform, g: &Grid, buckets: usize) -> Vec> { + if g.cols > MAX_SIGNAL_W || g.rows > MAX_ROWS { + return Vec::new(); + } + let buckets = buckets.clamp(1, g.cols.max(1)); + (0..buckets) + .map(|b| { + let (c0, c1) = (b * g.cols / buckets, ((b + 1) * g.cols / buckets).max(b * g.cols / buckets + 1).min(g.cols)); + let mut a = Acc::default(); + for col in c0..c1 { + for row in 0..g.rows { + let n = g.at(col, row); + if n > 0 { + a.add(w.level(row) * 100.0, n as u64); + } + } + } + a.level() + }) + .collect() +} + +/// A dense spot of a vectorscope. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Peak { + /// Cell coordinates on the scope's grid. + pub x: usize, + pub y: usize, + /// Cb, Cr at the cell center (percent: −50..50 is the nominal range). + pub cb: f64, + pub cr: f64, + /// Degrees counter-clockwise from +Cb; on an HLS scope, the hue (0 = red, 120 = green). + pub angle_deg: f64, + /// Distance from the center in percent of 0.5 (100 % red in BT.709 ≈ 102.6). + pub magnitude: f64, + /// Share of the plotted samples in this cell (0..1). + pub share: f64, +} + +/// The `n` densest cells holding at least `min_share` of the samples, densest first. A vectorscope +/// larger than [`MAX_VECTOR_SIZE`] gives no peaks. +pub fn peaks(v: &Vectorscope, n: usize, min_share: f32) -> Vec { + if v.size > MAX_VECTOR_SIZE { + return Vec::new(); + } + let total = v.samples.max(1) as f32; + let size = v.size.max(1); + // entries past the size² plane are not cells + let plane = v.size * v.size; + let mut cells: Vec<(u32, usize)> = v.data.iter().take(plane).enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| (*c, i)).collect(); + cells.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + cells + .into_iter() + .filter(|(c, _)| *c as f32 / total >= min_share) + .take(n) + .map(|(c, i)| { + let (x, y) = (i % size, i / size); + let [cb, cr] = v.point(x, y); + // the center cell has no hue + let angle = if v.hls && (cb, cr) != (0.0, 0.0) { + (angle_deg(cb, cr) - red_angle(v.matrix)).rem_euclid(360.0) + } else if v.hls { + 0.0 + } else { + angle_deg(cb, cr) + }; + Peak { + x, + y, + cb: round2(cb * 100.0), + cr: round2(cr * 100.0), + angle_deg: round2(angle), + magnitude: round2((cb * cb + cr * cr).sqrt() / 0.5 * 100.0), + share: (c as f64 / total as f64 * 10_000.0).round() / 10_000.0, + } + }) + .collect() +} + +/// Sparse cells of a vectorscope re-binned to `size`² (for a coarse numeric picture): `[x, y, count]`. +/// A vectorscope larger than [`MAX_VECTOR_SIZE`] gives no cells. +pub fn coarse(v: &Vectorscope, size: usize) -> Vec<[u32; 3]> { + if v.size > MAX_VECTOR_SIZE { + return Vec::new(); + } + let size = size.clamp(1, v.size.max(1)); + let mut out = vec![0u32; size * size]; + for y in 0..v.size { + for x in 0..v.size { + let c = v.at(x, y); + if c > 0 + && let Some(cell) = out.get_mut((y * size / v.size) * size + x * size / v.size) + { + *cell = cell.saturating_add(c); + } + } + } + out.iter().enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| [(i % size) as u32, (i / size) as u32, *c]).collect() +} diff --git a/crates/scopes/src/tests.rs b/crates/scopes/src/tests.rs new file mode 100644 index 0000000000..747ceaa5e8 --- /dev/null +++ b/crates/scopes/src/tests.rs @@ -0,0 +1,670 @@ +//! Scope math on generated frames with known values. + +use crate::*; +use craft_color::rgb_to_ycbcr; + +fn rgba8(w: usize, h: usize, mut f: impl FnMut(usize, usize) -> [u8; 3]) -> Vec { + let mut px = Vec::with_capacity(w * h * 4); + for y in 0..h { + for x in 0..w { + let [r, g, b] = f(x, y); + px.extend_from_slice(&[r, g, b, 255]); + } + } + px +} + +fn solid(w: usize, h: usize, c: [u8; 3]) -> Signal { + Signal::from_rgba8(w, h, &rgba8(w, h, |_, _| c)) +} + +/// 75 % color bars (code 191): white, yellow, cyan, green, magenta, red, blue, black; 32 px each. +const BAR: u8 = 191; +const BARS: [[u8; 3]; 8] = [[BAR, BAR, BAR], [BAR, BAR, 0], [0, BAR, BAR], [0, BAR, 0], [BAR, 0, BAR], [BAR, 0, 0], [0, 0, BAR], [0, 0, 0]]; + +fn bars() -> Signal { + Signal::from_rgba8(256, 16, &rgba8(256, 16, |x, _| BARS[x / 32])) +} + +fn code(v: u8) -> f32 { + v as f32 / 255.0 +} + +#[test] +fn single_color_lands_in_exact_histogram_bins() { + let s = solid(64, 36, [200, 100, 50]); + let n = 64 * 36; + let h = histogram(&s, &Params::default()); + assert_eq!(h.samples, n); + assert_eq!((h.r[200], h.g[100], h.b[50]), (n, n, n)); + assert_eq!(h.r.iter().sum::(), n); + let y = rgb_to_ycbcr(code(200), code(100), code(50), Matrix::Bt709)[0]; + assert_eq!(h.y[(y * 255.0).round() as usize], n); + assert_eq!((h.below, h.above, h.hdr), ([0; 4], [0; 4], None)); +} + +#[test] +fn ramp_fills_every_bin_and_waveform_row_equals_code_value() { + let s = Signal::from_rgba8(256, 10, &rgba8(256, 10, |x, _| [x as u8; 3])); + let p = Params::default(); + let h = histogram(&s, &p); + for k in 0..256 { + assert_eq!((h.r[k], h.g[k], h.b[k], h.y[k]), (10, 10, 10, 10), "bin {k}"); + } + for kind in [WaveformType::Luma, WaveformType::YcNoChroma] { + let w = waveform(&s, kind, &p); + let y = w.trace("Y").unwrap(); + for x in 0..256 { + assert_eq!(y.rows_in(x), vec![x], "{kind:?} column {x}"); + assert_eq!(y.at(x, x), 10); + } + } + let w = waveform(&s, WaveformType::Rgb, &p); + assert_eq!(w.traces.len(), 3); + for t in &w.traces { + assert!((0..256).all(|x| t.rows_in(x) == vec![x]), "{}", t.name); + } +} + +#[test] +fn color_bars_parade_levels_and_vectorscope_targets() { + let s = bars(); + let p = Params::default(); + // RGB parade: every bar column holds its channel's code value exactly + let par = parade(&s, ParadeType::Rgb, &p); + for (ch, name) in ["R", "G", "B"].iter().enumerate() { + let t = par.trace(name).unwrap(); + for (i, bar) in BARS.iter().enumerate() { + for x in i * 32..(i + 1) * 32 { + assert_eq!(t.rows_in(x), vec![bar[ch] as usize], "{name} bar {i}"); + assert_eq!(t.at(x, bar[ch] as usize), 16); + } + } + } + // RGB-White adds the luma trace; YUV has Y, Cb, Cr + assert_eq!(parade(&s, ParadeType::RgbWhite, &p).traces.iter().map(|t| t.name).collect::>(), ["R", "G", "B", "Y"]); + assert_eq!(parade(&s, ParadeType::Yuv, &p).traces.iter().map(|t| t.name).collect::>(), ["Y", "Cb", "Cr"]); + // Vectorscope: each colored bar on its 75 % target cell, white and black in the center + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let p = Params { matrix: m, ..Params::default() }; + let v = vectorscope_yuv(&s, &p); + assert_eq!(v.samples, 256 * 16); + let bar_samples = 32 * 16; + for t in targets(m, code(BAR)) { + let (x, y) = v.cell(t.cb, t.cr).unwrap(); + assert_eq!(v.at(x, y), bar_samples, "{m:?} {}", t.name); + } + let (cx, cy) = v.cell(0.0, 0.0).unwrap(); + assert_eq!(v.at(cx, cy), 2 * bar_samples); + // the densest spots: the center (two bars), then the six targets + let pk = summary::peaks(&v, 10, 0.01); + assert_eq!(pk.len(), 7); + assert_eq!((pk[0].x, pk[0].y, pk[0].share), (cx, cy, 0.25)); + assert!(pk[1..].iter().all(|k| k.share == 0.125)); + } +} + +#[test] +fn vectorscope_positions_of_primaries_are_known() { + let p = Params::default(); + // BT.709 red: Cb = −0.2126 / 1.8556 = −0.11457, Cr = 0.5 + let v = vectorscope_yuv(&solid(8, 8, [255, 0, 0]), &p); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.x, pk.y), (103, 21)); + assert_eq!((pk.share, v.samples), (1.0, 64)); + assert!((red_angle(Matrix::Bt709) - 102.906).abs() < 0.01, "{}", red_angle(Matrix::Bt709)); + assert!((red_angle(Matrix::Bt601) - 108.645).abs() < 0.01, "{}", red_angle(Matrix::Bt601)); + // the mean chroma of a flat color is its own + let [_, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, Matrix::Bt709); + assert!((v.mean[0] - cb).abs() < 1e-6 && (v.mean[1] - cr).abs() < 1e-6); + // greys sit in the center for every matrix + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let v = vectorscope_yuv(&solid(4, 4, [77, 77, 77]), &Params { matrix: m, ..p }); + assert_eq!(v.at(127, 127), 16, "{m:?}"); + } + // the skin-tone line sits between red and yellow + let yl = targets(Matrix::Bt709, 1.0)[5]; + assert!(red_angle(Matrix::Bt709) < SKIN_TONE_DEG && SKIN_TONE_DEG < angle_deg(yl.cb, yl.cr)); +} + +#[test] +fn hls_vectorscope_puts_hue_on_the_angle_and_saturation_on_the_radius() { + let p = Params::default(); + let red = red_angle(p.matrix); + for (rgb, hue) in + [([255, 0, 0], 0.0f32), ([255, 255, 0], 60.0), ([0, 255, 0], 120.0), ([0, 255, 255], 180.0), ([0, 0, 255], 240.0), ([255, 0, 255], 300.0)] + { + let v = vectorscope_hls(&solid(4, 4, rgb), &p); + let a = (red + hue).to_radians(); + let want = cell_of(0.5 * a.cos(), 0.5 * a.sin(), p.vector_size, VECTOR_EXTENT).unwrap(); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.x, pk.y), want, "{rgb:?}"); + assert!((pk.magnitude - 100.0).abs() < 0.6, "{rgb:?} {}", pk.magnitude); + // the per-sample helper agrees with the tabulated scope + let [cb, cr] = hls_point(rgb.map(code), p.matrix); + assert_eq!(cell_of(cb, cr, p.vector_size, VECTOR_EXTENT), Some(want), "{rgb:?}"); + } + // half-saturated red (HSL s = 0.5) at half the radius; grey in the center + let v = vectorscope_hls(&solid(4, 4, [191, 64, 64]), &p); + let pk = summary::peaks(&v, 1, 0.0)[0]; + let hue_off = pk.angle_deg.min(360.0 - pk.angle_deg); + assert!((pk.magnitude - 50.0).abs() < 1.0 && hue_off < 0.5, "{pk:?}"); + let v = vectorscope_hls(&solid(4, 4, [90, 90, 90]), &p); + assert_eq!(v.at(127, 127), 16); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.angle_deg, pk.magnitude), (0.0, 0.0), "{pk:?}"); + // Clamp Signal off: an over-range sample keeps its own hue + let over = Signal::from_fn(1, 1, |_, _| [1.2, 0.5, 0.0]); + let inside = Signal::from_fn(1, 1, |_, _| [1.0, 0.5, 0.0]); + let off = Params { clamp: false, ..p }; + let peak = |s: &Signal, p: &Params| summary::peaks(&vectorscope_hls(s, p), 1, 0.0)[0]; + assert_ne!((peak(&over, &off).x, peak(&over, &off).y), (peak(&inside, &off).x, peak(&inside, &off).y)); + assert_eq!((peak(&over, &p).x, peak(&over, &p).y), (peak(&inside, &p).x, peak(&inside, &p).y)); +} + +#[test] +fn yc_waveform_draws_chroma_around_luma() { + let p = Params::default(); + let w = waveform(&solid(4, 4, [128, 128, 128]), WaveformType::Yc, &p); + assert_eq!((w.trace("Y").unwrap().rows_in(0), w.trace("C").unwrap().rows_in(0)), (vec![128], vec![128])); + let w = waveform(&solid(4, 4, [255, 0, 0]), WaveformType::Yc, &p); + let [y, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, Matrix::Bt709); + let c = (cb * cb + cr * cr).sqrt(); + let row = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize; + assert_eq!(w.trace("Y").unwrap().rows_in(2), vec![row(y)]); + assert_eq!(w.trace("C").unwrap().rows_in(2), vec![row(y - c), row(y + c)]); +} + +#[test] +fn yuv_parade_offsets_chroma_to_mid_scale() { + let w = parade(&solid(4, 4, [128, 128, 128]), ParadeType::Yuv, &Params::default()); + assert_eq!(w.trace("Y").unwrap().rows_in(0), vec![128]); + assert_eq!(w.trace("Cb").unwrap().rows_in(0), vec![128]); + assert_eq!(w.trace("Cr").unwrap().rows_in(0), vec![128]); +} + +#[test] +fn decimation_keeps_whole_samples() { + let px = rgba8(1920, 1080, |x, y| [(x % 256) as u8, (y % 256) as u8, 7]); + let s = Signal::from_rgba8(1920, 1080, &px); + assert_eq!((s.w, s.h), (480, 270)); + assert_eq!(s.rgb[1], [code(4), 0.0, code(7)]); + assert_eq!(s.rgb[480], [0.0, code(4), code(7)]); + let s = Signal::from_rgba8(1921, 9, &rgba8(1921, 9, |_, _| [1, 2, 3])); + assert_eq!((s.w, s.h), (385, 9)); + assert!(Signal::from_rgba8(10, 10, &[0; 12]).is_empty()); +} + +#[test] +fn clamp_signal_controls_out_of_range_values() { + let s = Signal::from_fn(4, 4, |x, _| if x < 2 { [1.2, 0.5, -0.05] } else { [0.5, 0.5, 0.5] }); + let on = Params::default(); + let off = Params { clamp: false, ..on }; + let h = histogram(&s, &on); + assert_eq!((h.r[255], h.above[0], h.b[0], h.below[2]), (8, 8, 8, 8)); + let h = histogram(&s, &off); + assert_eq!((h.r[255], h.above[0], h.b[0], h.below[2]), (0, 8, 0, 8)); + // with clamping, the histogram's luma comes from the clamped R'G'B', as the waveform's does + let hot = Signal::from_fn(1, 1, |_, _| [2.0, -1.0, 0.0]); + let rows = waveform(&hot, WaveformType::Luma, &on).trace("Y").unwrap().rows_in(0); + let hh = histogram(&hot, &on); + assert_eq!(hh.y.iter().position(|&c| c > 0), rows.first().copied()); + // and the luma of the sample as it is still counts as out of range + assert_eq!((hh.below[3], hh.above[3]), (1, 0)); + let white = histogram(&Signal::from_fn(1, 1, |_, _| [2.0; 3]), &on); + assert_eq!((white.y[255], white.above[3]), (1, 1)); + // waveform: clamped onto the top row, or plotted above 100 % within −10..110 + let w = waveform(&s, WaveformType::Rgb, &on); + assert_eq!(w.trace("R").unwrap().rows_in(0), vec![255]); + let w = waveform(&s, WaveformType::Rgb, &off); + assert_eq!((w.lo, w.hi), (-0.1, 1.1)); + assert!(w.trace("R").unwrap().rows_in(0).is_empty(), "1.2 is outside −10..110"); + let r = w.trace("B").unwrap().rows_in(0); + assert_eq!(r, vec![row_of(-0.05, -0.1, 1.1, 256).unwrap()]); +} + +#[test] +fn hdr_axis_helpers() { + assert!(nits_to_pq(0.0) < 1e-5); + assert!((nits_to_pq(10_000.0) - 1.0).abs() < 1e-6); + // reference white (203 cd/m²) ≈ 58 % of the PQ range (BT.2408) + let w = linear_to_pq([1.0, 1.0, 1.0, 1.0])[0]; + assert!((w - nits_to_pq(203.0)).abs() < 1e-6 && (w - 0.58).abs() < 0.01, "{w}"); + // premultiplied: half-covered white is still white + assert!((linear_to_pq([0.5, 0.5, 0.5, 0.5])[0] - w).abs() < 1e-6); + assert!((sdr_to_pq(1.0) - nits_to_pq(100.0)).abs() < 1e-6); +} + +#[test] +fn nan_and_empty_signals_do_not_panic() { + let s = Signal::from_fn(3, 3, |x, _| if x == 1 { [f32::NAN; 3] } else { [0.5; 3] }); + for clamp in [true, false] { + let p = Params { clamp, ..Params::default() }; + for k in ScopeKind::ALL { + let _ = compute(k, &s, &Params { waveform: WaveformType::Yc, parade: ParadeType::RgbWhite, ..p }); + let _ = compute(k, &Signal::default(), &p); + } + } + assert!(summary::channel_stats(&Signal::default(), Matrix::Bt709).is_none()); + // NaN and infinite samples are left out of the levels, so every number stays finite + let st = summary::channel_stats(&s, Matrix::Bt709).unwrap(); + assert_eq!((st.r.min, st.r.max, st.r.mean, st.y.mean), (50.0, 50.0, 50.0, 50.0)); + assert!(st.chroma_mean.iter().all(|v| v.is_finite()) && st.saturation.is_finite()); + let inf = Signal::from_fn(2, 1, |x, _| if x == 0 { [f32::INFINITY, 0.25, 0.25] } else { [0.25; 3] }); + let st = summary::channel_stats(&inf, Matrix::Bt709).unwrap(); + assert_eq!((st.r.max, st.g.mean), (25.0, 25.0)); + assert!(summary::channel_stats(&Signal::from_fn(1, 1, |_, _| [f32::NAN; 3]), Matrix::Bt709).is_none()); +} + +#[test] +fn summaries_report_levels_in_percent() { + let s = solid(8, 8, [200, 100, 50]); + let st = summary::channel_stats(&s, Matrix::Bt709).unwrap(); + assert_eq!((st.r.mean, st.g.mean, st.b.mean), (78.43, 39.22, 19.61)); + assert_eq!((st.r.min, st.r.max), (78.43, 78.43)); + // a two-level frame: left half black, right half white + let s = Signal::from_rgba8(100, 4, &rgba8(100, 4, |x, _| if x < 50 { [0; 3] } else { [255; 3] })); + let w = waveform(&s, WaveformType::Luma, &Params::default()); + let cols = summary::trace_columns(&w, w.trace("Y").unwrap(), 4); + assert_eq!(cols.len(), 4); + assert_eq!(cols[0].unwrap(), summary::Level { min: 0.0, max: 0.0, mean: 0.0 }); + assert_eq!(cols[3].unwrap(), summary::Level { min: 100.0, max: 100.0, mean: 100.0 }); + assert_eq!((cols[1].unwrap().max, cols[2].unwrap().min), (0.0, 100.0)); + let c = summary::coarse(&vectorscope_yuv(&bars(), &Params::default()), 16); + assert_eq!(c.iter().map(|e| e[2]).sum::(), 256 * 16); +} + +#[test] +fn paint_adds_traces_and_leaves_empty_cells_transparent() { + let s = solid(4, 8, [128, 128, 128]); + let w = waveform(&s, WaveformType::Rgb, &Params::default()); + let layers: Vec<(&Grid, [f32; 3])> = w.traces.iter().zip([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]).collect(); + let (pw, ph, px) = paint::grids(&layers, paint::waveform_reference(w.per_column), 1.0); + assert_eq!((pw, ph, px.len()), (4, 256, 4 * 256 * 4)); + // row 128 from the bottom = image row 127; R+G+B coincide → white + let i = (127 * 4) * 4; + assert_eq!(&px[i..i + 4], &[255, 255, 255, 255]); + assert_eq!(&px[0..4], &[0, 0, 0, 0]); + // dimmed is darker than bright + assert!(paint::intensity(3, 100.0, Brightness::Dimmed.gain()) < paint::intensity(3, 100.0, Brightness::Bright.gain())); + let v = vectorscope_yuv(&bars(), &Params::default()); + let (n, _, vp) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + assert_eq!(vp.len(), n * n * 4); + // seven spots of 3 × 3 texels each (none touch) + assert_eq!(vp.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).count(), 7 * 9); +} + +#[test] +fn names_round_trip() { + for k in ScopeKind::ALL { + assert_eq!(ScopeKind::from_name(k.name()), Some(k)); + assert_eq!(ScopeKind::from_name(k.label()), Some(k)); + assert_eq!(serde_json::to_value(k).unwrap(), serde_json::Value::from(k.name())); + } + assert_eq!(ScopeKind::from_name("vectorscope"), Some(ScopeKind::VectorscopeYuv)); + assert_eq!(WaveformType::from_name("Luma and chroma, chroma hidden"), Some(WaveformType::YcNoChroma)); + assert_eq!(WaveformType::from_name("ycNoChroma"), Some(WaveformType::YcNoChroma)); + assert_eq!(ParadeType::from_name("rgb and luma"), Some(ParadeType::RgbWhite)); + assert_eq!(ColorSpace::from_name("709"), Some(ColorSpace::Rec709)); + assert_eq!(ColorSpace::from_name("Rec. 2100"), Some(ColorSpace::Rec2100)); + assert_eq!(Scale::from_name("8 bit"), Some(Scale::Bits8)); + assert_eq!(serde_json::to_value(Targets::Percent100).unwrap(), serde_json::Value::from("100")); + assert_eq!(ColorSpace::Auto.resolve(true), ColorSpace::Rec2100); + assert_eq!(ColorSpace::Auto.resolve(false).matrix(), Matrix::Bt709); +} + +// ------------------------------------------------------------------------------------ frames + +/// An NV12 frame of `w × h` with every pixel at one (Y', Cb, Cr) code value, `pad` spare bytes at +/// the end of each row of both planes. +fn nv12(w: usize, h: usize, pad: usize, [y, cb, cr]: [u8; 3]) -> (Vec, usize, Vec, usize) { + let ys = w + pad; + let cs = w.div_ceil(2) * 2 + pad; + let mut yp = vec![0xEE; ys * h]; + let mut uv = vec![0xEE; cs * h.div_ceil(2)]; + for row in yp.chunks_mut(ys) { + row[..w].fill(y); + } + for row in uv.chunks_mut(cs) { + for pair in row[..w.div_ceil(2) * 2].chunks_mut(2) { + pair.copy_from_slice(&[cb, cr]); + } + } + (yp, ys, uv, cs) +} + +fn read_nv12(w: usize, h: usize, pad: usize, ycc: [u8; 3], matrix: Matrix, range: Range) -> Signal { + let (y, y_stride, uv, uv_stride) = nv12(w, h, pad, ycc); + let mut s = Signal::default(); + s.fill(&Frame::Nv12 { width: w, height: h, y: &y, y_stride, uv: &uv, uv_stride, matrix, range }).unwrap(); + s +} + +/// 8-bit limited-range BT.709 code values of the 100 % color bars (SMPTE RP 219-1, table 1; +/// the Y'CbCr equations of ITU-R BT.709-6 item 3), decoded back to R'G'B'. +#[test] +fn nv12_bt709_limited_bars_decode_to_their_rgb() { + let bars: [([u8; 3], [f32; 3]); 8] = [ + ([235, 128, 128], [1.0, 1.0, 1.0]), + ([219, 16, 138], [1.0, 1.0, 0.0]), + ([188, 154, 16], [0.0, 1.0, 1.0]), + ([173, 42, 26], [0.0, 1.0, 0.0]), + ([78, 214, 230], [1.0, 0.0, 1.0]), + ([63, 102, 240], [1.0, 0.0, 0.0]), + ([32, 240, 118], [0.0, 0.0, 1.0]), + ([16, 128, 128], [0.0, 0.0, 0.0]), + ]; + for (ycc, want) in bars { + let s = read_nv12(6, 4, 0, ycc, Matrix::Bt709, Range::Limited); + assert_eq!((s.w, s.h, s.len()), (6, 4, 24)); + for got in &s.rgb { + for k in 0..3 { + // the published code values are rounded to whole codes: within 1.5 codes of 255 + assert!((got[k] - want[k]).abs() < 1.5 / 255.0, "{ycc:?}: {got:?} vs {want:?}"); + } + } + } +} + +#[test] +fn nv12_full_range_and_odd_sizes() { + // full range: Y' 255 with neutral chroma is white, Y' 0 is black + let s = read_nv12(5, 3, 3, [255, 128, 128], Matrix::Bt601, Range::Full); + assert_eq!((s.w, s.h), (5, 3)); + assert!(s.rgb.iter().all(|c| c.iter().all(|v| (v - 1.0).abs() < 0.01)), "{:?}", s.rgb[0]); + let s = read_nv12(1, 1, 0, [0, 128, 128], Matrix::Bt601, Range::Full); + assert!(s.rgb[0].iter().all(|v| v.abs() < 0.01), "{:?}", s.rgb[0]); + // a grey NV12 frame and the same grey as RGBA8 give the same histogram luma bin + let s = read_nv12(7, 5, 1, [126, 128, 128], Matrix::Bt709, Range::Limited); + let h = histogram(&s, &Params::default()); + let grey = ((126.0 - 16.0) / 219.0 * 255.0f32).round() as usize; + assert_eq!(h.y[grey], 35); +} + +#[test] +fn rgba_with_a_stride_reads_the_same_samples_as_packed_rgba() { + let (w, h) = (9, 5); + let packed = rgba8(w, h, |x, y| [x as u8 * 20, y as u8 * 40, 3]); + let stride = w * 4 + 12; + let mut strided = vec![0xAB; stride * h]; + for y in 0..h { + strided[y * stride..y * stride + w * 4].copy_from_slice(&packed[y * w * 4..(y + 1) * w * 4]); + } + let mut s = Signal::default(); + s.fill(&Frame::Rgba8 { width: w, height: h, stride, data: &strided }).unwrap(); + assert_eq!(s, Signal::from_rgba8(w, h, &packed)); + // the last row needs only its own pixels, not a whole stride + s.fill(&Frame::Rgba8 { width: w, height: h, stride, data: &strided[..stride * (h - 1) + w * 4] }).unwrap(); + assert_eq!(s.len(), w * h); +} + +#[test] +fn bad_frames_give_errors_and_an_empty_signal() { + let px = [0u8; 64]; + let mut s = solid(2, 2, [1, 2, 3]); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: 4, stride: 8, data: &px }), Err(FrameError::Stride { plane: "RGBA", stride: 8, needed: 16 })); + assert!(s.is_empty()); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: 5, stride: 16, data: &px }), Err(FrameError::Short { plane: "RGBA", len: 64, needed: 80 })); + assert_eq!(s.fill(&Frame::Rgba8 { width: usize::MAX, height: 2, stride: 16, data: &px }), Err(FrameError::TooLarge)); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: usize::MAX, stride: usize::MAX / 2, data: &px }), Err(FrameError::TooLarge)); + let nv = |width, height, y: &[u8], y_stride, uv: &[u8], uv_stride| { + let mut s = Signal::default(); + s.fill(&Frame::Nv12 { width, height, y, y_stride, uv, uv_stride, matrix: Matrix::Bt709, range: Range::Limited }) + }; + assert_eq!(nv(4, 4, &px[..16], 4, &px[..7], 4), Err(FrameError::Short { plane: "UV", len: 7, needed: 8 })); + assert_eq!(nv(5, 2, &px[..10], 5, &px[..6], 5), Err(FrameError::Stride { plane: "UV", stride: 5, needed: 6 })); + assert_eq!(nv(4, 4, &px[..15], 4, &px[..8], 4), Err(FrameError::Short { plane: "Y", len: 15, needed: 16 })); + // a frame with no area is valid and empty + assert_eq!(nv(0, 4, &[], 0, &[], 0), Ok(())); + assert_eq!(s.fill(&Frame::Rgba8 { width: 3, height: 0, stride: 0, data: &[] }), Ok(())); + assert_eq!(s.fill(&Frame::Rgba8 { width: usize::MAX, height: 0, stride: 0, data: &[] }), Ok(())); + assert_eq!(nv(usize::MAX, 0, &[], 0, &[], 0), Ok(())); + assert!(s.is_empty()); + assert!(FrameError::TooLarge.to_string().contains("too large")); +} + +#[test] +fn colorized_vectorscope_points_use_the_scope_matrix() { + let s = Signal::from_fn(1, 1, |_, _| [0.0, 1.0, 0.0]); + let p = Params { matrix: Matrix::Bt2020Ncl, ..Params::default() }; + let v = vectorscope_yuv(&s, &p); + assert_eq!(v.matrix, Matrix::Bt2020Ncl); + let [_, cb, cr] = rgb_to_ycbcr(0.0, 1.0, 0.0, Matrix::Bt2020Ncl); + let (x, y) = v.cell(cb, cr).unwrap(); + let (n, _, img) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + let px = &img[(y * n + x) * 4..(y * n + x) * 4 + 4]; + let [ccb, ccr] = v.point(x, y); + let tint = |m| craft_color::ycbcr_to_rgb(0.6, ccb * 0.8, ccr * 0.8, m).map(|c: f32| 0.55 + 0.45 * c.clamp(0.0, 1.0)); + let l = f32::from(px[3]) / 255.0; + let got = [0, 1, 2].map(|i| f32::from(px[i]) / 255.0 / l); + let (want, other) = (tint(Matrix::Bt2020Ncl), tint(Matrix::Bt709)); + let err = |t: [f32; 3]| (0..3).map(|i| (got[i] - t[i]).abs()).fold(0.0f32, f32::max); + assert!(err(want) < 0.005, "{got:?} vs {want:?}"); + assert!(err(other) > 0.01, "the BT.709 tint {other:?} is not told apart from {want:?}"); + // HLS points are colored by their hue: saturated yellow paints yellow, not orange + let yellow = Signal::from_fn(1, 1, |_, _| [1.0, 1.0, 0.0]); + let v = vectorscope_hls(&yellow, &Params::default()); + assert!(v.hls); + let [hx, hy] = hls_point([1.0, 1.0, 0.0], Matrix::Bt709); + let (x, y) = v.cell(hx, hy).unwrap(); + let (n, _, img) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + let px = &img[(y * n + x) * 4..(y * n + x) * 4 + 3]; + assert!(px[0].abs_diff(px[1]) <= 6 && px[2] + 40 < px[1], "{px:?}"); + // HLS peaks report the hue: yellow at 60°, green at 120° + assert!((summary::peaks(&v, 1, 0.0)[0].angle_deg - 60.0).abs() < 1.0, "{:?}", summary::peaks(&v, 1, 0.0)); + let green = vectorscope_hls(&Signal::from_fn(1, 1, |_, _| [0.0, 1.0, 0.0]), &Params { matrix: Matrix::Bt601, ..Params::default() }); + assert!((summary::peaks(&green, 1, 0.0)[0].angle_deg - 120.0).abs() < 1.0, "{:?}", summary::peaks(&green, 1, 0.0)); +} + +// ------------------------------------------------------------------------------------ reuse + +#[test] +fn into_functions_match_the_allocating_ones_and_keep_their_buffers() { + let frame_px = rgba8(1920, 1080, |x, y| [(x % 251) as u8, (y % 241) as u8, ((x + y) % 239) as u8]); + let frame = Frame::Rgba8 { width: 1920, height: 1080, stride: 1920 * 4, data: &frame_px }; + let p = Params::default(); + let mut s = Signal::default(); + let mut w = Waveform::default(); + let mut h = Histogram::default(); + let mut v = Vectorscope::default(); + let mut scratch = paint::Scratch::default(); + let mut img = Vec::new(); + let mut c = Computed::default(); + let mut run = |s: &mut Signal| { + s.fill(&frame).unwrap(); + waveform_into(s, WaveformType::Yc, &p, &mut w); + histogram_into(s, &p, &mut h); + vectorscope_hls_into(s, &p, &mut v); + let layers: Vec<(&Grid, [f32; 3])> = w.traces.iter().map(|t| (t, [1.0; 3])).collect(); + paint::grids_into(&layers, 10.0, 1.0, &mut scratch, &mut img); + compute_into(ScopeKind::Parade, s, &Params { parade: ParadeType::RgbWhite, ..p }, &mut c); + (s.rgb.as_ptr(), w.traces[1].data.as_ptr(), h.y.as_ptr(), v.data.as_ptr(), img.as_ptr(), w.clone(), h.clone(), v.clone(), c.clone()) + }; + let first = run(&mut s); + let second = run(&mut s); + assert_eq!((first.0, first.1, first.2, first.3, first.4), (second.0, second.1, second.2, second.3, second.4), "buffers were reallocated"); + assert_eq!(second.5, waveform(&s, WaveformType::Yc, &p)); + assert_eq!(second.6, histogram(&s, &p)); + assert_eq!(second.7, vectorscope_hls(&s, &p)); + assert_eq!(second.8, compute(ScopeKind::Parade, &s, &Params { parade: ParadeType::RgbWhite, ..p })); + // switching kinds keeps working and gives the same result as a fresh compute + let mut c = Computed::default(); + let lp = Params { waveform: WaveformType::Luma, parade: ParadeType::Yuv, ..p }; + for k in [ScopeKind::Parade, ScopeKind::Histogram, ScopeKind::VectorscopeYuv, ScopeKind::VectorscopeHls, ScopeKind::Waveform, ScopeKind::Parade] { + compute_into(k, &s, &lp, &mut c); + assert_eq!(c, compute(k, &s, &lp), "{k:?}"); + } +} + +// ------------------------------------------------------------------------------------ hostile input + +#[test] +fn hostile_params_and_signals_stay_bounded() { + let s = bars(); + // rows and grid sizes are clamped + let w = waveform(&s, WaveformType::Rgb, &Params { rows: usize::MAX, ..Params::default() }); + assert_eq!(w.traces[0].rows, MAX_ROWS); + let w = waveform(&s, WaveformType::Rgb, &Params { rows: 0, ..Params::default() }); + assert_eq!(w.traces[0].rows, 2); + let v = vectorscope_yuv(&s, &Params { vector_size: usize::MAX, ..Params::default() }); + assert_eq!(v.size, MAX_VECTOR_SIZE); + let v = vectorscope_hls(&s, &Params { vector_size: 0, ..Params::default() }); + assert_eq!((v.size, v.samples), (3, 256 * 16)); + // an even size becomes odd, so a gray sample lands on the center cell with no magnitude + let gray = Signal::from_fn(1, 1, |_, _| [0.5; 3]); + let v = vectorscope_yuv(&gray, &Params { vector_size: 256, ..Params::default() }); + assert_eq!(v.size, 257); + assert_eq!(v.cell(0.0, 0.0), Some((128, 128))); + assert_eq!(v.point(128, 128), [0.0, 0.0]); + // a signal whose public fields disagree reads only whole rows and never indexes past them + let odd = Signal { w: 1000, h: 1000, rgb: vec![[0.5; 3]; 10] }; + let w = waveform(&odd, WaveformType::Rgb, &Params::default()); + assert_eq!((w.traces[0].cols, w.per_column, w.traces[0].total()), (10, 0, 0)); + // sizes asked for past the caps are clamped, and samples past a clamped grid are dropped + let px = rgba8(2000, 4, |_, _| [9, 9, 9]); + let mut big = Signal::default(); + big.fill_max(&Frame::Rgba8 { width: 2000, height: 4, stride: 8000, data: &px }, usize::MAX, usize::MAX).unwrap(); + assert_eq!((big.w, big.h), (1000, 4), "2000 columns decimated by 2 to fit 1920"); + let f = Signal::from_rgba_f32_with(4000, 1, &vec![0.5; 16_000], usize::MAX, usize::MAX, |p| [p[0], p[1], p[2]]); + assert_eq!(f.w, 1334, "4000 columns decimated by 3"); + let g = Grid::new("Y", usize::MAX, usize::MAX); + assert_eq!((g.cols, g.rows, g.data.len()), (MAX_SIGNAL_W, MAX_ROWS, MAX_SIGNAL_W * MAX_ROWS)); + let wide = Signal::from_fn(3000, 2, |_, _| [0.5; 3]); + let w = waveform(&wide, WaveformType::Luma, &Params::default()); + assert_eq!((w.traces[0].cols, w.traces[0].total()), (MAX_SIGNAL_W, 2 * MAX_SIGNAL_W as u64)); + let wide = Signal { w: usize::MAX, h: 0, rgb: Vec::new() }; + assert_eq!(waveform(&wide, WaveformType::Luma, &Params::default()).traces[0].data.len(), 0); + // helpers outside their range answer None or 0 instead of panicking + assert_eq!(row_of(0.5, 0.0, 1.0, 1), None); + assert_eq!(row_of(0.5, 1.0, 1.0, 256), None); + assert_eq!(cell_of(0.0, 0.0, 1, VECTOR_EXTENT), None); + assert_eq!(cell_of(0.0, 0.0, 255, f32::NAN), None); + let g = Grid::new("Y", 3, 3); + assert_eq!((g.at(3, 0), g.at(0, 3), g.at(0, usize::MAX), g.at(usize::MAX, usize::MAX)), (0, 0, 0, 0)); + let v = vectorscope_yuv(&s, &Params::default()); + assert_eq!((v.at(0, usize::MAX), v.at(usize::MAX, 0)), (0, 0)); + let empty = Vectorscope::default(); + assert!(summary::coarse(&empty, 0).is_empty()); + assert!(summary::peaks(&empty, 5, 0.0).is_empty()); + assert_eq!(empty.at(0, 0), 0); +} + +#[test] +fn hand_built_values_past_the_caps_paint_nothing() { + let huge = Signal::from_fn(usize::MAX, 2, |_, _| [0.5; 3]); + assert_eq!((huge.w, huge.h, huge.len()), (MAX_SIGNAL_W, 2, 2 * MAX_SIGNAL_W)); + let mut scratch = paint::Scratch::default(); + let mut out = vec![1u8; 4]; + let v = Vectorscope { size: usize::MAX, ..Vectorscope::default() }; + assert_eq!(paint::vectorscope_into(&v, [1.0; 3], 1.0, true, &mut scratch, &mut out), (0, 0)); + assert!(out.is_empty()); + assert!(summary::coarse(&v, usize::MAX).is_empty()); + let big = Vectorscope { size: MAX_VECTOR_SIZE + 1, data: vec![1; 4], samples: 4, ..Vectorscope::default() }; + assert!(summary::peaks(&big, 5, 0.0).is_empty()); + assert!(summary::coarse(&big, 4).is_empty()); + // entries past the size² plane are not cells + let mut data = vec![0; 10]; + data[9] = 5; + let trailing = Vectorscope { size: 3, extent: VECTOR_EXTENT, data, samples: 5, ..Vectorscope::default() }; + assert!(summary::peaks(&trailing, 5, 0.0).is_empty()); + assert!(summary::coarse(&trailing, 3).is_empty()); + let g = Grid { name: "Y", cols: usize::MAX, rows: usize::MAX, data: Vec::new() }; + out.push(1); + assert_eq!(paint::grids_into(&[(&g, [1.0; 3])], 1.0, 1.0, &mut scratch, &mut out), (0, 0)); + assert!(out.is_empty()); + assert!(summary::trace_columns(&Waveform::default(), &g, usize::MAX).is_empty()); + let tall = Grid { name: "Y", cols: 4, rows: MAX_ROWS + 1, data: Vec::new() }; + assert_eq!(paint::grids_into(&[(&tall, [1.0; 3])], 1.0, 1.0, &mut scratch, &mut out), (0, 0)); +} + +// ------------------------------------------------------------------------------------ HDR + +#[test] +fn hdr_bins_split_sdr_and_stops() { + let px = Signal { w: 5, h: 1, rgb: vec![[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [4.0, 4.0, 4.0], [16.0, 16.0, 16.0], [f32::NAN, -1.0, f32::INFINITY]] }; + let mut h = Histogram::default(); + histogram_hdr_into(&px, Matrix::Bt709, HdrBins::new(4.0), &mut h); + let b = h.hdr.unwrap(); + assert_eq!(h.samples, 5); + assert_eq!(b.bin(1.0), b.from - 1, "SDR white is the last SDR bin"); + assert_eq!(b.bin(16.0), 255); + assert_eq!(b.bin(1e9), 255); + let two = b.bin(4.0); + assert!(two > b.from && two < 255, "{two}"); + assert_eq!(h.r[0], 2, "black and NaN"); + assert_eq!(h.b[255], 2, "16 and +inf"); + assert_eq!((h.below[1], h.above[2]), (1, 1), "-1 below, +inf above 2^4"); + assert!((above_sdr(&h) - 0.6).abs() < 1e-6, "{}", above_sdr(&h)); + // over-white samples in different channels each count once + let split = Signal { w: 2, h: 1, rgb: vec![[2.0, 0.5, 0.5], [0.5, 0.5, 2.0]] }; + histogram_hdr_into(&split, Matrix::Bt709, HdrBins::new(4.0), &mut h); + assert_eq!((h.above_sdr_samples, above_sdr(&h)), (2, 1.0)); + histogram_hdr_into(&Signal::default(), Matrix::Bt709, HdrBins::new(4.0), &mut h); + assert_eq!(above_sdr(&h), 0.0); + assert_eq!(above_sdr(&histogram(&bars(), &Params::default())), 0.0); + // the SDR half follows the sRGB curve: linear 0.5 is about 73.5 % of the way to SDR white + let half = b.bin(0.5); + assert_eq!(half, (craft_color::linear_to_srgb(0.5) * 127.0 + 0.5) as usize); +} + +/// A hand-built split outside the bins (any `from`, any `stops`) never panics and stays in range. +#[test] +fn hdr_bins_with_any_split_stay_in_range() { + for from in [0, 1, 2, 128, 255, 256, usize::MAX] { + for stops in [0.0, 3.0, f32::NAN, f32::INFINITY] { + let b = HdrBins { from, stops }; + for v in [f32::NAN, -1.0, 0.0, 0.5, 1.0, 2.0, 1e9] { + assert!(b.bin(v) < BINS, "{from} {stops} {v}"); + } + let mut h = Histogram::default(); + histogram_hdr_into(&Signal { w: 1, h: 1, rgb: vec![[2.0; 3]] }, Matrix::Bt2020Ncl, b, &mut h); + assert!((0.0..=1.0).contains(&above_sdr(&h))); + } + } +} + +/// `cargo test --release -p craft-scopes perf -- --ignored --nocapture` +#[test] +#[ignore] +fn perf_scopes_at_1080p() { + let mut seed = 0x1234_5678u32; + let px = rgba8(1920, 1080, |_, _| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + [seed as u8, (seed >> 8) as u8, (seed >> 16) as u8] + }); + let reps = 20; + let mut s = Signal::default(); + let frame = Frame::Rgba8 { width: 1920, height: 1080, stride: 1920 * 4, data: &px }; + let t = std::time::Instant::now(); + for _ in 0..reps { + s.fill(&frame).unwrap(); + } + println!("decimate RGBA 1920x1080: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + let (y, y_stride, uv, uv_stride) = nv12(1920, 1080, 0, [100, 120, 140]); + let nv = Frame::Nv12 { width: 1920, height: 1080, y: &y, y_stride, uv: &uv, uv_stride, matrix: Matrix::Bt709, range: Range::Limited }; + let t = std::time::Instant::now(); + for _ in 0..reps { + s.fill(&nv).unwrap(); + } + println!("decimate NV12 1920x1080: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + s.fill(&frame).unwrap(); + let p = Params::default(); + let mut c = Computed::default(); + for (k, wt, pt) in [ + (ScopeKind::Waveform, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::Waveform, WaveformType::Yc, ParadeType::Rgb), + (ScopeKind::Parade, WaveformType::Rgb, ParadeType::RgbWhite), + (ScopeKind::Histogram, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::VectorscopeYuv, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::VectorscopeHls, WaveformType::Rgb, ParadeType::Rgb), + ] { + let t = std::time::Instant::now(); + for _ in 0..reps { + compute_into(k, &s, &Params { waveform: wt, parade: pt, ..p }, &mut c); + std::hint::black_box(&c); + } + println!("{k:?} {wt:?}/{pt:?}: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + } +} diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index e80ca5a08b..38ec038b52 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -5,12 +5,23 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Source-level platform regression guards, test deadlines, hostile-input helpers and a reentrant test lock for the Craft application suite" +description = "Source-level platform regression guards, test deadlines, hostile-input helpers, a reentrant test lock and skip-or-fail helpers for the Craft application suite" publish = false +[features] +# 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. +font-coverage = ["dep:skrifa"] + [dependencies] +sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +skrifa = { workspace = true, optional = true } [target.'cfg(unix)'.dependencies] +libc = { version = "0.2", optional = true } rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } [lints] diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 3adaf23762..863715fb87 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -237,6 +237,79 @@ 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`. +## 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. + +A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. + +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a control character (NUL included), and a path listed twice. An empty optional column is `None`. The parser does not check that a name is valid on a given file system: a name Windows reserves (`<`, `>`, `"`, `|`, `?`, `*`, a trailing `.` or space, a device name such as `NUL`) or two names that differ only in case are accepted, so a manifest must use names that every file system it is verified on supports. +- `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. +- `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. +- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. After the open, `verify` also checks that the opened file is inside `dir`: on Linux, Android and Apple platforms by the path the kernel reports for the open file, and on other Unix systems, or on Linux and Android when `/proc/self/fd` cannot be read, by resolving the listed path again and comparing its device and inode with the opened file's. On Apple platforms an error from the path query fails verification with `VerifyError::Read` instead of falling back to the second lookup. That second lookup goes through the path again, so a folder changed during it is not detected. On Windows the location of the opened file is not checked again, so a part of the path changed into a link out of `dir` between the check and the open is not detected. In every case the opened file must still have the listed SHA-256. +- `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. With the folder variable unset, it calls `skip::skip` with the reason `corpus not given: set to its folder` and the required variable `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`), so the [skip](#skip) rule applies: unset or empty prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. With the folder variable set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. A `var` that is empty or holds `=` or a NUL character fails the test before the environment is read. Otherwise it returns the folder. + +`Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. + +## skip + +The `skip` module is not built for `wasm32`. A test that needs something a test environment may lack +(a program, a corpus file, the craft-fonts faces) skips or fails under one rule: + +The variable is read only when something is missing. + +| Value | Result | +|---|---| +| Not set or empty | The helper prints `SKIPPED: ` and one line feed to stderr, and the test returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. | +| `1` | The test fails. No skip line is printed. | +| Any other value, such as `0`, `true`, `yes`, ` 1` or `1` followed by a line feed | The test fails with the reason and the variable's name and value. No skip line is printed. | +| Not Unicode | The test fails with the reason and the variable's name. No skip line is printed. | + +A variable name that is empty or holds `=` or a NUL character also fails the test, before the +environment is read. + +`skip::required(var)` returns the same decision without failing the test: `Ok(false)`, `Ok(true)`, +or a `RequiredError` that names the variable. Every module of this crate that reads a required +variable reads it with `skip::required`, so one rule applies to all of them. + +The caller passes the name its repository uses today, such as `CRAFT_MEDIA_REQUIRE_ORACLES`, +`CRAFT_PDF_ORACLES_REQUIRED`, `PDFCRAFT_ORACLES_REQUIRED` or `FILMCRAFT_REQUIRE_ORACLES`. +`skip::REQUIRED_VAR` (`CRAFT_TEST_REQUIRED`) is the default name. + +```rust +use craft_testkit::skip::{REQUIRED_VAR, craft_fonts, skip}; + +#[test] +fn renders_with_qpdf() { + let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); + // ... +} + +#[test] +fn draws_japanese() { + if !craft_fonts(HAS_CRAFT_FONTS, CRAFT_FONTS_REQUIRED) { + return; + } + // ... +} +``` + +`or_skip!` evaluates a `Result` once, binds the `Ok` value, and on `Err` skips with the error's +`Display` text as the reason. The two-argument form returns `()`; a test that returns a `Result` +passes the value to return as the third argument, for example `Ok(())`. + +`craft_fonts(present, required)` takes both values from the caller's build: a build constant, an +`option_env!` value, or the table `craft-fonts-build` generates. A required failure names +`CRAFT_FONTS_REQUIRED=1`. + +`craft_fonts_cover(text, faces)` needs the `font-coverage` feature, which adds skrifa. It returns +`true` when one face maps every character of `text` that is not whitespace. Each face is font data +with its index in a collection (`0` for a single font). A face that does not parse covers nothing, +and coverage is not combined across faces. + +The module does not change the process environment. Its tests that read a real variable run the +test binary again as a child process with that variable set. + ## serial `serial` is native only. @@ -295,6 +368,22 @@ 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` | +### corpus + +| Code | Repository | Path | SHA | +|---|---|---|---| +| The manifest rows and the digest check of `pinned` | storytold/craft-libs | `crates/affinity/tests/support/corpus.rs:18-35` | `75a654f4` | + +### skip + +| Code | Repository | Path | Commit | +|---|---|---|---| +| `skip!`, `record` | storytold/lightcraft | `crates/testkit/src/lib.rs` | `7ebbb17a82` | +| `or_skip!`, `REQUIRED_VAR` | storytold/pdfcraft | `crates/oracle/src/lib.rs` | `ee9bf28126` | +| `require_*!`, `skip` | storytold/filmcraft | `crates/testkit/src/lib.rs`, `crates/testkit/src/oracle.rs` | `cff7e1442e` | +| `skip`, `skip_with` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` | +| `craft_fonts_cover` | storytold/gridcraft | `crates/ui-egui/src/theme.rs` | `06c2b1440b` | + ### rng | Module | Source | Path | Commit | @@ -345,6 +434,33 @@ 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. +### corpus + +| Consumer | Code it replaces | State | +|---|---|---| +| craft-libs `affinity` | `tests/support/corpus.rs`, which parses `corpus.tsv` (four tab-separated columns) and checks the folder `AFFINITY_CORPUS` names | Pending | +| craft-libs `raw` | `tests/it/raf_corpus_manifest.rs`, which checks the rows of the tab-separated `docs/raf-corpus.sha256` but not the files | Pending | +| LightCraft | `crates/raw/tests/it/corpus.rs` checks the RAF list | Pending | +| PhotoCraft | `crates/io/tests/it/corpus.rs` and `xtask/*-corpus.sha256` (two-space lists, to be converted to tabs) | Pending | +| CADCraft | `crates/io/src/roundtrip/tests.rs` scans `CADCRAFT_CORPUS_DIR` without a checksum list | Pending: needs a pinned list first | +| VectorCraft | `crates/affinity/tests/support/corpus.rs` reads a two-space list, to be converted to tabs | Pending | + +### skip + +| Consumer | Code it replaces | State | +|---|---|---| +| LightCraft | `lightcraft-testkit`'s `skip!`, which keeps its JSON skip log on top of `skip` | Not started | +| PdfCraft | `pdfcraft-oracle`'s `or_skip!`, which reads any value of `PDFCRAFT_ORACLES_REQUIRED` | Not started | +| FilmCraft | `filmcraft-testkit`'s `require_*!` and `skip`, which accept `1`, `true`, `yes` and `on` | Not started | +| GridCraft | `craft_fonts_cover`, which reads GridCraft's embedded face table | Not started | +| craft-libs `craft-media-testkit` | `skip` and `skip_with`, which accept `1`, `true`, `yes` and `on` | Not started | +| craft-libs `pdf` tests | `or_skip!` in `crates/pdf/tests/cos/oracle.rs`, which reads any value of `CRAFT_PDF_ORACLES_REQUIRED` | Not started | + +After an adoption, an app that reads any value as required skips on an empty value, and fails as +a configuration error on every other value except `1`, `0` included. An app that accepts `true`, `yes` +and `on` fails on those values as a configuration error. +Each adoption says which values change and keeps the variable name. + ### serial | Consumer | Module | Switched | diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs new file mode 100644 index 0000000000..96d6460074 --- /dev/null +++ b/crates/testkit/src/corpus.rs @@ -0,0 +1,1063 @@ +//! Pinned test corpora: a folder of files listed in a manifest, each checked against its SHA-256. +//! +//! A manifest has one tab-separated row per file: the SHA-256 as 64 hexadecimal digits, the +//! file's path relative to the corpus folder, and optional license and URL columns. In this +//! example each `\t` stands for one tab character: +//! +//! ```text +//! # Public Affinity documents +//! cc8ca0db0d8fc545eb29153be900f153fa6b7b7eac068d05e54a502aba1264fe\tafdesignload-color.afdesign\tMIT\thttps://example.org/color.afdesign +//! 9a17f500d09fb3b1a70d24aabdc2882955ec3eac3700a474549e6100be3a8484\tmore/layer_mode.afdesign +//! ``` +//! +//! [`Manifest::parse`] skips blank lines and lines whose first character other than a space or a +//! tab is `#`. A `#` later in a row is part of that row. It returns a [`ManifestError`] naming the +//! line of a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal +//! digits, a path that is empty, absolute or leaves the folder, or a path listed twice. Paths use +//! `/` between their parts. +//! +//! [`pinned`] is the gate a test calls: it returns the corpus folder named by a variable after +//! checking every listed file. When the variable is unset it skips or fails the test under the +//! rule of [`skip`](crate::skip::skip), and it fails the test on any other failure. [`verify`] +//! runs the same check and returns a [`VerifyError`] instead of failing. No function here +//! downloads a file or changes the process environment. +//! +//! Every input has a size limit, set by [`Limits`]: a manifest of at most 1 MiB and 10,000 rows, +//! and files of at most 8 GiB each, read 64 KiB at a time. + +use std::collections::HashSet; +use std::ffi::OsString; +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +/// The variable [`pinned`] reads when the caller names none. +pub const DEFAULT_VAR: &str = "CRAFT_CORPUS"; + +/// The suffix [`pinned`] adds to the folder variable's name to form the name of the variable that +/// makes the corpus required. +pub const REQUIRED_SUFFIX: &str = "_REQUIRED"; + +/// The size of each read while a file is hashed. +const CHUNK: usize = 64 * 1024; + +/// Size limits for a manifest and for the files it lists. An input over a limit is an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest manifest in bytes. Default 1 MiB. + pub max_manifest_bytes: usize, + /// The most rows a manifest may list. Default 10,000. + pub max_entries: usize, + /// The largest listed file in bytes. Default 8 GiB. + pub max_file_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: 1024 * 1024, max_entries: 10_000, max_file_bytes: 8 * 1024 * 1024 * 1024 } + } +} + +/// One row of a manifest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + digest: [u8; 32], + path: String, + license: Option, + url: Option, + line: usize, +} + +impl Entry { + /// The file's SHA-256. + pub fn digest(&self) -> &[u8; 32] { + &self.digest + } + + /// The file's path relative to the corpus folder, with `/` between its parts. + pub fn path(&self) -> &str { + &self.path + } + + /// The license column, when the row has one that is not empty. + pub fn license(&self) -> Option<&str> { + self.license.as_deref() + } + + /// The URL column, when the row has one that is not empty. + pub fn url(&self) -> Option<&str> { + self.url.as_deref() + } + + /// The 1-based line of the manifest that holds the row. + pub fn line(&self) -> usize { + self.line + } + + /// The file's path under `dir`. + fn path_in(&self, dir: &Path) -> PathBuf { + let mut path = dir.to_path_buf(); + path.extend(self.path.split('/')); + path + } +} + +/// A parsed manifest: the rows in the order the manifest lists them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Manifest { + entries: Vec, +} + +impl Manifest { + /// Parses `text` under the default [`Limits`]. + pub fn parse(text: &str) -> Result { + Self::parse_with_limits(text, &Limits::default()) + } + + /// Parses `text`. A manifest longer than `limits.max_manifest_bytes` or with more than + /// `limits.max_entries` rows is an error. + pub fn parse_with_limits(text: &str, limits: &Limits) -> Result { + if text.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let mut entries: Vec = Vec::new(); + let mut seen: HashSet<&str> = HashSet::new(); + for (index, raw) in text.lines().enumerate() { + let line = index + 1; + let content = raw.trim_start_matches([' ', '\t']); + if content.trim().is_empty() || content.starts_with('#') { + continue; + } + if entries.len() == limits.max_entries { + return Err(ManifestError::TooManyEntries { limit: limits.max_entries }); + } + let columns: Vec<&str> = raw.split('\t').collect(); + if !(2..=4).contains(&columns.len()) { + return Err(ManifestError::Columns { line, found: columns.len() }); + } + let digest = parse_digest(columns[0]).ok_or(ManifestError::Digest { line })?; + let path = columns[1]; + check_path(path).map_err(|reason| ManifestError::Path { line, reason })?; + if !seen.insert(path) { + let first = entries.iter().find(|e| e.path == path).map_or(0, |e| e.line); + return Err(ManifestError::Duplicate { line, first }); + } + let optional = |i: usize| columns.get(i).filter(|c| !c.is_empty()).map(|c| (*c).to_owned()); + entries.push(Entry { digest, path: path.to_owned(), license: optional(2), url: optional(3), line }); + } + Ok(Self { entries }) + } + + /// Reads and parses the manifest file at `path`. A path that is not a regular file is refused + /// before it is opened. Reading stops after `limits.max_manifest_bytes` bytes plus one, so an + /// oversized file is not read whole. + pub fn read(path: &Path, limits: &Limits) -> Result { + if !std::fs::metadata(path).map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let file = open_for_reading(path).map_err(ManifestError::Io)?; + if !file.metadata().map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let cap = u64::try_from(limits.max_manifest_bytes).unwrap_or(u64::MAX).saturating_add(1); + let mut bytes = Vec::new(); + file.take(cap).read_to_end(&mut bytes).map_err(ManifestError::Io)?; + if bytes.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let text = String::from_utf8(bytes).map_err(|_| ManifestError::NotUtf8)?; + Self::parse_with_limits(&text, limits) + } + + /// The rows, in manifest order. + pub fn entries(&self) -> &[Entry] { + &self.entries + } + + /// The paths of the rows, in manifest order. + pub fn names(&self) -> impl Iterator { + self.entries.iter().map(Entry::path) + } +} + +/// Decodes 64 ASCII hexadecimal digits, in either case. +fn parse_digest(text: &str) -> Option<[u8; 32]> { + let bytes = text.as_bytes(); + if bytes.len() != 64 { + return None; + } + let mut digest = [0u8; 32]; + let (pairs, _) = bytes.as_chunks::<2>(); + for (out, &[high, low]) in digest.iter_mut().zip(pairs) { + let high = char::from(high).to_digit(16)?; + let low = char::from(low).to_digit(16)?; + *out = u8::try_from(high * 16 + low).ok()?; + } + Some(digest) +} + +/// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none +/// empty, `.` or `..`, and no `\`, `:` or control character (NUL included) anywhere, so no +/// platform reads a row as an absolute path or a path outside the folder. It does not check that +/// each name is valid on a given file system: a name Windows reserves (`<>"|?*`, a trailing `.` or +/// space, a device name such as `NUL`) or one that differs from another only in case is accepted, +/// and the manifest must use names the file systems it is verified on support. +fn check_path(path: &str) -> Result<(), PathError> { + if path.is_empty() { + return Err(PathError::Empty); + } + if path.contains(['\\', ':']) || path.chars().any(char::is_control) { + return Err(PathError::Character); + } + for part in path.split('/') { + match part { + "" => return Err(if path.starts_with('/') { PathError::Absolute } else { PathError::EmptyPart }), + "." | ".." => return Err(PathError::DotPart), + _ => {} + } + } + Ok(()) +} + +/// Why a manifest path was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathError { + /// The path is empty. + Empty, + /// The path starts with `/`. + Absolute, + /// The path has an empty part (`a//b`, or a trailing `/`). + EmptyPart, + /// The path has a `.` or `..` part. + DotPart, + /// The path holds a `\`, a `:` or a control character. + Character, +} + +impl fmt::Display for PathError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Empty => "the path is empty", + Self::Absolute => "the path is absolute", + Self::EmptyPart => "the path has an empty part", + Self::DotPart => "the path has a . or .. part", + Self::Character => "the path holds a \\, a : or a control character", + }) + } +} + +/// Why a manifest could not be read or parsed. +#[derive(Debug)] +pub enum ManifestError { + /// The manifest is longer than the limit in bytes. + TooLarge { + /// The limit in bytes. + limit: usize, + }, + /// The manifest lists more rows than the limit. + TooManyEntries { + /// The limit in rows. + limit: usize, + }, + /// A row does not have 2, 3 or 4 tab-separated columns. + Columns { + /// The 1-based line of the row. + line: usize, + /// The number of columns found. + found: usize, + }, + /// A row's digest is not 64 hexadecimal digits. + Digest { + /// The 1-based line of the row. + line: usize, + }, + /// A row's path is refused. + Path { + /// The 1-based line of the row. + line: usize, + /// Why the path is refused. + reason: PathError, + }, + /// A row repeats the path of an earlier row. + Duplicate { + /// The 1-based line of the repeated row. + line: usize, + /// The 1-based line of the earlier row. + first: usize, + }, + /// The manifest path does not name a regular file. + NotAFile, + /// The manifest file is not UTF-8. + NotUtf8, + /// The manifest file could not be read. + Io(io::Error), +} + +impl fmt::Display for ManifestError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooLarge { limit } => write!(f, "the manifest is longer than {limit} bytes"), + Self::TooManyEntries { limit } => write!(f, "the manifest lists more than {limit} files"), + Self::Columns { line, found } => write!(f, "line {line}: {found} tab-separated columns, expected 2 to 4"), + Self::Digest { line } => write!(f, "line {line}: the SHA-256 is not 64 hexadecimal digits"), + Self::Path { line, reason } => write!(f, "line {line}: {reason}"), + Self::Duplicate { line, first } => write!(f, "line {line}: the path is already listed on line {first}"), + Self::NotAFile => f.write_str("the manifest is not a regular file"), + Self::NotUtf8 => f.write_str("the manifest is not UTF-8"), + Self::Io(error) => write!(f, "the manifest could not be read: {error}"), + } + } +} + +impl std::error::Error for ManifestError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } + } +} + +/// Why a corpus folder does not match its manifest. +#[derive(Debug)] +pub enum VerifyError { + /// The manifest lists no files, so the folder would be accepted without a check. + EmptyManifest, + /// The corpus folder could not be resolved. + Folder { + /// The folder. + dir: PathBuf, + /// The error resolving it. + error: io::Error, + }, + /// A listed file is missing or could not be resolved. + Missing { + /// The path the manifest lists. + path: String, + /// The error resolving it. + error: io::Error, + }, + /// A listed path resolves outside the corpus folder, through a symbolic link. + Escapes { + /// The path the manifest lists. + path: String, + }, + /// A listed path is not a regular file. + NotAFile { + /// The path the manifest lists. + path: String, + }, + /// A listed file is larger than the limit. + TooLarge { + /// The path the manifest lists. + path: String, + /// The limit in bytes. + limit: u64, + }, + /// A listed file could not be read. + Read { + /// The path the manifest lists. + path: String, + /// The read error. + error: io::Error, + }, + /// A listed file's SHA-256 differs from the manifest's. + Modified { + /// The path the manifest lists. + path: String, + }, +} + +impl fmt::Display for VerifyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyManifest => f.write_str("the manifest lists no files"), + Self::Folder { dir, error } => write!(f, "corpus folder {}: {error}", dir.display()), + Self::Missing { path, error } => write!(f, "{path}: missing: {error}"), + Self::Escapes { path } => write!(f, "{path}: resolves outside the corpus folder"), + Self::NotAFile { path } => write!(f, "{path}: not a regular file"), + Self::TooLarge { path, limit } => write!(f, "{path}: larger than {limit} bytes"), + Self::Read { path, error } => write!(f, "{path}: {error}"), + Self::Modified { path } => write!(f, "{path}: SHA-256 differs from the manifest"), + } + } +} + +impl std::error::Error for VerifyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Folder { error, .. } | Self::Missing { error, .. } | Self::Read { error, .. } => Some(error), + _ => None, + } + } +} + +/// Checks every file `manifest` lists in `dir` under the default [`Limits`]. +pub fn verify(dir: &Path, manifest: &Manifest) -> Result<(), VerifyError> { + verify_with_limits(dir, manifest, &Limits::default()) +} + +/// Checks every file `manifest` lists in `dir`: each must resolve inside `dir` after symbolic +/// links are followed, be a regular file of at most `limits.max_file_bytes` bytes, and have the +/// listed SHA-256. Returns the first failure in manifest order. An empty manifest is an error. +/// +/// The resolved path is checked before the file is opened. On Unix the opened file is checked +/// again: on Linux, Android and Apple platforms by the path the kernel reports for it, and +/// elsewhere, or on Linux and Android without that path, by resolving the listed path a second time +/// and comparing device and inode. That second lookup does not detect a folder inside `dir` that is +/// changed while it runs. On Windows the opened file's location is not checked again, so a part of +/// the path changed into a link out of `dir` between the check and the open is not detected. In +/// each case the file must still have the listed SHA-256. +pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> Result<(), VerifyError> { + if manifest.entries.is_empty() { + return Err(VerifyError::EmptyManifest); + } + let root = dir.canonicalize().map_err(|error| VerifyError::Folder { dir: dir.to_path_buf(), error })?; + let mut buf = vec![0u8; CHUNK]; + for entry in &manifest.entries { + verify_entry(&root, entry, limits, &mut buf)?; + } + Ok(()) +} + +fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Result<(), VerifyError> { + verify_entry_with(root, entry, limits, buf, open_for_reading) +} + +/// [`verify_entry`] with the function that opens the resolved path; tests change the path in it. +fn verify_entry_with( + root: &Path, + entry: &Entry, + limits: &Limits, + buf: &mut [u8], + open: impl FnOnce(&Path) -> io::Result, +) -> Result<(), VerifyError> { + let path = || entry.path.clone(); + let target = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + if !target.starts_with(root) { + return Err(VerifyError::Escapes { path: path() }); + } + let kind = std::fs::metadata(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + if !kind.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + let file = open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; + if !meta.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + #[cfg(unix)] + opened_file_is_inside(root, entry, &file, &meta)?; + if meta.len() > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + let mut reader = file.take(limits.max_file_bytes.saturating_add(1)); + let mut hasher = Sha256::new(); + let mut total: u64 = 0; + loop { + let n = match reader.read(buf) { + Ok(0) => break, + Ok(n) => n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(VerifyError::Read { path: path(), error }), + }; + total = total.saturating_add(n as u64); + if total > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + hasher.update(&buf[..n]); + } + if hasher.finalize().as_slice() != entry.digest.as_slice() { + return Err(VerifyError::Modified { path: path() }); + } + Ok(()) +} + +/// Checks, after the open, that the opened file is inside `root`, so a path changed into a link out +/// of the folder between the first check and the open is refused. On Linux, Android and Apple +/// platforms the kernel reports the open file's path, which must start with `root`; on Apple +/// platforms an error from that query fails the check with [`VerifyError::Read`]. On other Unix +/// systems, and on Linux and Android when `/proc/self/fd` cannot be read, the entry's path is +/// resolved again and must lead, without a link in its last part, to the opened file (the same +/// device and inode). +#[cfg(unix)] +fn opened_file_is_inside(root: &Path, entry: &Entry, file: &File, opened: &std::fs::Metadata) -> Result<(), VerifyError> { + use std::os::unix::fs::MetadataExt; + let path = || entry.path.clone(); + if let Some(actual) = opened_path(file).map_err(|error| VerifyError::Read { path: path(), error })? { + return if actual.starts_with(root) { Ok(()) } else { Err(VerifyError::Escapes { path: path() }) }; + } + let again = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + let now = std::fs::symlink_metadata(&again).map_err(|error| VerifyError::Read { path: path(), error })?; + if !again.starts_with(root) || (now.dev(), now.ino()) != (opened.dev(), opened.ino()) { + return Err(VerifyError::Escapes { path: path() }); + } + Ok(()) +} + +/// The path of the file `file` has open, as the kernel reports it in `/proc/self/fd`, or `None` +/// when that cannot be read (for example without a mounted `/proc`). +#[cfg(any(target_os = "linux", target_os = "android"))] +#[allow(clippy::unnecessary_wraps)] +fn opened_path(file: &File) -> io::Result> { + use std::os::fd::AsRawFd; + Ok(std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()) +} + +/// The path of the file `file` has open, as the kernel reports it. +#[cfg(target_vendor = "apple")] +fn opened_path(file: &File) -> io::Result> { + use std::os::unix::ffi::OsStringExt; + let path = rustix::fs::getpath(file)?; + Ok(Some(PathBuf::from(OsString::from_vec(path.into_bytes())))) +} + +/// `None`: the platform does not report the path of an open file. +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))))] +fn opened_path(_file: &File) -> io::Result> { + Ok(None) +} + +/// Opens `path` for reading. On Unix the file is opened with `O_NONBLOCK`, so a path that was +/// replaced by a named pipe after its type was checked opens at once instead of waiting for a +/// writer; the caller checks the opened file's type. Reads from a regular file are not affected. +fn open_for_reading(path: &Path) -> io::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + options.open(path) +} + +/// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file +/// `manifest` lists has been checked with [`verify`]. +/// +/// - Folder variable unset: calls [`skip`](crate::skip::skip) with the reason +/// `corpus not given: set to its folder` and the variable named `var` plus +/// [`REQUIRED_SUFFIX`] (by default `CRAFT_CORPUS_REQUIRED`). When that variable is unset or +/// empty, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns +/// `None`. When it is `1`, it fails the test. Any other value, `0` included, fails the test as a +/// configuration error. +/// - Folder variable set, even to an empty value: fails the test unless the manifest parses and +/// every listed file matches. +/// +/// A `var` that is empty or holds `=` or a NUL character fails the test before the environment is +/// read. It fails the test with a panic whose message names the variable and the failure. +#[allow(clippy::panic)] +pub fn pinned(var: Option<&str>, manifest: &str) -> Option { + let var = var.unwrap_or(DEFAULT_VAR); + if let Err(message) = check_var(var) { + panic!("{message}"); + } + match gate(std::env::var_os(var), var, manifest) { + Ok(Some(dir)) => Some(dir), + Ok(None) => { + let required_var = format!("{var}{REQUIRED_SUFFIX}"); + let _ = crate::skip::skip(&format!("corpus not given: set {var} to its folder"), &required_var); + None + } + Err(message) => panic!("{message}"), + } +} + +/// Refuses a folder variable name that is empty or holds `=` or a NUL character, the names +/// [`skip::required`](crate::skip::required) refuses. +fn check_var(var: &str) -> Result<(), String> { + if var.is_empty() || var.contains(['=', '\0']) { + return Err(format!("{var:?} cannot name the corpus folder variable: it is empty or holds `=` or a NUL character")); + } + Ok(()) +} + +/// The decision of [`pinned`] on the folder variable's value, without reading the environment or +/// printing: `Ok(None)` when the variable is unset, which [`pinned`] passes to +/// [`skip`](crate::skip::skip), and `Err` holds the message the test fails with. +fn gate(folder: Option, var: &str, manifest: &str) -> Result, String> { + let Some(folder) = folder else { + return Ok(None); + }; + if folder.is_empty() { + return Err(format!("{var} is set but empty")); + } + let dir = PathBuf::from(folder); + let manifest = Manifest::parse(manifest).map_err(|e| format!("corpus manifest for {var}: {e}"))?; + verify(&dir, &manifest).map_err(|e| format!("pinned corpus in {} ({var}): {e}", dir.display()))?; + Ok(Some(dir)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Output}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_CORPUS_CHILD"; + /// The folder variable the child's `pinned` reads. + const VAR: &str = "CRAFT_TESTKIT_CORPUS_DIR"; + /// The required variable that goes with [`VAR`]. + const REQUIRED: &str = "CRAFT_TESTKIT_CORPUS_DIR_REQUIRED"; + + const HELLO: &[u8] = b"hello world"; + /// SHA-256 of `hello world`. + const HELLO_SHA: &str = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; + const EMPTY_SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + /// A folder under the system temporary folder, removed on drop. + struct Scratch(PathBuf); + + impl Scratch { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("craft_testkit_corpus_{}_{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch folder"); + Self(dir) + } + + fn write(&self, rel: &str, bytes: &[u8]) -> PathBuf { + let path = self.0.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(&path, bytes).expect("write file"); + path + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn parse_err(text: &str) -> ManifestError { + Manifest::parse(text).expect_err("the manifest is refused") + } + + #[test] + fn comments_are_skipped() { + let text = format!("# pinned corpus\n # indented comment\n\t# tab-indented comment\n{HELLO_SHA}\thello.txt\n#{EMPTY_SHA}\tempty.txt\n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.names().collect::>(), ["hello.txt"]); + assert_eq!(manifest.entries()[0].line(), 4); + } + + #[test] + fn a_hash_inside_a_row_is_not_a_comment() { + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tdir/#1.txt\tMIT\thttps://example.org/a#b\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.path(), "dir/#1.txt"); + assert_eq!(entry.url(), Some("https://example.org/a#b")); + } + + #[test] + fn blank_lines_are_skipped() { + let text = format!("\n \n\t\n{HELLO_SHA}\thello.txt\n\n{EMPTY_SHA}\tempty.txt\n \t \n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.entries().len(), 2); + assert_eq!(manifest.entries()[0].line(), 4); + assert_eq!(manifest.entries()[1].line(), 6); + assert_eq!(Manifest::parse("").expect("parse").entries().len(), 0); + } + + #[test] + fn malformed_row_is_error() { + assert!(matches!(parse_err(HELLO_SHA), ManifestError::Columns { line: 1, found: 1 })); + assert!(matches!(parse_err(&format!("# c\n{HELLO_SHA} hello.txt\n")), ManifestError::Columns { line: 2, found: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\ta\tMIT\turl\textra\n")), ManifestError::Columns { line: 1, found: 5 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\t\n")), ManifestError::Path { line: 1, reason: PathError::Empty })); + assert!(matches!(parse_err("\thello.txt\n"), ManifestError::Digest { line: 1 })); + } + + #[test] + fn wrong_digest_length_is_error() { + assert!(matches!(parse_err(&format!("{}\ta\n", &HELLO_SHA[..63])), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}0\ta\n")), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!(" {HELLO_SHA}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn non_hex_digest_is_error() { + let bad = format!("{}g", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{bad}\ta\n")), ManifestError::Digest { line: 1 })); + let sign = format!("+{}", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{sign}\ta\n")), ManifestError::Digest { line: 1 })); + let wide = format!("{}é", &HELLO_SHA[..62]); + assert!(matches!(parse_err(&format!("{wide}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn rows_take_two_to_four_columns_and_empty_optional_columns_are_none() { + let text = format!( + "{HELLO_SHA}\ta.txt\n{HELLO_SHA}\tb.txt\tMIT\n{HELLO_SHA}\tc.txt\tMIT\thttps://example.org/c\n{HELLO_SHA}\td.txt\t\n{HELLO_SHA}\te.txt\t\thttps://example.org/e\n" + ); + let manifest = Manifest::parse(&text).expect("parse"); + let cols: Vec<_> = manifest.entries().iter().map(|e| (e.path(), e.license(), e.url())).collect(); + assert_eq!( + cols, + [ + ("a.txt", None, None), + ("b.txt", Some("MIT"), None), + ("c.txt", Some("MIT"), Some("https://example.org/c")), + ("d.txt", None, None), + ("e.txt", None, Some("https://example.org/e")), + ] + ); + } + + #[test] + fn crlf_lines_and_uppercase_digests_parse() { + let upper = HELLO_SHA.to_ascii_uppercase(); + let manifest = Manifest::parse(&format!("# c\r\n{upper}\thello.txt\tMIT\r\n\r\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.license(), Some("MIT")); + assert_eq!(entry.digest()[..4], [0xb9, 0x4d, 0x27, 0xb9]); + assert_eq!(entry.digest(), Manifest::parse(&format!("{HELLO_SHA}\thello.txt")).expect("parse").entries()[0].digest()); + } + + #[test] + fn duplicate_path_is_error() { + let text = format!("{HELLO_SHA}\ta/b.txt\n# c\n{HELLO_SHA}\ta/b.txt\n"); + assert!(matches!(parse_err(&text), ManifestError::Duplicate { line: 3, first: 1 })); + } + + #[test] + fn paths_that_leave_the_folder_are_errors() { + let cases = [ + ("/etc/passwd", PathError::Absolute), + ("../outside", PathError::DotPart), + ("a/../../outside", PathError::DotPart), + ("./a", PathError::DotPart), + ("a//b", PathError::EmptyPart), + ("a/", PathError::EmptyPart), + ("C:/Windows/win.ini", PathError::Character), + ("C:a", PathError::Character), + ("\\\\server\\share\\a", PathError::Character), + ("a\\..\\..\\b", PathError::Character), + ("a\u{1}b", PathError::Character), + ("a\u{7f}b", PathError::Character), + ("a\u{85}b", PathError::Character), + ]; + for (path, expected) in cases { + match parse_err(&format!("{HELLO_SHA}\t{path}\n")) { + ManifestError::Path { line: 1, reason } => assert_eq!(reason, expected, "{path}"), + other => panic!("{path}: {other}"), + } + } + } + + #[test] + fn manifest_limits_are_errors() { + let text = format!("{HELLO_SHA}\ta\n{HELLO_SHA}\tb\n"); + let limits = Limits { max_entries: 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooManyEntries { limit: 1 }))); + let limits = Limits { max_entries: 2, ..Limits::default() }; + assert_eq!(Manifest::parse_with_limits(&text, &limits).expect("parse").entries().len(), 2); + + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooLarge { .. }))); + let limits = Limits { max_manifest_bytes: text.len(), ..Limits::default() }; + assert!(Manifest::parse_with_limits(&text, &limits).is_ok()); + + let scratch = Scratch::new(); + let path = scratch.write("corpus.tsv", text.as_bytes()); + assert_eq!(Manifest::read(&path, &Limits::default()).expect("read").entries().len(), 2); + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::read(&path, &limits), Err(ManifestError::TooLarge { .. }))); + let bad = scratch.write("bad.tsv", b"\xff\xfe"); + assert!(matches!(Manifest::read(&bad, &Limits::default()), Err(ManifestError::NotUtf8))); + assert!(matches!(Manifest::read(&scratch.0.join("absent.tsv"), &Limits::default()), Err(ManifestError::Io(_)))); + } + + fn hello_corpus() -> (Scratch, Manifest) { + let scratch = Scratch::new(); + scratch.write("hello.txt", HELLO); + scratch.write("sub/empty.bin", b""); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\tMIT\n{EMPTY_SHA}\tsub/empty.bin\n")).expect("parse"); + (scratch, manifest) + } + + #[test] + fn a_matching_folder_verifies() { + let (scratch, manifest) = hello_corpus(); + verify(&scratch.0, &manifest).expect("the corpus matches"); + } + + #[test] + fn missing_file_fails() { + let (scratch, manifest) = hello_corpus(); + std::fs::remove_file(scratch.0.join("sub").join("empty.bin")).expect("remove"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Missing { path, .. }) => assert_eq!(path, "sub/empty.bin"), + other => panic!("{other:?}"), + } + assert!(matches!(verify(&scratch.0.join("absent"), &manifest), Err(VerifyError::Folder { .. }))); + } + + #[test] + fn modified_file_fails() { + let (scratch, manifest) = hello_corpus(); + scratch.write("hello.txt", b"hello world!"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Modified { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + + #[test] + fn an_empty_manifest_or_a_folder_entry_fails() { + let (scratch, _) = hello_corpus(); + assert!(matches!(verify(&scratch.0, &Manifest::default()), Err(VerifyError::EmptyManifest))); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tsub\n")).expect("parse"); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::NotAFile { .. }))); + } + + /// A named pipe is refused before it is opened; opening one for reading waits for a writer. + #[cfg(unix)] + #[test] + fn a_named_pipe_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("pipe"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tpipe\n")).expect("parse"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::NotAFile { path }) => assert_eq!(path, "pipe"), + other => panic!("{other:?}"), + } + } + + /// A manifest path that names a named pipe or a folder is refused before it is opened. + #[cfg(unix)] + #[test] + fn a_manifest_that_is_not_a_file_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("corpus.tsv"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + assert!(matches!(Manifest::read(&scratch.0, &Limits::default()), Err(ManifestError::NotAFile))); + assert!(matches!(Manifest::read(&fifo, &Limits::default()), Err(ManifestError::NotAFile))); + } + + /// Files are opened with `O_NONBLOCK`, read back from the open file's status flags in + /// `/proc/self/fdinfo`, so a path replaced by a named pipe after its type was checked opens at + /// once instead of waiting for a writer. + #[cfg(target_os = "linux")] + #[test] + fn files_are_opened_with_o_nonblock() { + use std::os::fd::AsRawFd; + let (scratch, _) = hello_corpus(); + let file = open_for_reading(&scratch.0.join("hello.txt")).expect("open"); + let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", file.as_raw_fd())).expect("read fdinfo"); + let flags = info.lines().find_map(|line| line.strip_prefix("flags:")).map(str::trim).expect("flags line"); + let flags = i32::from_str_radix(flags, 8).expect("octal flags"); + assert_ne!(flags & libc::O_NONBLOCK, 0, "flags {flags:o}"); + } + + #[test] + fn file_size_limit_is_error() { + let (scratch, manifest) = hello_corpus(); + let limits = Limits { max_file_bytes: HELLO.len() as u64, ..Limits::default() }; + verify_with_limits(&scratch.0, &manifest, &limits).expect("a file at the limit passes"); + let limits = Limits { max_file_bytes: HELLO.len() as u64 - 1, ..Limits::default() }; + match verify_with_limits(&scratch.0, &manifest, &limits) { + Err(VerifyError::TooLarge { path, limit }) => assert_eq!((path.as_str(), limit), ("hello.txt", 10)), + other => panic!("{other:?}"), + } + } + + #[test] + fn a_file_larger_than_one_read_hashes_whole() { + let scratch = Scratch::new(); + let bytes: Vec = (0..CHUNK * 2 + 7).map(|i| (i % 251) as u8).collect(); + scratch.write("big.bin", &bytes); + let hex: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); + let manifest = Manifest::parse(&format!("{hex}\tbig.bin\n")).expect("parse"); + verify(&scratch.0, &manifest).expect("the whole file is hashed"); + scratch.write("big.bin", &bytes[..CHUNK]); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::Modified { .. }))); + } + + #[cfg(unix)] + #[test] + fn a_symbolic_link_out_of_the_folder_fails() { + let outside = Scratch::new(); + let target = outside.write("hello.txt", HELLO); + let corpus = Scratch::new(); + std::os::unix::fs::symlink(&target, corpus.0.join("hello.txt")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\n")).expect("parse"); + match verify(&corpus.0, &manifest) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + std::os::unix::fs::symlink(&outside.0, corpus.0.join("out")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tout/hello.txt\n")).expect("parse"); + assert!(matches!(verify(&corpus.0, &manifest), Err(VerifyError::Escapes { .. }))); + } + + /// A file opened outside the folder, as after the listed path was changed into a link between + /// the first check and the open, is refused even when its contents match. + #[cfg(unix)] + #[test] + fn a_file_opened_outside_the_folder_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let entry = &manifest.entries[0]; + let opened = File::open(&other).expect("open the outside file"); + let meta = opened.metadata().expect("metadata"); + match opened_file_is_inside(&root, entry, &opened, &meta) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + let listed = File::open(root.join("hello.txt")).expect("open the listed file"); + let meta = listed.metadata().expect("metadata"); + opened_file_is_inside(&root, entry, &listed, &meta).expect("the listed file passes"); + } + + /// `verify` refuses a listed file that is changed into a link out of the folder after it was + /// resolved and before it is opened, even when the outside file's contents match. + #[cfg(unix)] + #[test] + fn a_file_changed_into_an_outside_link_before_the_open_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let mut buf = vec![0u8; CHUNK]; + let swap = |path: &Path| { + std::fs::remove_file(path)?; + std::os::unix::fs::symlink(&other, path)?; + open_for_reading(path) + }; + match verify_entry_with(&root, &manifest.entries[0], &Limits::default(), &mut buf, swap) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + + #[test] + fn the_gate_leaves_only_an_unset_folder_to_skip() { + let (scratch, _) = hello_corpus(); + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + assert_eq!(gate(None, VAR, &manifest), Ok(None)); + let dir = scratch.0.clone().into_os_string(); + assert_eq!(gate(Some(dir.clone()), VAR, &manifest), Ok(Some(scratch.0.clone()))); + let empty = gate(Some(OsString::new()), VAR, &manifest).expect_err("empty"); + assert!(empty.contains("empty"), "{empty}"); + let bad = gate(Some(dir.clone()), VAR, "# c\nnot a row\n").expect_err("bad manifest"); + assert!(bad.contains("line 2"), "{bad}"); + let missing = gate(Some(dir), VAR, &format!("{EMPTY_SHA}\tabsent.bin\n")).expect_err("missing"); + assert!(missing.contains("absent.bin"), "{missing}"); + } + + /// Runs `child` below in a new process of this test binary with the given variables set and + /// every other corpus variable removed, so no test changes this process's environment. + fn run_child(case: &str, vars: &[(&str, &str)]) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["corpus::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + for name in [VAR, REQUIRED, DEFAULT_VAR, "CRAFT_CORPUS_REQUIRED"] { + cmd.env_remove(name); + } + for (name, value) in vars { + cmd.env(name, value); + } + cmd.output().expect("run the test binary") + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + let found = match case.to_str() { + Some("named") => pinned(Some(VAR), &manifest), + Some("default") => pinned(None, &manifest), + other => panic!("unknown child case {other:?}"), + }; + eprintln!("pinned returned {}", found.map_or_else(|| "none".to_owned(), |d| d.display().to_string())); + } + + #[test] + fn an_unset_folder_follows_the_skip_rule() { + for value in [None, Some("")] { + let vars: Vec<(&str, &str)> = value.map(|v| (REQUIRED, v)).into_iter().collect(); + let out = run_child("named", &vars); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches(&format!("SKIPPED: corpus not given: set {VAR} to its folder\n")).count(), 1, "{value:?}: {err}"); + assert!(err.contains("pinned returned none"), "{value:?}: {err}"); + } + let out = run_child("named", &[(REQUIRED, "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("corpus not given: set {VAR} to its folder, and {REQUIRED}=1 forbids skipping")), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("pinned returned"), "{err}"); + for value in ["0", "true", " 1", "1\n"] { + let out = run_child("named", &[(REQUIRED, value)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{value:?}: {err}"); + assert!(err.contains(&format!("{REQUIRED}={value:?} is not empty or 1")), "{value:?}: {err}"); + assert!(!err.contains("SKIPPED:"), "{value:?}: {err}"); + assert!(!err.contains("pinned returned"), "{value:?}: {err}"); + } + } + + #[test] + fn pinned_reads_the_named_folder_and_fails_on_a_bad_one() { + let (scratch, _) = hello_corpus(); + let dir = scratch.0.to_str().expect("a UTF-8 temporary path"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains(&format!("pinned returned {dir}")), "{err}"); + + scratch.write("hello.txt", b"changed"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("hello.txt: SHA-256 differs from the manifest"), "{err}"); + + let out = run_child("named", &[(VAR, "")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{VAR} is set but empty")), "{err}"); + } + + #[test] + fn a_bad_folder_variable_name_fails_before_the_environment_is_read() { + for name in ["", "A=B", "A\0B"] { + assert!(check_var(name).is_err(), "{name:?}"); + let result = std::panic::catch_unwind(|| pinned(Some(name), "not a manifest")); + let payload = result.expect_err(&format!("{name:?} should fail the test")); + let message = payload.downcast_ref::().map(String::as_str).unwrap_or_default(); + assert!(message.contains("cannot name the corpus folder variable"), "{name:?}: {message}"); + } + assert_eq!(check_var(VAR), Ok(())); + } + + #[test] + fn pinned_defaults_to_craft_corpus() { + let out = run_child("default", &[]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: corpus not given: set CRAFT_CORPUS to its folder\n"), "{err}"); + + let out = run_child("default", &[("CRAFT_CORPUS_REQUIRED", "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_CORPUS_REQUIRED=1 forbids skipping"), "{err}"); + } +} diff --git a/crates/testkit/src/hostile.rs b/crates/testkit/src/hostile.rs index 2b34819e6c..43d9a4065a 100644 --- a/crates/testkit/src/hostile.rs +++ b/crates/testkit/src/hostile.rs @@ -7,13 +7,13 @@ //! a failing case can be found again from its label. It builds for every target, `wasm32` //! included. //! -//! [`hammer`] runs a parser on the unmodified seed, on every truncation of it and on the +//! `hammer` runs a parser on the unmodified seed, on every truncation of it and on the //! mutations, one case after another on a worker thread, with a time limit for each case. It fails //! the test, naming the case and the input length, when the parser panics or does not finish in //! time. The number of rounds is a count the caller gives, multiplied by a variable the caller //! names. [`DIVISOR_VARIABLE`] (`CRAFT_HOSTILE_DIVISOR`) runs a fraction of every sweep for quick -//! runs such as pull requests: every N-th truncation and 1/N of the rounds; [`divisor`] reads it -//! for sweeps written without [`hammer`]. [`hammer`], [`HammerConfig`] and [`divisor`] are not +//! runs such as pull requests: every N-th truncation and 1/N of the rounds; `divisor` reads it +//! for sweeps written without `hammer`. `hammer`, `HammerConfig` and `divisor` are not //! built for `wasm32`. use std::fmt::Write as _; @@ -39,11 +39,11 @@ use std::time::{Duration, Instant}; #[cfg(not(target_arch = "wasm32"))] const WORKER_NAME: &str = "craft-testkit hostile"; -/// The variable that multiplies a [`HammerConfig`]'s rounds unless -/// [`HammerConfig::with_multiplier_variable`] names another. +/// The variable that multiplies a `HammerConfig`'s rounds unless +/// `HammerConfig::with_multiplier_variable` names another. pub const DEFAULT_MULTIPLIER_VARIABLE: &str = "CRAFT_HOSTILE_MULT"; -/// The variable that divides every hostile-input sweep: with `N`, [`hammer`] runs the unmodified +/// The variable that divides every hostile-input sweep: with `N`, `hammer` runs the unmodified /// seed, every N-th truncation (lengths 0, N, 2N, ...) and 1/N of its rounds, rounded up. Unset, or /// 1, runs everything. The Workspace gate sets it and the nightly full run leaves it unset; a /// failing case is found again with the same value. @@ -54,7 +54,7 @@ pub const DIVISOR_VARIABLE: &str = "CRAFT_HOSTILE_DIVISOR"; #[cfg(not(target_arch = "wasm32"))] pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); -/// The most cases one [`hammer`] call runs: the unmodified seed, its truncations and the rounds +/// The most cases one `hammer` call runs: the unmodified seed, its truncations and the rounds /// together. A call that would run more fails before it runs any. pub const MAX_CASES: usize = 10_000_000; diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 3feb5129ca..aaa0a7d928 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -11,27 +11,37 @@ //! (or of `f16` for an `h` suffix), which browser WebGPU compilers reject. //! * [`guards::std_instant`]: flags uses of `std::time::Instant` in code paths targeting the web, //! where `std::time::Instant::now()` panics on `wasm32`. -//! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with -//! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. +//! * `guards::rust_sources`: directory crawler collecting `.rs` sources while excluding tests, with +//! size limits (`guards::rust_sources_with_limits`). It is not built for `wasm32`. //! //! [`rng`] holds two seeded generators for repeatable test input, [`rng::XorShift64`] and //! [`rng::XorShift64Star`], each with `next`, `below`, `byte` and `fill`. //! -//! On targets other than `wasm32`, [`deadline::with_deadline`] runs a test body on its own thread -//! and fails the test when the body does not finish within its limit, and [`deadline::wait_until`] +//! On targets other than `wasm32`, `deadline::with_deadline` runs a test body on its own thread +//! and fails the test when the body does not finish within its limit, and `deadline::wait_until` //! polls a condition until it holds and fails the test when the limit passes first. Both read an //! optional limit variable that the caller names, `CRAFT_TEST_TIMEOUT_SECS` by default. //! //! [`hostile::mutations`] yields a fixed sequence of damaged copies of a valid seed, on every -//! target. On targets other than `wasm32`, [`hostile::hammer`] runs a parser on the seed, every +//! target. On targets other than `wasm32`, `hostile::hammer` runs a parser on the seed, every //! truncation of it and those copies, one after another on a worker thread with a time limit for //! each, and fails the test with the case that panicked or did not finish. //! -//! On targets other than `wasm32`, [`serial`] holds [`serial::TestLock`], a lock that a `static` -//! can hold and that the thread holding it can take again, and [`serial::gpu_lock`], the one lock +//! On targets other than `wasm32`, `serial` holds `serial::TestLock`, a lock that a `static` +//! can hold and that the thread holding it can take again, and `serial::gpu_lock`, the one lock //! for GPU tests. Every GPU test in a process must take this lock, because a test that takes a //! different lock can run at the same time as one that takes this one. //! +//! `skip` decides what a test does when something it needs is missing (a program, a corpus, +//! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the +//! variable the caller names is `1`. A value other than unset, empty or `1` fails the test as a +//! configuration error. `skip::required` reads such a variable under this rule for any caller. +//! It is not built for `wasm32`. `skip::craft_fonts_cover` needs the `font-coverage` feature. +//! +//! With the `corpus` feature, `corpus` (native only) parses pinned-corpus manifests and checks a +//! corpus folder against them: `corpus::Manifest`, `corpus::verify` and the test gate +//! `corpus::pinned`, which skips or fails under the rule of `skip`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -42,6 +52,8 @@ //! under foreign host environments. They are lightweight syntactic regression gates designed to complement, //! rather than replace, platform integration tests and CI execution. +#[cfg(all(feature = "corpus", not(target_arch = "wasm32")))] +pub mod corpus; #[cfg(not(target_arch = "wasm32"))] pub mod deadline; pub mod guards; @@ -50,6 +62,8 @@ pub mod rng; pub mod sample_damage; #[cfg(not(target_arch = "wasm32"))] pub mod serial; +#[cfg(not(target_arch = "wasm32"))] +pub mod skip; #[cfg(not(target_arch = "wasm32"))] pub use deadline::{DeadlineLimit, wait_until, with_deadline}; diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs new file mode 100644 index 0000000000..e9dbb58527 --- /dev/null +++ b/crates/testkit/src/skip.rs @@ -0,0 +1,527 @@ +//! Skip-or-fail for a test that needs something a test environment may lack: a program, a corpus +//! file, the craft-fonts faces. +//! +//! An optional absence prints one line to stderr, `SKIPPED: `, and the test returns and +//! passes. When the variable the caller names is `1`, the absence fails the test instead and no +//! skip line is printed. Unset and empty leave the test optional. Any other value, such as `0`, +//! `true`, ` 1`, `1\n` or a value that is not valid Unicode, is a configuration error: the absence +//! fails the test with the variable's name and value. The caller passes the name its repository +//! uses, such as `CRAFT_MEDIA_REQUIRE_ORACLES` or `CRAFT_PDF_ORACLES_REQUIRED`; [`REQUIRED_VAR`] is +//! the default name. +//! +//! ```no_run +//! use craft_testkit::skip::{REQUIRED_VAR, skip}; +//! +//! fn find_qpdf() -> Result { +//! Err("qpdf is not on PATH".into()) +//! } +//! +//! // A test returning `()`: bind the program or return. +//! let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); +//! # let _ = qpdf; +//! +//! // The same rule without a `Result` to match on. +//! let gpu_available = false; +//! if !gpu_available && !skip("no GPU adapter", REQUIRED_VAR) { +//! return; +//! } +//! ``` +//! +//! A reason that holds a carriage return or a line feed is printed with them written as `\r` and +//! `\n`, so one skip is one line. Each line is written with one call while stderr is locked, so +//! lines from tests running in parallel do not mix; their order is not fixed. + +use std::ffi::{OsStr, OsString}; +use std::fmt; + +/// The default name of the variable that makes a skip fail the test. +pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; + +/// The variable `craft-fonts-build` reads, named by [`craft_fonts`] when it fails a test. +pub const FONTS_REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; + +/// A required variable name that cannot be read, or a value that is not unset, empty or `1`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RequiredError { + /// The variable name is empty or holds `=` or a NUL character. + BadName { variable: String }, + /// The value is not valid Unicode. + NotUnicode { variable: String }, + /// The value is valid Unicode but not empty or `1`. + BadValue { variable: String, value: String }, +} + +impl fmt::Display for RequiredError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + const FIX: &str = "set it to 1 to fail a test that lacks a prerequisite, or leave it unset or empty to skip the test"; + match self { + Self::BadName { variable } => write!(f, "{variable:?} cannot name a variable: it is empty or holds `=` or a NUL character"), + Self::NotUnicode { variable } => write!(f, "{variable} is not valid Unicode; {FIX}"), + Self::BadValue { variable, value } => write!(f, "{variable}={value:?} is not empty or 1; {FIX}"), + } + } +} + +impl std::error::Error for RequiredError {} + +/// Whether the variable `var` makes a missing prerequisite fail the test. Unset and empty return +/// `Ok(false)`, and `1` returns `Ok(true)`. Any other value, including `0` and a value that is not +/// valid Unicode, returns an error that names the variable. A name that is empty or holds `=` or a +/// NUL character returns an error before the environment is read. +pub fn required(var: &str) -> Result { + required_with(var, |name| std::env::var_os(name)) +} + +/// [`required`] with the variable lookup passed in. +fn required_with(variable: &str, lookup: impl FnOnce(&str) -> Option) -> Result { + if variable.is_empty() || variable.contains(['=', '\0']) { + return Err(RequiredError::BadName { variable: variable.to_owned() }); + } + parse_required(variable, lookup(variable).as_deref()) +} + +fn parse_required(variable: &str, value: Option<&OsStr>) -> Result { + let Some(value) = value else { + return Ok(false); + }; + if value.is_empty() { + return Ok(false); + } + if value == OsStr::new("1") { + return Ok(true); + } + Err(match value.to_str() { + Some(text) => RequiredError::BadValue { variable: variable.to_owned(), value: text.to_owned() }, + None => RequiredError::NotUnicode { variable: variable.to_owned() }, + }) +} + +/// Skip the calling test: print `SKIPPED: ` and return `false`, or fail the test when +/// `required_var` is `1`. A value of `required_var` that [`required`] rejects fails the test with +/// the reason and the error. The caller returns from the test itself: +/// `if !skip(reason, var) { return; }`. +#[allow(clippy::panic)] +pub fn skip(reason: &str, required_var: &str) -> bool { + match required(required_var) { + Ok(required) => skip_with(required, reason, required_var), + Err(error) => panic!("{reason}, and {error}"), + } +} + +/// Fail the test when `required` is set, otherwise print the skip line and return `false`. It +/// fails the test with a panic. +#[allow(clippy::panic)] +fn skip_with(required: bool, reason: &str, required_var: &str) -> bool { + if required { + panic!("{reason}, and {required_var}=1 forbids skipping this test"); + } + // Written to the process's stderr directly: `eprint!` is captured by the test harness and + // would hide the line from a default run. + let _ = std::io::Write::write_all(&mut std::io::stderr().lock(), skip_line(reason).as_bytes()); + false +} + +/// The skip line for `reason`, with its carriage returns and line feeds escaped, ending in one +/// line feed. +fn skip_line(reason: &str) -> String { + let mut line = String::with_capacity("SKIPPED: \n".len() + reason.len()); + line.push_str("SKIPPED: "); + for c in reason.chars() { + match c { + '\r' => line.push_str("\\r"), + '\n' => line.push_str("\\n"), + c => line.push(c), + } + } + line.push('\n'); + line +} + +/// Whether a test that needs the craft-fonts faces can run. Returns `true` when `present` is set. +/// Without the faces it prints a skip line and returns `false`, or fails the test when `required` +/// is set. The caller passes both values from its build: a build constant, an `option_env!` +/// value, or the table `craft-fonts-build` generates. +pub fn craft_fonts(present: bool, required: bool) -> bool { + present || skip_with(required, "craft-fonts faces unavailable (build with CRAFT_FONTS_DIR)", FONTS_REQUIRED_VAR) +} + +/// Whether one of `faces` maps every character of `text` that is not whitespace. Each face is +/// font data and the index of the face in a collection (`0` for a single font). A face that does +/// not parse covers nothing, and the characters must all come from the same face. Each combining +/// mark is a character of its own. Text that is empty or only whitespace is covered when at least +/// one face parses. Needs the `font-coverage` feature. +#[cfg(feature = "font-coverage")] +pub fn craft_fonts_cover(text: &str, faces: &[(&[u8], u32)]) -> bool { + use skrifa::MetadataProvider as _; + faces.iter().any(|&(data, index)| { + let Ok(font) = skrifa::FontRef::from_index(data, index) else { + return false; + }; + let map = font.charmap(); + text.chars().filter(|c| !c.is_whitespace()).all(|c| map.map(c).is_some()) + }) +} + +/// Binds the `Ok` value of a `Result` probe, or skips the calling test under the rule of +/// [`skip`](crate::skip::skip) and returns from it. The probe is evaluated once, and its error is +/// the skip reason, so the error type implements `Display`. +/// +/// `or_skip!(probe, var)` returns `()` and belongs in a test returning `()`. +/// `or_skip!(probe, var, value)` returns `value`, for example `Ok(())` in a test that returns a +/// `Result`. +#[macro_export] +macro_rules! or_skip { + ($probe:expr, $required_var:expr) => { + $crate::or_skip!($probe, $required_var, ()) + }; + ($probe:expr, $required_var:expr, $ret:expr) => { + match $probe { + ::core::result::Result::Ok(value) => value, + ::core::result::Result::Err(absent) => { + let _ = $crate::skip::skip(&::std::string::ToString::to_string(&absent), $required_var); + return $ret; + } + } + }; +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + use std::process::{Command, Output}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_SKIP_CHILD"; + /// A variable no test sets, for skips that must stay optional. + const NEVER_SET: &str = "CRAFT_TESTKIT_SKIP_NEVER_SET"; + + /// Runs `child` below in a new process of this test binary, with `REQUIRED_VAR` set to + /// `required` or removed, so no test changes this process's environment. + fn run_child(case: &str, required: Option<&str>) -> Output { + run_child_os(case, required.map(OsStr::new)) + } + + /// [`run_child`] with a value that need not be valid Unicode. + fn run_child_os(case: &str, required: Option<&OsStr>) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["skip::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + match required { + Some(value) => cmd.env(REQUIRED_VAR, value), + None => cmd.env_remove(REQUIRED_VAR), + }; + cmd.output().expect("run the test binary") + } + + fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).into_owned() + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + match case.to_str() { + Some("skip") => { + assert!(!skip("probe absent", REQUIRED_VAR)); + eprintln!("returned from skip"); + } + Some("or_skip") => { + let value: u32 = crate::or_skip!(Err::("probe absent"), REQUIRED_VAR); + eprintln!("ran on with {value}"); + } + Some("threads") => std::thread::scope(|s| { + for i in 0..8 { + s.spawn(move || skip(&format!("thread {i}\r\nsecond half"), REQUIRED_VAR)); + } + }), + other => panic!("unknown child case {other:?}"), + } + } + + /// Values other than unset, empty and `1`. + const INVALID: [&str; 11] = ["0", "true", "TRUE", "yes", "on", " 1", "1 ", "1\n", "01", "11", " "]; + + /// A value that is not valid Unicode: a lone surrogate on Windows, a byte that is not UTF-8 + /// elsewhere. + fn not_unicode() -> std::ffi::OsString { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStringExt as _; + std::ffi::OsString::from_wide(&[u16::from(b'1'), 0xD800]) + } + #[cfg(not(windows))] + { + use std::os::unix::ffi::OsStringExt as _; + std::ffi::OsString::from_vec(b"1\xff".to_vec()) + } + } + + /// Unset and empty are optional, `1` is required, and every other value, `0` included, is an + /// error that names the variable and the value. + #[test] + fn only_unset_empty_and_1_are_valid() { + let var = "CRAFT_PDF_ORACLES_REQUIRED"; + assert_eq!(parse_required(var, None), Ok(false)); + assert_eq!(parse_required(var, Some(OsStr::new(""))), Ok(false)); + assert_eq!(parse_required(var, Some(OsStr::new("1"))), Ok(true)); + for value in INVALID { + let error = parse_required(var, Some(OsStr::new(value))); + assert_eq!(error, Err(RequiredError::BadValue { variable: var.into(), value: value.into() }), "{value:?}"); + } + let message = RequiredError::BadValue { variable: var.into(), value: "1\n".into() }.to_string(); + assert!(message.starts_with("CRAFT_PDF_ORACLES_REQUIRED=\"1\\n\" is not empty or 1; "), "{message}"); + assert_eq!(message.lines().count(), 1, "{message}"); + } + + #[test] + fn a_value_that_is_not_unicode_is_an_error() { + let value = not_unicode(); + assert_eq!(parse_required(REQUIRED_VAR, Some(&value)), Err(RequiredError::NotUnicode { variable: REQUIRED_VAR.into() })); + let message = RequiredError::NotUnicode { variable: REQUIRED_VAR.into() }.to_string(); + assert!(message.starts_with("CRAFT_TEST_REQUIRED is not valid Unicode; "), "{message}"); + } + + #[test] + fn bad_variable_names_are_rejected_before_reading() { + for name in ["", "A=B", "A\0B"] { + let result = required_with(name, |_| panic!("the variable was read")); + assert_eq!(result, Err(RequiredError::BadName { variable: name.to_owned() }), "{name:?}"); + assert_eq!(required(name), Err(RequiredError::BadName { variable: name.to_owned() }), "{name:?}"); + + let failed = std::panic::catch_unwind(|| skip("probe absent", name)); + let message = failed.expect_err("a bad name fails the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.starts_with("probe absent, and "), "{message}"); + assert!(message.ends_with(" cannot name a variable: it is empty or holds `=` or a NUL character"), "{message}"); + } + } + + /// Absence is never silent, and which of the two loud forms it takes is decided by the + /// variable: `1` fails the test, and unset or empty skips. + #[test] + fn a_missing_oracle_is_fatal_exactly_when_it_is_required() { + let var = "CRAFT_PDF_ORACLES_REQUIRED"; + assert!(!skip_with(parse_required(var, None) == Ok(true), "qpdf is not on PATH", var)); + assert!(!skip_with(parse_required(var, Some(OsStr::new(""))) == Ok(true), "qpdf is not on PATH", var)); + + let failed = std::panic::catch_unwind(|| skip_with(parse_required(var, Some(OsStr::new("1"))) == Ok(true), "qpdf is not on PATH", var)); + let message = failed.expect_err("a required absence fails the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("qpdf is not on PATH"), "{message}"); + assert!(message.contains("CRAFT_PDF_ORACLES_REQUIRED=1"), "{message}"); + } + + #[test] + fn a_skip_line_is_one_line_with_its_reason_escaped() { + assert_eq!(skip_line("qpdf is not on PATH"), "SKIPPED: qpdf is not on PATH\n"); + let line = skip_line("first\r\nsecond\nthird\r"); + assert_eq!(line, "SKIPPED: first\\r\\nsecond\\nthird\\r\n"); + assert_eq!(line.lines().count(), 1); + assert_eq!(skip_line(""), "SKIPPED: \n"); + } + + /// The variable is read from the environment: unset and empty skip, and `1` fails the test. + #[test] + fn skip_reads_its_variable_from_the_environment() { + for value in [None, Some("")] { + let out = run_child("skip", value); + let err = stderr(&out); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches("SKIPPED: probe absent\n").count(), 1, "{value:?}: {err}"); + assert!(err.contains("returned from skip"), "{value:?}: {err}"); + } + let out = run_child("skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("probe absent, and CRAFT_TEST_REQUIRED=1 forbids skipping this test"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("returned from skip"), "{err}"); + } + + /// Any other value fails the test with the reason, the variable and the value, and prints no + /// skip line. + #[test] + fn an_invalid_variable_fails_the_test() { + for value in ["0", "true", "yes", " 1", "1\n"] { + let out = run_child("skip", Some(value)); + let err = stderr(&out); + assert!(!out.status.success(), "{value:?}: {err}"); + let expected = format!("probe absent, and CRAFT_TEST_REQUIRED={value:?} is not empty or 1; "); + assert!(err.contains(&expected), "{value:?}: {err}"); + assert!(!err.contains("SKIPPED:"), "{value:?}: {err}"); + assert!(!err.contains("returned from skip"), "{value:?}: {err}"); + } + + let out = run_child_os("skip", Some(¬_unicode())); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("probe absent, and CRAFT_TEST_REQUIRED is not valid Unicode; "), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + + for value in ["0", "true"] { + let out = run_child("or_skip", Some(value)); + let err = stderr(&out); + assert!(!out.status.success(), "{value:?}: {err}"); + assert!(err.contains(&format!("CRAFT_TEST_REQUIRED={value:?} is not empty or 1")), "{value:?}: {err}"); + assert!(!err.contains("SKIPPED:"), "{value:?}: {err}"); + assert!(!err.contains("ran on"), "{value:?}: {err}"); + } + } + + #[test] + fn or_skip_returns_from_the_test_when_optional_and_fails_when_required() { + let out = run_child("or_skip", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: probe absent\n"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + + let out = run_child("or_skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_TEST_REQUIRED=1"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + } + + #[test] + fn the_skip_line_shows_in_a_run_that_captures_test_output() { + let exe = std::env::current_exe().expect("the test binary's path"); + let out = Command::new(exe) + .args(["skip::tests::child", "--exact", "--test-threads=1"]) + .env(CHILD_CASE, "skip") + .env_remove(REQUIRED_VAR) + .output() + .expect("run the test binary"); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: probe absent\n"), "{err}"); + } + + #[test] + fn skip_lines_from_parallel_threads_stay_whole() { + let out = run_child("threads", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + let mut lines: Vec<&str> = err.lines().filter(|l| l.contains("SKIPPED") || l.contains("second half")).collect(); + lines.sort_unstable(); + let expected: Vec = (0..8).map(|i| format!("SKIPPED: thread {i}\\r\\nsecond half")).collect(); + assert_eq!(lines, expected, "{err}"); + } + + #[test] + fn or_skip_yields_the_value_and_evaluates_the_probe_once() { + let probes = Cell::new(0); + let probe = || { + probes.set(probes.get() + 1); + Ok::(7) + }; + let value = crate::or_skip!(probe(), NEVER_SET); + assert_eq!(value, 7); + assert_eq!(probes.get(), 1); + } + + #[test] + fn or_skip_returns_the_given_value_from_a_result_test() { + fn run(probes: &Cell) -> Result { + let value: u32 = crate::or_skip!( + { + probes.set(probes.get() + 1); + Err::("probe absent".into()) + }, + NEVER_SET, + Ok(0) + ); + Ok(value + 1) + } + let probes = Cell::new(0); + assert_eq!(run(&probes), Ok(0)); + assert_eq!(probes.get(), 1); + } + + #[test] + fn craft_fonts_runs_skips_or_fails() { + assert!(craft_fonts(true, false)); + assert!(craft_fonts(true, true)); + assert!(!craft_fonts(false, false)); + let failed = std::panic::catch_unwind(|| craft_fonts(false, true)); + let message = failed.expect_err("missing required faces fail the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("CRAFT_FONTS_REQUIRED=1"), "{message}"); + } + + /// A font holding only a format 12 `cmap` table that maps each range of code points. + #[cfg(feature = "font-coverage")] + fn face(ranges: &[(u32, u32)]) -> Vec { + let subtable_len = 16 + 12 * ranges.len() as u32; + let mut data = Vec::new(); + data.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + for v in [1u16, 16, 0, 0] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(b"cmap"); + for v in [0u32, 28, 12 + subtable_len] { + data.extend_from_slice(&v.to_be_bytes()); + } + for v in [0u16, 1, 3, 10] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(&12u32.to_be_bytes()); + data.extend_from_slice(&12u16.to_be_bytes()); + data.extend_from_slice(&0u16.to_be_bytes()); + for v in [subtable_len, 0, ranges.len() as u32] { + data.extend_from_slice(&v.to_be_bytes()); + } + let mut glyph = 1u32; + for &(start, end) in ranges { + for v in [start, end, glyph] { + data.extend_from_slice(&v.to_be_bytes()); + } + glyph += end - start + 1; + } + data + } + + #[test] + #[cfg(feature = "font-coverage")] + fn craft_fonts_cover_the_advertised_scripts() { + let latin_greek_cyrillic = face(&[(0x41, 0x5A), (0x61, 0x7A), (0x391, 0x3C9), (0x410, 0x44F)]); + let faces: &[(&[u8], u32)] = &[(&latin_greek_cyrillic, 0)]; + for sample in ["Craft", "Αλφα", "Привет", "Craft Αλφα Привет"] { + assert!(craft_fonts_cover(sample, faces), "{sample}"); + } + assert!(!craft_fonts_cover("日本", faces)); + assert!(!craft_fonts_cover("Craft!", faces)); + } + + #[test] + #[cfg(feature = "font-coverage")] + fn coverage_needs_one_face_that_parses_and_maps_every_character() { + let a = face(&[(u32::from('A'), u32::from('A'))]); + let b = face(&[(u32::from('B'), u32::from('B'))]); + let e = face(&[(u32::from('e'), u32::from('e'))]); + let e_acute = face(&[(u32::from('e'), u32::from('e')), (0x301, 0x301)]); + let garbage: &[u8] = b"not a font"; + + assert!(!craft_fonts_cover("", &[])); + assert!(!craft_fonts_cover("A", &[])); + assert!(!craft_fonts_cover("", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(&a, 1)]), "a single font has no face 1"); + + assert!(craft_fonts_cover("", &[(&a, 0)])); + assert!(craft_fonts_cover(" \t\n\u{3000}", &[(&a, 0)])); + assert!(craft_fonts_cover(" A A ", &[(&a, 0)])); + assert!(craft_fonts_cover("A", &[(garbage, 0), (&a, 0)])); + + assert!(craft_fonts_cover("A", &[(&a, 0), (&b, 0)])); + assert!(craft_fonts_cover("B", &[(&a, 0), (&b, 0)])); + assert!(!craft_fonts_cover("AB", &[(&a, 0), (&b, 0)]), "each face covers only part of the text"); + + assert!(!craft_fonts_cover("e\u{301}", &[(&e, 0)]), "the combining mark is not mapped"); + assert!(craft_fonts_cover("e\u{301}", &[(&e_acute, 0)])); + } +} diff --git a/crates/texture/README.md b/crates/texture/README.md index e738d2023d..3c6ebd025a 100644 --- a/crates/texture/README.md +++ b/crates/texture/README.md @@ -81,8 +81,15 @@ network I/O and has no `unsafe` code. - Values are linear data with no transfer curve. A NaN or infinite strength, sample or block scale, a block of 0, an occlusion product that overflows `f32`, mismatched sizes and a failed row read return a `TextureOpError`. +- **Texture sets from file names.** `texture_set::recognize` groups a list of image file names + into texture sets by their shared folder and stem, and gives each name the map role its suffix + or prefix names, with the normal convention and UDIM tile the name states. It reads names only: + no file is opened and no path is joined. Names that are not maps are returned with the reason, + and two names of one set with the same role and tile are both kept and reported. See + [Texture-set names](#texture-set-names). -Mirrored repeat, decoding and texture-set recognition are not in the crate yet. +DDS first-surface decoding is available with the `dds` feature. Other image decoding and +mirrored repeat are not supported. ## Cargo features @@ -90,6 +97,7 @@ No default features. | Feature | Provides | Pulls in | |---|---|---| +| `dds` | decodes the first DDS surface to RGBA floats | `dds`, `bytemuck` | | `parallel` | generated images, display conversion, height to normal and ORM packing fill rows on several threads; the results are the same | `rayon` | Without `parallel` the crate builds for `wasm32-unknown-unknown`. @@ -103,6 +111,67 @@ Without `parallel` the crate builds for `wasm32-unknown-unknown`. | `max_bytes` | 1 GiB (an 8192 × 8192 RGBA plane) | the same | | `MipLimits::max_chain_bytes` | 1.5 GiB (a chain over an 8192 × 8192 RGBA plane needs about 1.33 GiB) | `MipChain::try_build`, `from_levels` and `required_bytes`, with `MipLimits::image` for each level | +## Texture-set names + +`texture_set::recognize(names, &NameLimits::default())` reads each name's leaf, the part after +its last `/` or `\`; the part before it is the folder (the separator itself for a name such as +`/brick_albedo.png`). The leaf's extension must be `png`, `jpg`, `jpeg`, `tga`, `tif`, `tiff`, +`bmp`, `webp`, `exr` or `hdr`, in any case. The stem before it is split into words at every +character that is not a letter or digit, at lower-to-upper case changes (`BaseColor`) and between +digits and letters (`diff4k`), and words are compared after ASCII lower-casing. + +- Resolution (`1k` to `16k`, `16px` to `16384px`, a bare power of two from 128 to 16384), bit + depth (`8bit`, `16bit`, `32bit`), normal convention and a UDIM tile from `1001` to `1999` are + taken out of the stem wherever they are. A bare `1024` is a resolution, or tile 1024 when + another name of its set has a tile. A name with both a bare `1024` and a tile is ignored. +- `gl`, `ogl`, `opengl` and `open gl` mark an OpenGL normal map (green up), and `dx`, `directx`, + `direct x` and `d3d` (written without separators) a DirectX one (green down), as + `normal::NormalConvention` names them. `normalgl` and `normaldx` state a convention too, as role + words or as normal words right next to them. A normal map with neither has no convention, and + one with both is ignored. +- The role is named by the last words of the stem, or by the first words when the last words + name no role. Words right next to them that name the same role, as in `diffuse_color`, go + with them. The other words are the set's stem, and names with the same folder and stem words form one set. + A different role named right next to the role words, as in `albedo_normal`, makes the name + ambiguous, and it is ignored. An occlusion, a roughness and a metallic word in that order, such + as `ao_rough_metal`, name a packed map. +- Two names of one set with the same role and tile are both kept and listed in `duplicates`. + An identical repeated name, archive metadata (`__MACOSX`, `._` leaves), preview images + (`preview`, `previews`, `thumb`, `thumbs`, `thumbnail`, `sphere`, `render`, `swatch`, `icon`, + `screenshot`) and names with no role are ignored, each with its `IgnoreReason`. + +A pair below matches its two words with any separator or a case change between them +(`base_color`, `BaseColor`). A single letter is never a role, except a trailing `n`. + +| Role | Words | Word pairs | +|---|---|---| +| `BaseColor` | `basecolor`, `basecolour`, `albedo`, `diffuse`, `diff`, `color`, `colour`, `col`, `bc`, `basemap`, `maintex` | `base color`, `base colour`, `base map`, `main tex` | +| `Normal` | `normal`, `normalmap`, `normalgl`, `normaldx`, `nrm`, `nor`, `norm`, `nm`, `n`, `bumpmap` | `normal map`, `bump map` | +| `Roughness` | `roughness`, `rough`, `rgh` | | +| `Metallic` | `metallic`, `metalness`, `metal`, `met`, `mtl` | | +| `AmbientOcclusion` | `ambientocclusion`, `ao`, `occlusion`, `occ`, `ambocc` | `ambient occlusion` | +| `Height` | `height`, `heightmap`, `displacement`, `disp`, `displace`, `hgt`, `bump` | `height map` | +| `Emissive` | `emissive`, `emission`, `emissivecolor`, `emissionmap`, `emit`, `glow` | `emissive color`, `emissive colour`, `emission map` | +| `Opacity` | `opacity`, `alpha`, `transparency`, `cutout` | | +| `Glossiness` | `glossiness`, `gloss`, `smoothness`, `smooth` | | +| `PackedOrm` | `orm`, `arm`, `aorm` | | +| `UnsupportedMap` (ignored) | `cavity`, `curvature`, `specular`, `thickness`, `sheen`, `ior` | | + +The roles are the textures of the glTF 2.0 metallic-roughness material, section 3.9 +(): `baseColorTexture`, +`normalTexture`, `occlusionTexture` (red), `emissiveTexture`, and `metallicRoughnessTexture` +with roughness in green and metallic in blue, the layout `PackedOrm` names. MaterialX's +`standard_surface` has the matching inputs `base_color`, `normal`, `specular_roughness`, +`metalness`, `emission_color` and `opacity` +(). +Height and glossiness have neither; a glossiness map is labeled and its values are not +inverted. + +| `NameLimits` field | Default | On a list over it | +|---|---|---| +| `max_names` | 4096 | `NameError::TooManyNames`; the first name past the limit is taken from the iterator but not read, and no later name is taken | +| `max_name_bytes` | 1024 UTF-8 bytes, folder included | `NameError::NameTooLong` with the name's index | + ## Origin | Part | Source | @@ -113,6 +182,7 @@ Without `parallel` the crate builds for `wasm32-unknown-unknown`. | The Sobel normal, its strength scale, UV-tile clamp and uncovered-neighbor rule, the ORM channels and defaults, and the tests `gltf_png_matches_the_composite`, `directx_flips_green`, `height_becomes_normal_detail`, `ao_mixes_baked_and_channel`, `converted_maps_invert_and_derive_normals` and `uv_tiles_export_one_file_per_tile_without_padding_across`, with assertions on the new functions | TextureCraft `crates/formats/src/export/mod.rs`, `presets.rs` and `tests.rs` and `crates/core/src/channel.rs` at [b89badc](https://github.com/storytold/texturecraft/commit/b89badcd6f883751f79960f93c554fb77f063885) | | `ScalarSource`, row-at-a-time reading, the limit and non-finite checks, and the tiled-input tests | written here | | `mip`: mip chains, LOD and level selection, and their tests | written here | +| `texture_set` and its tests | written here; its words compared with TextureCraft `crates/formats/src/pbr_map/mod.rs` at [7a840ea](https://github.com/storytold/texturecraft/commit/7a840ea672bc3fc713911092f42c5c24c224f3e5) | ## Migration diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index d3a4ef1b5b..3c7f1e11ca 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -52,6 +52,7 @@ use rayon::prelude::*; pub mod normal; pub mod packing; mod source; +pub mod texture_set; #[cfg(test)] mod tiled_tests; diff --git a/crates/texture/src/texture_set.rs b/crates/texture/src/texture_set.rs new file mode 100644 index 0000000000..3be0baec72 --- /dev/null +++ b/crates/texture/src/texture_set.rs @@ -0,0 +1,1035 @@ +//! Texture sets recognized from image file names. +//! +//! [`recognize`] takes a list of file names, such as a folder listing or the entries of an +//! archive, groups the image names into [`TextureSet`]s by their shared stem, and gives each name +//! the [`MapRole`] that its suffix or prefix names: `Brick_BaseColor.png`, `brick_nor_gl_4k.exr` +//! and `brick_ARM.png` are the base color, an OpenGL normal map and a packed occlusion, +//! roughness and metallic map of the set `Brick`. The roles are the textures of the glTF 2.0 +//! metallic-roughness material, section 3.9 +//! (), and the matching inputs of +//! MaterialX's `standard_surface` +//! (), +//! plus height and glossiness. +//! +//! The module reads names only. It opens no file, joins or resolves no path and accepts names in +//! any Unicode. A name is split at its last `/` or `\`, and only the part after it, the leaf, is +//! read; the part before it is the folder, compared with `\` and `/` taken as equal. When the +//! name starts with its only separator, as in `/brick_albedo.png`, the folder is that separator. +//! [`NameLimits`] caps the number of names and the bytes of each, and the memory used grows only +//! with the names read. +//! +//! # Rules +//! +//! 1. Only a leaf whose extension is in [`IMAGE_EXTENSIONS`], in any ASCII case, is a map. +//! Archive metadata (a `__MACOSX` folder, a leaf starting with `._`) and preview images (a +//! word such as `preview`, `thumb` or `swatch`) are ignored, each with its [`IgnoreReason`]. +//! 2. The stem (the leaf without its extension) is split into words at every character that is +//! not a letter or digit, at a change from an ASCII lower-case to an upper-case letter +//! (`BaseColor`), before the last letter of an upper-case run followed by a lower-case letter +//! (`ORMMap`), and between ASCII digits and other characters (`diff4k`). A number directly +//! followed by `k`, `px` or `bit` stays one word (`4k`). Words are compared after ASCII +//! lower-casing; other characters are compared as they are. +//! 3. Resolution words (`1k` to `16k`, `16px` to `16384px`, a bare power of two from 128 to +//! 16384), bit depths (`8bit`, `16bit`, `32bit`), normal conventions (`gl`, `ogl`, `opengl`, +//! `open gl`; `dx`, `directx`, `direct x`, `d3d` written without separators) and a four-digit +//! UDIM tile from 1001 to 1999 are taken out wherever they are. A bare `1024` is a resolution, +//! or tile 1024 when another name of its set has a tile; a name with both a bare `1024` and a +//! tile is [`IgnoreReason::SeveralTiles`]. A normal map's convention also comes from +//! `normalgl` and `normaldx`, in its role words and in normal words right next to them; a +//! name that states both conventions is [`IgnoreReason::ConflictingNormalConvention`]. +//! 4. The role is named by the last remaining words (three, two or one), or by the first ones when +//! the last do not name a role. Words right next to them that name the same role, as in +//! `diffuse_color`, go with them. The words left over are the set's stem. A different role named +//! right next to the role words makes the name [`IgnoreReason::SeveralRoles`], except an +//! occlusion, a roughness and a metallic word in that order, which name +//! [`MapRole::PackedOrm`]. A single letter is never a role, except a trailing `n` (normal). +//! 5. Names with the same folder and the same stem words form one set, in the order of their +//! first name. Two names of one set with the same role and tile are both kept and listed in +//! [`TextureSet::duplicates`]; none of them is chosen. An identical repeated name is ignored +//! as [`IgnoreReason::DuplicateName`]. + +use std::collections::{HashMap, HashSet}; +use std::ops::Range; + +use crate::normal::NormalConvention; + +/// Default [`NameLimits::max_names`]. +pub const DEFAULT_MAX_NAMES: usize = 4096; +/// Default [`NameLimits::max_name_bytes`]. +pub const DEFAULT_MAX_NAME_BYTES: usize = 1024; + +/// File extensions of the names read as images, compared without regard to ASCII case. +pub const IMAGE_EXTENSIONS: [&str; 10] = ["png", "jpg", "jpeg", "tga", "tif", "tiff", "bmp", "webp", "exr", "hdr"]; + +/// The map an image file name names. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[non_exhaustive] +pub enum MapRole { + /// Base color, albedo or diffuse color: glTF `baseColorTexture`, MaterialX `base_color`. + BaseColor, + /// A tangent-space normal map: glTF `normalTexture`, MaterialX `normal`. + Normal, + /// Roughness: the green channel of glTF `metallicRoughnessTexture`, MaterialX + /// `specular_roughness`. + Roughness, + /// Metallic: the blue channel of glTF `metallicRoughnessTexture`, MaterialX `metalness`. + Metallic, + /// Ambient occlusion: glTF `occlusionTexture`, which is read from red. + AmbientOcclusion, + /// Height or displacement. + Height, + /// Emissive color: glTF `emissiveTexture`, MaterialX `emission_color`. + Emissive, + /// Opacity or alpha: MaterialX `opacity`. + Opacity, + /// Glossiness or smoothness, the inverse of roughness. The name is labeled only; no value is + /// inverted. + Glossiness, + /// One image with occlusion in red, roughness in green and metallic in blue (`ORM`, `ARM`). + PackedOrm, +} + +/// Caps on the names [`recognize`] reads. `#[non_exhaustive]`: start from +/// [`NameLimits::default`] and set the fields you change. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub struct NameLimits { + /// Most names in one call. Default [`DEFAULT_MAX_NAMES`]. To find a longer list, [`recognize`] + /// takes one name past the limit from the iterator and does not read it. + pub max_names: usize, + /// Most UTF-8 bytes in one name, folder included. Default [`DEFAULT_MAX_NAME_BYTES`]. + pub max_name_bytes: usize, +} + +impl Default for NameLimits { + fn default() -> Self { + Self { max_names: DEFAULT_MAX_NAMES, max_name_bytes: DEFAULT_MAX_NAME_BYTES } + } +} + +/// Why [`recognize`] read no list. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum NameError { + /// The list holds more than [`NameLimits::max_names`] names. The first name past the limit is + /// taken from the iterator but not read, and no later name is taken. + #[error("the list holds more than {limit} names")] + TooManyNames { limit: usize }, + /// The name at `index` is longer than [`NameLimits::max_name_bytes`]. + #[error("name {index} is {bytes} bytes long, over the limit of {limit}")] + NameTooLong { index: usize, bytes: usize, limit: usize }, +} + +/// Why a name is in no texture set. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum IgnoreReason { + /// The same name came earlier in the list. + DuplicateName, + /// The name ends with a separator, or its leaf has no letter or digit before the extension. + NoFileName, + /// The leaf has no extension, or one that is not in [`IMAGE_EXTENSIONS`]. + NotAnImage, + /// A `__MACOSX` folder or a leaf starting with `._`, as archivers write them. + ArchiveMetadata, + /// A preview, thumbnail or swatch image. + Preview, + /// No role word at the end or the start of the stem. + UnknownMap, + /// A known map that has no [`MapRole`], such as cavity or specular. + UnsupportedMap, + /// Two different roles named next to each other, such as `albedo_normal`. + SeveralRoles, + /// Two different UDIM tiles in one name. + SeveralTiles, + /// A normal map named both OpenGL and DirectX. + ConflictingNormalConvention, +} + +/// A name that is in no texture set. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IgnoredName<'a> { + /// Position of the name in the list. + pub index: usize, + /// The name as given. + pub name: &'a str, + pub reason: IgnoreReason, +} + +/// A name of a texture set and the map it names. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MapName<'a> { + /// Position of the name in the list. + pub index: usize, + /// The name as given. + pub name: &'a str, + pub role: MapRole, + /// For a normal map, the convention its name states; `None` when it states none, and for + /// every other role. + pub convention: Option, + /// The UDIM tile its name states. + pub tile: Option, +} + +/// Maps of one set that name the same role and tile. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DuplicateRole { + pub role: MapRole, + pub tile: Option, + /// Positions in [`TextureSet::maps`], in list order. There are at least two. + pub maps: Vec, +} + +/// The maps whose names share a folder and a stem. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TextureSet<'a> { + /// The folder part of the set's first name, without its last separator; empty for a bare + /// name, and the separator alone for a name such as `/brick_albedo.png`. + pub folder: &'a str, + /// The stem words of the set's first name, as written there: without its role words and the + /// words that rule 3 takes out, so `brick_4k_wall_albedo.png` gives `brick_wall`. Empty for a + /// name such as `normal.png`. Names whose stem words differ only in ASCII case or in the + /// separators between them are in the same set. + pub stem: String, + /// The maps in list order. + pub maps: Vec>, + /// Every role and tile that more than one map names, in the order of their first map. + pub duplicates: Vec, +} + +impl<'a> TextureSet<'a> { + /// The maps that name `role`, in list order. + pub fn maps_for(&self, role: MapRole) -> impl Iterator> + '_ { + self.maps.iter().filter(move |map| map.role == role) + } +} + +/// The texture sets of a list of names and the names that are in none. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Recognition<'a> { + /// The sets in the order of their first name. + pub sets: Vec>, + /// The names that are in no set, in list order. + pub ignored: Vec>, +} + +/// Groups the image file names of `names` into texture sets and names each one's map role. Reads +/// the names one at a time and stops at the first that breaks `limits`. +/// +/// Returns [`NameError::TooManyNames`] when `names` has more than [`NameLimits::max_names`] +/// entries; to find that out it takes one entry past the limit from the iterator, which a lazy +/// iterator has to produce, and does not read it. Returns [`NameError::NameTooLong`] for the first +/// name over +/// [`NameLimits::max_name_bytes`]. An empty list gives an empty [`Recognition`]. +pub fn recognize<'a>(names: impl IntoIterator, limits: &NameLimits) -> Result, NameError> { + let mut seen: HashSet<&'a str> = HashSet::new(); + let mut groups: HashMap<(String, String), usize> = HashMap::new(); + let mut sets: Vec> = Vec::new(); + let mut ignored = Vec::new(); + for (index, name) in names.into_iter().enumerate() { + if index >= limits.max_names { + return Err(NameError::TooManyNames { limit: limits.max_names }); + } + if name.len() > limits.max_name_bytes { + return Err(NameError::NameTooLong { index, bytes: name.len(), limit: limits.max_name_bytes }); + } + if !seen.insert(name) { + ignored.push(IgnoredName { index, name, reason: IgnoreReason::DuplicateName }); + continue; + } + match classify(name) { + Err(reason) => ignored.push(IgnoredName { index, name, reason }), + Ok(parsed) => { + let key = (parsed.folder.replace('\\', "/"), parsed.key.clone()); + let at = *groups.entry(key).or_insert_with(|| { + sets.push(SetBuilder::new(parsed.folder, parsed.stem.clone())); + sets.len() - 1 + }); + if let Some(set) = sets.get_mut(at) { + set.push(index, name, &parsed); + } + } + } + } + Ok(Recognition { sets: sets.into_iter().map(SetBuilder::finish).collect(), ignored }) +} + +/// A set being built, with a flag per map for a bare `1024` read as a resolution. +struct SetBuilder<'a> { + set: TextureSet<'a>, + bare_1024: Vec, +} + +impl<'a> SetBuilder<'a> { + fn new(folder: &'a str, stem: String) -> Self { + Self { set: TextureSet { folder, stem, maps: Vec::new(), duplicates: Vec::new() }, bare_1024: Vec::new() } + } + + fn push(&mut self, index: usize, name: &'a str, parsed: &Parsed<'a>) { + self.set.maps.push(MapName { index, name, role: parsed.role, convention: parsed.convention, tile: parsed.tile }); + self.bare_1024.push(parsed.bare_1024); + } + + fn finish(mut self) -> TextureSet<'a> { + if self.set.maps.iter().any(|map| map.tile.is_some()) { + for (map, bare) in self.set.maps.iter_mut().zip(&self.bare_1024) { + if *bare && map.tile.is_none() { + map.tile = Some(1024); + } + } + } + self.set.duplicates = duplicates(&self.set.maps); + self.set + } +} + +/// Every role and tile that more than one of `maps` names. +fn duplicates(maps: &[MapName<'_>]) -> Vec { + let mut slots: HashMap<(MapRole, Option), usize> = HashMap::new(); + let mut found: Vec = Vec::new(); + for (position, map) in maps.iter().enumerate() { + let at = *slots.entry((map.role, map.tile)).or_insert_with(|| { + found.push(DuplicateRole { role: map.role, tile: map.tile, maps: Vec::new() }); + found.len() - 1 + }); + if let Some(slot) = found.get_mut(at) { + slot.maps.push(position); + } + } + found.retain(|slot| slot.maps.len() > 1); + found +} + +/// What one name says. +struct Parsed<'a> { + folder: &'a str, + stem: String, + /// The stem words joined by `_`, the set's grouping key. + key: String, + role: MapRole, + convention: Option, + tile: Option, + bare_1024: bool, +} + +/// A role word, or a known map that has no [`MapRole`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Word { + Map(MapRole), + Unsupported, +} + +/// Every single role word. The README's table lists the same words. +const WORDS: &[(Word, &[&str])] = &[ + (Word::Map(MapRole::BaseColor), &["basecolor", "basecolour", "albedo", "diffuse", "diff", "color", "colour", "col", "bc", "basemap", "maintex"]), + (Word::Map(MapRole::Normal), &["normal", "normalmap", "normalgl", "normaldx", "nrm", "nor", "norm", "nm", "n", "bumpmap"]), + (Word::Map(MapRole::Roughness), &["roughness", "rough", "rgh"]), + (Word::Map(MapRole::Metallic), &["metallic", "metalness", "metal", "met", "mtl"]), + (Word::Map(MapRole::AmbientOcclusion), &["ambientocclusion", "ao", "occlusion", "occ", "ambocc"]), + (Word::Map(MapRole::Height), &["height", "heightmap", "displacement", "disp", "displace", "hgt", "bump"]), + (Word::Map(MapRole::Emissive), &["emissive", "emission", "emissivecolor", "emissionmap", "emit", "glow"]), + (Word::Map(MapRole::Opacity), &["opacity", "alpha", "transparency", "cutout"]), + (Word::Map(MapRole::Glossiness), &["glossiness", "gloss", "smoothness", "smooth"]), + (Word::Map(MapRole::PackedOrm), &["orm", "arm", "aorm"]), + (Word::Unsupported, &["cavity", "curvature", "specular", "thickness", "sheen", "ior"]), +]; + +/// Every two-word role. The README's table lists the same pairs. +const PAIRS: &[(MapRole, &[[&str; 2]])] = &[ + (MapRole::BaseColor, &[["base", "color"], ["base", "colour"], ["base", "map"], ["main", "tex"]]), + (MapRole::Normal, &[["normal", "map"], ["bump", "map"]]), + (MapRole::AmbientOcclusion, &[["ambient", "occlusion"]]), + (MapRole::Height, &[["height", "map"]]), + (MapRole::Emissive, &[["emissive", "color"], ["emissive", "colour"], ["emission", "map"]]), +]; + +/// Words that mark a preview image. +const PREVIEW_WORDS: [&str; 10] = ["preview", "previews", "thumb", "thumbs", "thumbnail", "sphere", "render", "swatch", "icon", "screenshot"]; + +fn word(text: &str) -> Option { + WORDS.iter().find(|(_, words)| words.contains(&text)).map(|(word, _)| *word) +} + +fn pair(first: &str, second: &str) -> Option { + PAIRS.iter().find(|(_, pairs)| pairs.iter().any(|[a, b]| *a == first && *b == second)).map(|(role, _)| *role) +} + +/// The role that the words of `span` name together. +fn span_word(words: &[&str], span: Range) -> Option { + match words.get(span)? { + [a, b, c] => { + let packed = word(a) == Some(Word::Map(MapRole::AmbientOcclusion)) + && word(b) == Some(Word::Map(MapRole::Roughness)) + && word(c) == Some(Word::Map(MapRole::Metallic)); + packed.then_some(Word::Map(MapRole::PackedOrm)) + } + [a, b] => pair(a, b).map(Word::Map), + [a] => word(a), + _ => None, + } +} + +/// The longest role span of one to three words at the end of `words`, or at the start when +/// `at_end` is false. A lone `n` counts only when `lone_n` is true. +fn edge_span(words: &[&str], at_end: bool, lone_n: bool) -> Option<(Word, Range)> { + let n = words.len(); + (1..=n.min(3)).rev().find_map(|k| { + let span = if at_end { n - k..n } else { 0..k }; + if k == 1 && !lone_n && words.get(span.start) == Some(&"n") { + return None; + } + span_word(words, span.clone()).map(|w| (w, span)) + }) +} + +/// The role of `words` and the positions of its role words, together with the words right next to +/// them that name the same role, or why the words name none. +fn find_role(words: &[&str]) -> Result<(MapRole, Range), IgnoreReason> { + let (found, mut span) = edge_span(words, true, true).or_else(|| edge_span(words, false, false)).ok_or(IgnoreReason::UnknownMap)?; + let at_end = span.end == words.len(); + // The words on the stem side of the role words, and a role they name right next to them. + loop { + let side = if at_end { words.get(..span.start) } else { words.get(span.end..) }.unwrap_or_default(); + match edge_span(side, at_end, false) { + Some((w, _)) if w != found => return Err(IgnoreReason::SeveralRoles), + Some((_, next)) if at_end => span.start = next.start, + Some((_, next)) => span.end += next.len(), + None => break, + } + } + match found { + Word::Map(role) => Ok((role, span)), + Word::Unsupported => Err(IgnoreReason::UnsupportedMap), + } +} + +/// What a name says, or why it is in no set. +fn classify(name: &str) -> Result, IgnoreReason> { + let (folder, leaf) = match name.rfind(['/', '\\']) { + // A name under the root keeps its separator as the folder. + Some(0) => name.split_at(1), + Some(at) => (name.get(..at).unwrap_or_default(), name.get(at + 1..).unwrap_or_default()), + None => ("", name), + }; + if name.split(['/', '\\']).any(|part| part == "__MACOSX") || leaf.starts_with("._") { + return Err(IgnoreReason::ArchiveMetadata); + } + if leaf.is_empty() { + return Err(IgnoreReason::NoFileName); + } + let (stem, extension) = leaf.rsplit_once('.').ok_or(IgnoreReason::NotAnImage)?; + if !IMAGE_EXTENSIONS.iter().any(|known| known.eq_ignore_ascii_case(extension)) { + return Err(IgnoreReason::NotAnImage); + } + let tokens = tokens(stem); + if tokens.is_empty() { + return Err(IgnoreReason::NoFileName); + } + if tokens.iter().any(|t| PREVIEW_WORDS.contains(&t.text.as_str())) { + return Err(IgnoreReason::Preview); + } + let extras = Extras::split(&tokens); + let words: Vec<&str> = extras.kept.iter().filter_map(|&i| tokens.get(i)).map(|t| t.text.as_str()).collect(); + let (role, span) = find_role(&words)?; + let rest = if span.start == 0 { extras.kept.get(span.end..) } else { extras.kept.get(..span.start) }.unwrap_or_default(); + let stem_text = stem_without_extras(stem, &tokens, rest); + let key = rest.iter().filter_map(|&i| tokens.get(i)).map(|t| t.text.as_str()).collect::>().join("_"); + // The conventions that the role words with one glued on state. + let glued: Vec = words + .get(span) + .unwrap_or_default() + .iter() + .filter_map(|w| match *w { + "normalgl" => Some(NormalConvention::OpenGl), + "normaldx" => Some(NormalConvention::DirectX), + _ => None, + }) + .collect(); + let convention = if role == MapRole::Normal { extras.convention(&glued)? } else { None }; + let tile = extras.tile()?; + // A bare 1024 next to a tile is a second tile. + if extras.bare_1024 && tile.is_some() { + return Err(IgnoreReason::SeveralTiles); + } + Ok(Parsed { folder, stem: stem_text, key, role, convention, tile, bare_1024: extras.bare_1024 }) +} + +/// The words of `stem` at the token positions `rest` (ascending) as written, each joined to the +/// one before by the text between them. Where extra words were taken out between two of them, +/// the join is the text before the first extra word, so `brick_4k_wall` gives `brick_wall`. +fn stem_without_extras(stem: &str, tokens: &[Token], rest: &[usize]) -> String { + let mut out = String::new(); + let mut previous: Option = None; + for &i in rest { + let Some(token) = tokens.get(i) else { continue }; + if let Some(p) = previous + && let (Some(before), Some(next)) = (tokens.get(p), tokens.get(p + 1)) + { + out.push_str(stem.get(before.end..next.start).unwrap_or_default()); + } + out.push_str(stem.get(token.start..token.end).unwrap_or_default()); + previous = Some(i); + } + out +} + +/// A word of a stem: its byte range in the stem and its text, ASCII lower-cased. +struct Token { + start: usize, + end: usize, + text: String, +} + +/// Whether a word ends between `previous` and `c`, given the character after `c`. +fn splits(previous: char, c: char, next: Option) -> bool { + (previous.is_ascii_lowercase() && c.is_ascii_uppercase()) + || (previous.is_ascii_uppercase() && c.is_ascii_uppercase() && next.is_some_and(|n| n.is_ascii_lowercase())) + || previous.is_ascii_digit() != c.is_ascii_digit() +} + +/// The words of `stem`. +fn tokens(stem: &str) -> Vec { + let chars: Vec<(usize, char)> = stem.char_indices().collect(); + let mut out: Vec = Vec::new(); + let mut current: Option = None; + let mut previous: Option = None; + for (n, &(i, c)) in chars.iter().enumerate() { + if !c.is_alphanumeric() { + out.extend(current.take()); + previous = None; + continue; + } + let next = chars.get(n + 1).map(|&(_, next)| next); + if previous.is_some_and(|p| splits(p, c, next)) { + out.extend(current.take()); + } + let token = current.get_or_insert_with(|| Token { start: i, end: i, text: String::new() }); + token.text.push(c.to_ascii_lowercase()); + token.end = i + c.len_utf8(); + previous = Some(c); + } + out.extend(current); + join_units(out) +} + +/// `tokens` with each number joined to a `k`, `px` or `bit` written right after it. +fn join_units(tokens: Vec) -> Vec { + let mut out: Vec = Vec::with_capacity(tokens.len()); + for token in tokens { + if let Some(last) = out.last_mut() + && last.end == token.start + && last.text.bytes().all(|b| b.is_ascii_digit()) + && matches!(token.text.as_str(), "k" | "px" | "bit") + { + last.text.push_str(&token.text); + last.end = token.end; + continue; + } + out.push(token); + } + out +} + +/// A word that is taken out of the stem. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Extra { + Size, + Convention(NormalConvention), + Tile(u16), + Bare1024, +} + +/// A number of at most five ASCII digits. +fn number(text: &str) -> Option { + if text.is_empty() || text.len() > 5 || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +fn single_extra(text: &str) -> Option { + match text { + "gl" | "ogl" | "opengl" => return Some(Extra::Convention(NormalConvention::OpenGl)), + "dx" | "directx" => return Some(Extra::Convention(NormalConvention::DirectX)), + "8bit" | "16bit" | "32bit" => return Some(Extra::Size), + _ => {} + } + if let Some(n) = text.strip_suffix('k') { + return number(n).filter(|n| (1..=16).contains(n)).map(|_| Extra::Size); + } + if let Some(n) = text.strip_suffix("px") { + return number(n).filter(|n| (16..=16384).contains(n)).map(|_| Extra::Size); + } + let n = number(text)?; + if text.len() == 4 && n == 1024 { + Some(Extra::Bare1024) + } else if text.len() == 4 && (1001..=1999).contains(&n) { + u16::try_from(n).ok().map(Extra::Tile) + } else { + ((128..=16384).contains(&n) && n.is_power_of_two()).then_some(Extra::Size) + } +} + +/// The extra word starting at `tokens[i]` and how many tokens it spans. +fn extra_at(tokens: &[Token], i: usize) -> Option<(Extra, usize)> { + let text = |k: usize| tokens.get(i + k).map(|t| t.text.as_str()); + // Whether tokens[i + k] ends where the next token starts. + let touches = |k: usize| matches!((tokens.get(i + k), tokens.get(i + k + 1)), (Some(a), Some(b)) if a.end == b.start); + match (text(0)?, text(1), text(2)) { + ("open", Some("gl"), _) => Some((Extra::Convention(NormalConvention::OpenGl), 2)), + ("direct", Some("x"), _) => Some((Extra::Convention(NormalConvention::DirectX), 2)), + ("d", Some("3"), Some("d")) if touches(0) && touches(1) => Some((Extra::Convention(NormalConvention::DirectX), 3)), + (first, _, _) => single_extra(first).map(|extra| (extra, 1)), + } +} + +/// The extra words of a stem and the positions of the other words. +struct Extras { + kept: Vec, + found: Vec, + bare_1024: bool, +} + +impl Extras { + fn split(tokens: &[Token]) -> Self { + let mut extras = Extras { kept: Vec::new(), found: Vec::new(), bare_1024: false }; + let mut i = 0; + while i < tokens.len() { + match extra_at(tokens, i) { + Some((Extra::Bare1024, len)) => { + extras.bare_1024 = true; + i += len; + } + Some((extra, len)) => { + extras.found.push(extra); + i += len; + } + None => { + extras.kept.push(i); + i += 1; + } + } + } + extras + } + + /// The normal convention the words and `glued` state, or an error when they state both. + fn convention(&self, glued: &[NormalConvention]) -> Result, IgnoreReason> { + let stated = self.found.iter().filter_map(|extra| match extra { + Extra::Convention(c) => Some(*c), + _ => None, + }); + let mut result = None; + for c in glued.iter().copied().chain(stated) { + match result { + Some(r) if r != c => return Err(IgnoreReason::ConflictingNormalConvention), + _ => result = Some(c), + } + } + Ok(result) + } + + /// The UDIM tile the words state, or an error when they state two. + fn tile(&self) -> Result, IgnoreReason> { + let mut result = None; + for extra in &self.found { + if let Extra::Tile(t) = extra { + match result { + Some(r) if r != *t => return Err(IgnoreReason::SeveralTiles), + _ => result = Some(*t), + } + } + } + Ok(result) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run<'a>(names: &[&'a str]) -> Recognition<'a> { + match recognize(names.iter().copied(), &NameLimits::default()) { + Ok(found) => found, + Err(e) => panic!("recognition failed: {e}"), + } + } + + /// The role and stem of one name, or why it is ignored. + fn one(name: &str) -> Result<(MapRole, String), IgnoreReason> { + let found = run(&[name]); + match (found.sets.first(), found.ignored.first()) { + (Some(set), None) => match set.maps.as_slice() { + [map] => Ok((map.role, set.stem.to_string())), + maps => panic!("{name}: {} maps", maps.len()), + }, + (None, Some(ignored)) => Err(ignored.reason), + _ => panic!("{name}: {found:?}"), + } + } + + fn role_named(label: &str) -> Option { + Some(match label { + "`BaseColor`" => Word::Map(MapRole::BaseColor), + "`Normal`" => Word::Map(MapRole::Normal), + "`Roughness`" => Word::Map(MapRole::Roughness), + "`Metallic`" => Word::Map(MapRole::Metallic), + "`AmbientOcclusion`" => Word::Map(MapRole::AmbientOcclusion), + "`Height`" => Word::Map(MapRole::Height), + "`Emissive`" => Word::Map(MapRole::Emissive), + "`Opacity`" => Word::Map(MapRole::Opacity), + "`Glossiness`" => Word::Map(MapRole::Glossiness), + "`PackedOrm`" => Word::Map(MapRole::PackedOrm), + "`UnsupportedMap` (ignored)" => Word::Unsupported, + _ => return None, + }) + } + + fn backticked(cell: &str) -> Vec { + cell.split('`').skip(1).step_by(2).map(str::to_string).collect() + } + + /// The README's word table: each role with its words and its pairs. + fn readme_table() -> Vec<(Word, Vec, Vec)> { + let readme = include_str!("../README.md"); + let section = readme.split("## Texture-set names").nth(1).unwrap_or_default(); + let section = section.split("\n## ").next().unwrap_or_default(); + let mut rows = Vec::new(); + for line in section.lines() { + let cells: Vec<&str> = line.split('|').map(str::trim).collect(); + if let [_, label, words, pairs, _] = cells.as_slice() + && let Some(role) = role_named(label) + { + rows.push((role, backticked(words), backticked(pairs))); + } + } + rows + } + + fn expect(word: Word) -> Result { + match word { + Word::Map(role) => Ok(role), + Word::Unsupported => Err(IgnoreReason::UnsupportedMap), + } + } + + #[test] + fn readme_table_lists_every_word_and_its_role() { + let table = readme_table(); + assert_eq!(table.len(), WORDS.len(), "README rows: {table:?}"); + for ((role, words, pairs), (code_role, code_words)) in table.iter().zip(WORDS) { + assert_eq!(role, code_role); + let code_words: Vec = code_words.iter().map(|w| w.to_string()).collect(); + assert_eq!(words, &code_words, "{role:?}"); + let code_pairs: Vec = + PAIRS.iter().filter(|(r, _)| Word::Map(*r) == *role).flat_map(|(_, pairs)| pairs.iter().map(|[a, b]| format!("{a} {b}"))).collect(); + assert_eq!(pairs, &code_pairs, "{role:?}"); + for word in words.iter().chain(pairs) { + let name = format!("brick_{}.png", word.replace(' ', "_")); + assert_eq!(one(&name), expect(*role).map(|r| (r, "brick".to_string())), "{name}"); + } + } + } + + /// `word` (one or more parts) in `case`, joined by `separator` or by case changes. + fn spell(parts: &[&str], case: usize, separator: &str) -> String { + let spelled: Vec = parts + .iter() + .map(|p| match case { + 0 => p.to_string(), + 1 => p.to_ascii_uppercase(), + _ => p.get(..1).unwrap_or_default().to_ascii_uppercase() + p.get(1..).unwrap_or_default(), + }) + .collect(); + spelled.join(separator) + } + + #[test] + fn every_word_in_any_case_separator_position_and_suffix() { + let mut spellings: Vec<(Vec<&str>, Word)> = Vec::new(); + for (word, words) in WORDS { + spellings.extend(words.iter().map(|w| (vec![*w], *word))); + } + for (role, pairs) in PAIRS { + spellings.extend(pairs.iter().map(|p| (p.to_vec(), Word::Map(*role)))); + } + spellings.push((vec!["ao", "rough", "metal"], Word::Map(MapRole::PackedOrm))); + spellings.push((vec!["occlusion", "roughness", "metallic"], Word::Map(MapRole::PackedOrm))); + let stems = ["brick", "Old Wall", "rock2", "ziegel_ß", "砖墙", "écorce"]; + let extras = ["", "_4k", "_2048", "-16bit", ".1001", "_512px"]; + let mut checked = 0; + for (parts, word) in &spellings { + for stem in stems { + for case in 0..3 { + for separator in ["_", "-", " ", "."] { + for extra in extras { + let spelled = spell(parts, case, separator); + let expected = expect(*word).map(|r| (r, stem.to_string())); + let suffix = format!("{stem}{separator}{spelled}{extra}.PNG"); + assert_eq!(one(&suffix), expected, "{suffix}"); + if parts.as_slice() != ["n"] { + let prefix = format!("{spelled}{separator}{stem}{extra}.png"); + assert_eq!(one(&prefix), expected, "{prefix}"); + } + checked += 1; + } + } + // Written right after an ASCII stem that ends in lower case, a word in title or + // upper case starts at its case change. + if case > 0 && stem.is_ascii() && stem.ends_with(|c: char| c.is_ascii_lowercase()) { + let glued = format!("{stem}{}.tga", spell(parts, 2, "")); + assert_eq!(one(&glued), expect(*word).map(|r| (r, stem.to_string())), "{glued}"); + } + } + } + } + assert!(checked > 10_000, "{checked} names checked"); + } + + #[test] + fn a_role_at_the_start_and_role_words_inside_the_stem() { + assert_eq!(one("albedo_brick.png"), Ok((MapRole::BaseColor, "brick".to_string()))); + assert_eq!(one("metal_plate_roughness.png"), Ok((MapRole::Roughness, "metal_plate".to_string()))); + assert_eq!(one("T_Brick_BC_4k.tga"), Ok((MapRole::BaseColor, "T_Brick".to_string()))); + assert_eq!(one("n_brick.png"), Err(IgnoreReason::UnknownMap)); + assert_eq!(one("brick_n.png"), Ok((MapRole::Normal, "brick".to_string()))); + for letter in ["r", "m", "d", "h"] { + assert_eq!(one(&format!("brick_{letter}.png")), Err(IgnoreReason::UnknownMap), "{letter}"); + } + } + + #[test] + fn normal_conventions_come_from_the_name() { + let convention = |name: &str| run(&[name]).sets.first().and_then(|s| s.maps.first()).and_then(|m| m.convention); + for name in ["brick_normal_gl.png", "brick_NormalGL.png", "brick_nor_opengl_4k.exr", "brick_normal-open-gl.png", "brick_normalgl.png"] { + assert_eq!(convention(name), Some(NormalConvention::OpenGl), "{name}"); + } + for name in ["brick_normal_dx.png", "Brick_NormalDX.png", "brick_nrm_directx.png", "brick_normal_d3d.png", "brick_normal_direct_x.png"] { + assert_eq!(convention(name), Some(NormalConvention::DirectX), "{name}"); + } + assert_eq!(convention("brick_normal.png"), None); + assert_eq!(convention("brick_albedo_dx.png"), None, "only a normal map has a convention"); + assert_eq!(one("brick_normal_gl_dx.png"), Err(IgnoreReason::ConflictingNormalConvention)); + assert_eq!(one("brick_NormalGL_dx.png"), Err(IgnoreReason::ConflictingNormalConvention)); + let found = run(&["brick_albedo_dx.png", "brick_normal_dx.png", "brick_normal_gl.png"]); + assert_eq!(found.sets.len(), 1, "convention words are not part of the stem"); + assert!(found.sets.iter().all(|s| s.duplicates.iter().any(|d| d.role == MapRole::Normal && d.maps == [1, 2]))); + } + + #[test] + fn a_normal_word_next_to_the_role_words_states_its_convention() { + let convention = |name: &str| run(&[name]).sets.first().and_then(|s| s.maps.first()).and_then(|m| m.convention); + assert_eq!(one("brick_normalgl_normaldx.png"), Err(IgnoreReason::ConflictingNormalConvention)); + assert_eq!(one("normalgl_normaldx_brick.png"), Err(IgnoreReason::ConflictingNormalConvention)); + assert_eq!(convention("brick_normaldx_normal.png"), Some(NormalConvention::DirectX)); + assert_eq!(convention("brick_normalgl_normal_gl.png"), Some(NormalConvention::OpenGl)); + assert_eq!(convention("brick_normalgl_normalgl_4k.png"), Some(NormalConvention::OpenGl)); + // The words next to the role words that name the same role are not in the stem. + let found = run(&[ + "brick_normal.png", + "brick_normal_normaldx.png", + "NormalGL_Normal_brick.png", + "brick_diffuse_color.png", + "brick_diffuse_color_albedo_bc.png", + "albedo_col_diffuse_brick.png", + ]); + let summary: Vec<(&str, Vec)> = found.sets.iter().map(|s| (s.stem.as_str(), s.maps.iter().map(|m| m.index).collect())).collect(); + assert_eq!(summary, [("brick", vec![0, 1, 2, 3, 4, 5])], "{:?}", found.ignored); + assert_eq!(one("brick_normal_nrm_normaldx_normalgl.png"), Err(IgnoreReason::ConflictingNormalConvention)); + assert_eq!(one("brick_normal_diffuse_color_albedo.png"), Err(IgnoreReason::SeveralRoles)); + } + + #[test] + fn d3d_is_read_only_when_its_letters_touch() { + let found = run(&["panel_d_3_d_normal_gl.png"]); + let maps: Vec<(&str, MapRole, Option)> = + found.sets.iter().flat_map(|s| s.maps.iter().map(|m| (s.stem.as_str(), m.role, m.convention))).collect(); + assert_eq!(maps, [("panel_d_3_d", MapRole::Normal, Some(NormalConvention::OpenGl))], "{:?}", found.ignored); + assert_eq!(one("panel_D3D_normal.png"), Ok((MapRole::Normal, "panel".to_string()))); + } + + #[test] + fn several_sets_in_one_folder() { + let found = run(&[ + "textures/brick_albedo.png", + "textures/wood_BaseColor.png", + "textures/Brick-Normal.png", + "textures\\wood_normal_4k.png", + "other/brick_albedo.png", + "textures/brick_4k_roughness.png", + ]); + let summary: Vec<(&str, &str, Vec)> = + found.sets.iter().map(|s| (s.folder, s.stem.as_str(), s.maps.iter().map(|m| m.index).collect())).collect(); + assert_eq!(summary, [("textures", "brick", vec![0, 2, 5]), ("textures", "wood", vec![1, 3]), ("other", "brick", vec![4])]); + assert!(found.ignored.is_empty()); + assert!(found.sets.iter().all(|s| s.duplicates.is_empty())); + } + + #[test] + fn size_and_convention_words_are_not_in_the_stem() { + let found = run(&["brick_4k_wall_albedo.png", "Brick4kWall_Normal_GL.png", "brick-d3d-wall_height.png", "brick_wall_2048_roughness.png"]); + let stems: Vec<(&str, usize)> = found.sets.iter().map(|s| (s.stem.as_str(), s.maps.len())).collect(); + assert_eq!(stems, [("brick_wall", 4)]); + let stem = |name: &str| one(name).map(|(_, stem)| stem); + assert_eq!(stem("Brick4kWall_Normal_GL.png"), Ok("BrickWall".to_string())); + assert_eq!(stem("brick-open-gl-wall_normal.png"), Ok("brick-wall".to_string())); + assert_eq!(stem("4k_brick_albedo.png"), Ok("brick".to_string())); + } + + #[test] + fn a_duplicate_role_is_reported_not_chosen() { + let found = run(&["brick_albedo.png", "brick_normal.png", "brick_diffuse_4k.jpg", "brick_albedo.png", "brick_col.tga"]); + let [set] = found.sets.as_slice() else { panic!("{found:?}") }; + assert_eq!(set.maps_for(MapRole::BaseColor).map(|m| m.index).collect::>(), [0, 2, 4]); + assert_eq!(set.duplicates, [DuplicateRole { role: MapRole::BaseColor, tile: None, maps: vec![0, 2, 3] }]); + assert_eq!(found.ignored, [IgnoredName { index: 3, name: "brick_albedo.png", reason: IgnoreReason::DuplicateName }]); + } + + #[test] + fn unknown_unsupported_and_other_names_are_ignored_with_a_reason() { + let cases = [ + ("brick_wood.png", IgnoreReason::UnknownMap), + ("brick_normal_v2.png", IgnoreReason::UnknownMap), + ("4k.png", IgnoreReason::UnknownMap), + ("brick_cavity.png", IgnoreReason::UnsupportedMap), + ("brick_albedo_normal.png", IgnoreReason::SeveralRoles), + ("brick_rough_metal.png", IgnoreReason::SeveralRoles), + ("brick_normal_map_roughness.png", IgnoreReason::SeveralRoles), + ("roughness_normal_map_brick.png", IgnoreReason::SeveralRoles), + ("brick_ao_rough_metal_albedo.png", IgnoreReason::SeveralRoles), + ("brick_albedo", IgnoreReason::NotAnImage), + ("brick_albedo.psd", IgnoreReason::NotAnImage), + ("readme.txt", IgnoreReason::NotAnImage), + ("brick_albedo_preview.png", IgnoreReason::Preview), + ("Thumbnail_brick_albedo.jpg", IgnoreReason::Preview), + ("__MACOSX/brick/brick_albedo.png", IgnoreReason::ArchiveMetadata), + ("brick/._brick_albedo.png", IgnoreReason::ArchiveMetadata), + ]; + for (name, reason) in cases { + assert_eq!(one(name), Err(reason), "{name}"); + } + } + + #[test] + fn only_a_leaf_starting_with_dot_underscore_is_archive_metadata() { + assert_eq!(one("assets/._materials/brick_albedo.png"), Ok((MapRole::BaseColor, "brick".to_string()))); + assert_eq!(one("assets\\._materials\\._brick_albedo.png"), Err(IgnoreReason::ArchiveMetadata)); + assert_eq!(one("a/__MACOSX/b/brick_albedo.png"), Err(IgnoreReason::ArchiveMetadata)); + } + + #[test] + fn a_rooted_name_is_not_in_the_set_of_a_bare_name() { + let found = run(&["brick_albedo.png", "/brick_normal.png", "\\brick_roughness.png"]); + let summary: Vec<(&str, &str, Vec)> = + found.sets.iter().map(|s| (s.folder, s.stem.as_str(), s.maps.iter().map(|m| m.index).collect())).collect(); + assert_eq!(summary, [("", "brick", vec![0]), ("/", "brick", vec![1, 2])]); + } + + #[test] + fn an_empty_list_gives_nothing() { + assert_eq!(run(&[]), Recognition::default()); + } + + #[test] + fn names_with_no_stem() { + let found = run(&["normal.png", "folder/BaseColor.jpg"]); + let stems: Vec<(&str, &str, usize)> = found.sets.iter().map(|s| (s.folder, s.stem.as_str(), s.maps.len())).collect(); + assert_eq!(stems, [("", "", 1), ("folder", "", 1)]); + for name in [".png", "textures/", "textures\\", "", "___.png", "brick/-.exr"] { + assert_eq!(one(name), Err(IgnoreReason::NoFileName), "{name:?}"); + } + } + + #[test] + fn udim_tiles_stay_apart() { + let found = run(&["brick_albedo.1001.exr", "brick_albedo.1002.exr", "brick_normal_1001.exr", "brick_albedo_1001_4k.exr"]); + let [set] = found.sets.as_slice() else { panic!("{found:?}") }; + let tiles: Vec> = set.maps.iter().map(|m| m.tile).collect(); + assert_eq!(tiles, [Some(1001), Some(1002), Some(1001), Some(1001)]); + assert_eq!(set.duplicates, [DuplicateRole { role: MapRole::BaseColor, tile: Some(1001), maps: vec![0, 3] }]); + assert_eq!(one("brick_albedo_1001_1002.png"), Err(IgnoreReason::SeveralTiles)); + assert_eq!(one("brick_albedo_1024_1001.exr"), Err(IgnoreReason::SeveralTiles)); + assert_eq!(one("brick_albedo_2000.png"), Err(IgnoreReason::UnknownMap), "2000 is neither a tile nor a size"); + let tile_1024 = |names: &[&str]| run(names).sets.iter().flat_map(|s| s.maps.iter().map(|m| m.tile)).collect::>(); + assert_eq!(tile_1024(&["brick_albedo_1024.png"]), [None], "a bare 1024 alone is a resolution"); + assert_eq!(tile_1024(&["brick_albedo_1023.png", "brick_albedo_1024.png"]), [Some(1023), Some(1024)]); + } + + #[test] + fn packed_and_separate_maps_have_their_own_roles() { + let found = + run(&["brick_ao.png", "brick_roughness.png", "brick_metallic.png", "brick_ARM.png", "brick_ao_rough_metal.png", "brick_gloss.png"]); + let [set] = found.sets.as_slice() else { panic!("{found:?}") }; + let roles: Vec = set.maps.iter().map(|m| m.role).collect(); + assert_eq!( + roles, + [MapRole::AmbientOcclusion, MapRole::Roughness, MapRole::Metallic, MapRole::PackedOrm, MapRole::PackedOrm, MapRole::Glossiness] + ); + assert_eq!(set.duplicates, [DuplicateRole { role: MapRole::PackedOrm, tile: None, maps: vec![3, 4] }]); + } + + #[test] + fn unicode_names_are_kept_as_written() { + let found = run(&[ + "Ziegel Ä/砖墙_BaseColor.png", + "Ziegel Ä\\砖墙-normal.png", + "ÉCORCE_albedo.png", + "écorce_normal.png", + "\u{202e}gnp_brick_ao.png", + "🧱_metal.png", + ]); + let stems: Vec<(&str, &str)> = found.sets.iter().map(|s| (s.folder, s.stem.as_str())).collect(); + assert_eq!(stems, [("Ziegel Ä", "砖墙"), ("", "ÉCORCE"), ("", "écorce"), ("", "gnp_brick"), ("", "")], "ASCII case only is folded"); + assert!(found.ignored.is_empty()); + } + + #[test] + fn the_name_count_limit_is_checked() { + // Six digits are never a size or a tile, so every name is its own set. + let names: Vec = (0..DEFAULT_MAX_NAMES).map(|i| format!("set{i:06}_albedo.png")).collect(); + let Ok(found) = recognize(names.iter().map(String::as_str), &NameLimits::default()) else { panic!("at the limit") }; + assert_eq!(found.sets.len(), DEFAULT_MAX_NAMES); + let past = names.iter().map(String::as_str).chain(["one_more_albedo.png"]); + assert_eq!(recognize(past, &NameLimits::default()), Err(NameError::TooManyNames { limit: DEFAULT_MAX_NAMES })); + // An endless list stops at the limit. + assert_eq!(recognize(std::iter::repeat("a_albedo.png"), &NameLimits::default()), Err(NameError::TooManyNames { limit: DEFAULT_MAX_NAMES })); + let none = NameLimits { max_names: 0, ..NameLimits::default() }; + assert_eq!(recognize([], &none), Ok(Recognition::default())); + assert_eq!(recognize(["a_albedo.png"], &none), Err(NameError::TooManyNames { limit: 0 })); + } + + #[test] + fn the_name_length_limit_counts_bytes() { + // "é" is two bytes: 2 × 506 + 12 = 1024. + let at = format!("{}x_normal.png", "é".repeat(506)); + assert_eq!(at.len(), DEFAULT_MAX_NAME_BYTES); + assert_eq!(one(&at).map(|(role, _)| role), Ok(MapRole::Normal)); + let over = format!("x{at}"); + let names = ["brick_albedo.png", over.as_str()]; + assert_eq!( + recognize(names, &NameLimits::default()), + Err(NameError::NameTooLong { index: 1, bytes: DEFAULT_MAX_NAME_BYTES + 1, limit: DEFAULT_MAX_NAME_BYTES }) + ); + let short = NameLimits { max_name_bytes: 15, ..NameLimits::default() }; + assert_eq!(recognize(["a_albedo.png", "brick_albedo.png"], &short), Err(NameError::NameTooLong { index: 1, bytes: 16, limit: 15 })); + } + + #[test] + fn hostile_names_at_the_limits() { + let tokens = "a_".repeat(506) + "albedo.png"; + let tiles = "1001_1002_".repeat(100) + "normal.png"; + let glued = "aB".repeat(506) + "_albedo.png"; + let separators = "/\\".repeat(510) + ".png"; + let mut names = vec![tokens.as_str(), tiles.as_str(), glued.as_str(), separators.as_str()]; + assert!(names.iter().all(|n| n.len() <= DEFAULT_MAX_NAME_BYTES)); + let filler: Vec = (0..DEFAULT_MAX_NAMES - names.len()).map(|i| format!("{}_{i}_normal_dx_4k.exr", "z".repeat(1000))).collect(); + names.extend(filler.iter().map(String::as_str)); + let Ok(found) = recognize(names.iter().copied(), &NameLimits::default()) else { panic!("hostile names") }; + let maps: usize = found.sets.iter().map(|s| s.maps.len()).sum(); + assert_eq!(maps + found.ignored.len(), DEFAULT_MAX_NAMES, "{:?}", found.ignored); + assert_eq!( + found.ignored.iter().map(|i| (i.index, i.reason)).collect::>(), + [(1, IgnoreReason::SeveralTiles), (3, IgnoreReason::NoFileName)] + ); + } +} diff --git a/crates/texture/tests/it/main.rs b/crates/texture/tests/it/main.rs new file mode 100644 index 0000000000..c798d9d248 --- /dev/null +++ b/crates/texture/tests/it/main.rs @@ -0,0 +1,3 @@ +//! The crate's integration tests, linked into one test binary. + +mod srgb; diff --git a/crates/texture/tests/it/srgb.rs b/crates/texture/tests/it/srgb.rs new file mode 100644 index 0000000000..3ccf5f4f3c --- /dev/null +++ b/crates/texture/tests/it/srgb.rs @@ -0,0 +1,157 @@ +//! The scalar sRGB pair against IEC 61966-2-1. +//! +//! The encoding is the one the ICC sRGB registry entry gives for IEC 61966-2-1:1999 +//! (); the decoding is the CSS Color 4 sample code +//! (). Outside `[0, 1]` the pair keeps +//! its own rule: negative values stay on the linear segment and values above 1 follow the power +//! segment. + +use craft_texture::{linear_to_srgb, srgb_to_linear}; + +/// The largest difference allowed between the `f32` pair and the `f64` formulas. +const STANDARD_TOLERANCE: f32 = 3.0e-7; +/// The 8-bit and 16-bit code ranges. +const DEPTHS: [u32; 2] = [255, 65_535]; + +fn encode64(c: f64) -> f64 { + if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } +} + +fn decode64(c: f64) -> f64 { + if c <= 0.040_45 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } +} + +/// Every code of a depth with its normalized value. +fn codes(max: u32) -> impl Iterator { + (0..=max).map(move |n| (n, n as f32 / max as f32)) +} + +/// The largest difference between `f` and `g` over every code of a depth, and the code it is at. +/// A difference that is not finite fails at its code. +fn worst(max: u32, f: impl Fn(f32) -> f32, g: impl Fn(f32) -> f32) -> (f32, u32) { + let mut most = (0.0, 0); + for (n, v) in codes(max) { + let d = (f(v) - g(v)).abs(); + assert!(d.is_finite(), "code {n} of {max} gives a difference of {d}"); + if d > most.0 { + most = (d, n); + } + } + most +} + +#[test] +#[should_panic(expected = "code 0 of 255 gives a difference of NaN")] +fn worst_fails_on_a_difference_that_is_not_finite() { + worst(255, |_| f32::NAN, |v| v); +} + +#[test] +fn encode_matches_the_standard_at_every_8_and_16_bit_code() { + for max in DEPTHS { + let (d, n) = worst(max, linear_to_srgb, |v| encode64(f64::from(v)) as f32); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} is {d} from the standard"); + } +} + +#[test] +fn decode_matches_the_standard_at_every_8_and_16_bit_code() { + for max in DEPTHS { + let (d, n) = worst(max, srgb_to_linear, |v| decode64(f64::from(v)) as f32); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} is {d} from the standard"); + } +} + +#[test] +fn every_encoded_code_round_trips() { + for max in DEPTHS { + for (n, v) in codes(max) { + let back = (linear_to_srgb(srgb_to_linear(v)) * max as f32).round() as u32; + assert_eq!(back, n, "code {n} of {max}"); + } + } +} + +#[test] +fn every_linear_code_round_trips_within_rounding() { + for max in DEPTHS { + let (d, n) = worst(max, |v| srgb_to_linear(linear_to_srgb(v)), |v| v); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} comes back {d} away"); + } +} + +#[test] +fn outputs_do_not_decrease_over_the_code_grids() { + for max in DEPTHS { + for f in [linear_to_srgb, srgb_to_linear] { + let out: Vec = codes(max).map(|(_, v)| f(v)).collect(); + let fall = out.windows(2).position(|w| w[1] < w[0]); + assert_eq!(fall, None, "the output falls after code {fall:?} of {max}"); + } + } +} + +#[test] +fn encode_changes_segment_after_0_0031308() { + let t = 0.003_130_8_f32; + for v in [t.next_down(), t] { + assert_eq!(linear_to_srgb(v), v * 12.92, "{v} is on the linear segment"); + } + let above = t.next_up(); + assert_eq!(linear_to_srgb(above), 1.055 * above.powf(1.0 / 2.4) - 0.055); + for v in [t.next_down(), t, above] { + assert!((linear_to_srgb(v) - encode64(f64::from(v)) as f32).abs() <= STANDARD_TOLERANCE, "{v}"); + } +} + +#[test] +fn decode_changes_segment_after_0_04045() { + let t = 0.040_45_f32; + for v in [t.next_down(), t] { + assert_eq!(srgb_to_linear(v), v / 12.92, "{v} is on the linear segment"); + } + let above = t.next_up(); + assert_eq!(srgb_to_linear(above), ((above + 0.055) / 1.055).powf(2.4)); + for v in [t.next_down(), t, above] { + assert!((srgb_to_linear(v) - decode64(f64::from(v)) as f32).abs() <= STANDARD_TOLERANCE, "{v}"); + } +} + +#[test] +fn zero_and_one_map_to_themselves() { + for f in [linear_to_srgb, srgb_to_linear] { + assert_eq!(f(0.0).to_bits(), 0.0_f32.to_bits()); + assert_eq!(f(-0.0).to_bits(), (-0.0_f32).to_bits()); + assert!((f(1.0) - 1.0).abs() <= f32::EPSILON); + } +} + +#[test] +fn values_above_one_follow_the_power_segment() { + for v in [1.000_001_f32, 1.5, 2.0, 10.0] { + let (e, d) = (encode64(f64::from(v)), decode64(f64::from(v))); + assert!((f64::from(linear_to_srgb(v)) - e).abs() <= e * 1.0e-6, "encode {v}"); + assert!((f64::from(srgb_to_linear(v)) - d).abs() <= d * 1.0e-6, "decode {v}"); + } + assert!((linear_to_srgb(2.0) - 1.353_256).abs() < 1.0e-6); + assert!((srgb_to_linear(2.0) - 4.953_846).abs() < 1.0e-5); +} + +#[test] +fn negative_values_stay_on_the_linear_segment() { + for v in [-f32::MIN_POSITIVE, -1.0e-6, -0.003_130_8, -0.040_45, -0.5, -1.0, -100.0] { + assert_eq!(linear_to_srgb(v), v * 12.92, "encode {v}"); + assert_eq!(srgb_to_linear(v), v / 12.92, "decode {v}"); + } + assert!((linear_to_srgb(-1.0) + 12.92).abs() < 1.0e-5); + assert!((srgb_to_linear(-1.0) + 0.077_399_38).abs() < 1.0e-7); +} + +#[test] +fn infinities_keep_their_sign_and_nan_stays_nan() { + for f in [linear_to_srgb, srgb_to_linear] { + assert_eq!(f(f32::INFINITY), f32::INFINITY); + assert_eq!(f(f32::NEG_INFINITY), f32::NEG_INFINITY); + assert!(f(f32::NAN).is_nan()); + } +} diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 12b7cf7f43..2758b2affa 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -612,11 +612,20 @@ pub(crate) fn run( let mut state = std::mem::take(cx.core.memory.shown::(state_id)); // A part that was not shown last pass lost its focus, and its typing run with it: the run is forgotten (step 4 // ended its gesture without putting back the value from before it), and the part starts afresh from its value. - if !crate::runtime::memory::shown_last_pass(&ctx, id) { - state = TextState::default(); - } else if state.edit_target != part.options.edit_target { - // The old target's draft and gesture must never reach the new target's binding. - cx.cancel(CancelReason::HostChanged); + let shown_last_pass = crate::runtime::memory::shown_last_pass(&ctx, id); + if !shown_last_pass || state.edit_target != part.options.edit_target { + // The old target's draft and gesture must never reach the new target's binding. A hidden part's gesture + // already ended, but its widget may still retain history and composition. + if shown_last_pass { + cx.cancel(CancelReason::HostChanged); + } + let widget = adapter::text_id(id, part.key); + adapter::clear_history(&ctx, widget); + crate::runtime::ime::request_interrupt(&ctx, widget); + // Input was folded before this part ran; discard events already queued for the old target too. + let _ = crate::runtime::ime::take(&ctx, widget, false); + // A focus change may already have handed the old composition to this adapter. + let _ = crate::runtime::ime::take_leaving(&ctx, widget); state = TextState::default(); } state.edit_target = part.options.edit_target; diff --git a/crates/ui-contract/src/primitives/color_ranges.rs b/crates/ui-contract/src/primitives/color_ranges.rs new file mode 100644 index 0000000000..d60ecedc46 --- /dev/null +++ b/crates/ui-contract/src/primitives/color_ranges.rs @@ -0,0 +1,50 @@ +//! The color ranges of a field's text: the inks a [`TextOptions::color_ranges`](crate::primitives::TextOptions::color_ranges) +//! gives stretches of the text, and the longest text a part colors. + +use std::ops::Range; + +/// The colour ranges of a text ([`TextOptions::color_ranges`](crate::primitives::TextOptions::color_ranges)): called with +/// the text each time the part lays it out, which is every frame the part shows. An app whose ranges are costly to find +/// keeps its own cache. +pub type ColorRanges = dyn Fn(&str) -> Vec; + +/// The longest text, in bytes, a part colours: a longer one is laid out in its plain ink, and its +/// [`ColorRanges`] is not called. It bounds the cost of an app's colouring (a highlighter whose time grows with the +/// square of the length on crafted input) at the size of a long script. +pub const COLORED_TEXT_LIMIT: usize = 16 * 1024; + +/// A theme colour for a stretch of a field's text. Each is the token's colour moved, where it has to be, to the text +/// contrast minimum on the field's fill, so every ink reads in every theme and contrast. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum RangeInk { + /// `text.muted`. + Muted, + /// `accent.text`. + Accent, + /// `status.good.fg`. + Good, + /// `status.warn.fg`. + Warn, + /// `status.bad.fg`. + Bad, + /// `status.info.fg`. + Info, +} + +/// One stretch of a text in an ink of its own: `range` is in bytes of the text the [`ColorRanges`] was given. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct ColorRange { + /// The bytes the ink covers. + pub range: Range, + /// Their ink. + pub ink: RangeInk, +} + +impl ColorRange { + /// The bytes `range` in `ink`. + pub fn new(range: Range, ink: RangeInk) -> Self { + ColorRange { range, ink } + } +} diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 88734b2d3b..07651d967d 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -2,6 +2,7 @@ mod auto_scroll_mark; pub mod backdrop; +mod color_ranges; mod content; mod draw; mod face; @@ -35,6 +36,7 @@ pub mod textures; mod tool; pub use auto_scroll_mark::AutoScrollMark; +pub use color_ranges::{COLORED_TEXT_LIMIT, ColorRange, ColorRanges, RangeInk}; pub use content::{ContentPainterCx, DocRun, DocText, FaceRun}; pub use draw::{Dashes, DataStrokeWidth, DataWidth, Draw, PaintShape, StrokeColor, StrokePlace, StrokeWidth, WellFill}; pub use face::FacePaint; @@ -65,8 +67,7 @@ pub(crate) use svg_set::Layer; pub use svg_set::{AppIcons, register_app_icons}; pub use text::{ChordText, HAlign, LayoutRun, LeastLayout, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; pub use text_input::{ - COLORED_TEXT_LIMIT, ColorRange, ColorRanges, Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, - ImeStamp, RangeInk, SubmitKey, TabKey, TextKey, TextOptions, + Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp, SubmitKey, TabKey, TextKey, TextOptions, }; pub use textures::TextureCache; pub use tool::ToolIcon; diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index e6d91c84fd..5c51fd6391 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -442,6 +442,11 @@ pub(crate) fn select(ctx: &Context, id: Id, anchor: usize, caret: usize) { text_edit::select(ctx, id, anchor, caret); } +/// Forgets the Undo/Redo history of the text widget `id`. +pub(crate) fn clear_history(ctx: &Context, id: Id) { + text_edit::clear_history(ctx, id); +} + /// `TextOptions::arrows_from_end`: before the widget reads a plain Left or Right, a selection of the whole text /// collapses to its end. fn arrows_from_end(ctx: &Context, widget: Id, len: usize) { diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index dda34fb8d0..293cbe9346 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -1,6 +1,6 @@ //! The types of text parts and editors (18.2, 18.4): keys, options, completion and the own-caret editor state. -use crate::primitives::TextLayout; +use crate::primitives::{ColorRanges, TextLayout}; use crate::runtime::env::{Label, Message}; use crate::style::Ink; use craft_behavior::{PartKey, TextPos}; @@ -52,50 +52,6 @@ pub enum TabKey { /// Whether a pasted text is whole ([`TextOptions::whole_paste`]). type WholePaste = dyn Fn(&str) -> bool; -/// The colour ranges of a text ([`TextOptions::color_ranges`]): called with the text each time the part lays it out, -/// which is every frame the part shows. An app whose ranges are costly to find keeps its own cache. -pub type ColorRanges = dyn Fn(&str) -> Vec; - -/// The longest text, in bytes, a part colours: a longer one is laid out in its plain ink, and its -/// [`ColorRanges`] is not called. It bounds the cost of an app's colouring (a highlighter whose time grows with the -/// square of the length on crafted input) at the size of a long script. -pub const COLORED_TEXT_LIMIT: usize = 16 * 1024; - -/// A theme colour for a stretch of a field's text. Each is the token's colour moved, where it has to be, to the text -/// contrast minimum on the field's fill, so every ink reads in every theme and contrast. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub enum RangeInk { - /// `text.muted`. - Muted, - /// `accent.text`. - Accent, - /// `status.good.fg`. - Good, - /// `status.warn.fg`. - Warn, - /// `status.bad.fg`. - Bad, - /// `status.info.fg`. - Info, -} - -/// One stretch of a text in an ink of its own: `range` is in bytes of the text the [`ColorRanges`] was given. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ColorRange { - /// The bytes the ink covers. - pub range: Range, - /// Their ink. - pub ink: RangeInk, -} - -impl ColorRange { - /// The bytes `range` in `ink`. - pub fn new(range: Range, ink: RangeInk) -> Self { - ColorRange { range, ink } - } -} - /// How a text part behaves beyond its codec. #[derive(Clone)] pub struct TextOptions { @@ -112,6 +68,7 @@ pub struct TextOptions { /// A parsable draft applies as typed whatever the codec says. pub live: bool, /// The owner of the current draft, when the same field can edit different values. + /// A change retires the old draft, editor history and composition while preserving the field's focus. pub edit_target: Option, /// Escape clears the text and commits the empty text while text shows, and goes on to the host once it is empty. pub clear_on_escape: bool, @@ -188,7 +145,7 @@ pub struct TextOptions { /// Colours stretches of the text: the ranges it gives, in order, take their inks and the rest the part's ink. A range /// that is empty, overlaps the one before, ends past the text or splits a character is skipped. Colour is display /// only: editing, the caret, selection, wrapping and what assistive technology reads are as without it. A masked or - /// disabled part, and a text past [`COLORED_TEXT_LIMIT`], show no colours. + /// disabled part, and a text past [`COLORED_TEXT_LIMIT`](crate::primitives::COLORED_TEXT_LIMIT), show no colours. pub color_ranges: Option>, } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 2b4fe72886..f64ccd5479 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -357,6 +357,14 @@ pub(crate) fn select(ctx: &Context, id: Id, anchor: usize, caret: usize) { state.store(ctx, id); } +/// Discards Undo and Redo belonging to the previous target while keeping the widget's caret and focus. +pub(crate) fn clear_history(ctx: &Context, id: Id) { + if let Some(mut state) = TextEditState::load(ctx, id) { + state.set_undoer(Default::default()); + state.store(ctx, id); + } +} + /// Whether the widget's field has an undo step and a redo step, as `(undo, redo)`, against its current text `text` /// (egui's undoer compares its steps with the text, which the widget's state does not hold). It reads the undoer and /// steps nothing, so it agrees with what [`undo`] would do now. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs index 96b3ebc464..cdc32a2d7a 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs @@ -203,7 +203,8 @@ fn preset_row(ui: &mut Ui, kit: &Kit<'_>, options: &mut SaveForWebOptions, live: } /// "Optimize to File Size…" and, once opened, its rows; OK, or Enter in the Desired File Size field, files the search. -/// While the rows are closed, the host's last answer shows as a line while the settings are the ones it found. +/// OK waits while the Desired File Size holds text that does not parse. While the rows are closed, the host's last +/// answer shows as a line while the settings are the ones it found. fn optimize_rows(ui: &mut Ui, kit: &Kit<'_>, options: &SaveForWebOptions, live: &mut Live, asked: &mut Asked) { let Kit { words, units, .. } = *kit; if !live.optimize.open { @@ -218,10 +219,19 @@ fn optimize_rows(ui: &mut Ui, kit: &Kit<'_>, options: &SaveForWebOptions, live: } return; } + let mut unparsed = false; row(ui, &words.optimize_size, "optimize-size", |ui| { - let edit = whole(units, words.optimize_size.clone(), live.optimize.desired_k(), DESIRED_K).submits().show(ui).edit; - if let Some(k) = edit.value().cloned().flatten() { - live.optimize.k = Some(k); + // An `f32` field takes no blank value, so empty text does not parse, as text that is not a number does not. + let edit = NumberField::named(words.optimize_size.clone(), Bind::given(live.optimize.desired_k() as f32)) + .codec(NumberCodec::new(units.reader(None), 0)) + .step(1.0) + .range(DESIRED_K) + .submits() + .show(ui) + .edit; + unparsed = edit.unparsed; + if let Some(k) = edit.value().copied() { + live.optimize.k = Some(f64::from(k)); } if edit.submitted && edit.submit_mods == craft_keymap::Mods::NONE { asked.optimize_request = Some(live.optimize.request(options)); @@ -247,7 +257,7 @@ fn optimize_rows(ui: &mut Ui, kit: &Kit<'_>, options: &SaveForWebOptions, live: Text::new(reason.clone()).role(TypeRole::Caption).shade(Shade::Faint).id_salt("optimize-refused").show(ui); } Row::new().id_salt("optimize-buttons").show(ui, |ui, _| { - if clicked(&Button::new(words.optimize_ok.clone()).id_salt("optimize-ok").default_stop().show(ui)) { + if clicked(&Button::new(words.optimize_ok.clone()).id_salt("optimize-ok").enabled(!unparsed).default_stop().show(ui)) { asked.optimize_request = Some(live.optimize.request(options)); } if clicked(&Button::new(words.optimize_cancel.clone()).id_salt("optimize-cancel").show(ui)) { diff --git a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs index c1d12cdfd9..49f176fb51 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs @@ -320,6 +320,40 @@ fn enter_in_the_optimize_rows_files_the_search_and_never_saves() { assert!(host.borrow_mut().get_mut::().and_then(HostedSaveForWeb::pick_path).is_some(), "with the rows closed Enter saves"); } +// While the Desired File Size holds text the field refuses (not a number, or empty), the Optimize rows' OK and Enter in +// the field file no search with the size the rows held before; once the text parses, OK files the typed size. +#[trial] +fn the_optimize_rows_file_nothing_while_the_size_text_is_refused() { + let (host, mut fixture) = open(HostedSaveForWeb::new("poster.psd", IMAGE, texture()).optimize()); + let opener = fixture.by_label("Optimize to File Size…").expect("the Optimize button"); + fixture.click(&opener).idle(4); + assert!(host.borrow_mut().get_mut::().expect("open").take_optimize_open(), "opening the rows asks for the opening size"); + host.borrow_mut().get_mut::().expect("open").answer_optimize_start(Some(48 * 1024)); + fixture.idle(4); + let request = |host: &Rc>| host.borrow_mut().get_mut::().and_then(HostedSaveForWeb::take_optimize_request); + + for (text, what) in [("abc", "text that is not a number"), ("", "an empty field")] { + let field = fixture.by_label("Desired File Size (K)").expect("the Desired File Size field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).key(Key::Backspace, Modifiers::NONE).type_text(text); + fixture.idle(2); + fixture.key(Key::Enter, Modifiers::NONE).idle(4); + assert!(request(&host).is_none(), "Enter in the field files nothing while it holds {what}"); + let ok = fixture.by_label("OK").expect("the rows' OK"); + fixture.click(&ok).idle(4); + assert!(request(&host).is_none(), "OK files nothing while the field holds {what}"); + } + + let field = fixture.by_label("Desired File Size (K)").expect("the Desired File Size field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("20"); + fixture.idle(2); + let ok = fixture.by_label("OK").expect("the rows' OK"); + fixture.click(&ok).idle(4); + let filed = request(&host).expect("OK files the search once the text parses"); + assert_eq!(filed.desired_k, 20.0, "the search asks for the typed size"); +} + /// The frame the animation shows after the host's passes. fn frame_of(host: &Rc>) -> u32 { host.borrow_mut().get_mut::().map(|web| web.frame()).expect("the dialog is open") diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index 98df71e3a0..d9198686e1 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -353,7 +353,8 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { } /// Identifies the target of this field's edit, for a control reused across drawings or selections. - /// Changing the key discards the previous draft even when the two bound values are equal. + /// Changing the key discards the previous draft, editor Undo/Redo and input-method composition even when the + /// two bound values are equal. Late composition commits cannot enter the new target's draft. /// The field keeps its identity and focus. #[must_use] pub fn edit_target(mut self, key: impl egui::AsIdSalt) -> Self { diff --git a/crates/ui-widgets/tests/it/text/number.rs b/crates/ui-widgets/tests/it/text/number.rs index 800e197568..1cfb122d94 100644 --- a/crates/ui-widgets/tests/it/text/number.rs +++ b/crates/ui-widgets/tests/it/text/number.rs @@ -836,3 +836,151 @@ fn changing_a_number_fields_edit_target_clears_the_old_draft_with_equal_values() assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(13.0))); } } + +/// The editor's Undo and Redo belong to the object being edited, even when the next object has the same value. +#[trial] +fn changing_a_number_fields_edit_target_discards_the_old_objects_undo_history() { + use craft_ui::testing::Fixture; + use std::rc::Rc; + + let target = Rc::new(Cell::new(0)); + let values = Rc::new([Cell::new(Some(START)), Cell::new(Some(START))]); + let (shown_target, shown_values) = (target.clone(), values.clone()); + let mut fixture = Fixture::new(move |ui| { + let current = shown_target.get(); + let model = &shown_values[current]; + let mut value = model.get(); + NumberField::new("Size", Bind::bound(&mut value)).id_salt("size").edit_target(current).show(ui); + model.set(value); + }); + fixture.settle(); + let field = fixture.by_label("Size").expect("the number field"); + fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text("9+9").settle(); + assert!(fixture.texts().iter().any(|text| text.text == "9+9")); + // Advance the fixture's manual clock so the editor seals this typing group in its history. + fixture.advance(2.0).settle(); + fixture.type_text("+1").advance(2.0).settle(); + assert!(fixture.texts().iter().any(|text| text.text == "9+9+1")); + target.set(1); + fixture.settle(); + assert!(!fixture.texts().iter().any(|text| text.text == "9+9")); + + for modifiers in [Modifiers::COMMAND, Modifiers::COMMAND | Modifiers::SHIFT, Modifiers::COMMAND] { + fixture.key(Key::Z, modifiers).settle(); + assert!(!fixture.texts().iter().any(|text| text.text.starts_with("9+9")), "Undo and Redo cannot restore another object's draft"); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(START)), "neither object adopts the old draft"); + } + fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text("5+8").key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(13.0)), "the new object still accepts a fresh edit"); +} + +/// Reappearing after a hidden pass forgets the old object's editor history and composition, even for equal values. +#[trial] +fn a_hidden_number_field_discards_the_old_objects_history_when_switching_targets() { + use craft_ui::testing::Fixture; + use std::rc::Rc; + + for composing in [false, true] { + let visible = Rc::new(Cell::new(true)); + let target = Rc::new(Cell::new(0)); + let values = Rc::new([Cell::new(Some(START)), Cell::new(Some(START))]); + let id = Rc::new(Cell::new(egui::Id::NULL)); + let (shown_visible, shown_target, shown_values, shown_id) = (visible.clone(), target.clone(), values.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + if !shown_visible.get() { + return; + } + let current = shown_target.get(); + let model = &shown_values[current]; + let mut value = model.get(); + let out = NumberField::new("Size", Bind::bound(&mut value)).id_salt("size").edit_target(current).show(ui); + shown_id.set(out.response.id); + model.set(value); + }); + fixture.settle(); + let field = fixture.by_label("Size").expect("the number field"); + fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text("9+9").settle(); + // Seal separate typing groups using only the fixture's manual clock. + fixture.advance(2.0).settle(); + fixture.type_text("+1").advance(2.0).settle(); + assert!(fixture.texts().iter().any(|text| text.text == "9+9+1")); + if composing { + fixture.frame(vec![Event::Ime(egui::ImeEvent::Preedit { text: "99".into(), active_range_chars: None })]).settle(); + assert!(fixture.texts().iter().any(|text| text.text.contains("99")), "A has a live composition"); + } + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(START))); + + let stable = id.get(); + visible.set(false); + fixture.idle(1); + assert!(fixture.by_label("Size").is_none(), "the field is hidden for a pass"); + target.set(1); + visible.set(true); + fixture.settle(); + let field = fixture.by_label("Size").expect("the reappearing number field"); + assert_eq!(id.get(), stable, "the same widget edits B"); + fixture.click(&field).settle(); + assert!(fixture.focused_stop().is_some_and(|(stop, _)| stop == stable), "B can be refocused"); + assert!(!fixture.texts().iter().any(|text| text.text.starts_with("9+9") || text.text.contains("99"))); + if composing { + fixture.frame(vec![Event::Ime(egui::ImeEvent::Commit("99".into()))]).settle(); + } + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(START)), "Enter cannot adopt A's draft or composition"); + + for modifiers in [Modifiers::COMMAND, Modifiers::COMMAND | Modifiers::SHIFT, Modifiers::COMMAND] { + fixture.key(Key::Z, modifiers).settle(); + assert!( + !fixture.texts().iter().any(|text| text.text.starts_with("9+9") || text.text.contains("99")), + "Undo and Redo cannot restore A's draft" + ); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(START)), "neither object adopts A's draft"); + } + fixture.key(Key::A, Modifiers::COMMAND).type_text("5+8").key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(13.0)), "B still accepts fresh input"); + } +} + +/// A composition begun for one object cannot commit into another object through the same field. +#[trial] +fn changing_a_number_fields_edit_target_discards_the_old_objects_composition() { + use craft_ui::testing::Fixture; + use std::rc::Rc; + + for (leave, queued) in [(false, true), (false, false), (true, false)] { + let target = Rc::new(Cell::new(0)); + let values = Rc::new([Cell::new(Some(START)), Cell::new(Some(START))]); + let (shown_target, shown_values) = (target.clone(), values.clone()); + let mut other = String::new(); + let mut fixture = Fixture::new(move |ui| { + let current = shown_target.get(); + let model = &shown_values[current]; + let mut value = model.get(); + NumberField::new("Size", Bind::bound(&mut value)).id_salt("size").edit_target(current).show(ui); + model.set(value); + craft_ui::text::TextField::new("Other", Bind::bound(&mut other)).show(ui); + }); + fixture.settle(); + let field = fixture.by_label("Size").expect("the number field"); + fixture.click(&field).key(Key::A, Modifiers::COMMAND).settle(); + fixture.frame(vec![Event::Ime(egui::ImeEvent::Preedit { text: "99".into(), active_range_chars: None })]).settle(); + assert!(fixture.texts().iter().any(|text| text.text.contains("99")), "the old object has a live preedit"); + target.set(1); + if queued { + fixture.frame(vec![Event::Ime(egui::ImeEvent::Preedit { text: "88".into(), active_range_chars: None })]).settle(); + assert!(!fixture.texts().iter().any(|text| text.text.contains("88")), "preedit queued in the switch frame belongs to the old target"); + } + if leave { + fixture.key(Key::Tab, Modifiers::NONE).settle(); + } else { + fixture.settle(); + fixture.frame(vec![Event::Ime(egui::ImeEvent::Commit("99".into()))]).settle(); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + } + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(START)), "the old composition cannot reach the new target (leave={leave})"); + fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text("13").key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!(values[1].get(), Some(13.0), "the new target still accepts fresh input"); + } +} diff --git a/crates/update/src/queue/tests.rs b/crates/update/src/queue/tests.rs index 9e92d7b161..9dcb35631b 100644 --- a/crates/update/src/queue/tests.rs +++ b/crates/update/src/queue/tests.rs @@ -81,38 +81,72 @@ fn behind_a_running_install( }) } +/// What a job of `installers_never_run_at_the_same_time` tells the test first. +enum Heard { + /// The queue made it wait. + Waiting, + /// Its installer is running, and stays running until the test sends on this channel. + Running(mpsc::Sender<()>), +} + +/// Each kind of job in turn holds the installer while jobs of every kind are started, and each of +/// those must wait. Each later call also stays running until the test has checked that it runs alone. #[trial] fn installers_never_run_at_the_same_time() { let queue = Queue::new(); let (inside, most, handled) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); - let enter = || { - most.fetch_max(inside.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst); - std::thread::sleep(Duration::from_millis(3)); - inside.fetch_sub(1, Ordering::SeqCst); - }; - std::thread::scope(|scope| { - for i in 0..24 { - let (queue, enter, handled) = (&queue, &enter, &handled); - scope.spawn(move || { - std::thread::sleep(Duration::from_millis(i % 5)); - let exec = |_: &[OsString], targets: &[OsString]| { - enter(); - handled.fetch_add(targets.len(), Ordering::SeqCst); - Ok(()) + // The kinds of job: 0 an install, 1 a removal, 2 a lone installer. + for first in 0..3 { + std::thread::scope(|scope| { + let (said, hears) = mpsc::channel(); + let job = |i: usize| { + let said = said.clone(); + let (queue, inside, most, handled) = (&queue, &inside, &most, &handled); + scope.spawn(move || { + let run = |targets: usize| { + most.fetch_max(inside.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst); + let (go, held) = mpsc::channel(); + said.send(Heard::Running(go)).unwrap(); + held.recv().unwrap(); + inside.fetch_sub(1, Ordering::SeqCst); + handled.fetch_add(targets, Ordering::SeqCst); + }; + let mut turn = |waiting: bool| { + if waiting { + said.send(Heard::Waiting).unwrap(); + } + }; + let exec = |_: &[OsString], targets: &[OsString]| { + run(targets.len()); + Ok(()) + }; + match (first + i) % 3 { + 0 => queue.batched(install(), os(&format!("{first}-{i}.deb")), &|| false, &mut turn, &exec).unwrap(), + 1 => queue.batched(remove(), os(&format!("app{first}-{i}")), &|| false, &mut turn, &exec).unwrap(), + _ => queue.alone(&|| false, &mut turn, || run(1)).unwrap(), + } + }); + }; + job(0); + let Heard::Running(holder) = hears.recv().unwrap() else { + panic!("the first job waited with no other installer running"); + }; + for i in 1..8 { + job(i); + assert!(matches!(hears.recv().unwrap(), Heard::Waiting), "job {i} started while job 0 of round {first} was running"); + } + drop(said); + holder.send(()).unwrap(); + // Every job has said it waits; from here on each call says it is running. + for heard in hears.iter() { + let Heard::Running(go) = heard else { + panic!("a job said twice that it waits"); }; - match i % 3 { - 0 => queue.batched(install(), os(&format!("{i}.deb")), &|| false, &mut |_| {}, &exec).unwrap(), - 1 => queue.batched(remove(), os(&format!("app{i}")), &|| false, &mut |_| {}, &exec).unwrap(), - _ => queue - .alone(&|| false, &mut |_| {}, || { - enter(); - handled.fetch_add(1, Ordering::SeqCst); - }) - .unwrap(), - } - }); - } - }); + assert_eq!(inside.load(Ordering::SeqCst), 1); + go.send(()).unwrap(); + } + }); + } assert_eq!(most.load(Ordering::SeqCst), 1); assert_eq!(handled.load(Ordering::SeqCst), 24); } diff --git a/crates/video/src/h264/encode/README.md b/crates/video/src/h264/encode/README.md index 94b8106584..fab82fa689 100644 --- a/crates/video/src/h264/encode/README.md +++ b/crates/video/src/h264/encode/README.md @@ -29,7 +29,10 @@ for p in enc.flush() { /* ... */ } - Input: planar 4:2:0 8-bit (`YuvFrame` with strides); any even size, non-multiple-of-16 sizes are cropped via the SPS frame cropping. `encode` returns an error (`Error::BadFrame`) instead of panicking on short or inconsistent planes, including strides whose size arithmetic would overflow. -- High 10: `cfg.profile = Profile::High10; cfg.bit_depth = 10;` (8 to 10) and `enc.encode16(&YuvFrame16 { … })` +- Semi-planar input: `enc.encode_nv12(&Nv12Frame { y, uv, y_stride, uv_stride }, pts)` takes NV12 (one plane of + interleaved Cb/Cr pairs) and `enc.encode_p010(&P010Frame { … }, pts)` takes P010 (the same arrangement with the value + in the high bits of each `u16`, for a High 10 encoder). Each codes the same stream as the planar picture. +- High 10: `cfg.profile = Profile::High10; cfg.bit_depth = 10;` (8 to 10) and `enc.encode16(&YuvFrame16 { … }, pts)` with samples in the low bits of each `u16` (values above the bit depth are clipped); 8-bit `YuvFrame`s are also taken and scaled up exactly. `cfg.intra_only = true` codes every picture as an IDR without reference frames (High 10 Intra with constraint_set3 for High 10). diff --git a/crates/video/src/h264/encode/mod.rs b/crates/video/src/h264/encode/mod.rs index 1627d14585..bc96c9fa57 100644 --- a/crates/video/src/h264/encode/mod.rs +++ b/crates/video/src/h264/encode/mod.rs @@ -225,6 +225,113 @@ impl EncoderConfig { writer: format!("craft-h264enc {}", env!("CARGO_PKG_VERSION")), } } + + /// The level_idc (41 = level 4.1) of the stream an encoder built from this configuration writes, + /// after the checks of [`Encoder::new`]: a configuration it rejects (an invalid size or frame rate, + /// or a picture size, frame rate or bitrate past level 6.2) gets the same error here. A requested + /// [`EncoderConfig::level`] below the needed level is raised to it. [`Encoder::new`] can still + /// fail when it cannot start its worker threads. + pub fn level_idc(&self) -> Result { + Ok(self.plan()?.level) + } + + /// Validate the configuration and derive the picture size in macroblocks, the rate limits and the level. + fn plan(&self) -> Result { + if self.width == 0 + || self.height == 0 + || !self.width.is_multiple_of(2) + || !self.height.is_multiple_of(2) + || self.width > 16384 + || self.height > 16384 + { + return Err(Error::InvalidDimensions(self.width, self.height)); + } + if self.fps_num == 0 || self.fps_den == 0 { + return Err(Error::InvalidFrameRate(self.fps_num, self.fps_den)); + } + if self.bframes > 3 { + return Err(Error::InvalidConfig("bframes must be 0..=3".into())); + } + if !(8..=10).contains(&self.bit_depth) { + return Err(Error::InvalidConfig(format!("bit depth {} is not supported (8 to 10)", self.bit_depth))); + } + if self.bit_depth > 8 && self.profile != Profile::High10 { + return Err(Error::InvalidConfig(format!("bit depth {} needs the High 10 profile", self.bit_depth))); + } + let mbw = self.width.div_ceil(16) as usize; + let mbh = self.height.div_ceil(16) as usize; + let fps = self.fps_num as f64 / self.fps_den as f64; + let max_refs = if self.intra_only { + 0 + } else if self.bframes > 0 && self.profile != Profile::Baseline { + 2 + } else { + 1 + }; + // QPY may go down to -QpBdOffset at higher bit depths. + let qp_min = -(Depth::new(self.bit_depth).qp_offset as f32); + if let Pass::Second(st) = &self.pass { + let invalid = + st.frames.is_empty() || !st.fps.is_finite() || st.fps <= 0.0 || st.frames.iter().any(|f| !f.qscale.is_finite() || f.qscale <= 0.0); + if invalid { + return Err(Error::InvalidConfig( + "second pass needs non-empty first-pass statistics with a positive fps and valid frame qscales".into(), + )); + } + if (st.fps - fps).abs() > fps.max(1.0) * 1e-9 { + return Err(Error::InvalidConfig("second-pass frame rate must match the first pass".into())); + } + } + match self.rate { + RateControl::Crf(crf) if !crf.is_finite() => { + return Err(Error::InvalidConfig("CRF must be finite".into())); + } + RateControl::Cbr { kbps: 0 } => { + return Err(Error::InvalidConfig("bitrate must be non-zero".into())); + } + RateControl::Vbr { target_kbps: 0, .. } => { + return Err(Error::InvalidConfig("bitrate must be non-zero".into())); + } + RateControl::Vbr { target_kbps, max_kbps } if max_kbps == 0 || max_kbps < target_kbps => { + return Err(Error::InvalidConfig("VBR maximum bitrate must be at least the non-zero target bitrate".into())); + } + _ => {} + } + let (kbps_for_level, vbv) = match (&self.rate, &self.pass) { + (RateControl::Qp(_), _) => (None, (None, None)), + (RateControl::Crf(c), _) => (Some(crf_level_kbps(*c, qp_min, mbw, mbh, fps)), (None, None)), + (RateControl::Cbr { kbps }, Pass::First) => (Some(*kbps), (None, None)), + (RateControl::Cbr { kbps }, _) => (Some(*kbps), (Some(*kbps), Some(*kbps))), + (RateControl::Vbr { max_kbps, .. }, Pass::First) => (Some(*max_kbps), (None, None)), + (RateControl::Vbr { max_kbps, .. }, _) => { + let buffer = + max_kbps.checked_mul(2).ok_or_else(|| Error::InvalidConfig("VBR buffer rate exceeds the supported integer range".into()))?; + (Some(*max_kbps), (Some(*max_kbps), Some(buffer))) + } + }; + // cpbBrVclFactor / 1000 (Table A-2): MaxBR scales by 1.25 for High and 3 for High 10. + let br_factor = match self.profile { + Profile::Baseline | Profile::Main => 1000, + Profile::High => 1250, + Profile::High10 => 3000, + }; + let auto = nal::pick_level(mbw as u32, mbh as u32, fps, max_refs as u32, kbps_for_level, br_factor) + .ok_or_else(|| Error::InvalidConfig("configuration exceeds H.264 level 6.2 limits".into()))?; + let level = self.level.map_or(auto, |l| nal::level_at_least(l, auto)); + Ok(Plan { mbw, mbh, fps, max_refs, qp_min, vbv, level }) + } +} + +/// What [`EncoderConfig::plan`] derives from a valid configuration. +struct Plan { + mbw: usize, + mbh: usize, + fps: f64, + max_refs: usize, + qp_min: f32, + /// VBV maximum rate and buffer size, in kbit/s and kbit. + vbv: (Option, Option), + level: u8, } /// A planar 4:2:0 8-bit input picture of the configured size. @@ -248,11 +355,35 @@ pub struct YuvFrame16<'a> { pub uv_stride: usize, } +/// A semi-planar 4:2:0 8-bit input picture (NV12) of the configured size: a luma plane and one chroma +/// plane of interleaved pairs, Cb first. A chroma row holds `width` bytes (`width / 2` pairs). Strides +/// are in bytes. +#[derive(Clone, Copy, Debug)] +pub struct Nv12Frame<'a> { + pub y: &'a [u8], + pub uv: &'a [u8], + pub y_stride: usize, + pub uv_stride: usize, +} + +/// A semi-planar 4:2:0 input picture in the P010 layout: the arrangement of [`Nv12Frame`] with 16-bit +/// samples whose value is in the high bits (a 10-bit sample `v` is stored as `v << 6`). The encoder keeps +/// the top [`EncoderConfig::bit_depth`] bits of each sample and ignores the rest. Strides are in samples. +#[derive(Clone, Copy, Debug)] +pub struct P010Frame<'a> { + pub y: &'a [u16], + pub uv: &'a [u16], + pub y_stride: usize, + pub uv_stride: usize, +} + /// The planes of one input picture. #[derive(Clone, Copy)] enum Source<'a> { Eight(&'a YuvFrame<'a>), Deep(&'a YuvFrame16<'a>), + Nv12(&'a Nv12Frame<'a>), + P010(&'a P010Frame<'a>), } /// One input row, 8- or 16-bit. @@ -260,6 +391,11 @@ enum Source<'a> { enum Row<'a> { Eight(&'a [u8]), Deep(&'a [u16]), + /// Interleaved chroma pairs and the index of the component in each pair (0 for Cb, 1 for Cr). + EightPairs(&'a [u8], usize), + /// P010 samples, with the value in the high bits. + High(&'a [u16]), + HighPairs(&'a [u16], usize), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -419,35 +555,12 @@ impl Core

{ } fn new_with_extra_motion_search_starts(mut cfg: EncoderConfig, extra_motion_search_starts: bool) -> Result { - if cfg.width == 0 - || cfg.height == 0 - || !cfg.width.is_multiple_of(2) - || !cfg.height.is_multiple_of(2) - || cfg.width > 16384 - || cfg.height > 16384 - { - return Err(Error::InvalidDimensions(cfg.width, cfg.height)); - } - if cfg.fps_num == 0 || cfg.fps_den == 0 { - return Err(Error::InvalidFrameRate(cfg.fps_num, cfg.fps_den)); - } - if cfg.bframes > 3 { - return Err(Error::InvalidConfig("bframes must be 0..=3".into())); - } - if !(8..=10).contains(&cfg.bit_depth) { - return Err(Error::InvalidConfig(format!("bit depth {} is not supported (8 to 10)", cfg.bit_depth))); - } - if cfg.bit_depth > 8 && cfg.profile != Profile::High10 { - return Err(Error::InvalidConfig(format!("bit depth {} needs the High 10 profile", cfg.bit_depth))); - } + let Plan { mbw, mbh, fps, max_refs, qp_min, vbv, level } = cfg.plan()?; if cfg.profile == Profile::Baseline || cfg.intra_only { cfg.bframes = 0; } cfg.keyint = if cfg.intra_only { 1 } else { cfg.keyint.max(1) }; let depth = Depth::new(cfg.bit_depth); - let mbw = cfg.width.div_ceil(16) as usize; - let mbh = cfg.height.div_ceil(16) as usize; - let fps = cfg.fps_num as f64 / cfg.fps_den as f64; let cabac = cfg.profile != Profile::Baseline; let high = cfg.profile.high(); let params = match cfg.preset { @@ -512,71 +625,14 @@ impl Core

{ depth, }, }; - let max_refs = if cfg.intra_only { - 0 - } else if cfg.bframes > 0 { - 2 - } else { - 1 + let rc_kind = match (&cfg.rate, &cfg.pass) { + (RateControl::Qp(q), _) => RcKind::Qp((*q).min(51)), + (RateControl::Crf(c), _) => RcKind::Crf(c.clamp(qp_min, 51.0)), + (RateControl::Cbr { kbps: target_kbps } | RateControl::Vbr { target_kbps, .. }, Pass::Second(st)) => { + ratecontrol::RateControl::plan_two_pass(st, *target_kbps) + } + (RateControl::Cbr { kbps: target_kbps } | RateControl::Vbr { target_kbps, .. }, _) => RcKind::Abr { kbps: *target_kbps }, }; - // QPY may go down to -QpBdOffset at higher bit depths. - let qp_min = -(depth.qp_offset as f32); - if let Pass::Second(st) = &cfg.pass { - let invalid = - st.frames.is_empty() || !st.fps.is_finite() || st.fps <= 0.0 || st.frames.iter().any(|f| !f.qscale.is_finite() || f.qscale <= 0.0); - if invalid { - return Err(Error::InvalidConfig( - "second pass needs non-empty first-pass statistics with a positive fps and valid frame qscales".into(), - )); - } - if (st.fps - fps).abs() > fps.max(1.0) * 1e-9 { - return Err(Error::InvalidConfig("second-pass frame rate must match the first pass".into())); - } - } - match cfg.rate { - RateControl::Crf(crf) if !crf.is_finite() => { - return Err(Error::InvalidConfig("CRF must be finite".into())); - } - RateControl::Cbr { kbps: 0 } => { - return Err(Error::InvalidConfig("bitrate must be non-zero".into())); - } - RateControl::Vbr { target_kbps: 0, .. } => { - return Err(Error::InvalidConfig("bitrate must be non-zero".into())); - } - RateControl::Vbr { target_kbps, max_kbps } if max_kbps == 0 || max_kbps < target_kbps => { - return Err(Error::InvalidConfig("VBR maximum bitrate must be at least the non-zero target bitrate".into())); - } - _ => {} - } - let (kbps_for_level, rc_kind, vbv) = match (&cfg.rate, &cfg.pass) { - (RateControl::Qp(q), _) => (None, RcKind::Qp((*q).min(51)), (None, None)), - (RateControl::Crf(c), _) => (Some(crf_level_kbps(*c, qp_min, mbw, mbh, fps)), RcKind::Crf(c.clamp(qp_min, 51.0)), (None, None)), - (RateControl::Cbr { kbps }, Pass::Second(st)) => { - (Some(*kbps), ratecontrol::RateControl::plan_two_pass(st, *kbps), (Some(*kbps), Some(*kbps))) - } - (RateControl::Cbr { kbps }, Pass::First) => (Some(*kbps), RcKind::Abr { kbps: *kbps }, (None, None)), - (RateControl::Cbr { kbps }, Pass::Single) => (Some(*kbps), RcKind::Abr { kbps: *kbps }, (Some(*kbps), Some(*kbps))), - (RateControl::Vbr { target_kbps, max_kbps }, Pass::Second(st)) => { - let buffer = - max_kbps.checked_mul(2).ok_or_else(|| Error::InvalidConfig("VBR buffer rate exceeds the supported integer range".into()))?; - (Some(*max_kbps), ratecontrol::RateControl::plan_two_pass(st, *target_kbps), (Some(*max_kbps), Some(buffer))) - } - (RateControl::Vbr { target_kbps, max_kbps }, Pass::First) => (Some(*max_kbps), RcKind::Abr { kbps: *target_kbps }, (None, None)), - (RateControl::Vbr { target_kbps, max_kbps }, Pass::Single) => { - let buffer = - max_kbps.checked_mul(2).ok_or_else(|| Error::InvalidConfig("VBR buffer rate exceeds the supported integer range".into()))?; - (Some(*max_kbps), RcKind::Abr { kbps: *target_kbps }, (Some(*max_kbps), Some(buffer))) - } - }; - // cpbBrVclFactor / 1000 (Table A-2): MaxBR scales by 1.25 for High and 3 for High 10. - let br_factor = match cfg.profile { - Profile::Baseline | Profile::Main => 1000, - Profile::High => 1250, - Profile::High10 => 3000, - }; - let auto = nal::pick_level(mbw as u32, mbh as u32, fps, max_refs as u32, kbps_for_level, br_factor) - .ok_or_else(|| Error::InvalidConfig("configuration exceeds H.264 level 6.2 limits".into()))?; - let level = cfg.level.map_or(auto, |l| nal::level_at_least(l, auto)); let (profile_idc, constraint) = match cfg.profile { Profile::Baseline => (66u8, 0xC0u8), // constraint_set0 + set1 => Constrained Baseline Profile::Main => (77, 0x40), @@ -835,27 +891,35 @@ impl Core

{ fn import(&mut self, f: Source) -> Result, Error> { let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); let (cw, ch) = (w / 2, h / 2); + // A semi-planar chroma row holds both components, so it is twice as wide in samples. + let semi = matches!(f, Source::Nv12(_) | Source::P010(_)); let (lens, ys, cs) = match f { Source::Eight(f) => ([f.y.len(), f.u.len(), f.v.len()], f.y_stride, f.uv_stride), Source::Deep(f) => ([f.y.len(), f.u.len(), f.v.len()], f.y_stride, f.uv_stride), + Source::Nv12(f) => ([f.y.len(), f.uv.len(), f.uv.len()], f.y_stride, f.uv_stride), + Source::P010(f) => ([f.y.len(), f.uv.len(), f.uv.len()], f.y_stride, f.uv_stride), }; + let crow = if semi { 2 * cw } else { cw }; let fits = |len: usize, stride: usize, pw: usize, ph: usize| { stride >= pw && stride.checked_mul(ph - 1).and_then(|n| n.checked_add(pw)).is_some_and(|n| len >= n) }; - if !(fits(lens[0], ys, w, h) && fits(lens[1], cs, cw, ch) && fits(lens[2], cs, cw, ch)) { + if !(fits(lens[0], ys, w, h) && fits(lens[1], cs, crow, ch) && fits(lens[2], cs, crow, ch)) { return Err(Error::BadFrame); } - if matches!(f, Source::Deep(_)) && self.depth.bits == 8 { + if matches!(f, Source::Deep(_) | Source::P010(_)) && self.depth.bits == 8 { return Err(Error::DeepInput); } let depth = self.depth; + // P010 keeps the value in the high bits of each sample: the top BitDepth bits are the sample. + let down = 16 - u32::from(depth.bits); let mut fr = self.new_frame(); for (k, (pl, stride, pw, ph)) in [(&mut fr.y, ys, w, h), (&mut fr.u, cs, cw, ch), (&mut fr.v, cs, cw, ch)].into_iter().enumerate() { let aw = pl.w; + let n = if semi && k > 0 { 2 * pw } else { pw }; for y in 0..pl.h { let sy = y.min(ph - 1); let o = pl.idx(0, y as isize); - let (a, b) = (sy * stride, sy * stride + pw); + let (a, b) = (sy * stride, sy * stride + n); let row = match (f, k) { (Source::Eight(f), 0) => Row::Eight(&f.y[a..b]), (Source::Eight(f), 1) => Row::Eight(&f.u[a..b]), @@ -863,12 +927,19 @@ impl Core

{ (Source::Deep(f), 0) => Row::Deep(&f.y[a..b]), (Source::Deep(f), 1) => Row::Deep(&f.u[a..b]), (Source::Deep(f), _) => Row::Deep(&f.v[a..b]), + (Source::Nv12(f), 0) => Row::Eight(&f.y[a..b]), + (Source::Nv12(f), c) => Row::EightPairs(&f.uv[a..b], c - 1), + (Source::P010(f), 0) => Row::High(&f.y[a..b]), + (Source::P010(f), c) => Row::HighPairs(&f.uv[a..b], c - 1), }; let dst = &mut pl.data[o..o + pw]; match row { // 8-bit samples scale up exactly: v << (BitDepth - 8). Row::Eight(r) => P::from_u8(dst, r, depth.shift), Row::Deep(r) => dst.iter_mut().zip(r).for_each(|(d, &s)| *d = P::of((s as i32).min(depth.max))), + Row::EightPairs(r, c) => dst.iter_mut().zip(r[c..].iter().step_by(2)).for_each(|(d, &s)| *d = P::of(i32::from(s) << depth.shift)), + Row::High(r) => dst.iter_mut().zip(r).for_each(|(d, &s)| *d = P::of(i32::from(s >> down))), + Row::HighPairs(r, c) => dst.iter_mut().zip(r[c..].iter().step_by(2)).for_each(|(d, &s)| *d = P::of(i32::from(s >> down))), } let last = pl.data[o + pw - 1]; pl.data[o + pw..o + aw].fill(last); @@ -1325,6 +1396,17 @@ impl Encoder { core!(&mut self.core, c => c.try_encode(Source::Deep(frame), pts)) } + /// Encode one NV12 picture, with the results and errors of [`Encoder::encode`]. + pub fn encode_nv12(&mut self, frame: &Nv12Frame, pts: i64) -> Result, Error> { + core!(&mut self.core, c => c.try_encode(Source::Nv12(frame), pts)) + } + + /// Encode one P010 picture, with the results and errors of [`Encoder::encode16`]: [`Error::DeepInput`] + /// for an 8-bit encoder. + pub fn encode_p010(&mut self, frame: &P010Frame, pts: i64) -> Result, Error> { + core!(&mut self.core, c => c.try_encode(Source::P010(frame), pts)) + } + /// Encode all buffered pictures. pub fn flush(&mut self) -> Vec { core!(&mut self.core, c => c.flush()) @@ -1343,6 +1425,34 @@ fn jobs_stride_c(mbw: usize) -> usize { mod tests { use super::*; + #[test] + fn level_idc_is_the_level_the_encoder_signals() { + let mut raised = EncoderConfig::new(1920, 1080, 30, 1); + raised.level = Some(30); + let mut kept = EncoderConfig::new(1280, 720, 30, 1); + kept.level = Some(51); + let mut bitrate = EncoderConfig::new(1920, 1080, 30, 1); + bitrate.rate = RateControl::Cbr { kbps: 40_000 }; + for cfg in [EncoderConfig::new(320, 240, 30, 1), EncoderConfig::new(3840, 2160, 60, 1), raised, kept, bitrate] { + let level = cfg.level_idc().unwrap(); + let params = Encoder::new(cfg).unwrap().codec_params(); + assert_eq!(level, craft_media::isobmff::AvcConfig::parse(¶ms.extradata).unwrap().level); + } + } + + #[test] + fn level_idc_rejects_what_the_encoder_rejects() { + let mut deep = EncoderConfig::new(320, 240, 30, 1); + deep.bit_depth = 10; + let odd = EncoderConfig::new(321, 240, 30, 1); + let no_rate = EncoderConfig::new(320, 240, 0, 1); + let past_level = EncoderConfig::new(7680, 4320, 300, 1); + for cfg in [odd, no_rate, past_level, deep] { + let check = cfg.level_idc().unwrap_err().to_string(); + assert_eq!(check, Encoder::new(cfg).err().unwrap().to_string()); + } + } + fn grey(w: usize, h: usize) -> (Vec, Vec, Vec) { (vec![128; w * h], vec![128; w * h / 4], vec![128; w * h / 4]) } @@ -1358,6 +1468,110 @@ mod tests { assert!(matches!(enc.encode(&f, 0), Err(Error::BadFrame))); } + /// Planar 8-bit picture `t` with different content in each plane. + fn ramp(w: usize, h: usize, t: usize) -> (Vec, Vec, Vec) { + let plane = |pw: usize, ph: usize, k: usize| (0..pw * ph).map(|i| ((i % pw) * (3 + k) + (i / pw) * (5 + 2 * k) + 7 * t) as u8).collect(); + (plane(w, h, 0), plane(w / 2, h / 2, 1), plane(w / 2, h / 2, 2)) + } + + /// `u` and `v` interleaved into rows of `stride` samples, Cb first, the rest of each row `pad`. + fn interleave(u: &[T], v: &[T], cw: usize, stride: usize, pad: T) -> Vec { + let mut uv = Vec::new(); + for (ru, rv) in u.chunks(cw).zip(v.chunks(cw)) { + ru.iter().zip(rv).for_each(|(&a, &b)| uv.extend([a, b])); + uv.resize(uv.len() + stride - 2 * cw, pad); + } + uv + } + + /// `p` in rows of `stride` samples, the rest of each row `pad`. + fn padded(p: &[T], pw: usize, stride: usize, pad: T) -> Vec { + p.chunks(pw).flat_map(|r| r.iter().copied().chain(std::iter::repeat_n(pad, stride - pw))).collect() + } + + fn streams(cfg: &EncoderConfig, mut encode: impl FnMut(&mut Encoder, usize) -> Vec) -> Vec> { + let mut enc = Encoder::new(cfg.clone()).unwrap(); + let mut packets: Vec = (0..4).flat_map(|t| encode(&mut enc, t)).collect(); + packets.extend(enc.flush()); + packets.into_iter().map(|p| p.data).collect() + } + + #[test] + fn nv12_input_codes_the_same_stream_as_planar_input() { + // 40x24 is not a multiple of 16, so the last macroblock column and row are padded from the edge. + let (w, h) = (40, 24); + let cfg = EncoderConfig::new(w as u32, h as u32, 30, 1); + let planar = streams(&cfg, |enc, t| { + let (y, u, v) = ramp(w, h, t); + enc.encode(&YuvFrame { y: &y, u: &u, v: &v, y_stride: w, uv_stride: w / 2 }, t as i64).unwrap() + }); + let semi = streams(&cfg, |enc, t| { + let (y, u, v) = ramp(w, h, t); + let (y, uv) = (padded(&y, w, w + 8, 0xee), interleave(&u, &v, w / 2, w + 6, 0xee)); + enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: w + 8, uv_stride: w + 6 }, t as i64).unwrap() + }); + assert_eq!(planar.len(), 4); + assert_eq!(planar, semi); + } + + #[test] + fn p010_input_codes_the_same_stream_as_16_bit_input() { + let (w, h) = (32, 16); + for bits in [9, 10] { + let mut cfg = EncoderConfig::new(w as u32, h as u32, 30, 1); + cfg.profile = Profile::High10; + cfg.bit_depth = bits; + // 10-bit samples: the 8-bit ramp with two more bits of detail. + let ten = |t: usize| { + let (y, u, v) = ramp(w, h, t); + let up = |p: Vec| p.iter().enumerate().map(|(i, &s)| (u16::from(s) << 2) | (i % 4) as u16).collect::>(); + (up(y), up(u), up(v)) + }; + let deep = streams(&cfg, |enc, t| { + let (y, u, v) = ten(t); + let keep = |p: Vec| p.iter().map(|&s| s >> (10 - bits)).collect::>(); + let (y, u, v) = (keep(y), keep(u), keep(v)); + enc.encode16(&YuvFrame16 { y: &y, u: &u, v: &v, y_stride: w, uv_stride: w / 2 }, t as i64).unwrap() + }); + let semi = streams(&cfg, |enc, t| { + let (y, u, v) = ten(t); + // the six low bits P010 leaves unused carry noise, which the encoder ignores + let p010 = |p: Vec| p.iter().enumerate().map(|(i, &s)| (s << 6) | ((i as u16 * 13) & 0x3f)).collect::>(); + let (y, u, v) = (p010(y), p010(u), p010(v)); + let (y, uv) = (padded(&y, w, w + 2, u16::MAX), interleave(&u, &v, w / 2, w, u16::MAX)); + enc.encode_p010(&P010Frame { y: &y, uv: &uv, y_stride: w + 2, uv_stride: w }, t as i64).unwrap() + }); + assert_eq!(deep.len(), 4); + assert_eq!(deep, semi, "bit depth {bits}"); + } + } + + #[test] + fn short_or_overflowing_semi_planar_frames_are_bad_frames() { + let mut enc = Encoder::new(EncoderConfig::new(4, 4, 30, 1)).unwrap(); + let y = vec![128u8; 16]; + // A chroma plane sized for one planar component holds only half of each interleaved row. + let uv = vec![128u8; 4]; + assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 2 }, 0), Err(Error::BadFrame))); + let uv = vec![128u8; 7]; + assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 4 }, 0), Err(Error::BadFrame))); + let uv = vec![128u8; 8]; + assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: usize::MAX }, 0), Err(Error::BadFrame))); + assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: usize::MAX / 3, uv_stride: 4 }, 0), Err(Error::BadFrame))); + assert!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 4 }, 0).is_ok()); + + let (y, uv) = (vec![0u16; 16], vec![0u16; 8]); + let p010 = P010Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 4 }; + assert!(matches!(enc.encode_p010(&p010, 1), Err(Error::DeepInput))); + let mut cfg = EncoderConfig::new(4, 4, 30, 1); + cfg.profile = Profile::High10; + cfg.bit_depth = 10; + let mut enc = Encoder::new(cfg).unwrap(); + let short = vec![0u16; 7]; + assert!(matches!(enc.encode_p010(&P010Frame { y: &y, uv: &short, y_stride: 4, uv_stride: 4 }, 0), Err(Error::BadFrame))); + assert!(enc.encode_p010(&p010, 0).is_ok()); + } + fn b_frame_encoder() -> Encoder { let mut cfg = EncoderConfig::new(16, 16, 30, 1); cfg.bframes = 2; diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs index 7e1eb82d05..c02614ae3d 100644 --- a/crates/video/src/theora/encoder.rs +++ b/crates/video/src/theora/encoder.rs @@ -103,7 +103,11 @@ fn alloc_vec_exact(val: T, n: usize) -> Result> { impl Encoder { /// Create a new encoder with the given configuration. + /// The frame-rate numerator and denominator must both be nonzero. pub fn new(config: EncoderConfig) -> Result { + if config.fps_num == 0 || config.fps_den == 0 { + return Err(Error::InvalidHeader("framerate cannot be zero")); + } if config.width == 0 || config.height == 0 || config.pic_width == 0 || config.pic_height == 0 { return Err(Error::DimensionMismatch("dimensions cannot be zero")); } @@ -158,8 +162,8 @@ impl Encoder { pic_height: config.pic_height.min(frame_height), pic_x: config.pic_x.min(frame_width - config.pic_width.min(frame_width)), pic_y: config.pic_y.min(frame_height - config.pic_height.min(frame_height)), - fps_num: config.fps_num.max(1), - fps_den: config.fps_den.max(1), + fps_num: config.fps_num, + fps_den: config.fps_den, par_num: 1, par_den: 1, color_space: config.color_space, diff --git a/crates/video/tests/it/h264_encode/main.rs b/crates/video/tests/it/h264_encode/main.rs index 7f7f70f79f..d2c9148248 100644 --- a/crates/video/tests/it/h264_encode/main.rs +++ b/crates/video/tests/it/h264_encode/main.rs @@ -8,5 +8,6 @@ mod crf_level_and_note; mod ffmpeg_oracle; mod high10_oracle; mod pinned_decisions; +mod semi_planar_oracle; mod thread_count; mod vbr_overshoot; diff --git a/crates/video/tests/it/h264_encode/semi_planar_oracle.rs b/crates/video/tests/it/h264_encode/semi_planar_oracle.rs new file mode 100644 index 0000000000..f95a5d1114 --- /dev/null +++ b/crates/video/tests/it/h264_encode/semi_planar_oracle.rs @@ -0,0 +1,75 @@ +//! NV12 and P010 input against ffmpeg's `nv12` and `p010le` layouts (skipped when ffmpeg is absent): +//! pictures ffmpeg converts from planar 4:2:0 code the same stream as the planar pictures. + +use super::common; + +use common::{Yuv, Yuv16, ffmpeg, le16, synth, synth10}; +use craft_video::h264::*; +use std::process::Command; + +/// `raw` (frames of `from`) converted by ffmpeg to frames of `to`. +fn convert(raw: &[u8], w: usize, h: usize, from: &str, to: &str) -> Vec { + let dir = common::out_dir("semi_planar"); + let src = dir.join(format!("{from}.raw")); + std::fs::write(&src, raw).unwrap(); + let out = Command::new(ffmpeg().unwrap()) + .args(["-nostdin", "-v", "error", "-f", "rawvideo", "-pix_fmt", from, "-s", &format!("{w}x{h}"), "-i"]) + .arg(&src) + .args(["-f", "rawvideo", "-pix_fmt", to, "-"]) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + out.stdout +} + +fn stream(cfg: &EncoderConfig, frames: usize, mut encode: impl FnMut(&mut Encoder, usize) -> Vec) -> Vec { + let mut enc = Encoder::new(cfg.clone()).unwrap(); + let mut packets: Vec = (0..frames).flat_map(|i| encode(&mut enc, i)).collect(); + packets.extend(enc.flush()); + assert_eq!(packets.len(), frames); + packets.iter().flat_map(|p| p.data.iter().copied()).collect() +} + +#[test] +fn ffmpeg_nv12_pictures_code_the_same_stream_as_planar_pictures() { + if ffmpeg().is_none() { + return; + } + let (w, h, n) = (96, 64, 5); + let frames: Vec = (0..n).map(|t| synth(w, h, t)).collect(); + let raw: Vec = frames.iter().flat_map(Yuv::bytes).collect(); + let nv12 = convert(&raw, w, h, "yuv420p", "nv12"); + let size = w * h * 3 / 2; + assert_eq!(nv12.len(), size * n); + let cfg = EncoderConfig::new(w as u32, h as u32, 30, 1); + let planar = stream(&cfg, n, |enc, i| enc.encode(&frames[i].frame(), i as i64).unwrap()); + let semi = stream(&cfg, n, |enc, i| { + let pic = &nv12[i * size..(i + 1) * size]; + let (y, uv) = pic.split_at(w * h); + enc.encode_nv12(&Nv12Frame { y, uv, y_stride: w, uv_stride: w }, i as i64).unwrap() + }); + assert!(planar == semi, "the NV12 stream differs from the planar one"); +} + +#[test] +fn ffmpeg_p010_pictures_code_the_same_stream_as_16_bit_pictures() { + if ffmpeg().is_none() { + return; + } + let (w, h, n) = (96, 64, 5); + let frames: Vec = (0..n).map(|t| synth10(w, h, t)).collect(); + let raw: Vec = frames.iter().flat_map(Yuv16::bytes).collect(); + let p010 = le16(&convert(&raw, w, h, "yuv420p10le", "p010le")); + let size = w * h * 3 / 2; + assert_eq!(p010.len(), size * n); + let mut cfg = EncoderConfig::new(w as u32, h as u32, 30, 1); + cfg.profile = Profile::High10; + cfg.bit_depth = 10; + let deep = stream(&cfg, n, |enc, i| enc.encode16(&frames[i].frame(), i as i64).unwrap()); + let semi = stream(&cfg, n, |enc, i| { + let pic = &p010[i * size..(i + 1) * size]; + let (y, uv) = pic.split_at(w * h); + enc.encode_p010(&P010Frame { y, uv, y_stride: w, uv_stride: w }, i as i64).unwrap() + }); + assert!(deep == semi, "the P010 stream differs from the 16-bit one"); +} diff --git a/crates/video/tests/it/theora.rs b/crates/video/tests/it/theora.rs index eadc09d29d..0d0dcc394b 100644 --- a/crates/video/tests/it/theora.rs +++ b/crates/video/tests/it/theora.rs @@ -49,6 +49,20 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { if mse == 0.0 { 99.0 } else { 10.0 * (255.0f64 * 255.0 / mse).log10() } } +#[test] +fn test_theora_encoder_rejects_zero_frame_rate_components() { + let config = EncoderConfig { width: 16, height: 16, pic_width: 16, pic_height: 16, ..EncoderConfig::default() }; + for (fps_num, fps_den) in [(0, 1), (25, 0), (0, 0)] { + assert!(matches!(Encoder::new(EncoderConfig { fps_num, fps_den, ..config.clone() }), Err(Error::InvalidHeader(_)))); + } + for (fps_num, fps_den) in [(1, 1), (30_000, 1001), (u32::MAX, u32::MAX)] { + let encoder = Encoder::new(EncoderConfig { fps_num, fps_den, ..config.clone() }).unwrap(); + let header = IdentificationHeader::parse(&encoder.headers().0).unwrap(); + assert_eq!((header.info.fps_num, header.info.fps_den), (fps_num, fps_den)); + assert_eq!((encoder.config().fps_num, encoder.config().fps_den), (fps_num, fps_den)); + } +} + #[test] fn test_theora_headers_roundtrip() { let cfg = EncoderConfig { diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 5b86932aeb..a49c72f7b6 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes, a per-step JSON report and the workspace version command" [lints] workspace = true @@ -18,10 +18,14 @@ lock = ["dep:libc"] report = ["dep:serde_json", "dep:craft-atomic"] # `cargo xtask stats`: files, lines and tests of Rust per workspace crate, read from `cargo metadata`. stats = ["dep:serde_json"] +# `cargo xtask version [set X.Y.Z[-pre]]`, with Cargo.toml and Cargo.lock replaced atomically and one +# `set` at a time per workspace through `lock`. +version = ["lock", "dep:craft-atomic", "dep:toml_edit"] [dependencies] craft-atomic = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } +toml_edit = { version = "0.25", optional = true } [target.'cfg(unix)'.dependencies] # O_NONBLOCK and O_NOFOLLOW for lock and owner opens that must not wait on a FIFO or follow a symlink. Constants only. diff --git a/crates/xtask/README.md b/crates/xtask/README.md index de63234f7e..8ac364d757 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -11,9 +11,10 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | | `stats` | `stats` | `run`, `collect` and `write_table`: files, lines and tests of Rust per workspace crate (`cargo xtask stats`) | +| `version` | `version` | `run`, `run_with`, `Limits`, `lock_dirs`, `read`, `replace`, `validate`: `cargo xtask version [set X.Y.Z[-pre]]` on the root `Cargo.toml` | No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `stats` adds -`serde_json`. +`serde_json`. `version` adds `craft-atomic` and `toml_edit` and turns on `lock`. ## Use @@ -218,6 +219,47 @@ Some("stats") => { A folder or file that cannot be read and a `.rs` file that is not UTF-8 are errors too. - `collect` returns the `Report` without writing it, and `write_table` writes a `Report`. +## Version + +```rust,no_run +use std::path::Path; +use craft_xtask::runner; + +/// `rest` holds the words after `version`. +fn version(rest: &[&str]) -> Result<(), String> { + let root = runner::root(Path::new(env!("CARGO_MANIFEST_DIR")))?; + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + craft_xtask::version::run(&root, &cargo, rest) +} +``` + +- `cargo xtask version` prints the `version` of `[workspace.package]`. +- `cargo xtask version set X.Y.Z[-pre]` checks the new version, writes it into `Cargo.toml`, runs + `cargo update --workspace --offline` in the root and, when that fails, `cargo update --workspace`, + and prints `version: OLD -> NEW`. It also moves the `version` of each path dependency in + `[workspace.dependencies]` whose requirement is `"OLD"` or `"=OLD"`; registry dependencies and path + dependencies at other versions keep theirs. Trailing ASCII spaces in a matching requirement are retained. +- A version is `MAJOR.MINOR.PATCH` with an optional `-pre.release`: no leading zeros, numbers up to + `u64::MAX`, and no build metadata (`+...`). +- When both updates fail, `Cargo.toml` and `Cargo.lock` are put back as they were (a lock file that did + not exist is removed) and the error says so. Both files are replaced atomically through + `craft-atomic`. +- Setting the current version prints `version: OLD (unchanged)` and writes only its lock file. +- One `set` runs at a time in a workspace. Before it reads `Cargo.toml`, it takes its locks and + holds them until it returns. On Unix it locks the workspace directory itself; on Windows it locks + `workspace.lock` in the first directory below, opened so that the file cannot be deleted while it + is held. Every process that writes the workspace shares that lock, and `cargo clean` cannot remove + it. It also takes the locks in `lock_dirs(root)`: + `target/xtask-version/version-/` (required; its owner file names the + run) and `~/.cache/craft-xtask/version-/` (when its file can be + opened). A `set` that finds a lock held returns an error naming the other run and writes + nothing. +- The root manifest is read and written with `toml_edit`, keeping comments, quotes and line endings + (LF and CRLF), and the version may be `[workspace.package]` `version`, a dotted key or an inline + table. A manifest that is not valid TOML (a duplicate key included), a version that is not a + one-line string, or a current version that is not valid is an error before anything is written. `Cargo.toml` is read up to 1 MiB + and `Cargo.lock` up to 64 MiB by default; `run_with` takes other `Limits`. + ## Origin | Part | Source | @@ -229,6 +271,9 @@ Some("stats") => { | `stats`: regular files only, and `a_walk_does_not_follow_directory_links` | WordCraft `xtask/src/stats.rs` at `6b163b33dc` | | `stats`: the entry budget that returns an error, and its two tests | CADCraft `xtask/src/stats.rs` at `ca87680fb0` | | `stats`: the per-file size limit, and its two tests | GridCraft `xtask/src/stats.rs` at `9e9f13114f` | +| `version`: `read`, `validate` with the overflow and prerelease checks, the restore after a failed update, and the tests `reads_the_workspace_version`, `replaces_only_the_workspace_version`, `keeps_crlf_line_endings`, `validates_versions`, `rejects_what_cargo_rejects`, `a_failed_update_restores_the_manifest` | SoundCraft `xtask/src/version.rs` at [6c84416](https://github.com/storytold/soundcraft/blob/6c84416c3cffb72d8d350ddfefc4fc9ee954ca1a/xtask/src/version.rs) | +| `version`: the path dependency pins and the test `moves_the_workspace_crates_pins_with_it` | PdfCraft `xtask/src/version.rs` at [3e30645](https://github.com/storytold/pdfcraft/blob/3e3064532f04fd6ec769c6bd7b2c97464757970e/xtask/src/version.rs) | +| `version`: the `toml_edit` edit that keeps quotes and line endings, the `=OLD` pins, the `Cargo.lock` restore, the size limits, the unchanged-version case and the one-`set`-at-a-time lock | written here | | The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `stats`, the metadata, total-size, depth and `--list` output limits, the metadata checks and the line naming failed listings | written here | | `assets`: `is_asset`, the exact-row check, `run`, the three asset folders and the test `detects_unattributed_assets` | VectorCraft `xtask/src/assets.rs` at [bada8e1](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/assets.rs) and DesignCraft `xtask/src/assets.rs` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/assets.rs) | | `assets`: the CADCraft and WordCraft extension lists, the `-z` listing, the exit-status check and the tests in `assets::tests::wordcraft` | CADCraft `xtask/src/assets.rs` at [8e69890](https://github.com/storytold/cadcraft/blob/8e6989022398ff5f79adaab77d19fdd7137591f3/xtask/src/assets.rs), WordCraft `xtask/src/assets.rs` at [42a5df5](https://github.com/storytold/wordcraft/blob/42a5df5f94e03288037f731ffd86dee7c7cf1332/xtask/src/assets.rs) | @@ -246,6 +291,7 @@ No app uses this crate yet. | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | | CADCraft, DeckCraft, DesignCraft, GridCraft, LightCraft, PhotoCraft, VectorCraft, WordCraft | Planned: `xtask/src/stats.rs` moves to `stats`. Each app's switch lists its per-crate counts before and after in its pull request. | +| SoundCraft, PdfCraft | Planned: `xtask/src/version.rs` moves to `version`, with the app's root and `CARGO` passed to `run`. `the_real_manifest_has_a_valid_version`, and PdfCraft's `workspace_rust_version_covers_the_ui_crate`, stay in the app. | | VectorCraft, DesignCraft, CADCraft, DeckCraft, WordCraft, GridCraft, LightCraft | Planned: `xtask/src/assets.rs` moves to `assets`, each with its own document, folders and row mode; LightCraft with `RowMode::Patterns`, its forbidden extensions and names, and `license_column: Some(4)`. The `cargo xtask assets` output stays in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index ab7f3b0569..77e5fa2dc3 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -16,6 +16,9 @@ //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. //! - `stats` (feature `stats`): files, lines and tests of Rust per workspace crate (`cargo xtask stats`). +//! - `version` (feature `version`): `cargo xtask version [set X.Y.Z[-pre]]`, which reads and sets the +//! `[workspace.package]` version of the root `Cargo.toml` and moves the workspace crates' path +//! dependency pins with it. //! //! ```no_run //! use std::path::Path; @@ -47,6 +50,8 @@ pub mod report; pub mod runner; #[cfg(feature = "stats")] pub mod stats; +#[cfg(feature = "version")] +pub mod version; /// Writes one diagnostic line to stderr. A failed write, such as one to a closed pipe, is ignored, so a /// diagnostic never stops a run. diff --git a/crates/xtask/src/version.rs b/crates/xtask/src/version.rs new file mode 100644 index 0000000000..6774bfd05f --- /dev/null +++ b/crates/xtask/src/version.rs @@ -0,0 +1,941 @@ +//! `cargo xtask version [set X.Y.Z[-pre]]`: the workspace version in the root `Cargo.toml`. +//! +//! The version is the `version` key of `[workspace.package]`; member crates inherit it with +//! `version.workspace = true`. [`read`] returns it, [`validate`] checks a new one and [`replace`] +//! returns the manifest with the new version, together with the `version` of every path dependency +//! in `[workspace.dependencies]` whose requirement is the old version (`"OLD"` or `"=OLD"`). +//! [`run`] is the command: the caller passes its workspace root, the Cargo program to run and the +//! words after `version`. +//! +//! The manifest is read with `toml_edit`, and each version string is replaced at its position in the +//! original text, so every byte outside the changed strings stays as it was, key order, comments and +//! line endings included. The root version may be written in any TOML form +//! (`[workspace.package]` with `version = "…"`, a dotted key, an inline table), with double or +//! single quotes, and keeps its quotes. A pin may also be a multi-line string and keeps its +//! delimiters. Trailing ASCII spaces in a pin are retained. A manifest that is not valid TOML +//! (a duplicate key included), a version that is not a one-line string, or a current version that is not valid +//! returns an error before anything is written. + +use std::ffi::OsStr; +use std::fs::File; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use toml_edit::{Document, Formatted, Item, Table, Value}; + +/// The largest root `Cargo.toml` [`run`] reads, in bytes. +pub const DEFAULT_MAX_MANIFEST_BYTES: u64 = 1 << 20; +/// The largest `Cargo.lock` [`run`] keeps in memory to put back after a failed `cargo update`, in bytes. +pub const DEFAULT_MAX_LOCK_BYTES: u64 = 64 << 20; +const USAGE: &str = "usage: cargo xtask version [set X.Y.Z[-pre]]"; + +/// Size limits for [`run_with`]. +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest root `Cargo.toml` that is read; a larger one is an error before anything is written. + pub max_manifest_bytes: u64, + /// The largest `Cargo.lock` that is kept to put back after a failed update; a larger one is an + /// error before anything is written. + pub max_lock_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: DEFAULT_MAX_MANIFEST_BYTES, max_lock_bytes: DEFAULT_MAX_LOCK_BYTES } + } +} + +impl Limits { + /// Sets the largest root `Cargo.toml` that is read. + pub fn with_max_manifest_bytes(mut self, bytes: u64) -> Self { + self.max_manifest_bytes = bytes; + self + } + + /// Sets the largest `Cargo.lock` that is kept for a restore. + pub fn with_max_lock_bytes(mut self, bytes: u64) -> Self { + self.max_lock_bytes = bytes; + self + } +} + +/// The `version` of `[workspace.package]`. +pub fn read(manifest: &str) -> Result { + let doc = parse(manifest)?; + root_version(&doc) +} + +/// `manifest` with the workspace version set to `new`, and every path dependency in +/// `[workspace.dependencies]` whose `version` is the old version (`"OLD"` or `"=OLD"`) moved with +/// it. Registry dependencies and path dependencies at other versions keep their requirement. +/// Trailing ASCII spaces in a pin are retained. Every other byte is unchanged. +pub fn replace(manifest: &str, new: &str) -> Result { + validate(new)?; + let doc = parse(manifest)?; + let old = root_version(&doc)?; + validate(&old).map_err(|e| format!("the current [workspace.package] version is not valid: {e}"))?; + let root = doc.get("workspace").and_then(|w| w.get("package")).and_then(|p| p.get("version")).and_then(as_string); + let mut edits = vec![(root.ok_or(NO_VERSION)?, new.to_owned())]; + for (pin, prefix, suffix) in path_pins(&doc, &old) { + edits.push((pin, format!("{prefix}{new}{suffix}"))); + } + let mut spans = Vec::with_capacity(edits.len()); + for (string, text) in edits { + let span = string.span().filter(|s| manifest.is_char_boundary(s.start) && manifest.is_char_boundary(s.end)); + let span = span.ok_or("Cargo.toml: a version to replace has no position in the file")?; + let quote = ["\"\"\"", "'''", "\"", "'"].into_iter().find(|q| manifest[span.clone()].starts_with(q)); + let quote = quote.ok_or("Cargo.toml: a version to replace is not a quoted string")?; + spans.push((span, format!("{quote}{text}{quote}"))); + } + spans.sort_by_key(|(span, _)| std::cmp::Reverse(span.start)); + let mut out = manifest.to_owned(); + for (span, text) in spans { + out.replace_range(span, &text); + } + Ok(out) +} + +/// Semver without build metadata: `MAJOR.MINOR.PATCH` plus an optional `-pre.release` tag. +/// +/// The three numbers have no leading zero and fit in a `u64`. Each prerelease identifier is +/// nonempty ASCII letters, digits and `-`, and a numeric one has no leading zero. +pub fn validate(v: &str) -> Result<(), String> { + let bad = || Err(format!("`{v}` is not a version like 1.2.3 or 1.2.3-rc.1")); + let (core, pre) = match v.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (v, None), + }; + let nums: Vec<&str> = core.split('.').collect(); + if nums.len() != 3 + || nums.iter().any(|n| !n.bytes().all(|b| b.is_ascii_digit()) || (n.len() > 1 && n.starts_with('0')) || n.parse::().is_err()) + { + return bad(); + } + let bad_id = |id: &str| { + id.is_empty() + || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + || (id.len() > 1 && id.starts_with('0') && id.bytes().all(|b| b.is_ascii_digit())) + }; + if let Some(p) = pre + && (p.is_empty() || p.split('.').any(bad_id)) + { + return bad(); + } + Ok(()) +} + +/// `cargo xtask version [set X.Y.Z[-pre]]` with the default [`Limits`]. +/// +/// `root` is the workspace root, `cargo_program` the Cargo to run there (an app usually passes its +/// `CARGO` variable, or `cargo`), and `args` the words after `version`. +/// +/// - With no words, prints the version. +/// - With `set NEW`, writes the new version into `Cargo.toml` (see [`replace`]), runs +/// `cargo update --workspace --offline` and, when that fails, `cargo update --workspace`, then prints +/// `version: OLD -> NEW`. When both updates fail, `Cargo.toml` and `Cargo.lock` are put back as they +/// were and the error says so. Setting the current version prints `version: OLD (unchanged)` and +/// writes only its lock file. One `set` runs at a time in a workspace: it holds its locks (see +/// [`lock_dirs`]) from reading `Cargo.toml` until it returns, and a `set` that finds a lock held +/// returns an error naming the other run and writes nothing. +/// - Other words return the usage error. +pub fn run(root: &Path, cargo_program: &OsStr, args: &[&str]) -> Result<(), String> { + run_with(root, cargo_program, args, &Limits::default()) +} + +/// [`run`] with the caller's [`Limits`]. +pub fn run_with(root: &Path, cargo_program: &OsStr, args: &[&str], limits: &Limits) -> Result<(), String> { + run_to(root, args, limits, None, &mut io::stdout(), || update_lock(root, cargo_program, limits.max_lock_bytes)) +} + +/// The directories of the owner-labeled locks that a `set` in the workspace at `root` holds. +/// +/// Before these, a `set` locks the workspace directory itself on Unix, and on Windows +/// `workspace.lock` in the first directory, opened so that it cannot be deleted while held. Every +/// process that writes the workspace shares that lock, and `cargo clean` cannot remove it. +/// +/// The first directory is `target/xtask-version/version-` in the +/// workspace: its lock is required and its owner file names the run that holds it. The second, when +/// there is a home directory, is `~/.cache/craft-xtask/version-`; a +/// `set` also takes the lock there when it can open the lock file. +/// +/// The locks are not on `Cargo.toml` or `Cargo.lock` because a lock on Windows is mandatory and +/// would stop the replacement of `Cargo.toml` and Cargo's own use of `Cargo.lock`. +pub fn lock_dirs(root: &Path) -> Result, String> { + let canonical = std::fs::canonicalize(root).map_err(|e| format!("{}: {e}", root.display()))?; + let name = format!("version-{:016x}", fnv1a(canonical.to_string_lossy().as_bytes())); + // A `target` linked from several workspaces holds one directory per workspace. + let mut dirs = vec![canonical.join("target").join("xtask-version").join(&name)]; + dirs.extend(std::env::home_dir().filter(|h| h.is_absolute()).map(|h| h.join(".cache").join("craft-xtask").join(name))); + Ok(dirs) +} + +/// The 64-bit FNV-1a hash, which stays the same across Rust releases. +fn fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)) +} + +/// [`run_with`] that prints to `out`, refreshes `Cargo.lock` with `update`, and keeps its locks in +/// `lock_at` (or [`lock_dirs`] when `None`). +fn run_to( + root: &Path, + args: &[&str], + limits: &Limits, + lock_at: Option<&[PathBuf]>, + out: &mut dyn Write, + update: impl FnOnce() -> Result<(), String>, +) -> Result<(), String> { + let new = match args { + [] => None, + ["set", new] => Some(*new), + _ => return Err(USAGE.into()), + }; + let manifest = root.join("Cargo.toml"); + let load = || -> Result<(String, String), String> { + let text = + String::from_utf8(read_bounded(&manifest, limits.max_manifest_bytes)?).map_err(|_| format!("{}: not UTF-8", manifest.display()))?; + let old = read(&text)?; + Ok((text, old)) + }; + let Some(new) = new else { + return say(out, &load()?.1); + }; + validate(new)?; + // Held from the read of `Cargo.toml` through any restore, so that two `set` runs never interleave + // and an unchanged version is not reported while another run may still put an older one back. + let _held = lock_workspace(root, lock_at, new)?; + let (text, old) = load()?; + let updated = replace(&text, new)?; + if old == new { + return say(out, &format!("version: {old} (unchanged)")); + } + let lock_path = root.join("Cargo.lock"); + let lock = read_lock(&lock_path, limits.max_lock_bytes)?; + write_file(&manifest, updated.as_bytes())?; + if let Err(e) = update() { + return Err(restore(&manifest, &text, &old, &lock_path, lock.as_deref(), e)); + } + say(out, &format!("version: {old} -> {new}")) +} + +/// The locks a `set` holds until it returns. +struct WorkspaceLock { + _base: File, + _held: Vec, +} + +/// The lock that every process writing the workspace at `root` shares and that `cargo clean` cannot +/// remove while it is held, or `None` when another process holds it. On Unix it is a lock on the +/// workspace directory itself. On Windows it is `workspace.lock` in `dir`, opened without delete +/// sharing, so the file cannot be deleted while it is open. +fn base_lock(root: &Path, dir: &Path) -> Result, String> { + let fail = |e: io::Error| format!("could not take the version lock, nothing was written: {e}"); + #[cfg(windows)] + let file = { + use std::os::windows::fs::OpenOptionsExt; + const FILE_SHARE_READ: u32 = 0x1; + const FILE_SHARE_WRITE: u32 = 0x2; + let _ = root; + std::fs::create_dir_all(dir).map_err(fail)?; + std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .open(dir.join("workspace.lock")) + .map_err(fail)? + }; + #[cfg(not(windows))] + let file = { + let _ = dir; + File::open(root).map_err(fail)? + }; + match file.try_lock() { + Ok(()) => Ok(Some(file)), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(std::fs::TryLockError::Error(e)) => Err(fail(e)), + } +} + +/// Takes the workspace's `version set` locks without waiting: [`base_lock`], then the owner-labeled +/// locks in `lock_at` (or [`lock_dirs`]). The lock in the first directory is required; a later +/// directory whose lock file cannot be opened is skipped. When another run holds any of them, +/// releases the others and returns an error that names that run. +fn lock_workspace(root: &Path, lock_at: Option<&[PathBuf]>, new: &str) -> Result { + let dirs = match lock_at { + Some(dirs) => dirs.to_vec(), + None => lock_dirs(root)?, + }; + let label = format!("pid {} in {}: cargo xtask version set {new}", std::process::id(), root.display()); + let busy = |dir: &Path| { + let config = crate::lock::LockConfig::new(dir, 1, ""); + let other = crate::lock::holders(&config).ok().and_then(|h| h.into_iter().next()).unwrap_or_else(|| "another run".to_owned()); + format!("another `cargo xtask version set` is running in this workspace ({other}); nothing was written, try again when it ends") + }; + let first = dirs.first().ok_or_else(|| "could not take the version lock: no lock directory".to_owned())?; + let Some(base) = base_lock(root, first)? else { + return Err(busy(first)); + }; + let mut held = Vec::new(); + for (i, dir) in dirs.iter().enumerate() { + let config = crate::lock::LockConfig::new(dir, 1, label.clone()); + match crate::lock::try_acquire(&config) { + Ok(Some(h)) => held.push(h), + Ok(None) => return Err(busy(dir)), + Err(e) if i == 0 => return Err(format!("could not take the version lock, nothing was written: {e}")), + Err(_) => {} + } + } + Ok(WorkspaceLock { _base: base, _held: held }) +} + +fn say(out: &mut dyn Write, line: &str) -> Result<(), String> { + writeln!(out, "{line}").map_err(|e| format!("write the output: {e}")) +} + +/// Puts `Cargo.toml` and `Cargo.lock` back after `cargo update` failed with `error`. +fn restore(manifest: &Path, text: &str, old: &str, lock_path: &Path, lock: Option<&[u8]>, error: String) -> String { + let mut msg = match write_file(manifest, text.as_bytes()) { + Ok(()) => format!("{error}; Cargo.toml restored to {old}"), + Err(r) => format!("{error}; could not restore Cargo.toml: {r}"), + }; + if let Err(r) = put_lock_back(lock_path, lock) { + msg.push_str(&format!("; could not restore Cargo.lock: {r}")); + } + msg +} + +/// The bytes of `Cargo.lock` at `path`, or `None` when there is no such file. +fn read_lock(path: &Path, max: u64) -> Result>, String> { + match std::fs::symlink_metadata(path) { + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + _ => read_bounded(path, max).map(Some), + } +} + +/// Writes `lock` to `path`, or removes the file when `lock` is `None`. +fn put_lock_back(path: &Path, lock: Option<&[u8]>) -> Result<(), String> { + match lock { + Some(bytes) => write_file(path, bytes), + None => match std::fs::remove_file(path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(format!("remove {}: {e}", path.display())), + _ => Ok(()), + }, + } +} + +/// The file at `path`, or an error when it is larger than `max` bytes. +fn read_bounded(path: &Path, max: u64) -> Result, String> { + let too_big = |len: u64| format!("{}: {len} bytes, more than the {max}-byte limit", path.display()); + let file = File::open(path).map_err(|e| format!("read {}: {e}", path.display()))?; + let len = file.metadata().map_err(|e| format!("read {}: {e}", path.display()))?.len(); + if len > max { + return Err(too_big(len)); + } + let mut bytes = Vec::new(); + file.take(max.saturating_add(1)).read_to_end(&mut bytes).map_err(|e| format!("read {}: {e}", path.display()))?; + if bytes.len() as u64 > max { + return Err(too_big(bytes.len() as u64)); + } + Ok(bytes) +} + +/// Replaces `path` atomically: a half-written root manifest breaks every build in the workspace. +fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> { + craft_atomic::atomic_write(path, bytes).map_err(|e| format!("write {}: {e}", path.display())) +} + +/// Refreshes the workspace members' entries in `Cargo.lock`, without upgrading dependencies. +fn update_lock(root: &Path, cargo_program: &OsStr, max_lock_bytes: u64) -> Result<(), String> { + let update = |offline: bool| { + let mut c = Command::new(cargo_program); + c.current_dir(root).args(["update", "--workspace"]); + if offline { + c.arg("--offline"); + } + crate::runner::run(c, if offline { "cargo update --workspace --offline" } else { "cargo update --workspace" }) + }; + update_lock_with(&root.join("Cargo.lock"), max_lock_bytes, update) +} + +/// Runs `update(true)` (offline) and, when it fails, `update(false)` after putting `Cargo.lock` at +/// `lock_path` back as it was before the first attempt, so the second attempt never reads a lock file +/// that the first one left half-written. When the lock file cannot be put back, returns that error. +fn update_lock_with(lock_path: &Path, max_lock_bytes: u64, mut update: impl FnMut(bool) -> Result<(), String>) -> Result<(), String> { + let saved = read_lock(lock_path, max_lock_bytes)?; + if update(true).is_ok() { + return Ok(()); + } + put_lock_back(lock_path, saved.as_deref())?; + update(false) +} + +const NO_VERSION: &str = "no `version` in [workspace.package] of the root Cargo.toml"; + +fn parse(manifest: &str) -> Result, String> { + Document::parse(manifest.to_owned()).map_err(|e| format!("Cargo.toml: {e}")) +} + +/// The string value of `item`, when it is one. +fn as_string(item: &Item) -> Option<&Formatted> { + match item.as_value()? { + Value::String(s) => Some(s), + _ => None, + } +} + +/// Whether `s`, which was parsed from `raw`, is written as a `"""…"""` or `'''…'''` string. +fn is_multi_line(s: &Formatted, raw: &str) -> bool { + let text = s.span().and_then(|span| raw.get(span)).unwrap_or_default(); + text.starts_with("\"\"\"") || text.starts_with("'''") +} + +/// The `[workspace.package]` version string. +fn root_version(doc: &Document) -> Result { + let item = doc.get("workspace").and_then(|w| w.get("package")).and_then(|p| p.get("version")).ok_or(NO_VERSION)?; + let s = as_string(item).ok_or("[workspace.package] version is not a string")?; + if is_multi_line(s, doc.raw()) { + return Err("[workspace.package] version is a multi-line string; write it as `version = \"X.Y.Z\"`".into()); + } + if s.value().is_empty() { + return Err("empty [workspace.package] version".into()); + } + Ok(s.value().clone()) +} + +/// The `version` strings of the path dependencies in `[workspace.dependencies]` that require `old` +/// (single-line or multi-line strings, matched by their decoded value), each with the operator in +/// front of the version (`""` or `"="`) and any trailing ASCII spaces. +fn path_pins<'a>(doc: &'a Table, old: &str) -> Vec<(&'a Formatted, String, String)> { + let Some(deps) = doc.get("workspace").and_then(|w| w.get("dependencies")).and_then(Item::as_table_like) else { + return Vec::new(); + }; + deps.iter() + .filter_map(|(_, dep)| { + let dep = dep.as_table_like()?; + dep.get("path")?; + let version = dep.get("version").and_then(as_string)?; + let requirement = version.value().trim_end_matches(' '); + let prefix = requirement.strip_suffix(old)?; + let suffix = &version.value()[requirement.len()..]; + matches!(prefix.trim(), "" | "=").then(|| (version, prefix.to_owned(), suffix.to_owned())) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + const MANIFEST: &str = "[workspace]\nmembers = [\"a\"]\n\n[workspace.package]\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[workspace.dependencies]\nfoo = { version = \"1\" }\n"; + + /// A workspace folder holding `manifest` as its `Cargo.toml` and, when given, `lock` as its `Cargo.lock`. + fn workspace(manifest: &str, lock: Option<&str>) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Cargo.toml"), manifest).unwrap(); + if let Some(lock) = lock { + std::fs::write(dir.path().join("Cargo.lock"), lock).unwrap(); + } + dir + } + + /// The lock directory of the tests' runs: inside the test's own workspace folder, which is removed + /// with it. + fn test_lock_dir(root: &Path) -> PathBuf { + root.join("target").join("xtask-version") + } + + fn run_limited(root: &Path, args: &[&str], limits: &Limits, update: impl FnOnce() -> Result<(), String>) -> Result<(), String> { + run_to(root, args, limits, Some(&[test_lock_dir(root)]), &mut Vec::new(), update) + } + + fn run_in(root: &Path, args: &[&str], update: impl FnOnce() -> Result<(), String>) -> (Result<(), String>, String) { + let mut out = Vec::new(); + let result = run_to(root, args, &Limits::default(), Some(&[test_lock_dir(root)]), &mut out, update); + (result, String::from_utf8(out).unwrap()) + } + + fn file(root: &Path, name: &str) -> Option { + std::fs::read_to_string(root.join(name)).ok() + } + + #[test] + fn reads_the_workspace_version() { + assert_eq!(read(MANIFEST).unwrap(), "0.1.0"); + assert!(read("[package]\nversion = \"1.0.0\"\n").is_err()); + } + + #[test] + fn replaces_only_the_workspace_version() { + let out = replace(MANIFEST, "1.2.3-rc.1").unwrap(); + assert_eq!(read(&out).unwrap(), "1.2.3-rc.1"); + assert_eq!(out, MANIFEST.replace("version = \"0.1.0\"", "version = \"1.2.3-rc.1\"")); + assert!(out.contains("foo = { version = \"1\" }")); + // Setting the old version back gives the same bytes. + assert_eq!(replace(&out, "0.1.0").unwrap(), MANIFEST); + } + + #[test] + fn keeps_crlf_line_endings() { + let crlf = MANIFEST.replace('\n', "\r\n"); + let out = replace(&crlf, "2.0.0").unwrap(); + assert_eq!(out, crlf.replace("\"0.1.0\"", "\"2.0.0\"")); + } + + #[test] + fn validates_versions() { + for ok in ["0.1.0", "1.20.300", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-x-y.2"] { + assert!(validate(ok).is_ok(), "{ok}"); + } + for bad in ["1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.0-", "1.0.0-a..b", "1.0.0+meta", "1.a.0", ""] { + assert!(validate(bad).is_err(), "{bad}"); + } + assert!(replace(MANIFEST, "nope").is_err()); + } + + #[test] + fn rejects_what_cargo_rejects() { + for bad in ["1.0.0-01", "1.0.0-rc.01", "1.0.0-0.00", "1.0.0-rc.1.007", "99999999999999999999.0.0", "1.18446744073709551616.0"] { + assert!(validate(bad).is_err(), "{bad}"); + assert!(replace(MANIFEST, bad).is_err(), "{bad}"); + } + for ok in ["1.0.0-0", "1.0.0-rc.0", "1.0.0-0a", "1.0.0-01a", "1.0.0-99999999999999999999", "18446744073709551615.0.0"] { + assert!(validate(ok).is_ok(), "{ok}"); + } + } + + #[test] + fn moves_the_workspace_crates_pins_with_it() { + let manifest = "[workspace.package]\nversion = \"0.1.0\"\n\n[workspace.dependencies]\n\ + own = { path = \"crates/own\", version = \"0.1.0\" }\n\ + exact = { path = \"crates/exact\", version = \"=0.1.0\" }\n\ + dep = { version = \"0.1.0\" }\n\ + other = { path = \"crates/other\", version = \"0.2\" }\n\ + newer = { path = \"crates/newer\", version = \"0.1.0-rc.1\" }\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert!(out.contains("own = { path = \"crates/own\", version = \"0.2.0\" }"), "{out}"); + assert!(out.contains("exact = { path = \"crates/exact\", version = \"=0.2.0\" }"), "{out}"); + assert!(out.contains("dep = { version = \"0.1.0\" }"), "a registry dependency keeps its version"); + assert!(out.contains("other = { path = \"crates/other\", version = \"0.2\" }")); + assert!(out.contains("newer = { path = \"crates/newer\", version = \"0.1.0-rc.1\" }")); + } + + #[test] + fn a_failed_update_restores_the_manifest() { + // Two sets in one workspace: a child started by another test must not hold the first one's lock. + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, None); + let (err, out) = run_in(dir.path(), &["set", "2.0.0"], || Err("cargo update failed".into())); + let err = err.unwrap_err(); + assert!(err.contains("restored to 0.1.0"), "{err}"); + assert_eq!(out, "", "a failed set printed success"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + let (ok, out) = run_in(dir.path(), &["set", "2.0.0"], || Ok(())); + assert_eq!(ok, Ok(())); + assert_eq!(out, "version: 0.1.0 -> 2.0.0\n"); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "2.0.0"); + } + + #[test] + fn the_real_manifest_has_a_valid_version() { + let text = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.toml")).unwrap(); + let version = read(&text).unwrap(); + validate(&version).unwrap(); + // craft-libs pins its own crates with `version = "=X.Y.Z"`; a set moves those pins too. + let out = replace(&text, "99.0.0").unwrap(); + let pins = text.matches(&format!("version = \"={version}\"")).count(); + assert!(pins > 0, "the root manifest has no `=` pin of its own version"); + assert_eq!(out.matches("version = \"=99.0.0\"").count(), pins, "{out}"); + assert_eq!(replace(&out, &version).unwrap(), text); + } + + #[test] + fn reads_commented_and_single_quoted_versions() { + let manifest = "[workspace.package] # shared\nversion = '1.2.3' # the release\nedition = \"2024\"\n"; + assert_eq!(read(manifest).unwrap(), "1.2.3"); + let out = replace(manifest, "1.3.0").unwrap(); + assert_eq!(out, "[workspace.package] # shared\nversion = '1.3.0' # the release\nedition = \"2024\"\n"); + let spaced = "[ workspace . package ]\n\"version\"=\"1.2.3\"#c\n"; + assert_eq!(replace(spaced, "1.2.4").unwrap(), "[ workspace . package ]\n\"version\"=\"1.2.4\"#c\n"); + } + + #[test] + fn decodes_hex_escapes_in_basic_strings() { + let manifest = "[workspace.package]\nversion = \"0\\x2E1.0\"\ndescription = \"caf\\xE9 \\x41\"\n"; + assert_eq!(read(manifest).unwrap(), "0.1.0"); + let out = replace(manifest, "0.2.0").unwrap(); + assert_eq!(out, "[workspace.package]\nversion = \"0.2.0\"\ndescription = \"caf\\xE9 \\x41\"\n"); + for bad in ["\\x2", "\\xG0", "\\x\""] { + let manifest = format!("[workspace.package]\nversion = \"0.1.0\"\nnote = \"{bad}\"\n"); + assert!(read(&manifest).is_err(), "{manifest:?}"); + } + } + + #[test] + fn accepts_dotted_workspace_package_version() { + for manifest in [ + "[workspace]\npackage.version = \"0.3.0\"\n", + "workspace.package.version = \"0.3.0\"\n", + "[workspace]\npackage = { version = \"0.3.0\", edition = \"2024\" }\n", + ] { + assert_eq!(read(manifest).unwrap(), "0.3.0", "{manifest}"); + assert_eq!(replace(manifest, "0.4.0").unwrap(), manifest.replace("0.3.0", "0.4.0")); + } + } + + #[test] + fn leaves_member_version_workspace_alone() { + let manifest = "[package]\nname = \"a\"\nversion.workspace = true\n\n[workspace.package]\nversion = \"0.1.0\"\n\n\ + [workspace.dependencies]\na = { path = \"a\", version.workspace = true }\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert_eq!(out, manifest.replace("version = \"0.1.0\"", "version = \"0.2.0\"")); + assert!(read("[package]\nversion.workspace = true\n").is_err()); + } + + #[test] + fn moves_multiline_path_dependency_pin() { + let manifest = "[workspace.package]\nversion = \"0.1.0\"\n\n\ + [workspace.dependencies]\n\ + spread = {\n path = \"crates/spread\",\n version = \"0.1.0\",\n}\n\ + dotted.path = \"crates/dotted\"\ndotted.version = \"0.1.0\"\n\n\ + [workspace.dependencies.own]\nversion = \"0.1.0\"\n# the crate\npath = \"crates/own\"\n\n\ + [workspace.dependencies.registry]\nversion = \"0.1.0\"\n"; + let out = replace(manifest, "0.1.1").unwrap(); + let expected = manifest.replacen("0.1.0", "0.1.1", 4); + assert_eq!(out, expected); + assert!(out.ends_with("[workspace.dependencies.registry]\nversion = \"0.1.0\"\n"), "{out}"); + } + + #[test] + fn keeps_the_order_of_interleaved_dotted_keys() { + let manifest = "[workspace]\npackage.version = \"0.1.0\"\nresolver = \"3\"\npackage.edition = \"2024\"\nmembers = [\"a\"]\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert_eq!(out, manifest.replace("0.1.0", "0.2.0")); + } + + #[test] + fn moves_a_pin_written_as_a_multi_line_string() { + let manifest = "[workspace.package]\nversion = \"0.1.0\"\n\n[workspace.dependencies]\n\ + a = { path = \"a\", version = \"\"\"=0.1.0\"\"\" }\n\ + b = { path = \"b\", version = '''0.1.0''' }\n\ + c = { path = \"c\", version = \"\"\"\n0.1.0\"\"\" }\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert!(out.contains("a = { path = \"a\", version = \"\"\"=0.2.0\"\"\" }"), "{out}"); + assert!(out.contains("b = { path = \"b\", version = '''0.2.0''' }"), "{out}"); + assert_eq!(read(&out).unwrap(), "0.2.0"); + assert_eq!(out.matches("0.1.0").count(), 0, "{out}"); + } + + #[test] + fn moves_path_pins_with_trailing_ascii_spaces() { + for delimiter in ["\"", "'", "\"\"\"", "'''"] { + for requirement in ["0.1.0 ", "=0.1.0 ", " = 0.1.0 "] { + let manifest = format!( + "[workspace.package]\nversion = \"0.1.0\"\n[workspace.dependencies]\n\ + a = {{ path = \"a\", version = {delimiter}{requirement}{delimiter} }} # pin\n" + ); + assert_eq!(replace(&manifest, "0.2.0").unwrap(), manifest.replace("0.1.0", "0.2.0")); + } + } + } + + #[test] + fn puts_the_lock_back_before_the_online_attempt() { + let dir = workspace(MANIFEST, Some("original\n")); + let lock = dir.path().join("Cargo.lock"); + let mut seen = Vec::new(); + let result = update_lock_with(&lock, 1 << 20, |offline| { + seen.push((offline, std::fs::read_to_string(&lock).unwrap())); + std::fs::write(&lock, "half").unwrap(); + if offline { Err("offline failed".into()) } else { Ok(()) } + }); + assert_eq!(result, Ok(())); + assert_eq!(seen, [(true, "original\n".to_owned()), (false, "original\n".to_owned())]); + // A lock that did not exist is removed before the second attempt. + std::fs::remove_file(&lock).unwrap(); + let mut existed = None; + let result = update_lock_with(&lock, 1 << 20, |offline| { + if offline { + std::fs::write(&lock, "half").unwrap(); + return Err("offline failed".into()); + } + existed = Some(lock.exists()); + Ok(()) + }); + assert_eq!(result, Ok(())); + assert_eq!(existed, Some(false)); + } + + #[test] + fn preserves_mixed_line_endings_and_rejects_a_lone_cr() { + let mixed = "[workspace]\r\nmembers = [\n\"a\",\r\n]\n[workspace.package]\r\nversion = \"0.1.0\"\nnote = \"\"\"\r\nx\n\"\"\"\r\n# end\r\n"; + let out = replace(mixed, "0.2.0").unwrap(); + assert_eq!(out, mixed.replace("0.1.0", "0.2.0")); + // A manifest without a final line ending keeps it that way. + for unended in [MANIFEST.trim_end().to_owned(), MANIFEST.trim_end().replace('\n', "\r\n")] { + assert_eq!(replace(&unended, "0.2.0").unwrap(), unended.replace("0.1.0", "0.2.0"), "{unended:?}"); + } + // TOML, and so Cargo, reads a CR only as part of CRLF. + let cr = MANIFEST.replace('\n', "\r"); + assert!(read(&cr).is_err()); + assert!(replace(&cr, "2.0.0").is_err()); + } + + #[test] + fn ignores_brackets_and_keys_inside_strings_and_arrays() { + let manifest = "[workspace]\nmembers = [\n [\"nested\"],\n \"b\",\n]\nnote = \"\"\"\n[workspace.package]\nversion = \"9.9.9\"\n\"\"\"\n\ + title = '[workspace.package]'\n\n[workspace.package]\nversion = \"0.1.0\"\n"; + assert_eq!(read(manifest).unwrap(), "0.1.0"); + assert_eq!(replace(manifest, "0.2.0").unwrap(), manifest.replace("\"0.1.0\"", "\"0.2.0\"")); + } + + #[test] + fn rejects_unsupported_and_ambiguous_manifests() { + let deep = format!("[workspace.package]\nversion = \"0.1.0\"\nx = {}{}\n", "[".repeat(100), "]".repeat(100)); + for (manifest, what) in [ + ("[workspace.package]\nversion = \"0.1.0\"\n[workspace]\npackage.version = \"0.2.0\"\n", "duplicate key"), + ("[workspace.package]\nversion = \"0.1.0\"\nversion = \"0.2.0\"\n", "duplicate key"), + ("[workspace.package]\nversion = \"\"\"0.1.0\"\"\"\n", "multi-line"), + ("[workspace.package]\nversion = '''0.1.0'''\n", "multi-line"), + ("[workspace.package]\nversion = 1\n", "not a string"), + ("[workspace.package]\nversion = \"\"\n", "empty"), + ("[workspace.package]\nversion = \"0.1.0\n", "Cargo.toml: TOML parse error"), + ("[workspace.package]\nversion = \"0.1.0\" extra\n", "Cargo.toml: TOML parse error"), + ("[workspace.package\nversion = \"0.1.0\"\n", "Cargo.toml: TOML parse error"), + ("[workspace.package]\nversion = \"\\q\"\n", "Cargo.toml: TOML parse error"), + (deep.as_str(), "Cargo.toml: TOML parse error"), + ("[workspace]\nmembers = []\n", "no `version`"), + ] { + let Err(e) = replace(manifest, "1.0.0") else { panic!("accepted {manifest:?}") }; + assert!(e.contains(what), "{manifest:?}: {e}"); + } + let Err(e) = replace("[workspace.package]\nversion = \"1.0\"\n", "1.0.1") else { panic!("an invalid current version was replaced") }; + assert!(e.contains("current"), "{e}"); + } + + #[test] + fn rejects_oversized_manifest_before_write() { + let dir = workspace(MANIFEST, None); + let ran = Cell::new(false); + let limits = Limits::default().with_max_manifest_bytes(MANIFEST.len() as u64 - 1); + let result = run_limited(dir.path(), &["set", "2.0.0"], &limits, || { + ran.set(true); + Ok(()) + }); + let Err(e) = result else { panic!("an oversized manifest was read") }; + assert!(e.contains("limit"), "{e}"); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + let exact = Limits::default().with_max_manifest_bytes(MANIFEST.len() as u64); + assert_eq!(run_limited(dir.path(), &[], &exact, || Ok(())), Ok(())); + + let dir = workspace(MANIFEST, Some("lock")); + let small_lock = Limits::default().with_max_lock_bytes(3); + let Err(e) = run_limited(dir.path(), &["set", "2.0.0"], &small_lock, || Ok(())) else { panic!("an oversized lock was read") }; + assert!(e.contains("Cargo.lock") && e.contains("limit"), "{e}"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + } + + #[test] + fn restores_lockfile_after_failed_update() { + let dir = workspace(MANIFEST, Some("old lock\r\n")); + let lock = dir.path().join("Cargo.lock"); + let (err, _) = run_in(dir.path(), &["set", "2.0.0"], || { + std::fs::write(&lock, "half-updated lock").unwrap(); + Err("cargo update failed".into()) + }); + assert!(err.unwrap_err().contains("restored to 0.1.0")); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\r\n")); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + + // A lock that the failed update created is removed again. + let dir = workspace(MANIFEST, None); + let lock = dir.path().join("Cargo.lock"); + let (err, _) = run_in(dir.path(), &["set", "2.0.0"], || { + std::fs::write(&lock, "new lock").unwrap(); + Err("cargo update failed".into()) + }); + assert!(err.is_err()); + assert!(!lock.exists()); + } + + #[test] + fn setting_current_version_does_not_run_cargo() { + let dir = workspace(MANIFEST, None); + let ran = Cell::new(false); + let (result, out) = run_in(dir.path(), &["set", "0.1.0"], || { + ran.set(true); + Ok(()) + }); + assert_eq!(result, Ok(())); + assert_eq!(out, "version: 0.1.0 (unchanged)\n"); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock"), None); + } + + #[test] + fn lock_dirs_cover_the_workspace_and_the_account() { + let (a, b) = (workspace(MANIFEST, None), workspace(MANIFEST, None)); + let dirs_a = lock_dirs(a.path()).unwrap(); + assert_eq!(lock_dirs(&a.path().join(".")).unwrap(), dirs_a, "two spellings of one root"); + assert_ne!(lock_dirs(b.path()).unwrap(), dirs_a); + let canonical = std::fs::canonicalize(a.path()).unwrap(); + assert_eq!(dirs_a[0].parent(), Some(canonical.join("target").join("xtask-version").as_path())); + // Both directories are named for the workspace, so a `target` shared by two workspaces keeps + // their locks apart. + let name = dirs_a[0].file_name().unwrap().to_string_lossy().into_owned(); + assert!(name.starts_with("version-"), "{name}"); + assert!(dirs_a.iter().all(|d| d.file_name() == dirs_a[0].file_name())); + for dir in &dirs_a[1..] { + assert!(dir.is_absolute() && dir.parent().is_some_and(|p| p.ends_with("craft-xtask")), "{}", dir.display()); + assert!(!dir.starts_with(&canonical), "{}", dir.display()); + } + assert!(dirs_a.len() <= 2); + assert!(lock_dirs(&a.path().join("missing")).is_err()); + // FNV-1a's published test value, so the name stays the same across builds. + assert_eq!(fnv1a(b"a"), 0xaf63_dc4c_8601_ec8c); + } + + #[test] + fn a_held_workspace_lock_refuses_the_set_whatever_the_lock_directories() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("old lock\n")); + let other = base_lock(dir.path(), &test_lock_dir(dir.path())).unwrap().expect("free lock"); + // A run whose owner-labeled lock directories differ from the holder's still meets its lock. On + // Windows that lock is `workspace.lock` in the first directory, so only the later ones differ. + let elsewhere = tempfile::tempdir().unwrap(); + #[cfg(windows)] + let dirs = [test_lock_dir(dir.path()), elsewhere.path().join("lock")]; + #[cfg(not(windows))] + let dirs = [elsewhere.path().join("lock")]; + let ran = Cell::new(false); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&dirs), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("another `cargo xtask version set`"))); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\n")); + drop(other); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())).0, Ok(())); + } + + #[test] + fn the_workspace_lock_is_required_and_a_later_one_is_optional() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, None); + // A directory cannot be made under a file. + let blocked = dir.path().join("Cargo.toml").join("lock"); + let first = test_lock_dir(dir.path()); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[first.clone(), blocked.clone()]), &mut Vec::new(), || Ok(())); + assert_eq!(result, Ok(())); + assert!(first.join("ci.lock").exists()); + + // A run holding the lock in a later directory refuses the set too. + let later = dir.path().join("later"); + let other = crate::lock::try_acquire(&crate::lock::LockConfig::new(&later, 1, "pid 8 in /w: cargo xtask version set 4.0.0")) + .unwrap() + .expect("free lock"); + let ran = Cell::new(false); + let dirs = [first.clone(), blocked.clone(), later.clone()]; + let result = run_to(dir.path(), &["set", "3.0.0"], &Limits::default(), Some(&dirs), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("pid 8 in /w"))); + assert!(!ran.get()); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "2.0.0"); + drop(other); + // The lock taken in the first directory before the refusal was released. + assert!(crate::lock::try_acquire(&crate::lock::LockConfig::new(&first, 1, "x")).unwrap().is_some()); + + // Without the first lock, nothing is written. + let dir = workspace(MANIFEST, None); + let blocked = dir.path().join("Cargo.toml").join("lock"); + let ran = Cell::new(false); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[blocked, test_lock_dir(dir.path())]), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("could not take the version lock"))); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + } + + #[test] + fn prints_the_version_and_rejects_other_words() { + let dir = workspace(MANIFEST, None); + assert_eq!(run_in(dir.path(), &[], || Ok(())), (Ok(()), "0.1.0\n".to_owned())); + for args in [&["set"][..], &["set", "1.0.0", "2.0.0"], &["get"], &["set", "1.0.0+meta"]] { + let (result, out) = run_in(dir.path(), args, || panic!("cargo ran for {args:?}")); + assert!(result.is_err(), "{args:?}"); + assert_eq!(out, ""); + } + assert_eq!(run_in(dir.path(), &["get"], || Ok(())).0, Err(USAGE.to_owned())); + assert!(run_in(&dir.path().join("missing"), &[], || Ok(())).0.unwrap_err().starts_with("read ")); + } + + #[test] + fn leaves_no_staging_files() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("lock")); + let names = || { + let mut n: Vec = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + n.sort(); + n + }; + let lock_files = || { + std::fs::read_dir(test_lock_dir(dir.path())).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect::>() + }; + let no_owner = |files: Vec| files.iter().all(|f| !f.ends_with(".owner")); + let _ = run_in(dir.path(), &["set", "2.0.0"], || Err("cargo update failed".into())); + assert_eq!(names(), ["Cargo.lock", "Cargo.toml", "target"]); + assert!(no_owner(lock_files()), "the owner file outlived the run: {:?}", lock_files()); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())).0, Ok(())); + assert_eq!(names(), ["Cargo.lock", "Cargo.toml", "target"]); + assert!(no_owner(lock_files()), "{:?}", lock_files()); + } + + #[test] + fn concurrent_set_is_refused_before_anything_is_written() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("old lock\n")); + let config = crate::lock::LockConfig::new(test_lock_dir(dir.path()), 1, "pid 7 in /w: cargo xtask version set 9.0.0"); + let other = crate::lock::try_acquire(&config).unwrap().expect("free lock"); + let ran = Cell::new(false); + let (result, out) = run_in(dir.path(), &["set", "2.0.0"], || { + ran.set(true); + Err("cargo update failed".into()) + }); + let err = result.unwrap_err(); + assert!(err.contains("another `cargo xtask version set`") && err.contains("pid 7 in /w"), "{err}"); + assert_eq!(out, ""); + assert!(!ran.get(), "cargo update ran while another set held the lock"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\n")); + // Reading the version does not take the lock. Setting the current one does: the other run may + // still put an older version back. + assert_eq!(run_in(dir.path(), &[], || Ok(())), (Ok(()), "0.1.0\n".to_owned())); + let (unchanged, out) = run_in(dir.path(), &["set", "0.1.0"], || Ok(())); + assert!(unchanged.is_err_and(|e| e.contains("pid 7 in /w")), "{out}"); + assert_eq!(out, ""); + // An invalid version is refused before the lock. + assert!(run_in(dir.path(), &["set", "nope"], || Ok(())).0.unwrap_err().contains("not a version")); + drop(other); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())), (Ok(()), "version: 0.1.0 -> 2.0.0\n".to_owned())); + } + + #[test] + fn replaces_the_existing_manifest() { + let dir = workspace(MANIFEST, None); + // An open reader of the old manifest does not stop the replacement. + let reader = File::open(dir.path().join("Cargo.toml")).unwrap(); + assert_eq!(run_in(dir.path(), &["set", "3.0.0"], || Ok(())).0, Ok(())); + drop(reader); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "3.0.0"); + } +} diff --git a/design/layers/craft-ui-contract/primitives.toml b/design/layers/craft-ui-contract/primitives.toml index 5a81e4050e..3675d0d4d2 100644 --- a/design/layers/craft-ui-contract/primitives.toml +++ b/design/layers/craft-ui-contract/primitives.toml @@ -4,6 +4,11 @@ config_version = 1 path = "primitives" layer = 3 +# color_ranges depends only on std, so it sits with runtime::egui's text editor, which paints its inks. +[[module]] +path = "primitives::color_ranges" +layer = 2 + [[module]] path = "primitives::textures" layer = 3